Email: Password:       Forgot Password 
    .netCodeSG
A Saarsha Group Online Community for dot net codes group like C#, Asp.NET, VB.NET, Sharepoint, JavaScript, JQuery, Ajax, SQL, WCF, WPF.
 
TECHNOLOGIES:
 

Create and consume WCF Restful Service

Article:
Viewed:  1583 
Posted On:  21/10/2014 05:42:30 
What is REST in WCF? How we can create Restfull services in WCF? What is the benefit of REST? How to consume WCF Restfull services ?  

REST stands for Representational State Transfer. This is a protocol for exchanging data over a distributed environment. The main idea behind REST is that we should treat our distributed services as a resource and we should be able to use simple HTTP protocols to perform various operations on that resource.

When we talk about the Database as a resource we usually talk in terms of CRUD operations. i.e. Create, Retrieve, Update and Delete. Now the philosophy of REST is that for a remote resource all these operations should be possible and they should be possible using simple HTTP protocols.

Now the basic CRUD operations are mapped to the HTTP protocols in the following manner:

GET: Retrieve the required data (representation of data) from the remote resource.

POST: Update the current representation of the data on the remote server.

PUT: Insert new data.

DELETE: Delete the specified data from the remote server. 

Now we will learn this REST WCF service by creating an example. 

Here in this example I am going to show REST WCF Service by taking an Employee example. 

Now Open Visual Studio -> New -> Project -> Select WCF left Side -> Select WCF Service Application -> OK

1.png

Image 1.

Now delete IService.cs and Service.cs files.

2.png

Image 2.

Now Right click on Solution Explorer -> Add New Item -> Select WCF Service -> Name it as EmployeeService.

3.png

Image 3.

Now I am going to create a Data Contract as EmployeeDataContract . Right click on Solution Explorer -> Add New Item -> Add a .cs file and do below code:

4.png

Image 4.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Runtime.Serialization;
 
namespace REST_WCF_Service
{
    [DataContract]
    public class EmployeeDataContract
    {
        [DataMember]
        public string EmployeeID { getset; }
 
        [DataMember]
        public string Name { getset; }
 
        [DataMember]
        public string JoiningDate { getset; }
 
        [DataMember]
        public string CompanyName { getset; }
 
        [DataMember]
        public string Address { getset; }
    }
}
 
Now open IEmployeeService.cs to define Interface.

using
 System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
 
namespace REST_WCF_Service
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IEmployeeService" in both code and config file together.
    [ServiceContract]
    public interface IEmployeeService
    {
 
        [OperationContract]
        [WebGet(UriTemplate = "/GetEmployeeDetails/{EmpId}", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
        EmployeeDataContract GetEmployeeDetails(string EmpId);
 
        [OperationContract]
        [WebInvoke(UriTemplate = "/AddNewEmployee"
                          RequestFormat = 
WebMessageFormat.Json, 
                          ResponseFormat = 
WebMessageFormat.Json, 
                          Method =
POST")]
        bool AddNewEmployee(EmployeeDataContract emp);
 
        [OperationContract]
        [WebInvoke(Method = "PUT", ResponseFormat = WebMessageFormat.Json)]
        void UpdateEmployee(EmployeeDataContract contact);
 
        [OperationContract]
        [WebInvoke(Method = "DELETE"
                          RequestFormat = 
WebMessageFormat.Json, 
                          ResponseFormat = 
WebMessageFormat.Json,
                          UriTemplate =
DeleteEmployee/{EmpId}")]
        void DeleteEmployee(string EmpId);
    }
}
 
Now Open EmployeeService.cs 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.Xml.Linq;
 
namespace REST_WCF_Service
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "EmployeeService" in code, svc and config file together.
    // NOTE: In order to launch WCF Test Client for testing this service, please select EmployeeService.svc or EmployeeService.svc.cs at the Solution Explorer
and start debugging.
    public class EmployeeService : IEmployeeService
    {
        public EmployeeDataContract GetEmployeeDetails(string EmpId)
        {
            EmployeeDataContract emp = new EmployeeDataContract();
 
            try
            {
                XDocument doc = XDocument.Load("H:\\EmployeeData.xml");
 
                IEnumerable<XElement> employee =
                    (from result in doc.Descendants("DocumentElement").Descendants("Employees")
                     where result.Element("EmployeeID").Value == EmpId.ToString()
                     select result);
 
                emp.EmployeeID = employee.ElementAt(0).Element("EmployeeID").Value;
                emp.Name = employee.ElementAt(0).Element("Name").Value;
                emp.JoiningDate = employee.ElementAt(0).Element("JoiningDate").Value;
                emp.CompanyName = employee.ElementAt(0).Element("CompanyName").Value;
                emp.Address = employee.ElementAt(0).Element("Address").Value;
            }
            catch (Exception ex)
            {
                throw new FaultException<string>
                        (ex.Message);
            }
            return emp;
        }
 
        public bool AddNewEmployee(EmployeeDataContract employee)
        {
            try
            {
                XDocument doc = XDocument.Load("H:\\EmployeeData.xml");
 
                doc.Element("DocumentElement").Add(
                        new XElement("Employees",
                        new XElement("EmployeeID", employee.EmployeeID),
                        new XElement("Name", employee.Name),
                        new XElement("JoiningDate", employee.JoiningDate),
                        new XElement("CompanyName", employee.CompanyName),
                        new XElement("Address", employee.Address)));
 
                doc.Save("H:\\EmployeeData.xml");
            }
            catch (Exception ex)
            {
                throw new FaultException<string>
                        (ex.Message);
            }
            return true;
        }
 
        public void UpdateEmployee (EmployeeDataContract employee)
        {
            try
            {
                XDocument doc = XDocument.Load("H:\\EmployeeData.xml");
                var target = doc
                     .Element("DocumentElement")
                     .Elements("Employees")
                     .Where(e => e.Element("EmployeeID").Value == employee.EmployeeID)
                     .Single();
 
                target.Element("Name").Value = employee.Name;
                target.Element("JoiningDate").Value = employee.JoiningDate;
                target.Element("CompanyName").Value = employee.CompanyName;
                target.Element("Address").Value = employee.Address;
 
                doc.Save("H:\\EmployeeData.xml");
            }
            catch (Exception ex)
            {
                throw new FaultException<string>
                        (ex.Message);
            }
        }
 
        public void DeleteEmployee(string EmpId)
        {
            try
            {
                XDocument doc = XDocument.Load("H:\\EmployeeData.xml");
                foreach (var result in doc.Descendants("DocumentElement").Descendants("Employees"))
                {
                    if (result.Element("EmployeeID").Value == EmpId.ToString())
                    {
                        result.Remove();
                        break;
                    }
                }
                doc.Save("H:\\EmployeeData.xml");
            }
            catch (Exception ex)
            {
                throw new FaultException<string>
                        (ex.Message);
            }
        }
    }
}


Now do the below changes in your web.config file to enable REST WCF:


<system.serviceModel>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true"
      multipleSiteBindingsEnabled="true" />
    <services>
      <service name="REST_WCF_Service.EmployeeService">
        <endpoint address="" behaviorConfiguration="REST_WCF_Service.EmployeeServiceAspNetAjaxBehavior"
          binding="webHttpBinding" contract="REST_WCF_Service.IEmployeeService" />
      </service>
    </services>
    <behaviors>
      <endpointBehaviors>
        <behavior name="REST_WCF_Service.EmployeeServiceAspNetAjaxBehavior">
          <webHttp/>
        </behavior>
      </endpointBehaviors>
    </behaviors>
  </system.serviceModel>


Now create a new Project (WindowForm) to consume this REST WCF service. Here I am going to use a WPF application.

<
Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="Consume WCF REST To Perform CRUD Operations" Height="471" Width="625">
    <Grid Margin="0,0,-67,-31">
        <Grid.ColumnDefinitions>
            <ColumnDefinition/>
            <ColumnDefinition Width="37*"/>
        </Grid.ColumnDefinitions>
        <Label Content="Employee Id" HorizontalAlignment="Left" Margin="36,36,0,0" VerticalAlignment="Top" Width="120" Grid.Column="1"/>
        <TextBox HorizontalAlignment="Left" Height="23" Margin="187,36,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="120" Grid.Column="1"
ame="txtEmpId"/>
        <Button Content="Click To View Employee Detail" HorizontalAlignment="Left" Margin="329,36,0,0" VerticalAlignment="Top" Width="194" Grid.Column="1"
lick="btn_ViewEmployeeDetail"/>
        <Label Content="Employee ID" HorizontalAlignment="Left" Margin="35.632,87,0,0" VerticalAlignment="Top" Grid.Column="1"/>
        <Label Content="Name" HorizontalAlignment="Left" Margin="35.632,135,0,0" VerticalAlignment="Top" Grid.Column="1"/>
        <Label Content="Joining Date" HorizontalAlignment="Left" Margin="35.632,191,0,0" VerticalAlignment="Top" Grid.Column="1"/>
        <Label Content="Company Name" HorizontalAlignment="Left" Margin="35.632,239,0,0" VerticalAlignment="Top" Grid.Column="1"/>
        <Label Content="Address" HorizontalAlignment="Left" Margin="35.632,290,0,0" VerticalAlignment="Top" Grid.Column="1"/>
        <TextBox HorizontalAlignment="Left" Height="23" Margin="187,87,0,0" TextWrapping="Wrap"  VerticalAlignment="Top" Width="120" Grid.Column="1"
ame="txtShowEmpId"/>
        <TextBox HorizontalAlignment="Left" Height="23" Margin="187,135,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="187" Grid.Column="1"
ame="txtShowEmpName"/>
        <TextBox HorizontalAlignment="Left" Height="23" Margin="187,195,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="187" Grid.Column="1"
ame="txtShowEmpJoiningDate"/>
        <TextBox HorizontalAlignment="Left" Height="23" Margin="187,243,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="187" Grid.Column="1"
ame="txtShowCompany"/>
        <TextBox HorizontalAlignment="Left" Height="44" Margin="187,290,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="187" Grid.Column="1"
ame="txtShowAddress"/>
        <Button Content="Add New Employee" Grid.Column="1" HorizontalAlignment="Left" Margin="50,379,0,0" VerticalAlignment="Top" Width="120"
eight="48" Click="btn_AddnewEmployee"/>
        <Button Content="Update Employee" Grid.Column="1" HorizontalAlignment="Left" Margin="205,379,0,0" VerticalAlignment="Top" Width="120"
eight="48" Click="btn_UpdateEmployee"/>
        <Button Content="Delete Employee" Grid.Column="1" HorizontalAlignment="Left" Margin="361,379,0,0" VerticalAlignment="Top" Width="120"
eight="48" Click="btn_DeleteEmployee"/>
 
    </Grid>
</Window>
 
Run the Application and perform CRUD operation by consuming REST WCF.

5.png

Image 5.

Code to perform above operations is:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.Net;
using System.IO;
using REST_WCF_Service;
 
namespace WPF_ClientApplication
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
 
        private void btn_AddnewEmployee(object sender, RoutedEventArgs e)
        {
            EmployeeDataContract employee = new EmployeeDataContract
            {
                EmployeeID = txtShowEmpId.Text,
                Name = txtShowEmpName.Text,
                JoiningDate = txtShowEmpJoiningDate.Text,
                CompanyName = txtShowCompany.Text,
                Address = txtShowAddress.Text
            };
 
            DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(EmployeeDataContract));
            MemoryStream mem = new MemoryStream();
            ser.WriteObject(mem, employee);
            string data = Encoding.UTF8.GetString(mem.ToArray(), 0, (int)mem.Length);
            WebClient webClient = new WebClient();
            webClient.Headers["Content-type"] = "application/json";
            webClient.Encoding = Encoding.UTF8;
            webClient.UploadString("http://localhost:23610/EmployeeService.svc/AddNewEmployee""POST", data);
            MessageBox.Show("Employee Saved Successfully..."); 

            txtShowEmpId.Text = "";
            txtShowEmpName.Text = "";
            txtShowEmpJoiningDate.Text = "";
            txtShowCompany.Text = "";
            txtShowAddress.Text = "";
        }
 
        private void btn_ViewEmployeeDetail(object sender, RoutedEventArgs e)
        {
            WebClient proxy = new WebClient();
            string serviceURL = string.Format("http://localhost:23610/EmployeeService.svc/GetEmployeeDetails/{0}", txtEmpId.Text);
            byte[] data = proxy.DownloadData(serviceURL);
            Stream stream = new MemoryStream(data);
            DataContractJsonSerializer obj = new DataContractJsonSerializer(typeof(EmployeeDataContract));
            EmployeeDataContract employee = obj.ReadObject(stream) as EmployeeDataContract;
            txtShowEmpId.Text = employee.EmployeeID;
            txtShowEmpName.Text = employee.Name;
            txtShowEmpJoiningDate.Text = employee.JoiningDate;
            txtShowCompany.Text = employee.CompanyName;
            txtShowAddress.Text = employee.Address;
        }
 
        private void btn_UpdateEmployee(object sender, RoutedEventArgs e)
        {
            EmployeeDataContract employeeContact = new EmployeeDataContract
            {
                EmployeeID = txtShowEmpId.Text,
                Name = txtShowEmpName.Text,
                JoiningDate = txtShowEmpJoiningDate.Text,
                CompanyName = txtShowCompany.Text,
                Address = txtShowAddress.Text
            };
 
            WebClient client = new WebClient();
            client.Headers["Content-type"] = "application/json";
 
            MemoryStream ms = new MemoryStream();
            DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(EmployeeDataContract));
            ser.WriteObject(ms, employeeContact);
 
            // invoke the REST method
            client.UploadData("http://localhost:23610/EmployeeService.svc/UpdateEmployee""PUT", ms.ToArray());
 
            MessageBox.Show("Employee updated Successfully...");
 
            txtShowEmpId.Text = "";
            txtShowEmpName.Text = "";
            txtShowEmpJoiningDate.Text = "";
            txtShowCompany.Text = "";
            txtShowAddress.Text = "";
 
        }
 
        private void btn_DeleteEmployee(object sender, RoutedEventArgs e)
        {
            WebClient client = new WebClient();
            client.Headers["Content-type"] = "application/json";
 
            MemoryStream ms = new MemoryStream();
            DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(string));
            ser.WriteObject(ms, txtEmpId.Text);
 
            // invoke the REST method
            byte[] data = client.UploadData("http://localhost:23610/EmployeeService.svc/DeleteEmployee""DELETE", ms.ToArray());
 
            MessageBox.Show("Employee deleted Successfully...");
 
            txtShowEmpId.Text = "";
            txtShowEmpName.Text = "";
            txtShowEmpJoiningDate.Text = "";
            txtShowCompany.Text = "";
            txtShowAddress.Text = "";
        }
    }
}

Below is my XML:

6.png

Image 6.

  Comment:
         HOME   |   Submit Article   |   Contact Us   |   About Us   |   Terms & Condition   |   Advertise With us