Wednesday, February 11, 2009

Silverlight Tip of the Day #10 - Full Implementation of a Silverlight Policy Server.

Before a Silverlight application can connect to a server it must first successfully connect to a policy server on that machine in order to proceed with the connection.

In this tip I will take you through every step you need to create and run your own policy server.

To start, create a new C# console application. Then, create a new XML file called “clientaccesspolicy.xml” and add it to your project. This is the file your Policy Server will send to a client giving it permission to proceed with the connection.

The contents of the “clientaccesspolicy.xml” are as follows:













Note that with Silverlight, sockets are limited to ports #4502-4534. Also, the policy server that sends this policy file to the connecting client must be run on port 943.

The code for the policy server itself is as follows:

using System;
using System.IO;
using System.Net;
using System.Net.Sockets;

namespace PolicyServer
{
// Encapsulate and manage state for a single connection from a client
class PolicyConnection
{
private Socket _connection;
private byte[] _buffer; // buffer to receive the request from the client
private int _received;
private byte[] _policy; // the policy to return to the client

// the request that we're expecting from the client
private static string _policyRequestString = "";

public PolicyConnection(Socket client, byte[] policy)
{
_connection = client;
_policy = policy;

_buffer = new byte[_policyRequestString.Length];
_received = 0;

try
{
// receive the request from the client
_connection.BeginReceive(_buffer, 0, _policyRequestString.Length, SocketFlags.None,
new AsyncCallback(OnReceive), null);
}
catch (SocketException)
{
_connection.Close();
}
}

// Called when we receive data from the client
private void OnReceive(IAsyncResult res)
{
try
{
_received += _connection.EndReceive(res);

// if we haven't gotten enough for a full request yet, receive again
if (_received < request =" System.Text.Encoding.UTF8.GetString(_buffer," policystream =" new" _policy =" new" _listener =" new" client =" null;" client =" _listener.EndAccept(res);" pc =" new" ps =" new" to="" your="" file="">\clientaccesspolicy.xml");
System.Threading.Thread.Sleep(System.Threading.Timeout.Infinite);
}
}
}
You will need to change where it says "\clientaccesspolicy.xml" to be the actual path to where you saved this file on your server.

Thank you,