Accessing a WCF Service WinRT vs Silverlight

Hi, last few days I got some questions from few folks that they are confused on how to call a WCF service in WinRT (Windows 8). This confusion occurs mainly if you are Silverlight dev or Windows Phone 7.5 dev and you are used to the traditional async method and the CompletedEvent.

In Silverlight these two are very handy and generated by the VS.

Think a very simple WCF service that you get once you create a WCF Application project in the Visual Studio. It comes with a simple method GetData which accepts an int and returns a string.

In Silverlight, VS generates the async method and the async CompletedEvent method for us. so we can simply call the service and get the results like this.

private void Button_Click_1(object sender, RoutedEventArgs e) { Service1Client proxy = new Service1Client(); proxy.GetDataCompleted += (GetDataSender, Ev) => { TxtName.Text = Ev.Result; }; proxy.GetDataAsync(10); }

 

But in WinRT if you try do the same thing you soon will find that you are missing the CompletedEvent.

This is handled differently using the await and async keywords in C# 5.0 Read it in detail here.

Here’s the implementation detail of how you can call a WCF service in WinRT. Click to enlarge the image.

image

As you see the GetDataAsync method generated by the VS returns an awaitable Task. So it is simple than Silverlight, this what you have to do. Simple at its best.

Capture1 

But it is better to know how things work, but that is beyond the scope of this article and you can learn about it here

But what if you need to have a separate Application logic layer and wants to do some processing in the data returned by the service. (more often you need that)

Here’s a way to get the CompletedEvent architecture from Application logic and notifying it to the UI. I’m having my own even handler here.

Create a Class1 (your application logic layer)

class Class1 { public event EventHandler<MyWebServiceEventArgs> DataProcessed; public void HandleMethod(int value) { ProcessData(value); } private async void ProcessData(int value) { Service1Client proxy = new Service1Client(); string result = await proxy.GetDataAsync(value); DataProcessed(null,new MyWebServiceEventArgs(result)); } }

Create MyWebServiceEventArgs derived from EventArgs

public class MyWebServiceEventArgs : EventArgs { private string _myVar; public string MyProperty { get { return _myVar; } set { _myVar = value; } } public MyWebServiceEventArgs(string result) { _myVar = result; } }

 

In your UI layer do this

private void BtnClick_Click(object sender, RoutedEventArgs e) { Class1 c1 = new Class1(); c1.DataProcessed += c1_DataProcessed; c1.HandleMethod(10); } void c1_DataProcessed(object sender, MyWebServiceEventArgs e) { TxtName.Text = e.MyProperty; }

 

Open-mouthed smile I brought the Silverlight CompletedEvent model to WinRT.

But you can simply live a happy life with async and await keywords.

Advertisement

Silverlight Dispatcher

Threading in Silverlight is simple and have very few classes and limited functionality.

In Silverlight we rarely go for the threading since the platform itself is asynchronous. Click to read how to do asynchronous programming in C# 5.0

In Silverlight the  main thread is incorporated with the Dispatcher, and we can use the BeginInvoke method of the Dispatcher class to update the UI from a different thread. According to the MSDN documentation Dispatcher in Silverlight is intended for the UI updates.

I’m using a dummy method which returns a string reversed of its input. And let’s assume it takes 4 seconds to complete the task.

So we need a thread to do the work, without blocking the UI. Once the task completed we have to display the string in the UI.

Here’s my simple and the dirty UI, a TextBox, a Button and a TextBlock to show the output.

image

Here’s the code goes under the Button click event , you can do the work in a thread and return the updates to the UI safely using Dispatcher.

{
string name = textBox1.Text;
Thread thread =new Thread(() =>
{  _reversedString = ReverseString(name);
   this.Dispatcher.BeginInvoke(() =>
     {
              textBlock1.Text = _reversedString;
     });
});
thread.Name =Reverse String Thread;
thread.Start();
}

When hitting the debug and break point we can ensure that our thread is really started and running.

1

Code for the ReverseString method

private string ReverseString(string input)
{
     char[] array = input.ToCharArray();
    Array.Reverse(array);
    Thread.Sleep(4000);
    return new String(array);
}

Let’s discuss how Dispatcher can communicate across threads.

You can clearly notice that, I got the Dispatcher object using this.Dispatcher. This gives the Dispatcher of the Page (MainPage).

Dispatcher is a member of the DependencyObject class. So all the elements mainly UI controls have the Dispatcher property.

Silverlight is a Single Threaded Apartment (STA) Model. And as mentioned earlier it is incorporated with the main thread of the Silverlight. It is the thread responsible of the creation of the UI elements.

Trying to create UI elements from custom threads will throw thread exceptions as they try get the one and only Dispatcher from a different thread.

Here I compare the difference Dispatcher obrtained. First I got the Dispatcher of the RootVisual. Second the TextBlock control. Third I get the Dispatcher reference of the Deplyoment.

System.Windows.Threading.Dispatcher appDisptcher = Application.Current.RootVisual.Dispatcher;
System.Windows.Threading.Dispatcher textBlockDispatcher = textBlock1.Dispatcher;
System.Windows.Threading.Dispatcher deploymentDispatcher = System.Windows.Deployment.Current.Dispatcher;
if (appDisptcher.Equals(textBlockDispatcher))
{
    MessageBox.Show(Root Visual Dispatcher is same as TextBlock Dispatcher);
    
    if (appDisptcher.Equals(deploymentDispatcher))
    {
          MessageBox.Show(All three are same indeed);
    }
}

You can see that all Dispatchers equal. So Dispatcher works from one golden rule that is Silverlight is Single Threaded Apartment (STA) model where with that main thread Dispatcher is incorporated.

Singleton Pattern

Singleton pattern is a simple design pattern in software practice and sometimes considered as an anti-pattern due its tight coupling nature.

A very simple non thread safe implementation of the Singleton pattern would be like this.

Singleton non thread safe

class Singleton
{
  privatestatic Singleton _instance;
  private Singleton()
  {
    Console.WriteLine(Singleton instantiated);
  }
 
publicstatic Singleton SingletonInstance
{
  get
   {
        if (_instance ==null)
            {
               // delay the object creation to demonstrate the thread saftey.
               Thread.Sleep(1500);
            _instance =new Singleton();
            }
      return     _instance;
  }
 }
}

Run the above class using Main method shown below, you can notice Singleton constructor is called twice by the both threads, since it is not thread safe. ( You can use the same Main methid implementation for all 3 Singleton implementations)

Main method implementation

class Program
{
staticvoid Main(string[] args)
{
new Thread(() => { Singleton sin1 = Singleton.SingletonInstance; }).Start();
Singleton sin2 = Singleton.SingletonInstance;
 
Console.ReadKey();
}
}

Singleton thread safe

Making the above implementation to a thread safe code is not a complex task, we can use our same old locking technique.

class Singleton
{
privatestatic Singleton _instance;
privatestaticobject _lock =newobject();
 
private Singleton()
{
Console.WriteLine(Singleton instantiated);
}
 
publicstatic Singleton SingletonInstance
{
get
{
lock (_lock)
{
if (_instance ==null)
  {
      // delay the object creation to demonstrate the thread saftey.
        Thread.Sleep(1500);
         _instance =new Singleton();
   }
return _instance;
}
}
}
}

The above is a perfect Singleton implementation in C#. But is there any other way that we can have the Singleton behavior without compensating our performance into locking. Because locking is a performance drop for sure.

Singleton C# way  – The trendy way

This is a neat and a trendy way to implement the Singleton.

We do not use locks in this implementation and it is very fast yet purely thread safe.

class Singleton
{
    privatestaticreadonly Singleton _instance;
 
    static Singleton()
    {
             _instance =new Singleton();
     }
 
    private Singleton()
   {
       Console.WriteLine(Singleton instantiated);
    }
 
   public static Singleton SingletonInstance
  {
     get
    {
      return _instance;
     }
  }
}

The magic is, static constructor.

A static constructor is used to initialize any static data, or to perform a particular action that needs to be performed once only. It is called automatically before the first instance is created or any static members are referenced.

To remeber simply you can think that the static constructor is called when the class is loaded.

More about static constructors in this MSDN article.

Asynchronous Programing C# 5.0

C# 5.0 mostly bluff about the asynchronous programming. Of course it has some really kick ass features in the asynchronous programming world.

First of all, asynchronous programing is not new in C# 5.0. It’s been there from C# 1.0, so what’s the big deal now ?

In C# 5.0 they have created a whole new, very tidy and easy programing approach in asynchronous programing. It’s really very tidy.

Here’s a WPF sample application which downloads the headers of an HTTP request and displays in a TextBox. Simply we all know that if we do this without threads our UI will hang until the download operation completes. The solution we’ve been using is threading.

Here I want to make a point; conceptually we all know that using the threads for the above problem will yield the solution for UI unresponsiveness.  But it creates challenges like monitoring the threads and updating the UI, handling exceptions and code untidiness.

Again one more point, when using the threads for the above problem .NET provides various solutions. In Win Forms using the BackgroundWorker is the popular way, in WPF we go for the Dispatcher, we also have our same old IAsyncCallback and delegates mechanism, using the thread pool explicitly, creating and customizing our own threads.

As you see, almost all the above methods are cluttered every where, developers use their own way to handle the problem, not bad but it’s not good either.

And also we have our problems in updating the UI; especially when updating a UI control from a different thread. We get the Cross thread access exceptions.

Here’s the code that shows one way of how the above scenario can be implemented prior to C# 5.0 in WPF.

 private void OldAsyncTechnique()
        {
            SynchronizationContext sync = SynchronizationContext.Current;

            var req = (HttpWebRequest)WebRequest.Create("https://thuruinhttp.wordpress.com");
            req.Method = "HEAD";

            req.BeginGetResponse((asyncResult) =>
            {
                var resp = (HttpWebResponse)req.EndGetResponse(asyncResult);
                sync.Post(delegate
                {
                    TxtHeaders.Text = FormatHeaders(resp.Headers);
                }, null);
            }, null);
        }

Here I get the SynchronizationContext of the current thread, (means the main UI thread) and creates my web request. Then I call the asynchronous BeginGetResponse method of the HttpWebRequest class.

To make the code compact, I called the EndGetResponse in lamda. Using the SynchronizationContext of the UI thread I post the message to the UI control.

But this very complex and I have to pass state object parameters and all. (I have passed null here).

Note : This is not the only way to do this.

 

In C# 5.0 we have new keywords async and await. (You still can enable this in .NET 4 by installing the Async CTP, but since the VS 2012 and .NET 4.5 is released do not waste your time on doing this. You can simply upgrade yourself to .NET 4.5 world)

Here’s the code.

 private async void NewMethod()
        {
            HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create("https://thuruinhttp.wordpress.com");
            req.Method = "HEAD";
            HttpWebResponse res = (HttpWebResponse) await req.GetResponseAsync();
            TxtHeaders.Text = FormatHeaders(res.Headers);
        }

Simple as that. You declare the method async and make an awaitable type.

When the code hits the await keyword the method returns immediately, and once the await got the results, the method begins the execution from where it left. Simple theory.

But how it is possible, again that is simple inside C# when you compile the above code, C# compiler rewrites the above code in a fine and an efficient old way.

The real working pattern and how things happen are complex and it used the TPL heavily.

Important : Once you install .NET 4.5 you will get the GetResponseAsync() in the WebClient class. And most classes are enriched with these types of async methods in .NET 4.5. We can have our async and await functionality in our custom classed as well.

Here’s the implementation of the FormatHeaders method.

 private string FormatHeaders(WebHeaderCollection collection)
        {
            StringBuilder builder = new StringBuilder();
            foreach (var s in collection.Keys)
            {
                builder.Append(s + " : ");
                builder.Append(collection[s.ToString()].ToString());
                builder.Append(Environment.NewLine);
            }

            return builder.ToString();
        }

C# 5.0 – Caller Information

C# 5.0 has some new features which can aid us in debugging and logging.

Take a look at this code below on how we do logging prior to C# 5.0. Here we have the need of logging the details of the call made to MethodB()

1 class Program 2 { 3 static void Main(string[] args) 4 { 5 InsertToLog("Main"); 6 MethodB(); 7 MethodA(); 8 9 Console.ReadKey(); 10 } 11 12 private static void MethodA() 13 { 14 InsertToLog("MethodA"); 15 MethodB(); 16 } 17 18 private static void MethodB() 19 { 20 } 21 22 private static void InsertToLog(string methodName) 23 { 24 Console.WriteLine("{0} called MethodB at {1} ", methodName, DateTime.Now); 25 } 26 }

In the above code all the methods who call the MethodB() has to make a call to InsertToLog(string methodName). This has 2 major problems.

1) Code repetition

2) Very easily one can miss a call (simply forget to call InsertToLog)

So it would be nice to have the InsertToLog method inside MethodB and if we can pass the caller information to MethodB.

C# 5.0 has this feature. Look at the code below.

1 class Program 2 { 3 static void Main(string[] args) 4 { 5 //InsertToLog("Main"); 6 MethodB(); 7 MethodA(); 8 9 Console.ReadKey(); 10 } 11 12 private static void MethodA() 13 { 14 //InsertToLog("MethodA"); 15 MethodB(); 16 } 17 18 private static void MethodB( 19 [CallerMemberName] string memberName = "", 20 [CallerFilePath] string filepath = "", 21 [CallerLineNumber] int linenumber = 0) 22 { 23 InsertToLog(memberName,filepath,linenumber); 24 } 25 26 private static void InsertToLog(string methodName, string filepath, int linenumber) 27 { 28 Console.WriteLine("{0} called MethodB at {1} from {2} on line number {3}", methodName, DateTime.Now,filepath,linenumber); 29 } 30 }

In order to use the caller information you have add the following reference.

 

using System.Runtime.CompilerServices;