Rashim's Blog

Archive for May 2013


Generally, I don’t write about anything else except the technical stuffs until unless I am impressed with, which has a factual value on our work or livelihood. This time I am going to write the things which really fascinated me more and hence can’t resist myself without sharing.

We, all, distinguish that Individuals in a corporate (here I especially mean software company), who want to make their career path in a different angle, always try to be inventive, creative and self-motivated. To know the easiest and effective way of achieving these qualities, sometimes we study huge books, articles and blogs as well as attend to the seminar which is in a sense good and certainly it also makes a good impact on us. But is this the only or right way to be innovative or is this the good pathway to make a vision for mission?

Well, company culture also plays the vital role for the novelty. A great software company culture, which has proper mentors to guide us in the right direction as well as has a good learning environment from which we can easily learn a lot not only our technical stuffs but also the things that we need in our daily lives, can give us the space to share and put our ideas without any hesitation whatever the ideas are. Think of this way, we usually spend almost 8-9 hours a day in our office, and if the office structure is not well enough, we might not feel comfort to work or to stay there for a longer period of time. And if the people, we are working with, are not matured and logical enough how do we expect good ideas from them or share our views to them. In fact, those types of people (who are not matured and logical enough) do not have such personality to provide values of our thoughts as well as concepts, besides they can put us in frustration over our capabilities. If we continue with such folks, over the period of time we might go to dust. At the same time, if we are very much engaged with our work without involving in other fun activities (playing tournament, treats, gossiping…), we might be bored at work, and in this situation, we should never presume that our brain will deliver good things. So, I think in a good custom software company, there must have a well decorated office related to the work, way of entertainment, good mentors and cool environment to learn and to teach so that we, all, one day shall be good assets for us and for the company as well which eventually leads to increase the productivity.

Fortunately, I have got the opportunity and have been working in such a cool and attractive environment where I spend each and every day by learning at least a single new thing by following the way of problem solving tactics and the approach to face complex difficulties of our mentors which ultimately have changed my way of problem solving skills and strategies. I think you have already caught up in which company I am working currently, yes this is KAZ Software. You will get an idea about how much fun we do while we are at our office if you go through our company website mainly in company & culture section.

Advertisements

Though Performance blocking and Sluggishness are the tailbacks for any application, we can easily overcome these bottlenecks by using asynchronous programming. But old-style practice for asynchronous programming is not way easy enough to write, debug and maintain. So what is the contemporary approach??

Well, In my view, this is Task based asynchronous programming, which is updated in .Net 4.5 through the use of keywords await and async. But what do async and await do? async and await are the way of controlling continuation. When a method uses the async keyword, it means it is an asynchronous method, which might have an await keyword inside, and if it has an await keyword, async will activate it. So, simply async activates the await, from which point, the asynchronous has been started. There is a nice explanation that has been given here.

In WCF we can also consider an asynchronous operation while the service operation creates a delaying call. There are three ways to implement asynchronous operations

In this post I am going to use task-based asynchronous operation since this is the most contemporary strategy.

Okay. Let’s move to the code,

A very simple Service contract such as,

 [ServiceContract]
 public interface IMessage
 {
     [OperationContract]
     Task<string> GetMessages(string msg);
 }

With this simple contract, the implementation is just straight forward,

 public class MessageService : IMessage
 {
    async Task<string> IMessage.GetMessages(string msg)
    {
       var task = Task.Factory.StartNew(() =>
                                      {
                                          Thread.Sleep(10000);
                                          return "Return from Server : " + msg;
                                      });
      return await task.ConfigureAwait(false);
    }
 }

Here, the method is marked with the async keyword, which means it might use await keyword inside. It also means that the method will be able to suspend and then resume asynchronously at await points. Moreover, it points the compiler to boost the outcome of the method or any exceptions that may happen into the return type.

Service hosting,

 class Program
 {
     static void Main(string[] args)
     {
        var svcHost = new ServiceHost(typeof (MessageService));
        Console.WriteLine("Available Endpoints :\n");
        svcHost.Description.Endpoints.ToList().ForEach(endpoints=> Console.WriteLine(endpoints.Address.ToString()));
        svcHost.Open();
        Console.ReadLine();
     }
 }

Finally Service Configuration,

<?xml version="1.0"?>
 <configuration>
     <system.serviceModel>
       <services>
          <service name="Rashim.RND.WCF.Asynchronous.ServiceImplementation.MessageService">
             <host>
                 <baseAddresses>
                     <add baseAddress="net.Tcp://localhost:8732/"/>
                     <add baseAddress="http://localhost:8889/"/>
                 </baseAddresses>
             </host>
             <endpoint address="Tcp" binding="netTcpBinding" contract="Rashim.RND.WCF.Asynchronous.Services.IMessage"/>
             <endpoint address="Http" binding="basicHttpBinding" contract="Rashim.RND.WCF.Asynchronous.Services.IMessage">
                 <identity>
                      <dns value="localhost"/>
                 </identity>
             </endpoint>
             <endpoint address="mex" binding="mexTcpBinding" contract="IMetadataExchange"/>
             <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
          </service>
       </services>
       <behaviors>
          <serviceBehaviors>
             <behavior>
                 <serviceMetadata/>
             </behavior>
          </serviceBehaviors>
       </behaviors>
     </system.serviceModel>
     <startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5"/></startup>
</configuration>

After Configuring the service,we need to configure the client app to consume the service.

A simple Console Application(Client),

class Program
 {
    static void Main(string[] args)
    {
       GetResult();
       Console.ReadLine();
    }

    private async static void GetResult()
    {
       var client = new Proxy("BasicHttpBinding_IMessage");
       var task = Task.Factory.StartNew(() => client.GetMessages("Hello"));
       var str = await task;
       str.ContinueWith(e =>
       {
          if (e.IsCompleted)
           {
              Console.WriteLine(str.Result);
           }
       });
      Console.WriteLine("Waiting for the result");
    }
 }

Client Configuration,

<?xml version="1.0"?>
 <configuration>
   <system.serviceModel>
     <bindings>
       <basicHttpBinding>
         <binding name="BasicHttpBinding_IMessage" />
       </basicHttpBinding>
     </bindings>
     <client>
       <endpoint address="http://localhost:8889/Http" binding="basicHttpBinding"
          bindingConfiguration="BasicHttpBinding_IMessage" contract="Rashim.RND.WCF.Asynchronous.Services.IMessage"
           name="BasicHttpBinding_IMessage" />
     </client>
   </system.serviceModel>
 </configuration>

Finally,proxy class is given below through which the client will consume the services.

public class Proxy : ClientBase<IMessage>, IMessage
 {
    public Proxy()
    {
    }
    public Proxy(string endpointConfigurationName) :
    base(endpointConfigurationName)
    {
    }
    public Task<string> GetMessages(string msg)
    {
      return Channel.GetMessages(msg);
    }
 }

That’s it. Very easy stuff though. You can download the source code from here.


%d bloggers like this: