Blue Theme Orange Theme Green Theme Red Theme
 
Home | Forums | Videos | Photos | Downloads | Blogs | E-Books | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Login Close
User Id:
Password:
 
Forgot Password
Forgot Username
Why Register
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
 Resources  
Close
 Our Network  
Close
Search :       Advanced Search »
Home » WCF » HTTP Post from SilverLight application to a REST Service

HTTP Post from SilverLight application to a REST Service

This Article will expalin , how to create REST service which work on JSON data format. Then It will explain about how to perform HTTP GET and HTTP POST operation from a SilverLight client on a REST service on JSON Data Format.

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
   Print Read/Post comments Post a comment  Rate  
   Email to a friend  Bookmark  Similar Articles  Author's other articles  
Download Files:
SilverLightRestTesting.zip
 
Become a Sponsor




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.

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

WCFService1.gif

Solution explorer would like more or less,

WCFService2.gif

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

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.

WCFService3.gif

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.

WCFService4.gif

Click on browse button.

WCFService5.gif

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

WCFService6.gif

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

WCFService7.gif

WCFService8.gif

Click on OK

WCFService9.gif

WCFService10.gif

WCFService11.gif

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

WCFService12.gif


Upto this step REST service has been published in IIS.

Click on Start->Run and type Inetmgr then click ok.


WCFService13.gif

Click on Test website.

WCFService14.gif

Right click and select Properties.

WCFService15.gif

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

WCFService16.gif

Select Yes for warning message.

WCFService17.gif

Click on Directory Security. Then select Edit

WCFService18.gif

Now select Integrated Windows Authentication. Uncheck Anonymous authentication.

WCFService19.gif

Click on Test then Service1.svc and browse.

WCFService20.gif


WCFService21.gif

Step 6:

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; }
        }
    }

     

  3. 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
 [Top] Rate this article
 About the author
 
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 .
 
Looking for C# Consulting?
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.
Free access to .NET Memory Management video
Everything you need to know about Garbage Collection, Temporary Objects, Fragmentation, Finalization and common causes of memory leaks in .NET. Watch the video here.
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.
 
   Print Read/Post comments Post a comment  Rate  
   Email to a friend  Bookmark  Similar Articles  Author's other articles  
Download Files:
SilverLightRestTesting.zip
 
 Post a Feedback, Comment, or Question about this article
Subject:  
Comment:  
Become a Sponsor
 Comments

 Hosted by MaximumASP  |  Found a broken link?  |  Contact Us  |  Terms & conditions  |  Privacy Policy  |  Site Map  |  Suggest an Idea  |  Media Kit
Current Version: 5.2009.6.2
 © 1999 - 2009  Mindcracker LLC. All Rights Reserved