Performing DML Operations using WCF REST Service and Silverlight

Posted by: Mahesh Sabnis , on 2/24/2010, in Category Silverlight 2, 3, 4 and 5
Views: 27854
Abstract: WCF REST has provided a mechanism for developing loosely coupled applications. Using Silverlight 3.0 as a client, a light weight consumer of WCF REST service can be created without adding a proxy into the client application.
Performing DML Operations using WCF REST Service and Silverlight
 
As a professional working on WCF REST and Silverlight 3.0, I have been very interested in performing DML operations using Silverlight 3.0 and WCF REST Service which exposes CRUD Operations. A couple of days ago, while conducting a training session, one of the participants asked me a question about WCF REST Services exposing CRUD operations and consuming it using Silverlight 3.0, for loosely coupled application development. I immediately thought of doing some research on it and convert it into an article to help out other users who may have the same requirement.
Now most of you might have started working on WCF REST - one of the most important features of WCF. It allows using WCF service by clients like PHP, JAVA etc. REST supports verbs like GET, PUT, POST and DELETE. These verbs represent operations performed using http requests.
In this article I have designed a WCF REST service which is performing GET and POST operations and it is used by Silverlight 3.0 client application. Let us see the steps required to implement the solution.
Step 1: Open VS2008, create a blank solution and name it as ‘SILV3_CallingRESTDMLService’. To this solution, add a new WCF Service Application form ‘Web’ project Type and name it as ‘WCF_DMLService’ as shown below:
NewProject
Step 2: Rename ‘IService1.cs’ to ‘IService’ and ‘Service1.Svc.cs’ to ‘Service.Svc’.
Step 3: Since this is a WCF REST service, add a reference to ‘System.ServiceModel.Web’. This namespace provides classes for defining behavior for Operations in Service for REST. Web Service Host activation for the WCF service is provided by this namespace.
Step 4: Right Click on the ‘Service.Svc’ and select ‘View Markup’ and change the file as shown below:
<%@ ServiceHost Language="C#" Debug="true"
Service="WCF_DMLService.Service"
CodeBehind="Service.svc.cs"
 Factory="System.ServiceModel.Activation.WebServiceHostFactory"%>
 
Here the attribute ‘Factory’ represents the Web Activation for WCF service.
Step 5: Write the following code in ‘IService.cs’.
C#
[DataContract(Name = "Employee", Namespace = "")]
public class Employee
{
    [DataMember]
    public int EmpNo { get; set; }
    [DataMember]
    public string EmpName { get; set; }
    [DataMember]
    public int DeptNo { get; set; }
    [DataMember]
    public int Salary { get; set; }
}
VB.NET
<DataContract(Name := "Employee", Namespace := "")> _
Public Class Employee
      Private privateEmpNo As Integer
      <DataMember> _
      Public Property EmpNo() As Integer
            Get
                  Return privateEmpNo
            End Get
            Set(ByVal value As Integer)
                  privateEmpNo = value
            End Set
      End Property
      Private privateEmpName As String
      <DataMember> _
      Public Property EmpName() As String
            Get
                  Return privateEmpName
            End Get
            Set(ByVal value As String)
                  privateEmpName = value
            End Set
      End Property
      Private privateDeptNo As Integer
      <DataMember> _
      Public Property DeptNo() As Integer
            Get
                  Return privateDeptNo
            End Get
            Set(ByVal value As Integer)
                  privateDeptNo = value
            End Set
      End Property
      Private privateSalary As Integer
      <DataMember> _
      Public Property Salary() As Integer
            Get
                  Return privateSalary
            End Get
            Set(ByVal value As Integer)
                  privateSalary = value
            End Set
      End Property
End Class
 
The above class will be serialized from Service to Consumer.
Step 6: Now add the following ServiceContract code to the same file (IService.cs)
C#
using System.Runtime.Serialization;
using System.ServiceModel;
 
using System.ServiceModel.Web;
 
namespace WCF_DMLService
{
    [ServiceContract]
    public interface IService
    {
        [OperationContract]
        [WebInvoke(RequestFormat = WebMessageFormat.Xml,
            ResponseFormat = WebMessageFormat.Xml,
            BodyStyle = WebMessageBodyStyle.Bare,
            UriTemplate = "/CreateEmployee/{empNo}/{empName}/{salary}/{deptNo}",
            Method="POST")]
        int InsertEmployee(string empNo, string empName, string salary, string deptNo);
 
        [OperationContract]
        [WebInvoke(RequestFormat = WebMessageFormat.Xml,
            ResponseFormat = WebMessageFormat.Xml,
            BodyStyle = WebMessageBodyStyle.Bare,
            UriTemplate = "/DeleteEmployee/{empNo}",
            Method = "POST")]
        int DeleteEmployee(string empNo);
 
        [OperationContract]
        [WebGet(RequestFormat = WebMessageFormat.Xml,
            ResponseFormat = WebMessageFormat.Xml,
            BodyStyle = WebMessageBodyStyle.Bare
            )]
        Employee[] GetAllEmployee();
    }
 
}
 
VB.NET
Imports System.Runtime.Serialization
Imports System.ServiceModel
 
Imports System.ServiceModel.Web
 
Namespace WCF_DMLService
      <ServiceContract> _
      Public Interface IService
            <OperationContract, WebInvoke(RequestFormat := WebMessageFormat.Xml, ResponseFormat := WebMessageFormat.Xml, BodyStyle := WebMessageBodyStyle.Bare, UriTemplate := "/CreateEmployee/{empNo}/{empName}/{salary}/{deptNo}", Method:="POST")> _
            Function InsertEmployee(ByVal empNo As String, ByVal empName As String, ByVal salary As String, ByVal deptNo As String) As Integer
 
            <OperationContract, WebInvoke(RequestFormat := WebMessageFormat.Xml, ResponseFormat := WebMessageFormat.Xml, BodyStyle := WebMessageBodyStyle.Bare, UriTemplate := "/DeleteEmployee/{empNo}", Method := "POST")> _
            Function DeleteEmployee(ByVal empNo As String) As Integer
 
            <OperationContract, WebGet(RequestFormat := WebMessageFormat.Xml, ResponseFormat := WebMessageFormat.Xml, BodyStyle := WebMessageBodyStyle.Bare)> _
            Function GetAllEmployee() As Employee()
      End Interface
 
End Namespace
 
In the above code, I have used ‘WebGet’ and ‘WebInvoke’ attributes along with ‘OperationContract’. These attributes are present under the namespace ‘System.ServiceModel.Web’ and indicates that operations defined in the contract will be called by the web programming model. WebGet has HTTP ‘GET’ by default and ‘WebInvoke’ can be used for HTTP ‘PUT’, ‘POST’ and ‘DELETE’ verbs. Request and Response formats can be either ‘XML’ or ‘JSON’.
Step 7: Open ‘Service.Svc.cs’ and write the following code:
C#
using System;
using System.Collections.Generic;
 
using System.Data.SqlClient;
 
namespace WCF_DMLService
{
    public class Service : IService
    {
 
        #region IService Members
 
        public int InsertEmployee(string empNo, string empName, string salary, string deptNo)
        {
            int Inserterd = 0;
            SqlConnection Conn = new SqlConnection("Data Source=.;Initial Catalog=Company;Integrated Security=SSPI");
            Conn.Open();
            SqlCommand Cmd = new SqlCommand();
            Cmd.Connection = Conn;
            Cmd.CommandText = "Insert into Employee Values(@EmpNo,@EmpName,@Salary,@DeptNo)";
           
            Cmd.Parameters.AddWithValue("@EmpNo",Convert.ToInt32(empNo));
            Cmd.Parameters.AddWithValue("@EmpName", empName);
            Cmd.Parameters.AddWithValue("@Salary", Convert.ToInt32(salary));
            Cmd.Parameters.AddWithValue("@DeptNo", Convert.ToInt32(deptNo));
 
            Inserterd = Cmd.ExecuteNonQuery();
 
            Conn.Close();
            return Inserterd;
        }
 
        public int DeleteEmployee(string empNo)
        {
            int Deleted = 0;
            SqlConnection Conn = new SqlConnection("Data Source=.;Initial Catalog=Company;Integrated Security=SSPI");
            Conn.Open();
            SqlCommand Cmd = new SqlCommand();
            Cmd.Connection = Conn;
            Cmd.CommandText = "Delete from Employee where EmpNo=@EmpNo";
            Cmd.Parameters.AddWithValue("@EmpNo",Convert.ToInt32(empNo));
            Deleted = Cmd.ExecuteNonQuery();
            return Deleted;
        }
 
        public Employee[] GetAllEmployee()
        {
            List<Employee> lstEmp = new List<Employee>(); 
            SqlConnection Conn = new SqlConnection("Data Source=.;Initial Catalog=Company;Integrated Security=SSPI");
            Conn.Open();
            SqlCommand Cmd = new SqlCommand("Select * from Employee",Conn);
            SqlDataReader Reader = Cmd.ExecuteReader();
            while (Reader.Read())
            {
                lstEmp.Add(new Employee()
                    {
                         EmpNo=Convert.ToInt32(Reader["EmpNo"]),
                         EmpName = Reader["EmpName"].ToString(),
                         DeptNo = Convert.ToInt32(Reader["DeptNo"]),
                         Salary = Convert.ToInt32(Reader["Salary"])
                    });  
            }
            Reader.Close();
 
            Conn.Close();
 
            return lstEmp.ToArray();
        }
 
        #endregion
    }
}
 
VB.NET
Imports System
Imports System.Collections.Generic
 
Imports System.Data.SqlClient
 
Namespace WCF_DMLService
      Public Class Service
            Implements IService
 
            #Region "IService Members"
 
            Public Function InsertEmployee(ByVal empNo As String, ByVal empName As String, ByVal salary As String, ByVal deptNo As String) As Integer
                  Dim Inserterd As Integer = 0
                  Dim Conn As New SqlConnection("Data Source=.;Initial Catalog=Company;Integrated Security=SSPI")
                  Conn.Open()
                  Dim Cmd As New SqlCommand()
                  Cmd.Connection = Conn
                  Cmd.CommandText = "Insert into Employee Values(@EmpNo,@EmpName,@Salary,@DeptNo)"
 
                  Cmd.Parameters.AddWithValue("@EmpNo",Convert.ToInt32(empNo))
                  Cmd.Parameters.AddWithValue("@EmpName", empName)
                  Cmd.Parameters.AddWithValue("@Salary", Convert.ToInt32(salary))
                  Cmd.Parameters.AddWithValue("@DeptNo", Convert.ToInt32(deptNo))
 
                  Inserterd = Cmd.ExecuteNonQuery()
 
                  Conn.Close()
                  Return Inserterd
            End Function
 
            Public Function DeleteEmployee(ByVal empNo As String) As Integer
                  Dim Deleted As Integer = 0
                  Dim Conn As New SqlConnection("Data Source=.;Initial Catalog=Company;Integrated Security=SSPI")
                  Conn.Open()
                  Dim Cmd As New SqlCommand()
                  Cmd.Connection = Conn
                  Cmd.CommandText = "Delete from Employee where EmpNo=@EmpNo"
                  Cmd.Parameters.AddWithValue("@EmpNo",Convert.ToInt32(empNo))
                  Deleted = Cmd.ExecuteNonQuery()
                  Return Deleted
            End Function
 
            Public Function GetAllEmployee() As Employee()
                  Dim lstEmp As New List(Of Employee)()
                  Dim Conn As New SqlConnection("Data Source=.;Initial Catalog=Company;Integrated Security=SSPI")
                  Conn.Open()
                  Dim Cmd As New SqlCommand("Select * from Employee",Conn)
                  Dim Reader As SqlDataReader = Cmd.ExecuteReader()
                  Do While Reader.Read()
                        lstEmp.Add(New Employee() With {.EmpNo=Convert.ToInt32(Reader("EmpNo")), .EmpName = Reader("EmpName").ToString(), .DeptNo = Convert.ToInt32(Reader("DeptNo")), .Salary = Convert.ToInt32(Reader("Salary"))})
                  Loop
                  Reader.Close()
 
                  Conn.Close()
 
                  Return lstEmp.ToArray()
            End Function
 
            #End Region
      End Class
End Namespace
 
Step 8: In the Web.config change the endpoint binding to ‘webHttpBinding’ as below:
<endpointaddress=""
          binding="webHttpBinding"
          contract="WCF_DMLService.IService">
</endpoint>
Step 9: Publish this service to IIS and test it out. If everything’s been configured as explained, you should get the following output:
Service
Now change the url written below in the address bar and press enter
The following output should be displayed:
Localhost
Currently it shows all the employees. One important thing here is that you can perform this operation only for ‘WebGet’ and not for ‘WebInvoke’ because the browser can perform only HTTP GET operation. Close the browser.
Step 10: To the same solution, add a new Silverlight application and name it as ‘SILV3_RESTDMLClient’.
Step 11: Design the Xaml UI as per your requirements. I am not a very good designer so pardon me for the design shown below J
Design
The Xaml for the UI is as shown below:
<UserControl xmlns:data="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Data"  x:Class="SILV3_RESTDMLClient.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d" d:DesignWidth="710" d:DesignHeight="510">
   
    <Grid x:Name="grdMain" Width="700" Height="500">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="300"></ColumnDefinition>
            <ColumnDefinition Width="400"></ColumnDefinition>
        </Grid.ColumnDefinitions>
            <Grid x:Name="grdDML" Grid.Column="0">
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="100"></ColumnDefinition>
                    <ColumnDefinition Width="200"></ColumnDefinition>
                </Grid.ColumnDefinitions>
                <Grid.RowDefinitions>
                    <RowDefinition Height="80"></RowDefinition>
                    <RowDefinition Height="80"></RowDefinition>
                    <RowDefinition Height="80"></RowDefinition>
                   <RowDefinition Height="80"></RowDefinition>
                    <RowDefinition Height="80"></RowDefinition>
                </Grid.RowDefinitions>
                <TextBlock Grid.Column="0" Grid.Row="0" Text="EmpNo"></TextBlock>
                <TextBlock Grid.Column="0" Grid.Row="1" Text="EmpName"></TextBlock>
                <TextBlock Grid.Column="0" Grid.Row="2" Text="Salary"></TextBlock>
                <TextBlock Grid.Column="0" Grid.Row="3" Text="DeptNo"></TextBlock>
 
                <TextBox x:Name="txteno" Grid.Column="1" Grid.Row="0"></TextBox>
                <TextBox x:Name="txtename" Grid.Column="1" Grid.Row="1"></TextBox>
                <TextBox x:Name="txtsal" Grid.Column="1" Grid.Row="2"></TextBox>
                <TextBox x:Name="txtdno" Grid.Column="1" Grid.Row="3"></TextBox>
            <Grid x:Name="grdButton" Grid.Row="4" Grid.Column="1">
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="65"></ColumnDefinition>
                    <ColumnDefinition Width="65"></ColumnDefinition>
                    <ColumnDefinition Width="65"></ColumnDefinition>
                </Grid.ColumnDefinitions>
                <Button x:Name="btnInsert" Content="Insert" Grid.Column="0" Click="btnInsert_Click"></Button>
                <Button x:Name="btnDelete" Content="Delete" Grid.Column="1" Click="btnDelete_Click"></Button>
                <Button x:Name="btnGetAll" Content="Get All" Grid.Column="2" Click="btnGetAll_Click"></Button>
            </Grid>
            </Grid>
           <Grid x:Name="grdDisplay" Grid.Column="1">
              <data:DataGrid x:Name="grdEmployee" ItemsSource="{Binding}"  Width="280"    AutoGenerateColumns="False">
                <data:DataGrid.Columns>
                    <data:DataGridTextColumn Header="EmpNo" Binding="{Binding EmpNo}"></data:DataGridTextColumn>
                    <data:DataGridTextColumn Header="EmpName" Binding="{Binding EmpName}"></data:DataGridTextColumn>
                    <data:DataGridTextColumn Header="Salary" Binding="{Binding Salary}"></data:DataGridTextColumn>
                    <data:DataGridTextColumn Header="DeptNo" Binding="{Binding DeptNo}"></data:DataGridTextColumn>
                </data:DataGrid.Columns>
            </data:DataGrid>
           </Grid>
        </Grid>
</UserControl>
 
Since all calls from Silverlight to Web resources are asynchronous, I have used classes like:
WebClient - used for downloading all contents asynchronously and
WebRequest and WebResponse - for asynchronous ‘POST’ operations. 
Step 13: To the Silverlight project, add a reference to ‘System.Runtime.Serialization’. Note that this reference must be targeting to version ‘2.0.5.0’. Silverlight 3.0 does not support the framework like 3.0/3.5 for this reference. (If any knows any workaround, I am all ears)
C#
using System.Runtime.Serialization;
namespace SILV3_RESTDMLClient
{
    public class Employee
    {
        [DataMember]
        public int EmpNo { get; set; }
        [DataMember]
        public string EmpName { get; set; }
        [DataMember]
        public int DeptNo { get; set; }
        [DataMember]
        public int Salary { get; set; }
    }
}
 
VB.NET
Imports System.Runtime.Serialization
Namespace SILV3_RESTDMLClient
      Public Class Employee
            Private privateEmpNo As Integer
            <DataMember> _
            Public Property EmpNo() As Integer
                  Get
                        Return privateEmpNo
                  End Get
                  Set(ByVal value As Integer)
                        privateEmpNo = value
                  End Set
            End Property
            Private privateEmpName As String
            <DataMember> _
            Public Property EmpName() As String
                  Get
                        Return privateEmpName
                  End Get
                  Set(ByVal value As String)
                        privateEmpName = value
                  End Set
            End Property
            Private privateDeptNo As Integer
            <DataMember> _
            Public Property DeptNo() As Integer
                  Get
                        Return privateDeptNo
                  End Get
                  Set(ByVal value As Integer)
                        privateDeptNo = value
                  End Set
            End Property
            Private privateSalary As Integer
            <DataMember> _
            Public Property Salary() As Integer
                  Get
                        Return privateSalary
                  End Get
                  Set(ByVal value As Integer)
                        privateSalary = value
                  End Set
            End Property
      End Class
End Namespace
Step 12: In the ‘Get All’ button click, write the following code:
C#
WebClient webClient;
private void btnGetAll_Click(object sender, RoutedEventArgs e)
{
    webClient = new WebClient();
    webClient.DownloadStringCompleted+=new DownloadStringCompletedEventHandler(webClient_DownloadStringCompleted);
    webClient.DownloadStringAsync(new Uri("http://localhost/RESTVDDML/Service.svc/GetAllEmployee", UriKind.Absolute)); 
   
 
}
 
void webClient_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
    XDocument xDoc = XDocument.Parse(e.Result);
 
    var AllEmps = from Emp in xDoc.Descendants("Employee")
                  select new Employee()
                  {
                      EmpNo = Convert.ToInt32(Emp.Descendants("EmpNo").First().Value ),
                      EmpName = Emp.Descendants("EmpName").First().Value,
                      Salary = Convert.ToInt32(Emp.Descendants("Salary").First().Value),
                      DeptNo = Convert.ToInt32(Emp.Descendants("DeptNo").First().Value)
                  };
    grdEmployee.DataContext = AllEmps.ToList(); 
}
VB.NET
Private webClient As WebClient
Private Sub btnGetAll_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
      webClient = New WebClient()
      AddHandler webClient.DownloadStringCompleted, AddressOf webClient_DownloadStringCompleted
      webClient.DownloadStringAsync(New Uri("http://localhost/RESTVDDML/Service.svc/GetAllEmployee", UriKind.Absolute))
 
 
End Sub
 
Private Sub webClient_DownloadStringCompleted(ByVal sender As Object, ByVal e As DownloadStringCompletedEventArgs)
      Dim xDoc As XDocument = XDocument.Parse(e.Result)
 
      Dim AllEmps = From Emp In xDoc.Descendants("Employee") _
                    Select New Employee()
                               Convert.ToInt32(Emp.Descendants("Salary").First().Value), DeptNo = Convert.ToInt32(Emp.Descendants("DeptNo").First().Value)
                               Emp.Descendants("EmpName").First().Value, Salary = Convert.ToInt32(Emp.Descendants("Salary").First().Value), DeptNo
                               Convert.ToInt32(Emp.Descendants("EmpNo").First().Value), EmpName = Emp.Descendants("EmpName").First().Value, Salary
                               EmpNo = Convert.ToInt32(Emp.Descendants("EmpNo").First().Value), EmpName
      grdEmployee.DataContext = AllEmps.ToList()
End Sub
 
In the above code, I have made use of XLINQ. Using ‘WebClient’ class the request is made to the url for downloading string contents form the web. Since WCF REST used POX, the response is in the form of XML. This XML data is read using XLINQ and the data is put in Employee class.
Step 13: Write the following code for Insert and Delete button:
C#
private void btnInsert_Click(object sender, RoutedEventArgs e)
{
    try
    {
        string uploadUrl = "http://localhost/RESTVDDML/Service.svc/CreateEmployee/" + txteno.Text + "/" + txtename.Text + "/" + txtsal.Text + "/" + txtdno.Text ;
        WebRequest addRequest = WebRequest.Create(uploadUrl);
        addRequest.Method = "POST";
        //Begin the Asynchrnous Request
        addRequest.BeginGetRequestStream(CallBackAddRequest,addRequest); 
    }
    catch (Exception ex)
    {
        HtmlPage.Window.Alert(ex.Message);
    }
}
 
void CallBackAddRequest(IAsyncResult ar)
{
    //Contains information of the Async object containing Request Information
    WebRequest req = (WebRequest)ar.AsyncState;
                        //Returns stream for writing data to the Web Resource
    Stream reqStream = req.EndGetRequestStream(ar);
    reqStream.Close();
 
    //Now Collect the response Asynchronously
    req.BeginGetResponse(CallBackResponse, req);  
}
//Response Callback, is mandatory to complete operations on the receiving end
void CallBackResponse(IAsyncResult ar)
{
    try
    {
        WebRequest req = (WebRequest)ar.AsyncState;
        //Collect the reponse
        WebResponse res = req.EndGetResponse(ar);
        Stream strResult = res.GetResponseStream();
 
        strResult.Close();
        res.Close();
    }
    catch (Exception ex)
    {
        string s = ex.Message;
    }
}
 
 
 
private void btnDelete_Click(object sender, RoutedEventArgs e)
{
    string delUrl = "http://localhost/RESTVDDML/Service.svc/DeleteEmployee/" + txteno.Text;
    //Create WebRequest Object
    WebRequest delRequest = WebRequest.Create(delUrl);
   delRequest.Method = "POST";
    //Make the Asynchronius Call
    delRequest.BeginGetRequestStream(CallBackDeleteRequest,delRequest); 
}
 
//The Async Delete CallBack
void CallBackDeleteRequest(IAsyncResult ar)
{
    //Contains information of the Async object containing Request Information
    WebRequest req = (WebRequest)ar.AsyncState;
    //Returns stream for writing data to the Web Resource
    Stream reqStream = req.EndGetRequestStream(ar);
    reqStream.Close();
 
    //Now Collect the response Asynchronously
    req.BeginGetResponse(CallBackResponse, req);  
}
 
VB.NET
Private Sub btnInsert_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
      Try
            Dim uploadUrl As String = "http://localhost/RESTVDDML/Service.svc/CreateEmployee/" & txteno.Text & "/" & txtename.Text & "/" & txtsal.Text & "/" & txtdno.Text
            Dim addRequest As WebRequest = WebRequest.Create(uploadUrl)
            addRequest.Method = "POST"
            'Begin the Asynchrnous Request
            addRequest.BeginGetRequestStream(AddressOf CallBackAddRequest,addRequest)
      Catch ex As Exception
            HtmlPage.Window.Alert(ex.Message)
      End Try
End Sub
 
Private Sub CallBackAddRequest(ByVal ar As IAsyncResult)
      'Contains information of the Async object containing Request Information
      Dim req As WebRequest = CType(ar.AsyncState, WebRequest)
                                    'Returns stream for writing data to the Web Resource
      Dim reqStream As Stream = req.EndGetRequestStream(ar)
      reqStream.Close()
 
      'Now Collect the response Asynchronously
      req.BeginGetResponse(AddressOf CallBackResponse, req)
End Sub
'Response Callback, is mandatory to complete operations on the receiving end
Private Sub CallBackResponse(ByVal ar As IAsyncResult)
      Try
            Dim req As WebRequest = CType(ar.AsyncState, WebRequest)
            'Collect the reponse
            Dim res As WebResponse = req.EndGetResponse(ar)
            Dim strResult As Stream = res.GetResponseStream()
 
            strResult.Close()
            res.Close()
      Catch ex As Exception
            Dim s As String = ex.Message
      End Try
End Sub
 
 
Private Sub btnDelete_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
      Dim delUrl As String = "http://localhost/RESTVDDML/Service.svc/DeleteEmployee/" & txteno.Text
      'Create WebRequest Object
      Dim delRequest As WebRequest = WebRequest.Create(delUrl)
   delRequest.Method = "POST"
      'Make the Asynchronius Call
      delRequest.BeginGetRequestStream(AddressOf CallBackDeleteRequest,delRequest)
End Sub
 
'The Async Delete CallBack
Private Sub CallBackDeleteRequest(ByVal ar As IAsyncResult)
      'Contains information of the Async object containing Request Information
      Dim req As WebRequest = CType(ar.AsyncState, WebRequest)
      'Returns stream for writing data to the Web Resource
      Dim reqStream As Stream = req.EndGetRequestStream(ar)
      reqStream.Close()
 
      'Now Collect the response Asynchronously
      req.BeginGetResponse(AddressOf CallBackResponse, req)
End Sub
 
The above code makes use of ‘WebRequest’ and ‘WebResponse’ classes and its asynchronous methods like:
·         BeginGetRequestStream
·         EndGetRequestStream - Returns data to be written to the internet resource.
·         BeginGetResponse
·         EndGetResponse - Returns the data from the internet.
The above ‘End’ methods indicate completion of Request and Response Operations to Web resources over internet. Remember without completing this Async, operation calls will not be completed.
Step 14: Now run the Silverlight application and click on ‘Get All’. You will get all the rows from the table displayed in a DataGrid. Similarly you can also test the Insert and Delete operations.
DataGrid
Enter Data in text boxes and press on ‘Insert’ button and then click on the ‘Get All’ button to see the newly added record. The newly added record is shown below (marked in RED).
NewRecords
The same way you can test ‘Delete’ too.
Conclusion: WCF REST has provided a mechanism for developing loosely coupled applications.    Using Silverlight 3.0 as a client, a light weight consumer of WCF REST service can be created without adding a proxy into the client application.
The entire source code of this article can be downloaded over here
If you liked the article,  Subscribe to the RSS Feed or Subscribe Via Email
Give a +1 to this article if you think it was well written. Thanks!
Recommended Articles


Page copy protected against web site content infringement by Copyscape


User Feedback
Comment posted by anil on Thursday, July 26, 2012 12:33 AM
Tell the same in using ASP.NET?
Comment posted by anil on Wednesday, August 1, 2012 7:13 AM
I have no idea about silverlight,
pls give me  perform DML operations Using ASP.NET webpages
Comment posted by Ajeeth on Sunday, August 11, 2013 3:27 AM
I hope this is not a proper way to choose the verbs and URI in REST. Whid do you use POST for GetEmployees?
Comment posted by Rudresh on Tuesday, June 24, 2014 11:38 AM
Superb article nice explained.please keep up the work.
thansks lot

Post your comment
Name:  
E-mail: (Will not be displayed)
Comment:
Insert Cancel