Monday, January 24, 2011

RESTful WCF JSON Service

RAVAGE

Some of my friends inquired me on creating a WCF REST service that supports JSON data format. Observing the nature of their projects, I understood that the client that’s going to utilize/consume this service is going to be a mobile client (iPhone, Andriod,…). So I just created a proof of concept and handed over the service to them. Though this is simple, configuring and hosting the service even locally leads to several exceptions that will drive us ahead of the predicted time. Hence, in order to eradicate those confusions, I explain in this post on creating a simple WCF REST service with just the required configurations and implementations.

IDE : VisualStudio 2010
Framework: .Net 4.0
Assumption: Prior knowledge in .Net and WCF.


Above specified IDE and framework is just to understand the explanations specified in this post. This is also applicable for framework “.Net 3.5” and related IDE (VS 2008).

Projects in our Solution

Project TypePurposeReferences
WCF Service LibraryHolds the DataContract and ServiceContract.System.ServiceModel.Web.dll
WCF Service ApplicationSpecifies the hosting service.Our “WCF Service Library” project reference.
Console ApplicationActs as client application to verify our service in respective data format(JSON here).Our “WCF Service Library” project reference. WCF REST Starter Kit references Microsoft.Http.dll, Microsoft.Http.Extensions.dll and Microsoft.ServiceModel.Web.dll.

WCF Service Library

As we do with simple WCf service, need to create the DataContract.

While specifying the OperationContract, we need to add the WebGet or WebInvoke attribute based on the nature of the operation/ which HTTP method we're going to use . Simply, use WebGet if your service operation wants to respond to GET method, use WebInvoke otherwise.

In order to make use of WebGet or WebInvoke attribute, first we need to add reference to System.ServiceModel.Web.dll. If the dll is not available to add reference, do verify the target framework. If it is ".NET Framework 4 Client Profile", change it to ".NET Framework 4" and then try adding reference.

Snippet 1

namespace VerifcationWcfServiceLibrary
{
    [ServiceContract]
    public interface IVerificationService
    {
        [OperationContract]
        [WebInvoke(ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json, UriTemplate = "/AuthCode/AuthReq/", Method = "PUT")]        
        AuthorizationResponse Authenticate(AuthenticationRequest request);

    }

    [DataContract]
    public class AuthenticationRequest
    {
        string userName = string.Empty;
        string authorizationCode = string.Empty;

        [DataMember]
        public string UserName
        {
            get { return userName; }
            set { userName = value; }
        }

        [DataMember]
        public string AuthorizationCode
        {
            get { return authorizationCode; }
            set { authorizationCode = value; }
        }
    }

    [DataContract]
    public class AuthorizationResponse
    {
        bool valid = false;
        string message = string.Empty;
        DateTime validToDate = DateTime.Now;
        string serverURL = string.Empty;

        [DataMember]
        public bool Valid
        {
            get { return valid; }
            set { valid = value; }
        }

        [DataMember]
        public string Message
        {
            get { return message; }
            set { message = value; }
        }

        [DataMember]
        public DateTime ValidToDate
        {
            get { return validToDate; }
            set { validToDate = value; }
        }

        [DataMember]
        public string ServerURL
        {
            get { return serverURL; }
            set { serverURL = value; }
        }
    }
}

Actually I’m trying to expose a service with a single method that uses a custom data type for input parameter(AuthenticationRequest) and another custom data type as return type(AuthorizationResponse).

WebInvoke attribute is the only new thing I’ve specified specific to REST. As you can infer from the above code, we need to explicitly specify the ResponseFormat, RequestFormat and UriTemplate. If we skip out the ResponseFormat and RequestFormat, then it’ll consider the data format as XML. UriTemplate is an important property which specifies the Uri template for the service operation, which is the access point for the service operation. Hence, whichever client going to call the service operation, needs to specify the URI of the specific operation only based on the UriTemplate.

Now create an implementation for the above defined operation contract.

Snippet 2


namespace VerifcationWcfServiceLibrary
{
    public class VerificationService : IVerificationService
    {        
        public AuthorizationResponse Authenticate(AuthenticationRequest request)
        {
            WebOperationContext.Current.OutgoingResponse.StatusCode = System.Net.HttpStatusCode.OK;

            AuthorizationResponse response = new AuthorizationResponse();
            response.Valid = true;
            response.ValidToDate = DateTime.Now.AddDays(7);
            response.Message = request.AuthorizationCode;
            response.ServerURL = "http://info.titodotnet.com/";

            return response;
        }

    }
}

We’re done with WCF Service Library(VerifcationWcfServiceLibrary here).

WCF Service Application

Create WCF Service(.svc) file (VerificationService.svc here).
Add reference to the project WCF Service Library(VerifcationWcfServiceLibrary).
Remove the “.svc.cs” code behind file and view the “.svc” markup.
Modify the “ServiceHost” directive as follows.

Snippet 3


<%@ ServiceHost Language="C#" Debug="true" 
    Service="VerifcationWcfServiceLibrary.VerificationService" 
    CodeBehind="VerifcationWcfServiceLibrary.VerificationService.cs" 
    Factory="System.ServiceModel.Activation.WebServiceHostFactory" %>


As specified, Service should be the fully qualified name of our service class, CodeBehind should be the file name of our service and the Factory should be “WebServiceHostFactory” in order to use WebServiceHost to host the service.

If you miss out the Factory attribute, it’ll throw “unsupported media type” exception. Instead you can also use “WebServiceHost2Factory” of WCF REST starter kit.

Here comes the main part – configuration.

Snippet 4

<system.serviceModel>
  <behaviors>
    <serviceBehaviors>
      <behavior name="DefaultServiceBehavior">
        <serviceMetadata httpGetEnabled="true"/>
        <serviceDebug includeExceptionDetailInFaults="false"/>
      </behavior>
    </serviceBehaviors>
    <endpointBehaviors>
      <behavior name="WebHttpBehavior">
        <webHttp/>
      </behavior>
    </endpointBehaviors>
  </behaviors>
  <services>
    <service behaviorConfiguration="DefaultServiceBehavior" name="VerificationService">
      <endpoint behaviorConfiguration="WebHttpBehavior" binding="webHttpBinding"
        bindingConfiguration="" contract="VerifcationWcfServiceLibrary.IVerificationService"/>
    </service>
  </services>
</system.serviceModel>

We need to specify the webHttp behavior on an endpoint with webHttpBinding. Most of the people get confused while specifying the behavior, whether to use webHttp or enableWebScript. WebScriptEnablingBehavior(enableWebScript) is specially targeted for ASP.NET AJAX client. Hence, do use WebHttpBehavior(webHttp) for pure RESTful WCF service.

Console Application

The purpose of the Console Application(JsonBehaviorTestConsoleApplication here) is to validate and verify the service we created and to run our unit test cases if any. As I specified earlier since the client can be any mobile client or any other application, we need to test our services by sending and receiving object in JSON(or XML) specific format. For accessing the service, we can make use of the WCF REST starter kit, which provides the required helper functions and wrapper classes.

Make sure that you add the references that I mentioned initially in this post.
The reason for having “WCF Service Library” project reference is because, we can create .Net CLR(managed) instance for the data contract we have in “WCF Service Library” project, assign the values we needed and convert the object into JSON(or XML) specific format.

Following is the snippet for accessing the above created service operation.

Snippet 5

namespace JsonBehaviorTestConsoleApplication
{
    class JsonTestClient
    {
        static void Main(string[] args)
        {
            AuthenticationRequest request = new AuthenticationRequest();
            
            request.UserName = "test username";
            request.AuthorizationCode = "test authcode";

            using (HttpClient restClient = new HttpClient())
            {
                HttpContent paramContent = HttpContentExtensions.CreateJsonDataContract(request);
                
                Console.WriteLine("*******************AuthCode/AuthReq*******************");
                HttpResponseMessage resp = restClient.Put("http://localhost.:1517/VerificationService.svc/AuthCode/AuthReq", paramContent);
                resp.EnsureStatusIsSuccessful();
                Console.WriteLine("*******************Header*******************");
                Console.WriteLine(resp.Headers.ToString());

                Console.WriteLine("*******************Content*******************");
                var result = resp.Content.ReadAsString();
                Console.WriteLine(result);

                Console.Read();
            }
        }
    }
}

The service operation need to be called only with the UriTemplate we specified in the WebInvoke attribute using the HttpClient instance with respective method based on the Method attribute we specified earlier.

As most of might have already noticed, I’ve used “localhost.:1517”(affix dot(.) at the end of "localhost") in the above snippet, in order to capture my localhost traffic in fiddler which otherwise won’t get caught. Using Fiddler for verifying the data format and actual values passed across the wire is very common and effective.

SUMMARY

You can also bypass WCF Service Library project and create the required contracts and services in WCF Service Application itself. But make sure that you don’t add direct WCF Service Application project reference in the Console Application in order to use the data contract. Instead copy the required data contract locally in your Console Application.

REFERENCE

http://msdn.microsoft.com/en-us/library/dd203052.aspx
http://msdn.microsoft.com/en-us/library/ee391967.aspx
http://blogs.msdn.com/b/endpoint/archive/2010/01/18/automatic-and-explicit-format-selection-in-wcf-webhttp-services.aspx

Saturday, January 8, 2011

Regulator / FlowControlManager Pattern

Regulator is the object which holds the responsibility of managing the control flow between group of related objects by handling the state change of the objects and passing messages between them.

Components

Regulator / FowControlManager : Holds the instances of related objects (Colleagues) and observes the Colleagues for change in their state.
 Colleague : Ability to notify the change in its state and focuses on its core responsibility. Wont hold reference to any of related objects or Regulator.

Scenario

Consideration : Silverlight application following MVVM.
Generally in Silverlight applications we use to separate the application into individual modules in order to create seperate XAP files and download to use it as and when needed. Let us imagine such a small module which has a landing page displaying some details along with few links(Detail1,Detail2). Upon clicking the links, the respective views(DetailView1, DetailView2) need to be displayed on the desiered location on the landing page itself. Also different messages need to be sent to different views based on the behavior and actions performed in other views and landing page.

Simply we can handle this by hand over the entire responsibility to the ViewModel of the landing page. If we do so, the landing ViewModel need to hold this control flow management and message passing mechanism in addition to its functionality.

Instead if we have an object that manages the flow control and message passing, then the respective ViewModels can just concentrate on their functionality without bothering about flow of control and message passing.

If Detail1 link is clicked on the landing page, Regulator takes this responsibility by observing Detail1 link got clicked on landing page, pass required details to the DetailView1.ViewModel and passes the DetailView1 to the LandingPage.

Component Responsibility

Colleagues just notifies about change of state which need to be observed.Regulator observes the state changes of the Colleagues as it holds their instances, passes the needed messages to respective instances and controls the flow.
State change can be notified through effective use of events and NotifyPropertyChanged mechanism we use in Silverlight.

Related patterns

Most of you might have already smelled the flavour of Mediator, Observer and Facade pattern.
Its true but the notion differs.
Unlike Mediator pattern, Colleagues in Regulator pattern won't hold reference to Regulator instance. Regulator itself subscribes to required state change notification of Colleagues.

Edit
10JAN2011
My friend upon having a glimpse at the title asked me where did I got the title from? Actually I should have specified about this at time of writing the article itself. I just named it based on the functionality and nature of implementation. Just thinking whether I've done anything unlawful.

Saturday, December 25, 2010

Pattern for Silverlight child window

RAVAGE


I just wanted to convey the enitre motivation of this article in a simple sentence which resulted in the 'keyword like' entry as the title "Pattern for Silverlight child window". As per my observation the UI approach (way of presentation to the end user) for Silverlight varies with that of ASP.Net UI. In most of the Silverlight applications that I visited, I didn't noticed the heavy usage of the child (popup) window for interaction purpose except the light usage of notification purpose such as confirmation / information display dialogs. If we do need to use the child window for interaction purpose, then the first idea that we need to plan is about how to share object between the parent and the child window.


I came across a similar situation in my project where my client wanted to present the child window for interaction purpose in order to produce a native UI approach. I thought of implementing this without breaking the MVVM pattern. To achieve that, first I thought of sharing the same ViewModel object between the parent and child. It got ruled out immediately due to well know reasons of maintainabiltiy and scalability. Not all the members of the object will be common for both parent and child window. Hence sharing same ViewModel / object won't be the right choice.

Next option is to have two seperate view models for parent and child dialog holding reference to each other. This is better than the previous one, but think of the case having more than one child window which will result in the parent holding reference to each of the child window and each child window holds reference to the parent. Going one step forward, think of a case having more than one parent view and multiple child view which are related, might end up with each object having reference to other as a worst case scenario. So, are there any pattern that provides solution for the above case? Yes, as many article over the web  suggests, Mediator pattern provides us the solution.

MEDIATOR FOR PARENT-CHILD VIEW

Mediator holds the instances of the parent and child objects and manage the interactions between the objects. The parent and child objects in turn holds the reference of the mediator and notifies the mediator about the relevant changes. Having received the change notification, the mediator will call the required update / action aginst the objects in relation to the change.

I implemented this change in my project and worked fine for me. But out of curiosity, I further fine tuned this implementation such that the parent and child view objects interact with the mediator using Observer pattern.

The implementation goes something like as follows:
I created an abstract class called Colleague which holds the instance for the Mediator as a property and an Update method which can be overriden by the class that inherits it.
Then I created an Mediator class which provides the methods to Attach, Detach and Notify. The Attach methods takes in an object of type Colleague as parameter and adds to a list of Colleague(to be notified). The Detach method takes in an Colleague type as parameter which removes from the list of Colleague. The Notify method iterates through the list of Colleague object and calls the Update method on each Colleague object.

The parent and child ViewModels inherits the Colleague class and overrides the Update method if needed. For example I was about to pass a selected item from my child ViewModel to my parent ViewModel. To achieve that upon selecting a particluar item from a list of items in the child view, I'll call the Notify method of my Mediator by passing the selected item. My parent ViewModel in its constructor will subscribe to receive the notification by calling and passing itself as paramter to the Attach method of the Mediator object. Upon the Mediator receives the notification from child view, it calls Update method of the Colleague (parent in this case) which got  subscribed to it.

STRUCTURE




SUMMARY

I actually have described an idea about the implementation in my project. Based on my project scenario, I had extended the same concept to handle multiple parent and child view models for which the usage of Observer pattern for interaction with the Medaitor helped me to produce a scalable and maintainable code. On the whole my idea is to implement a Mediator which acts as a change request manager holding the responsibility of interaction between the ViewModels. In my case, since I had only one change request manager (Mediator), I eliminated the introduction of abstract Mediator class. After completing my implementation, I realized that single instance for my Mediator holds good for my scenario. Hence, finally I also implemented Singleton pattern for my Mediator class.

Wednesday, December 1, 2010

System.Security.SecurityException: Dialogs must be user-initiated.

The Printing API in Silverlight 4 helps us a lot like printing the entire page, printing a specific portion of a page……

In order to get a quick idea on the print API do have a look at this(A look at the Printing API in Silverlight 4) article on silverlightshow.

While implementing this print API in my project I came across the following error in some scenarios.

System.Security.SecurityException: Dialogs must be user-initiated.

This error message initially leads to lot of confusion and upon search found the cause. As all the developers do, I was debugging the code by putting breakpoint. The problem is I put the breakpoint over the line where the object initiation for PrintDocument happens. Something like……
 
 
 
So when the exception “ System.Security.SecurityException: Dialogs must be user-initiated.” got raised while using print API for Silverlight 4 in debug mode, ensure that you didn’t put breakpoint over the code that invokes the Print method.

REFERENCE

http://johnpapa.net/silverlight/printing-tip-ndash-handling-user-initiated-dialogs-exceptions/

Tuesday, November 30, 2010

System.ServiceModel.FaultException`1 was unhandled by user code

System.ServiceModel.FaultException`1 was unhandled by user code


Handling WCF SOAP Fault exception in Silverlight:
http://msdn.microsoft.com/en-us/library/ee844556(VS.95).aspx

The above specified article helps us on handling WCF SOAP exceptions in Silverlight. In that article it is clearly specified that in order to consume the SOAP faults, we need to adopt either of the following options.

  • HTTP status code modification 
  • Using alternate client HTTP stack

Similarly the faults are of two types. 
  • Declared faults 
  • Undeclared faults

In one of my project, I was about to handle faults in Silverlight whose sole purpose is for debugging. To achieve that, among the above, I used HTTP status code modification with undeclared fault type.

Upon implementing the endpoint behavior extensions(as specified in the msdn article) , I was eager to view the exception in Silverlight but resulted in the exception "System.ServiceModel.FaultException`1 was unhandled by user code" at my client(Silverlight app).

After having searched a lot, I found out a solution in a blog. It simply advised to change the following debugging option in the visual studio environment.

Under the Tools> Options menu, uncheck the following: 
  • Enable the exception assistant
  • Enable Just My Code(Managed only)





REFERENCE

Sunday, August 1, 2010

Dependency Injection

RAVAGE

After several years of familiarization of the concepts of Dependency Injection (DI) and Inversion of control (IOC), I just came to know about the existence of those concepts. Thanks to Silverlight, PRISM (CAL) and MEF which made me explore the concepts DI and IOC.

Anybody who wants to write an article or explore in depth about Dependency Injection  will never fail to read Martin Fowler's article Inversion of Control Containers and the Dependency Injection pattern, for which I'm no exception.

Inversion Of Control

To understand from the name, its inverting the control of creation. Let's take the case of using the framework in an application, the framework takes the responsibility of creating objects/elements and the application will be hooked up with the created object as and when needed. Fowler states this with the example of UI framework and the application/program where the UI framework holds the responsibility of creating the graphical elements and the application instead creates the event handlers for those fields/graphical elements.

Dependency Injection

Think of a scenario class A uses class B which means class A depends on class B. In order to make use of class B in class A,  usually what we do is we'll write code to instantiate class B in class A. While instantiating class B, we need to pass the values that class B expects, to be clear, we need to satisfy the dependencies of class B. Say if class B expects and depends on class C, then in class A we need to instantiate class C first and then pass it to class B. Also we need to make sure that we should satisfy the dependencies of class C if any.

Ok, now think of changing the instantiating structure of the dependency object. For that we need to change the code in all the areas where it got used. In our example if class c changes its expectation(expects different parameter), we need to change the source code in class A.

There are situations that we don't know the concrete implementation at the time of writing the code or during compile time for various reasons - like we may need the code developed to be reused and the concrete implementation will be known sometime later.

In the above mentioned cases/paragraphs, just the scenarios are mentioned and the intentions are incomplete. Are there any solution for this? If so what is it? How to handle this? Dependency Injection is one solution to handle that.

Dependency Injection Types

  • Constructor injection
  • Setter injection
  • Interface injection
Constructor injection and setter injection are commonly used injection techniques.

As you guess for constructor injection, we need to specify the dependencies as the parameter for the constructor of the class which requires it. Since we're trying to get rid of the concrete implementation, we need to specify the type (interface) of the dependency which it confirms to.

For setter injection, dependencies are exposed as properties which will be set during the instantiation process.

Ok, who'll hold the responsibility of creating, managing and injecting these dependencies? Builder object or containers will do that for you.

Containers

Containers - Are these containers new to .Net based applications? As quoted in msdn CLR itself is a container. If you think it is more generic, let's take the case of asp.net web applications, where there are times that we've used a common base class for handling security, authentication, common functionalities, etc. These base classes can also be considered as a form of container.

Since the containers will create, manage and inject objects, it avoids tight coupling of objects with its dependencies. Containers acts as a repository or lookup manager that maintains instances. We need to map or configure the containers which instances need to be used on which context. Containers also takes additional responsibilities like managing the lifetime of the objects, so that it supplies singleton or new instances upon requests.

Microsoft patterns and practices provides a lightweight extensible container called Unity Application Block. Prism which is used to create modular WPF or Silverlight applications usually uses this Unity Application Block as container.

SUMMARY

Basically Dependency Injection containers decouples the classes from its dependencies and also the responsibility of managing the dependencies. The issues that we face with DI is it's hard to track while debugging. Also we need to make sure that the container has the ability to resolve the dependency where its required. Previously I've specified in this article that dependency injection is one solution. Other solution generally proposed for this scenario is Service Locator.

REFERENCE

http://martinfowler.com/articles/injection.html
http://msdn.microsoft.com/en-us/library/ff649378.aspx
http://msdn.microsoft.com/en-us/library/aa973811.aspx
http://msdn.microsoft.com/en-us/magazine/cc163739.aspx
http://tutorials.jenkov.com/dependency-injection/when-to-use-dependency-injection.html

Saturday, June 26, 2010

Factory Method - Pattern

INTRO

Factory pattern - Here comes the most commonly quoted pattern Factory method (next to Singleton Pattern). Factory method is frequntly used in lot of real time scenarios especially in the framework libraries. While developing a reusable library which contains core/base implementation, there are times where we need to work with or maintain the relationship between objects which will be created later during the implentation of those libraries. I've discussed one such case below under the Implementation in .Net.

Ultimate aim is to create a Product object and work on it which will be available some time later (as specified above). The name Factory resembles the real-world factory since it holds the responsibility of creating the objects (Products). Simply speaking the Client uses the Factory method to create a specific type of Product.

PLOT

Creator is the one who provides the interface for creating an object by holding the Factory method with him.
Factory method in the Creator returns a specific type of object Product.
Creator delegates the responsibility of "which class to be instantiated" to its subclass ConcreteCreator.
ConcreteCreator overrides the Factory method and it is responsible for creating the ConcreteProduct that adheres to the Product type. 

 GOF STRUCTURE


IMPLEMENTATION IN .NET

IEnumerable interface in .Net exposes a Factory method GetEnumerator(). The collection classes in .Net implements this IEnumerable interface to incur enumerator for a collection. Since foreach statement evaluates the type that implements IEnumerable, most of the collection classes will make use of this IEnumerable. ArrayList, HashTable, List,Dictionary are some of the examples.

IEnumerable needs to work on object of type IEnumerator, for iterating over the collection. Object of type IEnumerator knows how to iterate over the collection object of type IEnumerable.

ArrayList implements the IEnumerable and overrides the GetEnumerator method to create the object of ArrayListEnumeratorSimple which implements the IEnumerator.

Participants mapping

Creator : IEnumerable
ConcreteCreator : ArrayList
ConcreteProduct : ArrayListEnumeratorSimple
Product : IEnumerator

SUMMARY

I've just focussed on the case of delegating the responsibility of creating the instances to the subclass. There are also cases where the factory method in the ConcreteCreator defines the default instantiation and parameterized Factory methods used to identify and create specific ConcreteProduct.

REFERENCE

For references and more info:
Design Patterns: Elements of Reusable Object-Oriented Software
http://msdn.microsoft.com/en-us/magazine/cc188707.aspx#S5
http://ondotnet.com/pub/a/dotnet/2003/08/11/factorypattern.html
http://msdn.microsoft.com/en-us/library/ee817667.aspx
Creative Commons License
This work by Tito is licensed under a Creative Commons Attribution 3.0 Unported License.