WebGet and HttpWebRequest class in SilverLight

No.of Views2340
Bookmarked0 times
Downloads 
Votes0
By  Dhananjay Kumar   On  21 Apr 2010 10:04:25
Tag : Silver Light and XAML , Applications
This article will discuss about, different way of consuming HTTP enabled service (like REST).This article, will explain about WebGet and HttpWebRequest
emailbookmarkadd commentsprint

Images in this article missing? We recently lost them in a site migration. We're working to restore these as you read this. Should you need an image in an emergency, please contact us at info@codegain.com

 

Objective

This article will discuss about, different way of consuming HTTP enabled service (like REST).This article, will explain about WebGet and HttpWebRequest.  Before reading this article, I will suggest readers to read my previous articles on REST, ADO.NET Data Service and Cross Domain issue on our site.

Assumption

1.    Already REST service has been created and hosted within placed client access policy file.
2.    There is a SilverLight Client. Which is going to consume WebGet service of REST

How to access HTTP based service in Silver Light?

1.    HTTP based service returned data on a HTTP request in a particular URI

2.    HTTP request can be send any type of URI like,

http://trvlsdw002/synergyservices/appointmentservice.svc/Appointments/

http://b068ltrv/SynergyService/AppointmentService.svc/Appointments/Mahesh

http://localhost:22947/AppointmentService.svc"/Appointments/Praveen

3.    HTTP request  is cofigured to work with , verb GET
4.    Required parameter to invoke service (WebGet sercvice) should be appended with URI
 

Image Loading

5.    The output service data is contained in HTTP Response.
6.    Format of data depends on service implementation, but it mainly in format of JOSN, XML or RSS.

Silver Light provides two methods for sending HTTP request

1.    WebClient
2.    HttpWebRequest
 

Difference between WebClient and HttpWebRequest

1.    HttpWebRequest supports large subset of HTTP Protocol , which makes it better option for advanced scenarios
2.    HttpWebRequest uses asynchronous programming model which uses delegates but on the other hand WebClient uses event based asynchronous programming model. So it is easier to use and it needs lessee line of code.
3.    Callback for WebClient is raised for HTTP Response and it is invoked on the same user interface thread. So it is easier to update property of UI element. That is why it is easy with WebClient to bind UI properties with data of Http response.
 Whereas, HttpWebRequest callback run on different thread. So there is need of write extra code for UI binding.
 

WebClient

Namespace:  System.Net

 WebClient class is being used in SilverLight control which is hosted in a webpage. The following table describes WebClient methods for uploading data to a resource.

Image Loading

The following table describes WebClient methods for downloading data from a resource. 

Image Loading

Steps to call Http based service


1.    Create URI , where request is to be sent


string baseuri = "http://trvlsdw002/synergyservices/appointmentservice.svc/Appointments";


2.    Take care of cross domain issue here.
3.    Create instance of WebClient. don’t forget to ass namespace System.Net

WebClient wc = new WebClient();   

4.    Now ,

  wc.DownloadStringCompleted += ParseProducts_AsXml;

Here ParseProducts_AsXml is  event , which will parse HTTP Response  in XML format.

If response format is JSON , then

   wc.DownloadStringCompleted += ParseProducts_AsJson

Note : Here , ParseProducts_AsXml and ParseProducts_AsJson are user defined events. We need to define these events later.


5.      Now need to call ,
 

Uri uri = new Uri(baseuri);
wc.DownloadStringAsync(uri);

6.    Parse the response either as XML or as JOSN depending on response type of Http Response.
For parsing as XML, given code might help. Here response is being passed in Product business object. In e.Result, result stream is coming to SilverLight application. Just need to desterilize that. 
 

private void ParseProducts_AsXml(object sender, DownloadStringCompletedEventArgs e)
        {
            string abc = "";
            string rawXmlresponse = e.Result;
            XDocument xdoc = XDocument.Parse(rawXmlresponse);
 var query = from product in xdoc.Descendants(abc +  "Product")
                        select new Product
                                   {
       ProductId = product.Element("ProductId").Value.ToInt(),
       ProductName = product.Element("ProductName").Value,
      UnitPrice = product.Element("UnitPrice").Value.ToDecimal()
                                   };
       List<Product> products = query.ToList() as List<Product>;
            lstProducts.DataContext = products;
        }

For parsing as JOSN below code might help.

private void ParseProducts_AsJson(object sender, DownloadStringCompletedEventArgs e)
        {
            string raw = e.Result;

            JsonArray json;
            if (JsonArray.Parse(raw) as JsonArray == null)
                json = new JsonArray { JsonObject.Parse(raw) as JsonObject };
            else
                json = JsonArray.Parse(raw) as JsonArray;

           
           var query = from product in json
                        select new Product
                                   {
          ProductId = (int)product["ProductId"],
          ProductName = (string)product["ProductName"],
            UnitPrice = (decimal)product["UnitPrice"]
                                   };
            List<Product> products = query.ToList() as List<Product>;
            lstProducts.DataContext = products;
        }

For Desterilizing as JOSN using DataContractJsonSerliazer

private void ParseProducts_AsJson_UsingDataContractJsonSerializer(
            object sender, DownloadStringCompletedEventArgs e)
        {

            string json = e.Result;

            DataContractJsonSerializer serializer =
                new DataContractJsonSerializer(typeof(List<Product>));

            //DataContractJsonSerializer serializer = new DataContractJsonSerializer(products.GetType());
MemoryStream stream =
                new MemoryStream(Encoding.UTF8.GetBytes(json));

            List<Product> products = serializer.ReadObject(stream) as List<Product>;

            stream.Close();
            lstProducts.DataContext = products;
        }

Note

1.    There is no direct way, to expose DataContract to client in RESTful service.  So workaround need to be done.  There is need to create Business class at SilverLight client side. In above examples business class is Product.
2.    All the code written above is consuming REST service, which is returning List of appointments.
 

[OperationContract(Name="GetAllAppointments")]
 [WebGet(UriTemplate = "/Appointments/")]
 List<AppointmentDTO> GetAppointments();

Here, AppointmentDTO is business object. Which has to be created at client side too?

Conclusion

In this article i have exaplined , access webGet and WebRequest method in REST services.i hope this help to you.

 
Sign Up to vote for this article
 
About Author
 
Dhananjay Kumar
Occupation-Software Engineer
Company-Infosys Technolgies,Pune
Member Type-Gold
Location-India
Joined date-20 Jul 2009
Home Page-http://dhananjaykumar.net/
Blog Page-http://dhananjaykumar.net/
Dhananjay Kumar is Microsoft MVP on connected system. He blogs at http://dhananjaykumar.net/ . You can follow him http://twitter.com/debugmode_/ and reach him at dhananjay.25july@gmail.com
 
 
Other popularSectionarticles
    Performance is a vital part for any application possibly more important for web based app.With wizard based approach of RIA service generally we tends to comprise all entities, exposing to the client and also allowing the DomainService to go for everything from the database. Not only this approach takes a toll on security, but also it loads the middle tier unreasonably. So this post is about few tips using which we can improve the performance. Well mostly we will cover the Pagination, Limiting
    Published Date : 10/Apr/2011
    My earlier post was about the basic CRUD operations on entities with relation .We had discussed about creating simple association and querying as well as Invoking CRUD operation onto them.As i have mentioned there ,here in this article we will have an in-depth look into Presentation Model and its mode of handling related multiple entities.
    Published Date : 10/Mar/2011
    Silvelight is latest buzz in Microsoft.NET Technologies. Silverlight enable us to create rich user interface for the web based application
    Published Date : 16/May/2010
    This article will demonstrate how to build a traditional master page style application in Silverlight.
    Published Date : 16/Feb/2010
    In the previous lesson we talked about COM automation support introduced in Silverlight 4 and we said that COM automation is available only for Silverlight OOB (Out-of-Browser) applications that have Elevated Trust, and that’s one of the security restrictions imposed by Silverlight. Today, we’re going to talk about COM automation in more details and give few Silverlight examples that make use of this great feature.
    Published Date : 31/Mar/2011
Comments
There is no comments for this articles.
Leave a Reply
Title:
Display Name:
Email:
(not display in page for the security purphase)
Website:
Message:
Please refresh your screen using Ctrl+F5
If you can't read this number refresh your screen
Please input the anti-spam code that you can read in the image.
^ Scroll to Top