Thursday, 11 July 2013

WCF REST Based Service Call using JQuery.

Hello friends, I received lot of feedback for my earlier posts. This encourages me to keep writing. Thank you for your feedback.

Ok, let's come back. Today I am going to show you, How to consume WCF REST Service using jQuery.

Problem Scenario:  
Assume we have a page which has three dropdowns to select Country, State and than City. Initially only Country dropdown values will be populated with page load but others will not. On selection of Country, State dropdown values should be populated for the selected country and same for City dropdown. Though the code which I am going to show here is different from the scenario I discussed here but it will help you to solve this kind of problem.

Below sample code shows WCF REST service example which will be consumed through jQuery. Here in my service I have two methods, One returns list of cities as json serialized string object and the other method takes some input (json serialized string) and returns a json serialized string.
Code Sample for Service Definition.:
and here the service method implementation.

Note: new JavaScriptSerializer().Serialize(object) is used to convert a object to json serialized object.
Now let's see how we can call to these methods using jQuery.

GET Request
Here we will see, how to make a GET request to call WCF REST based service method GetCities which returns list of city in a json serialized string form. Below is the code sample to do this.

        type: "GET", //- Type of request - Optional
        url: 'http://localhost:84/RESTService.svc/cities', //A string containing the URL to which the request is sent.
        dataType: "json", //data type returns from the server
        success: function (response) { //A callback function that is executed if the request succeeds.
            var result = jQuery.parseJSON(response);
            var html = "List of Cities are: <br\>";
            for (var i = 0; i < result.length; i++) {
                    html += result[i].Value + "<br\>";
        error: function (xhr) {
            $("#div2").html("An error occured: " + xhr.status + ':' + xhr.statusText);

Here in above example I specified request type, request url and datatype to the method $.ajax(); Most important thing here is the request url. If url is not found or wcf service is not available in that case it will throw error. So here I also handled error as well. Next if service call is successful then control will fall under success callback function. As we are getting a serialized json object in string form from the server so we need to parse it to json first (because it's a object collection.) and that I am doing here using jQuery.parseJSON() method.
Now we have a json object as result value, shown below:
>> result
[[object Object],[object Object],[object Object],[object Object],[object Object]] {
    [0] : {...},
    [1] : {...},
    [2] : {...},
    [3] : {...},
    [4] : {...},
    [prototype] : []

It says we have five Name and Value pair object as per WCF REST Service method. We can access these value by writing code like result[0].Value and result[0].Name.
Important points to take care:
1. Here the Name and Value properties are case sensitive as per the properties definition in WCF REST Service method. So if we write result[0].value to access value then it will not return any value.
2. Another very important point here is, we are parsing the json string directly using response object.
 var result = jQuery.parseJSON(response);
and we have the value of response coming back is:
>> response
"[{"Name":"Select City","Value":"-1"},{"Name":"Bangalore","Value":"Bangalore"},{"Name":"Chennai","Value":"Chennai"},{"Name":"Goa","Value":"Goa"},{"Name":"Delhi","Value":"Delhi"}]"

The point which I want highlight here is, the response json string is not wrapped. Because in the WCF REST Service it is mentioned, not to wrap the response by using below attributes value:
BodyStyle=WebMessageBodyStyle.Bare,. If it would be wrapped then the output string would be bit different as shown below:
>> response
    [prototype] : {...},
    GetCitiesResult : "[{"Name":"Select City","Value":"-1"},{"Name":"Bangalore","Value":"Bangalore"},{"Name":"Chennai","Value":"Chennai"},{"Name":"Goa","Value":"Goa"},{"Name":"Delhi","Value":"Delhi"}]"

In this case we would have modified few line of code like this:
var result = jQuery.parseJSON(response.GetCitiesResult )

POST Request
Now we will make a POST request and we will send a json serialized string to WCF REST service method and based on that response will be returned back again as a json serialized string form.
 Let's see the below sample code for POST request:
  var JSONObject = { "userData": { "FName": "Binod", "LName": "Mahto"} };
        type: 'POST',
        url: "http://localhost:84/RESTService.svc/Message",
        data: JSON.stringify(JSONObject),
        contentType: "application/json",
        dataType: "json", //Expected data format from server
        processdata: true, //True or False
        success: function (response) {

        error: function (xhr, ajaxOptions, thrownError) {
            $("#div1").html("An error occured: " + xhr.status + ':' + xhr.statusText);

In above example I mentioned request type as POST. There are few points which we have to take care is:
1. data: which we need to send as POST request should be json serialized string form. Which we are doing here using JSON.stringify() method.
2. content type: It must be "application/json". Instead of this if we write only "json" it will throw error as "400:Bad Request".
3.  datatype: It must be "json" only. Instead of this if we write "application/json" then it will throw error by saying "200:OK" but surprisingly error object 'xhr' will have the response output as well.
>> xhr
    [Methods] : {...},
    [prototype] : {...},
    readyState : 4,
    responseText : "{"GetWelcomeMessageResult":"\"Hi Binod Mahto Current time is:10:12 AM\""}",
    status : 200,
    statusText : "OK"

So to avoid this kind of head banging issue datatype's value must be written as "json" only.
4. Response output is wrapped here. If you see the response output here, you will find there is name attached with response string as "GetWelcomeMessageResult". And this happened because in the WCF REST method specifically it is mentioned to wrap the response object (by using attribute value BodyStyle = WebMessageBodyStyle.Wrapped). And the catch here is, the extra string which will be added to json string will have concatenation string of method name and 'Result' string. for Ex: GetWelcomeMessageResult. 
5. Another important thing here is that when you send the json serialized object (as I am sending userData here) to the server then it must be wrapped with the exact parameter name mentioned in the WCF REST service method.
 var JSONObject = { "userData": { "FName": "Binod", "LName": "Mahto"} };
In my case here my WCF REST Service method expects UserData object as per data contract.
    public class UserData
        public string FName { get; set; }

        public string LName { get; set; }

and the parameter name in service method is mentioned as "UserData userData". So suppose if I change my JSONObject value as 
var JSONObject = { "UserData": { "FName": "Binod", "LName": "Mahto"} };  then WCF Service method will be called but userData parameter value will be null. So we should keep this in mind that parameter name is tightly coupled with the json request format.

I guess I mentioned all the important points here for which generally people has to struggle a lot. But still if I missed something please feel free to mention those as your comment/feedback.

Thank You 

Friday, 12 April 2013

What's New in C# 4.0

Below are new features introduced in c#4.0 with example:
1.       Dynamic Lookup: It resolves types in a program at runtime. It’s very useful in below scenarios:
a.       Office Automation or COM Interop scenarios.
b.      Consuming types written in dynamic languages (like IronPython, IronRuby…)
c.       Call Reflection : currently we use Reflection to instantiate a class when a types is not known at compile type.

2.       Named and Optional Parameters: Named arguments enable you to specify an argument for a particular parameter by associating the argument with the parameter's name rather than with the parameter's position in the parameter list. Optional Parameters enable you to omit arguments for some parameters. Both techniques can be used with methods, indexers, constructors, and delegates.

3.       Covariance and Contravariance: covariance and contravariance refers to the ordering of types from narrower to wider and their interchange ability or equivalence in certain situations (such as parameters, generics, and return types). (Source- Wikipedia).
Types that are
·         covariant: converting from a specialized type (Cats) to a more general type (Animals): Every cat is an animal.
·         contravariant: converting from a general type (Shapes) to a more specialized type (Rectangles): Is this shape a rectangle?

If you see above example here, you will find two interesting point here inside Main method. If you try to compile this program in .Net Framework 3.5 or less you will get error in second line of Main method saying “An explicit conversation exist (are you  missing a cast?)”.
IEnumerable<Person> persons = new List<Employee>();
It’s really surprising, If a base class called Person can hold the object of his child class called Employee, then why this is not applicable in with group of objects. SO this is where C#4.0 introduced a feature called Covariance. SO if you compile it under C# 4.0 compiler you will not get any error.
So the result here is: Covariance preserves assignment compatibility.

In above example, I have an overloaded method called PrintPerson. If you compile above code in C# 3.5 or less version you will get error on last line of code.
IEnumerable<Employee> empList = new List<Employee>();
But in C# 4.0 or later version it works fine. SO this is where C#4.0 introduced a feature called Contravariance.

4.       COM Interop Enhancement.
In C# 4.0, calling COM object become more easier. For an example let’s talk about Microsoft.Office.Interop.Word. We will write a code to open a word file in C# 3.5 and C#4.0 and then we will see what’s enhancements is done in C#4.0.

If you see the above code here, it says itself about the enhancement of COM Interop library. Writing code become more easier than earlier version of C#.

Thank You for reading. Feel free to give your feedback.

Saturday, 2 March 2013

All about JsonObject.

A JSONObject is an unordered collection of name/value pairs. The JSON format is often used for serializing and transmitting structured data over a network connection. It is used primarily to transmit data between a server and web application, serving as an alternative to XML.

for example: 
Below example shows the JSON representation for list of cities in india:
                                {"name":"Select City", "value":"-1"},
                                {"name":"Bangalore", "value":"Bangalore"},

And the xml format for this will be
<name>Select City</name>
<value> -1</value>
<name> Bangalore </name>
<value> Bangalore </value>
<name> Chennai </name>
<value> Chennai </value>
<value> Goa </value>
<name>Delhi </name>
<value> Delhi</value>
</Cities >

Another Example of JSON format data is:
                                "firstName": "Binod", "lastName": "Mahto",
                                  {"city": "Bangalore", "state": "Karnataka", "country": "India"},
                                  {"provider": "Gmail","id": ""}
And the xml format for above data is:
  <firstName> Binod </firstName>
  <lastName> Mahto </lastName>
     <Country>India</ Country >
  </ Email >

Advantages of using JSON:
  • ·         It is much simpler than XML.
  • ·         No extra tags or attributes to represent data.
  • ·         Language independent.
  • ·         Very lightweight text-data
  • ·         Because of simplicity of converting xml to JSON, it is more adoptable.

Disadvantages of using JSON:
  • ·         Lack of display capability as it’s not a mark-up language.
  • ·         JSON does not have a <[CDATA[]]> feature, so it is not well suited to act as a carrier of sounds or images or other large binary payloads.
  • ·         JSON is optimized for data. Besides, delivering executable programs in a data-interchange system could introduce dangerous security problems.

Now let’s see how to consume/use JSON object in HTML.
HTML code:
<!DOCTYPE html>
<h2>JSON Object Example</h2>
Name: <span id="jname"></span><br />
Address: <span id="jadd"></span><br />
Contact:<span id="jemail"></span><br />
var JSONObject= {
                                "firstName": "Binod", "lastName": "Mahto",
                                                "city": "Bangalore", "state": "Karnataka", "country": "India"
                                                "Provider": "Gmail","id": ""
document.getElementById("jname").innerHTML= JSONObject.Person[0].firstName +" "+ JSONObject.Person[0].lastName
document.getElementById("jadd").innerHTML=JSONObject.Person[0] +", "+JSONObject.Person[0].address.state+", "+JSONObject.Person[0]

Here I have created a JSON Object in JavaScript which contains a person information. Next I am reading the values from the JSON Object and displaying it to the HTML Page. In html I have three span html tag with id where values are getting assigned through JavaScript.
Below is the screen shot of above html code:
Now let me show you an example of using JSONObject in mvc application. In below example I have a dropdown which shows list of countries. 
Below is the code for my controller class.

Here in above code I have method called GetCountries in controller which return list of countries. Now in view we will consume this JSONObject using Jquery.
Below is the code for View:

consumption of JSONObject using Jquery call.
and below is the output :

That's all. Now you are ready to play with JSONObject. 

Thank you for the reading. Feel free to give your feedback/suggestion.


Saturday, 23 February 2013

ASP.NET MVC 3 Dependency Injection using Unity.MVC3

ASP.NET MVC 3 Dependency Injection
Dependency injection (DI) is a design pattern and it is based on separating component behaviour from dependency resolution without object intervention. In other words we can say it removes the tightly coupled dependency between objects and components in collaboration model where there are contributors and consumers.
To know more about Dependency Injection Pattern, Please follow below links:
Dependency Injection is a particular implementation of Inversion of Control (IoC) principle, which says, An Object should not create other object in which they rely. It means the consumer object receives his dependencies inside constructor properties or arguments.
The advantages of using Dependency Injection pattern and Inversion of Control are:
·         Reduces class coupling
·         Increases code reusing
·         Improves code maintainability
·         Improves application testing

In ASP.Net MVC framework we need Dependency Injection to remove dependency between consumer (say controller) and contributors (service/business layer object).

Now let’s move on Implementation of Dependency Injection in ASP.Net MVC 3. Here we will talk about using Dependency Injection inside an MVC controller. We can also use Dependency Injection inside MVC View and MVC Action Filter.

I assume, you already have the knowledge regarding ASP.Net MVC3.
Before starting first thing we have to do is, IoC container which basically create dependency resolver per HTTP request. And I feel let’s not do that as there are lot many open sources available which provides library to do this like Ninject, Unity and so on.

Here I am going to use Unity.MVC3 and will show you, How you can use Dependency Injection inside controller using Unity.MVC3 IoC library. We will discuss to perform CRUD operation

Introduction of Unity.MVC3:
 A library that allows simple Integration of Microsoft's Unity IoC container with ASP.NET MVC 3. This project includes a bespoke Dependency Resolver that creates a child container per HTTP request and disposes of all registered IDisposable instances at the end of the request.

How to get this library: To include this on project, Right click on your MVC3 app solution in visual studio and click on “Manage NuGet Packages” and search of Unity (refer below pic).

Here you have select Unity.MVC3 (Highlighted on) click to install. Once you installed this you can see below highlighted (in pic) dlls reference in your project:

Next step we will create a service(with interface and implementation)  which is basically responsible to communicate with DB.

And then we create the actual service class which perform all my CRUD operation to create, delete, edit and modify user details to the DB.

Now we will create a controller factory class for Unity which implements IControllerFactory interface, extending CreateController and ReleaseController methods to work with Unity. This factory will create the instances of the controllers that work with Dependency Injection.
A controller factory is an implementation of the IControllerFactory interface, which is responsible both for locating a controller type and for instantiating an instance of that controller type.
The following implementation of CreateController finds the controller by name inside the Unity container and returns an instance if it was found. Otherwise, it delegates the creation of the controller to an inner factory. One of the advantages of this logic is that controllers can be registered by name.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Microsoft.Practices.Unity;

namespace MyMVC3WebApp.Factories
    public class UnityControllerFactory: IControllerFactory
        private IUnityContainer unityContainer;
        private IControllerFactory defaultInnerFactory;

        public UnityControllerFactory(IUnityContainer container)
            : this(container, new DefaultControllerFactory())

        protected UnityControllerFactory(IUnityContainer container, IControllerFactory innerFactory)
            unityContainer = container;
            defaultInnerFactory = innerFactory;

        public IController CreateController(System.Web.Routing.RequestContext requestContext, string controllerName)
                return unityContainer.Resolve<IController>(controllerName);
            catch (Exception ex)
                return defaultInnerFactory.CreateController(requestContext, controllerName);

        public System.Web.SessionState.SessionStateBehavior GetControllerSessionBehavior(System.Web.Routing.RequestContext requestContext, string controllerName)
            return System.Web.SessionState.SessionStateBehavior.Default;

        public void ReleaseController(IController controller)

Now next steps we have to register this Unity Library. While installing Unity.MVC3 you have observed, there is class called Bootstrapper.cs is been added to the solution including above mentioned dlls (shown in below pic, highlighted one).

Now next step we have to register our service Type inside BuilUnityController method present under Bootstrapper class.

Highlighted code in above pic is to register our service.

And the last step we have to do is, call the Initialize method of the Bootstrapper class from the global.asax.cs file. Shown in below pic

Now we have done with the create part and will see how I am using this inside my controller.
Now if you see, controller receives the business object through constructor and use this to perform CRUD operation. So here our controller is no more depended on creation object of service class on which it relays.

Please feel free to give your suggestion/feedback.

Thank You for reading this.