REST service on JSON Message format

Objective

  1. How to create REST service for JSON request and response format.
  2. How to create SilverLight Client, which will consume a REST service on JSON data format.
  3. How to POST data in JSON format from SilverLight client.
     

Working explanation

Here, I am trying to insert data in static list and fetch it back at SilverLight client.
Step 1

Create new WCF Service Application

File -> New -> Project -> Web -> WCF Service Application

Step 2

Remove all the default code in service1.svc and IService1.cs. Paste the below code there in IService1.cs .

Note

  1. If you have changed the name of service interface then take care of that. If you have changed IService1 to ITest then update code in ITest.cs. if you have changed name of Service1.cs then update code in changed class.
  2. In this sample, I am adding object of Test class in a static list and fetching it back. If you want to perform pure Data base operation (CRUD). Just replace Insert code and get Code with your database operation code.
  3. Add reference of System.ServiceModel.Web to IService1.cs.
  4. Now what is Test class here? And where it should be declared and created. So just right click on service project and add a class. Give name of the class Test and paste below code over there.

Test.cs


 namespace SilverLightRestTesting
{
public class Test{
public int Marks { get; set; }

public String Name { get; set; }
}}

 IService1.cs

using System;

using System.Collections.Generic;using System.Linq;

using System.Runtime.Serialization;

using System.ServiceModel;

using System.Text;

using System.ServiceModel.Web; 

namespace SilverLightRestTesting

{

[ServiceContract]

public interface IService1{
[OperationContract] [WebGet(UriTemplate=“/Data”,BodyStyle=WebMessageBodyStyle.Bare,RequestFormat=WebMessageFormat.Json,ResponseFormat=WebMessageFormat.Json)]
List<Test> GetTest();

[OperationContract]
[WebInvoke(UriTemplate = “/Data”, BodyStyle = WebMessageBodyStyle.Bare, RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
void InsertTest(Test t);
}}

Service1.cs

using System;

using System.Collections.Generic;

using System.Linq;

using System.Runtime.Serialization;

using System.ServiceModel;

using System.Text;

 namespace SilverLightRestTesting
{
public class Service1 : IService1{
static List<Test> testList = newList<Test>();
public List<Test> GetTest()
{
return testList;
}
public void InsertTest(Test t)
{
testList.Add(t);
}
}}

 Step 3
Open Web.Config file and delete below highlighted code. In other words delete all default bindings and endpoints for existing service model. Delete existing <system.serviceModel>
Step 4
Create a SilverLight application.

  1. Create two buttons on SilverLight markup. One for getting the records from the service and other for Insert into the service. .
  2. Right click on SilverLight application and add the class Test. Because in REST services DataContract are not exposed to the client.

     Test.cs

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

 namespace SilverLightRestTesting
{
public class Test{
public int Marks { get; set; }

public String Name { get; set; }
}}

  1. Let us suppose button name is Insert for Insert into Static list of service. Write below code on click event of Insert button.
private void Insert_Click(object sender, RoutedEventArgs e){

Test t1 = new Test() { Name = “Civics”, Marks = 100 };
DataContractJsonSerializer jsondata = newDataContractJsonSerializer(typeof(Test));
MemoryStream mem = newMemoryStream();
jsondata.WriteObject(mem,t1);
string josnserdata = Encoding.UTF8.GetString(mem.ToArray(), 0, (int)mem.Length);
WebClient cnt = new WebClient();

cnt.UploadStringCompleted += new UploadStringCompletedEventHandler(cnt_UploadStringCompleted);
cnt.Headers[“Content-type”] = “application/json”;
cnt.Encoding = Encoding.UTF8;
cnt.UploadStringAsync(new
Uri(uri), “POST”, josnserdata);
}
void cnt_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
{
var x = e;
}

  1. To get all the records in form of JSON from REST service , let us suppose button name is Display. Then write below code on click event of Display button.

private void display_Click(object sender, RoutedEventArgs e)

WebClient cnt = new WebClient();

cnt.DownloadStringCompleted += new DownloadStringCompletedEventHandler(cnt_DownloadStringCompleted);
cnt.DownloadStringAsync(new
Uri(uri));
}
void cnt_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e){

string str = e.Result;

JsonArray json;

if (JsonArray.Parse(str) asJsonArray == null)

json = newJsonArray { JsonObject.Parse(str) asJsonObject };
else

json = JsonArray.Parse(str) asJsonArray;
var q = from t in json
select new Test{
Marks = (int)t[“Marks”],Name = (String)t[“Name”]};
List<Test> tr = q.ToList() as List<Test>;
}

{

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Create a website or blog at WordPress.com