Saturday, June 22, 2013

Access WCF Rest Services from JQuery Part 2

This is the Part 2 of the Post.
You can find Part 1 Here

In this post we'll see how to access the service we created using JQuery.

First we'll see the insert Employee part.
here we are posting the Employee object from  JQuery to WCF, As I'm using IIS Express its localhost you can give your service url correctly.

$.ajax({
 url: "http://localhost:53840/SampleService.svc/insertemployee",
 type: "POST",
 processData: true,
 contentType: "application/json",
 data: '{"Id":1, "Name":"Guru"}',
 dataType: "json",
 crossDomain : true,
 success: function(data) { alert(data) },
 error : function(data){alert('error')}
 
});

In this method we are getting all the employees as a json object array to the client side.
You do more by changing the Uri template and send information to the server side when using GET.

$.ajax({
 url: "http://localhost:53840/SampleService.svc/GetEmployees",
 type: "GET",
 processData: true,
 contentType: "application/json",
 dataType: "json",
 crossDomain : true,
 success: function(data) { alert(data) },
 error : function(data){alert('error')}
 
}); 

Thats it now you can access you service from JQuery.

Download Sample

Please Leave a Comment.

Access WCF Rest Services from JQuery Part 1

Hi Readers, this post is about creating the wcf service that is going to be accessed from jquery,

This service is very simple it allows you to add an employee via POST and retrieve all the employees via GET.
You can learn how to create a GET request and POST request.

As the first step you’ll have to create a WCF service project in Visual Studio (I’m using 2012). Here I’m creating the project as “WCF Rest Sample”.
You can use the Service1 which comes as default but I’ve created a new service called “SampleService” so that it’s easy to understand.

Then create the required classes, the given image shows the project structure.






Lets see the code for each class

The data provider class is used to contain the employee objects, in real world you can use a database as the data source.

public static class DataProvider
{
    private static List<Employee> Employees = new List<Employee>();

    public static List<Employee> GetEmployees()
    {
        return Employees;
    }

    public static void AddEmployee(Employee employee)
    {
        Employees.Add(employee);
    }
}

The next class is our Entity Employee this will be transferred as Json

[DataContract]
public class Employee
{
    [DataMember]
    public int Id { get; set; }

    [DataMember]
    public string Name { get; set; }
}

Then our service contract here the methods are declared and appropriate settings are made to change the request and response to json.

[ServiceContract]
public interface ISampleService
{
    [OperationContract]
    [WebInvoke(ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)]
    int InsertEmployee(Employee employee);

    [OperationContract]
    [WebGet(ResponseFormat = WebMessageFormat.Json)]
    List<Employee> GetEmployees();
}

This is the implementation for the service.

public class SampleService : ISampleService
{
    public int InsertEmployee(Employee employee)
    {
        DataProvider.AddEmployee(employee);
        return 1;
    }

    public List<Employee> GetEmployees()
    {
        return DataProvider.GetEmployees();
    }
}

In the global.asax file only the Begin request method is modified so that the service can be accessed from Firefox and Chrome.

protected void Application_BeginRequest(object sender, EventArgs e)
{
    HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
    if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
    {
        HttpContext.Current.Response.AddHeader("Cache-Control", "no-cache");
        HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST");
        HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept, x-requested-with");
        HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
        HttpContext.Current.Response.End();
    } 
}

Now you'll have to do the appropriate changes the the web.config to turn the service into REST.

Now you can run the service and see the methods that are available using the help page (Enabled in the Web.config file).


Now our service is ready to be called from JQuery.
The jquery part will be explained in Part 2.

Tuesday, June 4, 2013

Syncing tables using Merge in SQL Server

Hi Readers,

In this post I'll explain how to use the 'Merge' statement in sql server to Sync two tables.
For this we'll need two tables, one will act as the source and the other one will act as the destination.

First create the required tables

CREATE TABLE SourceTable
(
 ID INT IDENTITY PRIMARY KEY,
 Name VARCHAR(100)
);

CREATE TABLE DestinationTable
(
 ID INT PRIMARY KEY,
 Name VARCHAR(100)
);


Then insert some data to the source table
INSERT INTO SourceTable VALUES('George');
INSERT INTO SourceTable VALUES('Saman');
INSERT INTO SourceTable VALUES('Kamal');
INSERT INTO SourceTable VALUES('Nimal');
INSERT INTO SourceTable VALUES('Sunil');
INSERT INTO SourceTable VALUES('Mark');
INSERT INTO SourceTable VALUES('Bill');
INSERT INTO SourceTable VALUES('Paul');
INSERT INTO SourceTable VALUES('Sean');
INSERT INTO SourceTable VALUES('Shane');
INSERT INTO SourceTable VALUES('Elvis');
Now we'll come to the Merge Statement

MERGE DestinationTable D
USING SourceTable S
ON D.ID=S.ID 
WHEN MATCHED AND D.Name!=S.Name THEN UPDATE SET D.Name=S.Name
WHEN NOT MATCHED BY SOURCE THEN DELETE
WHEN NOT MATCHED BY TARGET THEN INSERT(ID,Name) VALUES(S.ID,S.Name);

As this is the first time , all the rows will be inserted
So we'll do some changes to the table (insert, update , delete)
DELETE FROM SourceTable WHERE Name='Bill';
UPDATE SourceTable SET Name='Mark2' WHERE Name= 'Mark';
INSERT INTO SourceTable VALUES('Alex');
Now if we run the merge statement again we can see that both the tables are synced.
You can schedule it to a job so that the tables will be in sync.