|
|
|
|
|
Home
»
WCF
»
HTTP Post from SilverLight application to a REST Service
|
|
|
Author Rank:
|
|
Technologies:
.NET 3.0 and 3.5, Silverlight,Visual C# .NET
|
|
Total downloads :
|
59
|
|
Total page views :
|
1984
|
|
Rating :
|
|
0/5
|
|
This article has been rated :
|
0 times
|
|
|
|
|
Download
Files:
|
|
|
|
|
|
|
|
|
|
|
Similar ArticlesMost ReadTop RatedLatest
|
|
Related EbooksTop Videos
|
|
|
Description
|
|
Author Jeff Scanlon assumes you’re already comfortable with the basics of .NET coding and with WPF, and they help you build on your existing knowledge to make your journey to Silverlight 2 proficiency as quick and painless as possible.
|
|
|
|
|
|
|
|
|
|
|
|
|
Objective:
-
How to create REST service for JSON request and response format.
-
How to create SilverLight Client, which will consume a REST service on JSON data format.
-
How to POST data in JSON format from SilverLight client.
Pre Requisite
Reader should have basic knowledge of REST services. For more on REST read my other articles.
Working explanation
Here, I am trying to insert data in static list and fetch it back at SilverLight client.
For Solution follow below steps:
Step 1:
Create new WCF Service Application
File -> New -> Project -> Web -> WCF Service Application

Solution explorer would like more or less,

Step 2:
Remove all the default code in service1.svc and IService1.cs. Paste the below code there in IService1.cs .
Note :
-
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.
-
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.
-
Add reference of System.ServiceModel.Web to IService1.cs.
-
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
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; } } }
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 { // NOTE: If you change the interface name "IService1" here, you must also update the reference to "IService1" in Web.config. [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 { // NOTE: If you change the class name "Service1" here, you must also update the reference to "Service1" in Web.config and in the associated .svc file. public class Service1 : IService1 { static List<Test> testList = new List<Test>();
public List<Test> GetTest() { return testList; } public void InsertTest(Test t) { testList.Add(t); } } }
Explanation of code:
[OperationContract] [WebGet(UriTemplate="/Data",BodyStyle=WebMessageBodyStyle.Bare,RequestFormat=WebMessageFormat.Json,ResponseFormat=WebMessageFormat.Json ] List<Test> GetTest();
Here, Response format, Request Format all are attributed with message format as JOSN. This service GetTest() will return List<Test> .
[OperationContract]
[WebInvoke(UriTemplate = "/Data", BodyStyle = WebMessageBodyStyle.Bare, RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)] void InsertTest(Test t);
Here, Response format, Request Format all are attributed with message format as JOSN. This service InsertTest(Test t) will take Test object as input parameter and insert this into a static list.
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:
Right click on Service1.cs and open View markup.

In Markup of RestService.cs , add below code there
Factory="System.ServiceModel.Activation.WebServiceHostFactory"
So after adding code the markup would look like
Markup of RestService.cs
<%@ ServiceHost Language="C#" Debug="true" Service="SilverLightRestTesting.Service1" CodeBehind="Service1.svc.cs" Factory="System.ServiceModel.Activation.WebServiceHostFactory" %>
Step 5:
Hosting the service in IIS.
Right click on Service Project and click on Publish.

Click on browse button.

Click on Create New Virtual Directory to create a virtual directory.

Give a Alias name and browse to the folder where you have created the service.


Click on OK



Click ok and publish the REST service in IIS. At bottom of visual studio Publish succeeded message should come.

Upto this step REST service has been published in IIS.
Click on Start->Run and type Inetmgr then click ok.

Click on Test website.

Right click and select Properties.

Check Write checkbox and from drop down list select Scripts and Executable

Select Yes for warning message.

Click on Directory Security. Then select Edit

Now select Integrated Windows Authentication. Uncheck Anonymous authentication.

Click on Test then Service1.svc and browse.


Step 6:
Create a SilverLight application.
-
Create two buttons on SilverLight markup. One for getting the records from the service and other for Insert into the service.
-
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; } } }
-
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 = new DataContractJsonSerializer(typeof(Test)); MemoryStream mem = new MemoryStream(); 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;
}
4. 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) { //throw new NotImplementedException(); string str = e.Result; JsonArray json; if (JsonArray.Parse(str) as JsonArray == null) json = new JsonArray { JsonObject.Parse(str) as JsonObject }; else json = JsonArray.Parse(str) as JsonArray;
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>;
}
Summary:
In this article, I explained about REST service on JSON data format and HTTP POST from SilverLight application. Download Zip file and run the service. You would have better understanding of , what I am trying to in above sample.
Happy Coding..
|
|
|
Login
to add your contents and source code to this article
|
|
|
|
|
|
|
|
|
|
|
|
Dhananjay Kumar
I am Dhananjay Kumar. I passed computer science & engineering from AEC Agra in year 2007. I born and brought up in Jamshedpur , Jharkhand.I am MCTS on WCF, MOSS Development , .Net Framework 2.0 Web Application so far. I read and write on WCF, SilverLight , SharePoint , ASP.Net MVC, ASP.Net 3.5 Extensions , .Net 4.0 , C# 3.0 , C# 4.0 etc etc. Currently , I am working for UST Global as Software Engineer and active member of Microsoft COE team .
|
|
|
|
|
|
|
|
|
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional
consulting company, our consultants are well-known experts in .NET and many of them
are MVPs, authors, and trainers. We specialize in Microsoft .NET development and
utilize Agile Development and Extreme Programming practices to provide fast pace
quick turnaround results. Our software development model is a mix of Agile Development,
traditional SDLC, and Waterfall models.
|
|
Click here to learn more about C# Consulting. |
|
|
|
|
|
|
|
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon.
Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees.
As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
|
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
|
Go.NET
Build custom interactive diagrams, network, workflow editors, flowcharts, or software design tools. Includes many predefined kinds of nodes, links, and basic shapes. Supports layers, scrolling, zooming, selection, drag-and-drop, clipboard, in-place editing, tooltips, grids, printing, overview window, palette. 100% implemented in C# as a managed .NET Control. Document/View/Tool architecture with many properties&events. Optional automatic layout.
|
Dundas Software
Dundas Chart for .NET is the most advanced .NET charting package available today. With an extremely complete feature set, elegant architecture and easy implementation, Dundas Chart can quickly add advanced Charting functionality to enhance and transform ASP.NET and Windows Forms applications. Whether you are implementing charting into internal projects, or building applications for clients, Dundas Chart offers advanced technology and advanced results to get the most out of data.
|
Clickatell's SMS Gateway
Clickatell's Developer Solutions allow you to SMS enable any website or
application via a range of API's. Learn More about our API connections.
|
Microsoft Visual Studio 2010
Microsoft Visual Studio 2010 offers more to developers than any other
Visual Studio release. Work more productively and collaboratively-with
greater control over your work at every step. The Beta 2 can give you a
head start on achieving efficiency.
|
|
|
|
|
|
|
|
|
Download
Files:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|