WCF and JSON Fusion

Goldytech
Posted by in WCF category on for Beginner level | Views : 11900 red flag

This post teaches you how can you unleash the power of WCF and JSON. Complete walkthrough with sample code as download
Introduction
JavaScript Object Notation (JSON) a lightweight, text-based data exchange format. Data formatted according to the JSON standard can be easily parsed by JavaScript code thus making it an ideal data exchange format for Ajax-style Web applications.The .NET Framework 3.5 includes improvements to Windows Communication Foundation (WCF) to support JSON serialization. With these enhancements developers can easily use JSON serialization in your WCF services, and consume those services from your client-side code just as you have been able to do with ASMX services.In this post I will be doing a complete walkthrough of the example of how to consume WCF service through JavaScript code. WCF service method will return us the collection object. The same object we shall be accessing via client side code and update UI. I assume that the readers have the basic knowledge of WCF services.
WCF + JSON

Earlier it was not possible to represent the data in the object format returned by the server to the client. You would only get the vanilla xml. But with invent of JSON that is now become history. Any data returned by the server can be used as object in the same fashion how you created that object with the server side code. Let me talk now about the solution which is provided in this post. From the functional point of view , the app is very super simple it will display the employees names as per the progress of your keyboard strokes. Precisely speaking it is a progressive search. The opportunities are immense once you have the JSON object returned from the server then using JavaScript rich object model, you can do wonders on the client side giving it real Ajax touch. From technical aspects our Visual Studio 2008 with SP1 solution consists of 2 projects.

  1. WCF Service Library
  2. ASP .net Web Application
The WCF service library has Employee class which is marked with Data Contract attribute in WCF.This is our key object and we shall be working with it in our JavaScript code.

[DataContract]
   public class Employee
   {
       int empId;

       string empName;

       [DataMember]
       public int EmployeeID
       {
           get { return empId; }
           set { empId = value; }
       }

       [DataMember]
       public string EmployeeName
       {
           get { return empName; }
           set { empName = value; }
       }

       public Employee(int Employeeid, string EmployeeName)
       {
           empId = EmployeeID;
           empName = EmployeeName;
       }
       public Employee()
       {
       }
   }

The above code is no brainer , simple class with two simple properties. Let us now have a look at the operation contract method code.

[OperationContract]
        Employee[] GetEmployeeInfo(string value);

The operation contract method returns the array of employees. The actual implementation of this method is shown below.

public Employee[] GetEmployeeInfo(string value)
        {
            List<Employee> RtnEmployees = GetAllEmployees();
            List<Employee> FilterEmployees = new List<Employee>();
            FilterEmployees = RtnEmployees.Where(e => e.EmployeeName.ToLower().StartsWith(value.ToLower())).Select(e => e).ToList();
            return FilterEmployees.ToArray();
        }

The GetAllEmployees method returns me the list of all employees, in this solution I have hard coded the names but in real time scenarios this will be coming from the actual database and it would be good if you store the collection in cache , so it does not hit the database with every key stroke.

So that is the end of WCF Service Library project code , now let us come to ASP .net Web Application project code.First thing that needs to be done on this project is adding the reference of WCF Service Library project. Most of the developers have mind set that the Service Library project can be only set as a Service Reference. No folks you can also set the dll reference also. In this sample I have done the same. So now the next big question comes how do I reference to my service without the .svc file. Hold your horses. In fact it is pretty simple and straight forward. You need to add a text file in your project and rename the file extension from .txt to .svc and next you need to add the following code in the .svc file

<%@ ServiceHost Language ="C#" Service ="WcfServiceLibrary.Service1" Factory ="System.ServiceModel.Activation.WebScriptServiceHostFactory" %>

You need to change the above code for the Service attribute to correspond to your namespace and class names and obviously the language of your choice in the Language attribute. So that's it you are done now. The only thing that is pending is to give the reference of the service which can be achieved by the ScriptManager tag. The code is shown below.

<asp:ScriptManager ID="ScriptManager1" runat="server">
        <Services>
            <asp:ServiceReference Path="~/WCFService.svc" />
        </Services>
    </asp:ScriptManager>

So your aspx page knows that there is a service reference attached to it. Now we can call this service methods via JavaScript code.

<script language="JavaScript" type="text/JavaScript">
        function getFilterEmployees() {
            goldytech.WCFJsonFusion.IService1.GetEmployeeInfo(document.getElementById("TxtEmpName").value, onCallBack)
        }
        function onCallBack(RtnJSON) {
            if (RtnJSON.length > 0) {
                Result.innerHTML = "";
                for (i = 0; i < RtnJSON.length; i++) {
                    Result.innerHTML += "Employee Id " + RtnJSON[i].EmployeeID + " Employee Name " + RtnJSON[i].EmployeeName + "<br/>";

                }
            }
            else {
                Result.innerHTML = "No matching Employees found";
            }

        }
    </script>

The getFilterEmployees JavaScript function calls the service method GetEmployeeInfo , which is an operation contract and returns me the array of Employee class , which is the data contract. One important thing to note over here is the namespace (goldytech.WCFJSONFusion), this namespace was provided in the ServiceContract attribute of WCF. The onCallBack function , which accepts the parameter of return object from the server , I am able to access that object via its properties like EmployeeID and EmployeeName. So you have seen the dual power of WCF and JSON. I have got the complete object with all its properties instead of just xml. The object that is returned I can do whatever with it. In the above example I am looping through the array and displaying the results in the div tag.

Closure
The WCF and JSON duo can do wonders for you. It is the ultimate combo of two great technologies. Do let me know your comments for it. Download the sample code for this post from here.
Page copy protected against web site content infringement by Copyscape

About the Author

Goldytech
Full Name: Muhammad Afzal Qureshi
Member Level: Bronze
Member Status: Member
Member Since: 8/4/2009 10:58:17 PM
Country: India

http://goldytech.wordpress.com
Hello Everyone Myself Muhammad Afzal , aka GoldyTech. Thats my pen name. I reside in India and work as a solution Architect on .NET platform. I hope you must have enjoyed reading my blog. Please leave your comments or suggestions good or bad and help me to improve

Login to vote for this post.

Comments or Responses

Login to post response

Comment using Facebook(Author doesn't get notification)