Saturday, January 30, 2010

The "Fancy Proxy" - having fun with WCF - 4-MSMQ Duplex

This article is part of The "Fancy Proxy" tutorial - implementing a few advance ideas in WCF in one solution.

This is the 4th step - MSMQ Duplex.

Ok...so let's see what we explored till now:
In the first two steps we saw simple TCP & simple MSMQ samples on the 3rd we experienced a sample a bit more complex - duplex.

Duplex allowed us to use two "one-way" interfaces to build a dialog between the client & the server in duplex the client actually leaves his endpoint and "becomes" the server waiting for the real one to call him back...
This is nice, but it's not quite the disconnected solution we are looking for.
MSMQ is, but then the "online" code would be weird & not natural using only one-way communication.

So what we're really looking for is a way to work with MSMQ but not only one-way but both-ways - meaning some kind of combination between MSMQ & Duplex.
Looking for this type of solution I was amazed to discover Microsoft did not implemented a "two-way" solution for MSMQ...All the samples I found included use of old MSMQ libraries code...opening queues etc..that's not WCF...WCF is suppose to separate between the code & the transport decisions....hmmm...

Then I found a great work by Nicolas Dorier called Duplex MSMQ I won't get deep here on how he implemented this if you want to read about it better go to the source on Code Project.
So let's take this excellent solution for a spin..

First we open a queue for the server & for the client since they will both talk to each other using queues (in develop environment it's on the same machine, in production it will of course be separated).




The contract is similar to duplex solution, it includes two "one-way" interfaces when the second acts as the "callback" interface of the first one.


[ServiceContract(CallbackContract=typeof(ISampleContractCallback))]
public interface ISampleContract
{
[OperationContract(IsOneWay=true)]
void GetData(Guid identifier);

[OperationContract(IsOneWay = true)]
void Execute(Guid identifier);
}

public interface ISampleContractCallback
{
[OperationContract(IsOneWay = true)]
void SendData(Guid identifier, string answer);
}


Same on the server's code - looks like regular duplex solution, notice the 'GetCallbackChannel' that retrieves the channel back to the client.


public void GetData(Guid identifier)
{
Console.WriteLine("recieved GetData request (id {0})", identifier);

ISampleContractCallback client = OperationContext.Current.GetCallbackChannel();

//get data by identifier
string answer = "hi! from server";

client.SendData(identifier, answer);
}

public void Execute(Guid identifier)
{
Console.WriteLine("recieved Execute request (id {0})", identifier);
}


The host is the same as previous steps...

On the client's code there are some changes, the proxy gets the channel from the 'DuplexMsmqChannelFactory' (part of the duplex-msmq solution) and it implements both interfaces, I showed here one way to implement this using events though it's not part of our final solution.


public class testFancyProxyProxy:ISampleContract, ISampleContractCallback
{
private ISampleContract proxy;

public delegate void AnswerArrivedHandler(object sender, AnswerArrivedArgs args);

public event AnswerArrivedHandler AnswerArrived;

public testFancyProxyProxy()
{
proxy = DuplexMsmqChannelFactory.GetChannel(ConfigurationSettings.AppSettings["ClientURI"],
this,
ConfigurationSettings.AppSettings["ServerURI"]);
}

#region ISampleContract Members

public void GetData(Guid identifier)
{
proxy.GetData(Guid.NewGuid());
}

public void Execute(Guid identifier)
{
proxy.Execute(Guid.NewGuid());
}

#endregion

#region ISampleContractCallback Members

public void SendData(Guid identifier, string answer)
{
OnAnswerArrived(this, new AnswerArrivedArgs(identifier, answer));
}

#endregion

protected void OnAnswerArrived(object sender, AnswerArrivedArgs args)
{
if (AnswerArrived != null)
{
AnswerArrived(sender, args);
}
}
}

public class AnswerArrivedArgs:EventArgs
{
private Guid _identifier;
private string _answer;

public AnswerArrivedArgs(Guid identifier, string answer)
{
_identifier = identifier;
_answer = answer;
}

public Guid Identifier { get { return _identifier; } }
public string Answer { get { return _answer; } }
}


And the consumer, simple test:


public void Run()
{
Console.WriteLine("press any key to run..");
Console.Read();

proxy = new testFancyProxyProxy();

proxy.AnswerArrived += new testFancyProxyProxy.AnswerArrivedHandler(proxy_AnswerArrived);

proxy.GetData(Guid.NewGuid());

proxy.Execute(Guid.NewGuid());

Console.WriteLine("press any key to close client..");
Console.Read();
}

private void proxy_AnswerArrived(object sender, AnswerArrivedArgs args)
{
Console.WriteLine("answer from server for id {0}: {1}", args.Identifier, args.Answer);
}




That's it for this step.

2 more steps to go...in the next one we will see a nice way to wrap & encapsulate the changing of the proxy (online/offline) using dynamic proxy & than we will combine all we learned here together in the final step.

Till than...

Feel free to ask/comment...

Diego

PS: Source download

Saturday, January 16, 2010

The "Fancy Proxy" - having fun with WCF - 3-Simple Duplex

This article is part of The "Fancy Proxy" tutorial - implementing a few advance ideas in WCF in one solution.

This is the 3rd step - Simple Duplex

Ok..so why duplex?! in the final step I want to have a proxy that dynamically changes between online & offline state - in previous step we looked at MSMQ - that would be our "offline" solution...I need an "online" solution that will work implementing the same interface, which is "one-way", but I also want to benefit from the "online" state and actually receive "answers" from the server...

So...let's implement a simple Duplex on WCF - to do just that.

We'll start with the contract, since Duplex is designed for async processing, it is built from two "one-way" interfaces, the second acts as the callback interface.

We'll use the same contract as previous samples, we'll see the second -
ISampleContractCallback is registered as the "CallbackContract" of the first interface:

[ServiceContract(CallbackContract=typeof(ISampleContractCallback))]
public interface ISampleContract
{
[OperationContract(IsOneWay=true)]
void GetData(Guid identifier);

[OperationContract(IsOneWay = true)]
void Execute(Guid identifier);
}

public interface ISampleContractCallback
{
[OperationContract(IsOneWay = true)]
void SendData(Guid identifier, string answer);
}


Next we'll implement this interface on server side - our "business logic", here we'll call back the client with the "answer":

public class testFancyProxyService:ISampleContract
{
public void GetData(Guid identifier)
{
Console.WriteLine("recieved GetData request (id {0})", identifier);

ISampleContractCallback client = OperationContext.Current.GetCallbackChannel();

//get data by identifier
string answer = "hi! from the server";

client.SendData(identifier, answer);
}

public void Execute(Guid identifier)
{
Console.WriteLine("recieved Execute request (id {0})", identifier);
}
}


As previous samples, the host does not change:

class Program
{
private static ServiceHost serviceHost = null;

static void Main(string[] args)
{
try
{
startListening();

Console.WriteLine("Server is up, press any key to stop it...");
Console.Read();
}
catch (Exception ex)
{
Console.WriteLine(string.Format("Error: {0}\n\n Stack:{1}", ex.Message, ex.StackTrace));
Console.Read();
}
finally
{
stopListening();
}
}

private static void startListening()
{
// Create a ServiceHost for the CalculatorService type and
// provide the base address.
serviceHost = new ServiceHost(typeof(testFancyProxyServer.testFancyProxyService));

// Open the ServiceHostBase to create listeners and start
// listening for messages.
serviceHost.Open();
}

private static void stopListening()
{
if (serviceHost != null)
{
if (serviceHost.State == CommunicationState.Opened)
{
serviceHost.Close();
}
}
}
}


The server's endpoint stays as the "regular" TCP sample

<endpoint address="net.tcp://localhost:8080/testFancyProxy" binding="netTcpBinding"
bindingConfiguration=""
contract="testFancyProxyContracts.ISampleContract" />


Same thing on client side - we'll code a small proxy - here we'll create a 'DuplexChannelFactory' instead of a "regular" ChannelFactory:

public class testFancyProxyProxy:ISampleContract
{
InstanceContext m_context;
private NetTcpBinding tcpBinding;
private EndpointAddress endPointAddress;
ISampleContract proxy;

public testFancyProxyProxy(InstanceContext context)
{
m_context = context;
tcpBinding = new NetTcpBinding(SecurityMode.Transport);
endPointAddress = new EndpointAddress(ConfigurationSettings.AppSettings["ServerURI"]);

proxy = new DuplexChannelFactory(m_context, tcpBinding).CreateChannel(endPointAddress);
}

public void GetData(Guid identifier)
{
proxy.GetData(identifier);
}

public void Execute(Guid identifier)
{
proxy.Execute(identifier);
}
}


Testing...to receive an answer from server, we'll add implementation for ISampleContractCallback.

public class testFancyProxyConsumer : ISampleContractCallback
{
private static InstanceContext m_context = null;
private testFancyProxyClient.testFancyProxyProxy proxy;

public void Run()
{
m_context = new InstanceContext(this);

proxy = new testFancyProxyProxy(m_context);
proxy.GetData(Guid.NewGuid());

proxy.Execute(Guid.NewGuid());
}

//ISampleContractCallback:
public void SendData(Guid identifier, string answer)
{
Console.WriteLine("answer from server for id {0}: {1}", identifier, answer);
}
}





That's it!! 3rd step - that's it for the basics, till now we saw simple TCP, simple MSMQ and simple Duplex...next step we'll start with the more advanced steps towards our final goal - a duplex-dynamic proxy.

Till next step...
Diego

PS: source download

Friday, January 8, 2010

The "Fancy Proxy" - having fun with WCF - 2-Simple MSMQ

This article is part of The "Fancy Proxy" tutorial - implementing a few advance ideas in WCF in one solution.

This is the 2nd step - Simple MSMQ

2st step, lets implement a simple MSMQ on WCF - so we understand the basics.

We'll start with the contract, since one of MSMQs benefits is support of disconnected enviroment, the interface it implements can be only "one-way" (we'll explore this later on...).

So we'll start with the same contract (except the "two-way" method):

[ServiceContract]
public interface ISampleContract
{
//[OperationContract]
//string GetData(Guid identifier);

[OperationContract(IsOneWay=true)]
void Execute(Guid identifier);
}


Next we'll implement this interface on server side - our "bussiness logic":

public class testFancyProxyService:ISampleContract
{
public void Execute(Guid identifier)
{
Console.WriteLine"recieved Execute request (id {0})", identifier);
}
}


Next, lets host the service, this host did not change from previous step which is super-cool, specially for those who experiment MSMQ before WCF existed:

class Program
{
private static ServiceHost serviceHost = null;

static void Main(string[] args)
{
try
{
startListening();

Console.WriteLine("Server is up, press any key to stop it...");
Console.Read();
}
catch (Exception ex)
{
Console.WriteLine(string.Format("Error: {0}\n\n Stack:{1}", ex.Message, ex.StackTrace));
Console.Read();
}
finally
{
stopListening();
}
}

private static void startListening()
{
// Create a ServiceHost for the CalculatorService type and
// provide the base address.
serviceHost = new ServiceHost(typeof(testFancyProxyServer.testFancyProxyService));

// Open the ServiceHostBase to create listeners and start
// listening for messages.
serviceHost.Open();
}

private static void stopListening()
{
if (serviceHost != null)
{
if (serviceHost.State == CommunicationState.Opened)
{
serviceHost.Close();
}
}
}
}


Configure the server's endpoint to listen to the private "testFancyProxy" queue.

<services>
<service name="testFancyProxyServer.testFancyProxyService">
<endpoint address="net.msmq://localhost/private/testFancyProxy"
binding="netMsmqBinding" bindingConfiguration="NoMSMQSecurity"
contract="testFancyProxyContracts.ISampleContract" />
</service>
</services>
<bindings>
<netMsmqBinding>
<binding name="NoMSMQSecurity" maxReceivedMessageSize="1073741824">
<readerQuotas maxArrayLength="1073741824" />
<security>
<transport msmqAuthenticationMode="None" msmqProtectionLevel="None" />
<message clientCredentialType="Windows" />
</security>
</binding>
</netMsmqBinding>
</bindings>


Create the queue (Computer management->Services and Applications->Message Queuing->Private Queues):





Same thing on client side - we'll code a small proxy (yes, you can instead use "add service reference" on visual studio :-)) - again, this class is exactly as in previous sample since msmq stuff are in config file only:


public class testFancyProxyProxy:ISampleContract
{
ChannelFactory channelFactory;
ISampleContract proxy;

public testFancyProxyProxy()
{
channelFactory = new ChannelFactory("msmqEndPoint");
proxy = channelFactory.CreateChannel();
}

public void Execute(Guid identifier)
{
proxy.Execute(identifier);
}
}


Configure the client and test it:

<system.serviceModel>
<client>
<endpoint address="net.msmq://localhost/private/testFancyProxy"
binding="netMsmqBinding" bindingConfiguration="NoMSMQSecurity"
contract="testFancyProxyContracts.ISampleContract"
name="msmqEndPoint"/>
</client>
<bindings>
<netMsmqBinding>
<binding name="NoMSMQSecurity" maxReceivedMessageSize="1073741824">
<readerQuotas maxArrayLength="1073741824" />
<security>
<transport msmqAuthenticationMode="None" msmqProtectionLevel="None" />
<message clientCredentialType="Windows" />
</security>
</binding>
</netMsmqBinding>
</bindings>
</system.serviceModel>


Testing...(same as previous sample...):

public class testFancyProxyConsumer
{
private testFancyProxyClient.testFancyProxyProxy proxy;

public void Run()
{
proxy = new testFancyProxyProxy();
Guid identifier = Guid.NewGuid();
proxy.Execute(identifier);

Console.WriteLine("Message {0} sent", identifier);
}
}





That's it!! 2nd step - nice & simple..

So you may ask..."if everything is the same except the config...what do I need MSMQ for??"

Well...there are a few..async processing, managing priority etc, we'll explore the relevant benefit - disconnected enviroment.

Lets add time stamp to the messages both on client & server.

Now lets start only the client.




After a few minutes, lets start the server.




As you can see the server recieved the message altough it was down when the message was sent - isn't that cool?


Till next step...
Diego

PS: source download