Thursday, February 25, 2010

Tic Tac Toe TSQL Style

I found some pretty cool article By Adam Haines on http://www.sqlservercentral.com
Tic Tac Toe TSQL Style.
Old game in T-SQL style - must read and try .

Monday, February 15, 2010

The "Fancy Proxy" - having fun with WCF - 6-DynamicDuplexProxy

A little project I was doing at home lately lead me to search for a solution to disconnected application.

In my imagination I imagined an application that knows to work both "online" and "offline"...not just that but also knows how to switch between them when needed and of course - controlled from WCF configuration or other infrastructure that will be as "transparent" as possible for the programmer who writes the application.

Sounds a little like science fiction? not quite...

Gathering information from all sort of good articles & blogs I've reach to a nice project which I've decided to share with you in a kind of tutorial structure to help who ever finds this interesting - step by step.
I know the code could & should pass a bit of polish, but hey! remember it's just an idea not production material :-)

Each step in this "tutorial" represents a step in the way for the full solution, this is only to help understand each concept seperately, feel free to jump over a few steps or go directly to the final step...

1- Simple TCP
2- Simple MSMQ
3- Simple Duplex
4- MSMQ Duplex
5- Simple Dynamic proxy
6- Dynamic & Duplex proxy

This is the final step of this tutorial.

Let's review the main modifications from previous steps and test it.

The final step shows a combination of two previously reviewed steps -
TCP-Duplex and MSMQ-Duplex.
The TCP-Duplex will work when the client is connected to the server and the MSMQ-Duplex will work when it's disconnected.
We'll start with the contract, here we can see a regular duplex contract built from two "one-way" interfaces, the 2nd interface is the callback interface of the 1st 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);
}


The server implementation of this contract is very simple, the only thing worth mentioning here is the 'GetCallbackChannel' call which allows us to retrieve the client's endpoint & allows the server to send back an 'answer' (see 3- Simple Duplex step for more information on this).

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

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

 ISampleContractCallback client = OperationContext.Current.GetCallbackChannel();

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

 client.SendData(identifier, answer);
}


The host didn't change much from previous steps, the only change is the call for 'AddToExistingServiceHost', this helper method adds the MSMQ-Duplex endpoint to previously configured TCP-Duplex endpoint.

private static void startListening()
{

 serviceHost = new ServiceHost(typeof(testFancyProxyServer.testFancyProxyService));

          //msmq duplex server
 DuplexMsmqServices.AddToExistingServiceHost(serviceHost,
 typeof(testFancyProxyServer.testFancyProxyService),
 typeof(ISampleContract),
 ConfigurationSettings.AppSettings["MSMQServerURI"]);


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


In the client we will see a proxy very similar to previous step.
The proxy here uses:

1. 'NetworkChange.NetworkAvailabilityChanged' to track the network availability.

2. DynamicTargetProxyInterceptor which wraps "Castle DynamicProxy" 'ChangeInvocationTarget' to transparently switch between the 'online' and 'offline' proxies.

/// 
/// this class intercepts each call to proxy
/// and check if it needs to switch to secondary target
/// 
public class DynamicTargetProxyInterceptor : IInterceptor
{
 private readonly T _secondaryTarget;

 public DynamicTargetProxyInterceptor(T secondaryTarget)
 {
 _secondaryTarget = secondaryTarget;
 }     

 public void Intercept(IInvocation invocation)
 {
  var primaryTarget = invocation.InvocationTarget as IProxySelectorDesicion;

  if (primaryTarget.IsOnline == false)
  {
   ChangeToSecondaryTarget(invocation);
  }
 invocation.Proceed();
 }

 private void ChangeToSecondaryTarget(IInvocation invocation)
 {
  var changeProxyTarget = invocation as IChangeProxyTarget;
  changeProxyTarget.ChangeInvocationTarget(_secondaryTarget);
 }
}


3. Nicolas Dorier's MSMQ Duplex to implement the 'offline' proxy - using the same duplex contract over MSMQ on both client & server - allowing a duplex dialog between them.

Playing a bit with previous dynamic proxy sample I've noticed that when switching from the 'offline' proxy back to previously 'used' TCP proxy I get a CommunicationException - the solution for this included registering to ICommunicationObject.Faulted event to handle this exception by recreating a new 'online' proxy:
void SampleContractProxy_Faulted(object sender, EventArgs e)
{
 ((ICommunicationObject)sender).Abort();

 if (sender is ISampleContract)
 {
  sender = CreateProxy(currentEndPoint);
 } 
}


Another modification is the 'OfflineWaitTimeOut' property which allows the proxy's consumer to wait for the MSMQ-Duplex message to arrive getting a sync-like behavior, this way the code's flow is cleaner but it has an obvious cost - the client actually waits for the answer (go figure...:-)).
Anyway, like in previous sample the proxy also contains the 'AnswerArrived' event which will trigger when the server 'answers' immediately if we set the 'OfflineWaitTimeOut' to 0 or when we reach the 'OfflineWaitTimeOut' if set (it can also be set to infinite time out - not really recommended, but the option exists..).

public string GetDataSync(Guid identifier)
{
 Console.WriteLine("enter GetDataSync {0}", DateTime.Now.ToString("hh:MM:ss"));
 GetData(identifier);

 wait4Signal();

 Console.WriteLine("leave GetDataSync {0}", DateTime.Now.ToString("hh:MM:ss"));

 return Answer;
}

public void SendData(Guid identifier, string answer)
{
 wait4Event.Set();
 Answer = answer;

 //this event can be usefull to recieve answers
 //in offline mode when time-out is defined
 if (AnswerArrived != null)
 {
  AnswerArrived(this, new AnswerArrivedArgs(identifier, answer));
 }
}

private void wait4Signal()
{
 if (wait4Event == null)
 { 
  wait4Event = new ManualResetEvent(false);
 }

 wait4Event.WaitOne(offlineWaitTimeOut);
 wait4Event.Reset();
}


Testing the solution...

Looking at the proxy's consumer code:

- We create two proxies one represents the 'online' endpoint & the other one the 'offline' endpoint.
- We send both to the 'DynamicTargetProxyFactory'.
- We call the server's methods in a loop while connecting and disconnecting from the network.
public class testFancyProxyConsumer
{
 private const string ONLINE_ENDPOINT = "Online";
 private const string OFFLINE_ENDPOINT = "Offline";

 private SampleContractProxy onlineProxy;
 private SampleContractProxy offlineProxy;
 private ISampleContractSync proxy;
 private DynamicTargetProxyFactory dp;


 public void Run()
 {
  onlineProxy = new SampleContractProxy(ONLINE_ENDPOINT, true);
  offlineProxy = new SampleContractProxy(OFFLINE_ENDPOINT, true);

  offlineProxy.OfflineWaitTimeOut = 1000;
  offlineProxy.AnswerArrived += new SampleContractProxy.AnswerArrivedHandler(offlineProxy_AnswerArrived);


  dp = new DynamicTargetProxyFactory(onlineProxy, offlineProxy);

  proxy = dp.GetCurrentTarget();

  Guid testGuid;

  for (int i = 0; i < 10; i++)
  {
   testGuid = Guid.NewGuid();

   proxy.Execute(testGuid);
 
   Console.WriteLine(string.Format("{1} excute {0}", testGuid, DateTime.Now));

   Console.WriteLine(string.Format("{3} GetDataSync {0} on '{1}' proxy result:{2}",
      testGuid, proxy.CurrentEndPoint,
      proxy.GetDataSync(testGuid), DateTime.Now));


   Console.ReadLine();
  }
 }

 private void offlineProxy_AnswerArrived(object sender, AnswerArrivedArgs args)
 {
  Console.WriteLine("answer finally arrived, identifier={0}, answer={1}", args.Identifier, args.Answer);
 }
}
The result: The proxy handles everything and switches between the two proxies, the proxy's consumer doesn't need to do anything about this nor it notices the switches and even more important - all calls reached the server - isn't it a fancy proxy ??! :-) That's it on this subject. Feel free to ask or comment... Diego PS: Source Download

Friday, February 5, 2010

The "Fancy Proxy" - having fun with WCF - 5-Simple DynamicProxy

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

This is the 5th step - Simple DynamicProxy.

The plot thickens..

As mentioned before one of our main goals is to develop a proxy that can work both when the server is connected & disconnected.
We saw clues for the main idea in previous articles of this tutorial.
On "Online mode" the application will work with using regular TCP connection.
On "Offline mode" it will use MSMQ-Duplex.
But how can we identify the need for the switch between them? how can we change between them? can we make the change transparent for the proxy consumer??

The best solution I found for this is using a wonderfull design pattern called - dynamic proxy - this pattern allows us to include dynamic behavior around an object, yet neither change the object's existing code nor its interface
In a previous article of mine I've explored a use of this pattern building a
transverse application policy (AOP – Aspect Orient Programming in .NET).

This design pattern is nicely implemented in a free & open source library called "Castle DynamicProxy" written by a group called "Castle Project".
If you want to read more about the uses of this library, I recommend Krzysztof Ko┼║mic's blog (Castle Dynamic Proxy tutorial).

Back to our little project, we'll start exploring the use of dynamic proxy relevant for the previously mentioned goal.

1st we'll look at the contract..simple as in previous samples:

[ServiceContract]
public interface ISampleContract
{
[OperationContract(IsOneWay=true)]
void Execute(Guid identifier);
}


Host stays the same, the server could not be simpler:


public class testFancyProxyService:ISampleContract
{
#region ISampleContract Members

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

#endregion
}


In server's (and client's) app.config we will add two endpoints, TCP for the 'online mode' and MSMQ for the 'offline mode':


<endpoint name="Online"
address="net.tcp://localhost:8080/testFancyProxy" binding="netTcpBinding"
bindingConfiguration=""
contract="testFancyProxyContracts.ISampleContract" />
...
<endpoint name="Offline"
address="net.msmq://localhost/private/testFancyProxy"
binding="netMsmqBinding" bindingConfiguration="NoMSMQSecurity"
contract="testFancyProxyContracts.ISampleContract" />


Now lets look at real point of this article, in the client side I've written a new interface & two classes (besides the references to "Castle dynamic proxy" of course).
The interface IProxySelectorDesicion speaks for itself:

public interface IProxySelectorDesicion
{
bool IsOnline { get; }
}


The 'DynamicTargetProxyFactory' receives in it's ctor two objects, in our case the first one will represent the 'online' proxy & the second the 'offline'.


///
/// builds the transparent proxy
/// and registers the relevant interceptor
///

///
public class DynamicTargetProxyFactory
{
private readonly IProxySelectorDesicion _primaryTarget;
private readonly T _secondaryTarget;
private ProxyGenerator _generator;

public DynamicTargetProxyFactory(IProxySelectorDesicion primaryTarget,
T secondaryTarget)
{
_primaryTarget = primaryTarget;
_secondaryTarget = secondaryTarget;
_generator = new ProxyGenerator();
}
...


This class is also responssible to register the interceptor, the interceptor that will later let us "inject" our code to message chain.


...
public T GetCurrentTarget()
{
var interceptor = new DynamicTargetProxyInterceptor(_secondaryTarget);
object target = _generator.CreateInterfaceProxyWithTargetInterface(typeof(T), _primaryTarget, interceptor);
return (T)target;
}
...


The 2nd class is the acutal interceptor I've called 'DynamicTargetProxyInterceptor'. As you can see next, the interceptor checks on every intercept if primaryTarget.IsOnline (primaryTarget in our case will be the 'online mode' proxy)and if the answer is 'no' it uses 'ChangeInvocationTarget' method to switch to the secondary target (in our case the 'offline mode' proxy).
ain't that cool?! :-)


///
/// this class intercepts each call to proxy
/// and check if it needs to switch to secondary target
///

public class DynamicTargetProxyInterceptor : IInterceptor
{
private readonly T _secondaryTarget;

public DynamicTargetProxyInterceptor(T secondaryTarget)
{
_secondaryTarget = secondaryTarget;
}

public void Intercept(IInvocation invocation)
{
var primaryTarget = invocation.InvocationTarget as IProxySelectorDesicion;
if (primaryTarget.IsOnline == false)
{
ChangeToSecondaryTarget(invocation);
}
invocation.Proceed();
}

private void ChangeToSecondaryTarget(IInvocation invocation)
{
var changeProxyTarget = invocation as IChangeProxyTarget;
changeProxyTarget.ChangeInvocationTarget(_secondaryTarget);
}
}


Now lets look at the proxy, this time I've used the "Add service reference.." on Visual Studio & just expanded it using parallel partial class.
This class implements 'IProxySelectorDesicion' and registers to 'NetworkAvailabilityChanged' event to be update the network availability status.


public partial class SampleContractClient : IProxySelectorDesicion
{
private bool isOnline;

public SampleContractClient(string endpointConfigurationName, bool dummy)
: base(endpointConfigurationName)
{
bool connected = NetworkInterface.GetIsNetworkAvailable();
UpdateConnectionStatus(connected);

NetworkChange.NetworkAvailabilityChanged += OnAvaiabilityChanged;
}

#region IProxySelectorDesicion Members

public bool IsOnline
{
get { return isOnline; }
}
#endregion

private void OnAvaiabilityChanged(object sender, NetworkAvailabilityEventArgs args)
{
UpdateConnectionStatus(args.IsAvailable);
}

private void UpdateConnectionStatus(bool connected)
{
isOnline = connected;
}
}


Finally let's look at the consumer, here we can see we construct two proxies (offline/online) send them both to the 'DynamicTargetProxyFactory' and execute...
The 'DynamicTargetProxyFactory' will handle everything and change between this two proxies depending on the network availability :-)


public class testFancyProxyConsumer
{
private const string ONLINE_ENDPOINT = "Online";
private const string OFFLINE_ENDPOINT = "Offline";

private SampleContractClient onlineProxy;
private SampleContractClient offlineProxy;
private ISampleContract proxy;
private DynamicTargetProxyFactory dp;


public void Run()
{
onlineProxy = new SampleContractClient(ONLINE_ENDPOINT, true);
offlineProxy = new SampleContractClient(OFFLINE_ENDPOINT, true);

dp = new DynamicTargetProxyFactory(onlineProxy, offlineProxy);

proxy = dp.GetCurrentTarget();

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


Testing...

To test the switch between proxies, we will do the following steps:
1. Put the server on different machine (don't forget to open the server queue & change the client config to point the server machine).
2. Add a console.writeline on the proxy's desicion in Intercept method in DynamicTargetProxyInterceptor and the 'proxy.Execute' in a loop.
3. Start the server.
4. Disconnect the client from the network.
5. Run the application in the client - we'll see the use of the offline proxy (using MSMQ in this case).
6. Connect the client to the network, call a server method, the online proxy will be chosen (regular TCP channel).
7. The server will receive all calls (thanks to MSMQ...).

The result:

On the left we can see the client in a local machine, we can see the switch between the offline & the online proxy, on the right we can see the remote server machine showing that all the messages arrived - offline & online...



This step's mission is accomplished.

Till next time...

Diego

PS: Source Download