Monday, February 18, 2008

Use RelayBinding to Expose Your Service to the world through MS Service Bus

To use Microsoft implementation of ESB at http://www.biztalk.net/, We need only use RelayBinding in WCF + Biztalk Service Extension.
In fact Service Config could be as simple as the following:

<configuration>
<system.serviceModel>
<services>
<service name="JQD.HomeLabService">
<endpoint contract="JQD.IHomeLabService"
name="JQD.HomeLabService"
binding="relayBinding" />
...
and the corresponding code are also simple:

static void Main(string[] args)
{
CardSpaceTokenProvider tok = new CardSpaceTokenProvider();
string rHostName = RelayBinding.DefaultRelayHostName;
Uri rHostUri = new Uri(String.Format("sb://{0}/services/{1}/HomeLabService",rHostName,tok.GetUserName()));
ServiceHost rHost = new ServiceHost(typeof(HomeLabService), rHostUri);
rHost.Description.Endpoints[0].Behaviors.Add(tok);
rHost.Open();
Console.ReadLine();
rHost.Close();
}

Clearly, the endpoint "sb://conect.biztalk.net/services/jqd2001/HomeLabService" will be correctly relayed to your server every running code has a correct cardSpace token.

For a piece of code to reach your web services through relay, it only need to know the contract

[ServiceContract()]
public interface IHomeLabService
{
[OperationContract()]
string HeartBeat();
}

and it then need to connect to MS ESB:


static void Main(string[] args)
{
ChannelFactory f = new ChannelFactory(new RelayBinding(),
"sb://connect.biztalk.net/services/jqd2001/HomeLabService");
f.Open();
IHomeLabService ch =f.CreateChannel();
Console.WriteLine( ch.HeartBeat());
f.Close();

Noticeably, RelayBinding is the key to traverse NAT or firewall and without expose your server to the internet directly.

No comments: