A WCF Chat Service & Client

I attended a interview recently for which the pre-requisite was to develop a chat application using WCF as part of a code challenge. The requirement was quite simple, so instead of taking the usual route of creating a WCF service and adding its reference to a client application, I decided to hand code everything without any configuration or service references!

Of course the  assumption here is that the service and client applications are owned by a single company/team so that the contracts can be shared between the service and client.

The complete code is available in my Github account.

The Problem Statement
Goal - Create a Chat Server and Client application using 
.NET 4.0/4.5 with WCF as the communication mechanism. 
The Chat Server should be a standalone application and 
the Chat Client should be a standalone application with 
a basic UI for users to interact and exchange messages 
through the Chat server. Stability of the code is a 
must-have and it should be ensured that the 
Server/Client do not crash during operation to 
maintain quality user experience. 

The basic functionality to be supported is as follows: 

1. The chat server should open up a TCP port for
 listening to incoming client requests. 

2. The server should be able to handle at 
least 2 distinct clients’ communication in parallel. 

3. On successful connection with the server, 
the chat client should be able to send plain text 
messages to the server. 

4. The server should be able to respond to each 
message by a static message "Hello!" appended 
with the server's timestamp. 

5. Both chat clients should be able to communicate 
with the server without the messages of either being 
visible to the other one. 

The Approach

Since the service contract has to be shared between the service and client the best place to create the service contract is in a common library project. I have created a “contract” folder which has few more sub folders having contracts for service, response, request,  fault and a contract for callback service (more on this later).

image

The Duplex Message Exchange Pattern via Callbacks

IEAChatService.cs is the service contract defined as shown below

 [ServiceContract(
        SessionMode = SessionMode.Required, 
        CallbackContract= typeof(IChatCallback))]
 public interface IEAChatService

I have defined a CallbackContract for this service contract. This callback contract interface is defined in IChatCallback.cs and is implemented by the client application (EA.Client.EAChat.UI).

    [ServiceContract]
    public interface IChatCallback
    {
        [OperationContract(IsOneWay=true)]
        void RefreshUserList(List<User> onlineUsers);

        [OperationContract]
        void ResponseMessage(ResponsePacket response);
    }

This contract is called as a duplex service contract. Duplex service contract is a message exchange pattern where service as well as client can send messages to other independently. Since this interface is implemented by client (EA.Client.EAChat.UI), the service can directly call the client methods. In this case, whenever a new user enters the chat room the Register  method of the EAChatService.cs calls the callback method RefreshUserList on the client, so that client can refresh the user interface and show the name of the newly entered user in the list of users of the chat room. Below is the relevant piece of code.

       public void Register(User userHandle)
        {
            try
            {
						//---irrelevant code removed ---------
                       foreach (KeyValuePair<string, IChatCallback> kvp in registeredUser)
                        {
                            IChatCallback callback = kvp.Value;
                            callback.RefreshUserList(onlineUsers);
                        }
                    }

                }
               // ---irrelevant code removed ---------

            }
            catch (UserHandleInUseException uEx)
            {
                log.Error("User handle is alread in use. Error Detail: " + uEx.Message);
                throw;

            }
            
            
        }
The Service Side Code

EAChatService.cs inherits from ServiceBase.cs. ServiceBase class has some common properties used why the EAChatService class. For instance, the ServiceBase class has a protected getter property  which returns the channel to the client instance which called the operation currently. Below is the code snippet.

      protected IChatCallback Callback
       {
           get
           {
               return OperationContext.Current.GetCallbackChannel<IChatCallback>();
           }
       }

 

ServiceBase class also has a protected dictionary for registeredUsers which stores the userID and the corresponding Callback as a keyvalue pair in the dictionary object. Since multiple users may call the Register method at once, the critical section of adding users in the dictionary is synchronized using a lock. below is the complete code of register method.

       public void Register(User userHandle)
        {
            try
            {
                if (!registeredUser.ContainsKey(userHandle.UserId) &&
                    !registeredUser.ContainsValue(Callback))
                {
                    lock (syncObject)
                    {
                        registeredUser.Add(userHandle.UserId, Callback);
                        onlineUsers.Add(userHandle);

                        foreach (KeyValuePair<string, IChatCallback> kvp in registeredUser)
                        {
                            IChatCallback callback = kvp.Value;
                            callback.RefreshUserList(onlineUsers);
                        }
                    }

                }
                else
                {
                    throw new UserHandleInUseException(ServiceFaultCode.HANDLE_IN_USE, "User with this handle already exist. Please choose a different handle.");
                }
            }
            catch (UserHandleInUseException uEx)
            {
                log.Error("User handle is alread in use. Error Detail: " + uEx.Message);
                throw;

            }
            
            
        }
The Client Code

The client code is implemented in the ChatWindow cliass. The ChatWindow  class has a SynchronizationContext which is used to marshal messages from one thread to another thread. You must be wondering, why do we need to marshal messages from one thread to another. The reason is that the client UI runs on a separate thread and the duplex message from the WCF service is delivered to the client application via another thread. Now the message sent from WCF service as part of duplex call cannot be directly used by the client UI. To enable the message transmission between the UI thread and callback thread, we use the UI thread’s SynchronizationContext and call its Post method to pass the message. I am using Unity container to hold and resolve instances of SynchronizationContext object. Below is the implementation of RefreshUserList callback method which demonstrates the SynchronizationContext usage.

       public void RefreshUserList(List<User> onlineUsers)
        {
            ClearOnlineUserList();

            foreach (User user in onlineUsers)
            {

                SendOrPostCallback callback =
                delegate(object state)
                {
                    this.OnlineUserListBox.Items.Add(user.UserId);
                };

                _uiSyncContext = (SynchronizationContext)container.Resolve(typeof(SynchronizationContext));
                _uiSyncContext.Post(callback, user.UserId);
            }
        }
The WCF endpoint & Hosting

The WCF endpoint is configured programmatically in the EA.Host.ServiceHostEngine project where we have the logic of hosting the WCF service as well.

I have defined an Interface IHostScheme.cs which has the declaration of  Host method and this interface is implemented by NetTcpHost.cs. Since one of the assumptions is that this chat application works in intranet, I choseto use NetTcp binding for the communication. In future if we decide to make to this chat application work in extranet then we can create another class implementing the IHostScheme interface with appropriate binding implementation.

Lets look at the NetTcpScheme.cs class.

    public class NetTcpHost : IHostScheme
    {
        public ServiceHost Host(string portNumber, bool enableMetaData)
        {
            Type contractType = typeof(IEAChatService);
            Type serviceType = typeof(EAChatService);

            Uri baseAddress = GetBaseAddress(portNumber);

            ServiceHost serviceHost = new ServiceHost(serviceType, baseAddress);
            serviceHost.AddServiceEndpoint(contractType, new NetTcpBinding(), baseAddress.AbsoluteUri);

            ServiceMetadataBehavior metaDataBehavior = new ServiceMetadataBehavior();
            metaDataBehavior.HttpGetEnabled = false;
            serviceHost.Description.Behaviors.Add(metaDataBehavior);

            if (enableMetaData)
            {
                serviceHost.AddServiceEndpoint(ServiceMetadataBehavior.MexContractName,
              MetadataExchangeBindings.CreateMexTcpBinding(), "mex");
            }
            

            return serviceHost;
        }

        private Uri GetBaseAddress(string portNumber)
        {
            string prefix = ConfigurationManager.AppSettings["nettcp_prefix"];
            string chatServicePath = ConfigurationManager.AppSettings["EAChatServicePath"];

            return new Uri(prefix + portNumber + chatServicePath);


        }
    }

The code is pretty much self explanatory. This class is responsible for creating a ServiceHost and a ServiceEndpoint. To create a ServiceHost, we need the type of Service contract and to create a service endpoint which will be hosted by the ServiceHost, we need the contract’s type, address (along with the port) where we will host the service and binding is set to NetTcpBinding because that’s one of the requirement in the problem statement that communication has to take place over tcp port.

I have made HttpGetEnabled property of ServiceMetadataBehavior to false, as I don’t se any benefit of exposing the wsdl over http for our application. However, MEX endpoint is made configurable, so that if in future we wish to create a new client and create a proxy using svcutil for communication, we could do so easily.

That’s it! There are other utility projects and relatively less interesting code in the solution, so I will skip the remaining details.

Feel free to use the code and modify it according to your requirements. The code is available  in my Github account.

If you have any queries, feel free to ask in the comments section.

Mobile Push Notification Service – Design Approach (Part 1)

A high level design of Mobile push notification service.

Overview of Push Notifications

In this article, I am going to design the architecture for implementing push notifications for you mobile application. This part only has design and architecture information, code will be covered in Part 2.

If you are new to push notifications, please read wiki article about the technology and also about GCM and APN services.

Below diagram depicts a high level overview of device registration process.

DeviceReg

  1. Device sends sender ID, application ID to GCM server for registration.
  2. Upon registration Cloud Service (GCM/APNs) sends a unique registration ID to the device.
  3. After receiving the registration ID from the cloud service the device will forward the registration ID to the Push Notification Web Service.
  4. The Push Notification web service will store the registration ID in a local database for later use.

a. Whenever Push Notification service needs to send the notification, it has to call GCM/APN service with registration ID of the device which is stored in the database.

b. GCM/APN service will deliver the notification to respective mobile device based on the registration ID.

Push Notification service would require an outbound internet connection to send messages to cloud services. Make sure to open two outbound ports on your push notification server.

Push Notification Components

You would need to implement two components:

  1. Push Notification Web Service

Push notification web service could be a rest service. Bare minimum the web service should have two functionalities. One, to register new device and Second, to unregister a device.

  1. Push Notification Windows Service.

You need to implement a windows service which could spawn multiple threads to listen to a messaging queue at a specified address. This service should be capable to pick up messages as and when it arrives to the messaging queue. The service will then query the local database and get a list of eligible devices which should receive the notification message and communicate with the cloud messaging services to get the notifications delivered.

Push Notification Windows service is a Microsoft Windows® terminology. On non-windows platform this windows service will be a process which will be initiated with a start-up batch file which could be hooked up with tomcat initialization process.

Push Notification Architecture

Diagram below depicts the push notification architecture at high level.

HLD

  1. As depicted in the diagram above, the first step is get the unique device ID from the cloud messaging service. The mobile application should make a call to the cloud messaging service every time it is launched. It is important to make this call every time as it may so happen that the unique device ID assigned earlier has now expired.
  2. Second step is to call the Push Notification web service from the mobile application and include the unique device ID (received from cloud messaging service) in the payload. You may want to pass some additional information like the device type, device operating system etc in the payload. A sample payload JSON is shown below:

    DevicePayload:{
    
    deviceId:'APA9sdsdA',
    
    deviceType:'mobile/tablet',
    
    deviceOS:'android/apple',
    
    userID:'xyz@gmail.com',
    
    }
    
    
  3. Push notification web service will persist the payload in a local database.
  4. Core product which is responsible for generating events per user will create notification messages and publish it to the Messaging Queue.
  5. Push notification windows service’s functionality is to constantly poll the Messaging Queue and pull any new message that arrives to the queue. The service should then query the local database to get the device id associated with the user id for which the notification was generated.
  6. With the fetched device id, the windows service will then communicate with cloud messaging services (GCM/APN).

This is the architecture at high level to design push notification service for your mobile application. In the next article (Part-2), I will cover the code required to communicate with the cloud messaging services.

A Thread Safe Singleton Class in .NET

In this post I will demonstrate creating a singleton class in .Net that is thread safe. As usual the singleton class should have a private constructor as shown below so that any other class cannot “directly” create an instance of our singleton class.

Apart from that, I have created two global variables, one to hold the instance of the Singleton class and another one of type object which will be used later for synchronization between threads (more on that later).

    static SingletonSample _instance;
    static readonly object _synchronizer = new object();
    /// &amp;lt;summary&amp;gt;
    /// Private C'tor, so that this class cannot be instantited by other classes directly
    /// &amp;lt;/summary&amp;gt;
    private SingletonSample()
    {

    }

Method 1 – Using synchronization lock

 

GetInstance is a public static method, this method is the only way by which any other class can get instance of the singleton class.

Below code snippet uses double check pattern before creating the instance of the singleton class. The first If statement, if true, will give the instance of Singleton class instantly. However, if _instance variable is null then program will enter a critical section (the lock statement) synchronized using a global object (_synchronizer). Inside the critical section, I am checking the _instance  variable again if it is null (double check), if it is, then we finally create the instance of the class.

One interesting point to note here is, I am not creating the instance directly and returning it back. I am first assigning the class reference into a temporary object of type SingletonClass (tempInstance) and then doing a  Volatile write on the actual instance variable (_instance).

 

 

        /// &amp;lt;summary&amp;gt;
        /// Method is responsible for providing instance of this class.
        /// &amp;lt;/summary&amp;gt;
        /// &amp;lt;returns&amp;gt;Instance of SingleTonSample class&amp;lt;/returns&amp;gt;
        public static SingletonSample GetInstance()
        {
            //If instance is available return that.
            if (_instance != null)
                return _instance;

            //Critical section. Ony one thread can enter at a time.
            lock(_synchronizer)
            {
                //Check again if the instance in null
                if(_instance == null)
                {
                    SingletonSample tempInstance = new SingletonSample();
                    //Volatile write to make sure that _instance is 
                    //populated with tempInstance reference without any compiler optimization.
                    Volatile.Write(ref _instance, tempInstance);
                }
            }

            return _instance;
        }

The problem with this approach is that if this method is used in a highly parallel system, the critical section will cause all threads to do nothing but wait for an instance of Singleton class to be created. However, this will happen only once when the first instance is getting created, but still, this is wasteful of the resources.

Below is another, more efficient way of creating a singleton which neither uses double check pattern nor it has a critical section for thread synchronization.

Method 2 – Without Critical Section or Double Check

Below method will allow multiple threads to create instance of Singleton class, but Interlocked class’s CompareExchange will make sure that only one instance is assigned to _instance variable. Objects created by other  threads and not assigned to _instance variable will soon become Orphan and  will be garbage collected at a later point of time by the CLR.

        /// &amp;lt;summary&amp;gt;
        /// Method is responsible for providing instance of this class without critical section
        /// or double check pattern.
        /// &amp;lt;/summary&amp;gt;
        /// &amp;lt;returns&amp;gt;Instance of SingletonSample class&amp;lt;/returns&amp;gt;
        public static SingletonSample GetInstance()
        {
            //If instance is available return that.
            if (_instance != null)
                return _instance;
            
            SingletonSample tempInstance = new SingletonSample();
            /*Multiple threads will create singleton object, but only 
            *one will be asssgined to _instance variable. Rest others will be 
            *GC'd (Garbage Collected) later at some point of time. 
            */
            Interlocked.CompareExchange(ref _instance, tempInstance,null);
            
            return _instance;
        }

Both methods are thread safe. However, method 2 is marginally more efficient and lean as compared to the first one.