27 March 2014

REST-ful Service Example

     This sample explains about the creating the RESTful service to create and updating the resource information available at the sever side. This Restful service will be consumed using client console application.

This sample explains about the creating the RESTful service to create and updating the resource information available at the sever side. This Restful service will be consumed using client console application.

Step 1: For our example we are suing “Employee Data” class as Data Access Layer for storing and reading the employee information.

Data Model class:
Namespace MyFirstRESTfulService
{
    [Data Contract]
    Public class Employee
    {
        [Data Member]
        Public int EmpId {get; set ;}
        [Data Member]
        Public string Fname {gets; set ;}
        [Data Member]
        Public string L name {get; set ;}
        [Data Member]
        Public DateTime Join Date {get; set ;}
        [Data Member]
        Public int Age { get; set; }
        [Data Member]
        Public int Salary {get; set; }
        [Data Member]
        Public string Designation {gets; set ;}
    }
Public partial class EmployeeData
    {
      Private static readonly EmployeeData _instance = new EmployeeData();
      Private EmployeeData () { }
      Public static EmployeeData Instance
      {
       Get
        {
          Return _instance;
         }
      }
Private List< Employee> empList = new List < Employee> ()
  {
    new Employee() { EmpId  = 1, Fname = "Sam", Lname = "kumar",   JoinDate=new DateTime(2010,7, 21), Age=30,Salary=10000,Designation="Software Engineer"},     
    new Employee() { EmpId = 2, Fname = "Ram", Lname = "kumar", JoinDate=new DateTime(2009,6,8), Age=35,Salary=10000,Designation="Senior Software Engineer"},     
    new Employee() { EmpId = 3, Fname = "Sasi", Lname = "M", JoinDate=new DateTime(2008,3,5), Age=39,Salary=10000,Designation="Projet Manager"},      
    new Employee() { EmpId = 4, Fname = "Praveen", Lname = "KR", JoinDate=new DateTime(2010, 5,1), Age=56,Salary=10000,Designation="Projet Manager"},    
     new Employee() { EmpId = 5, Fname = "Sathish", Lname = "V", Join Date = new DateTime(2006,12,15), Age=72,Salary=10000,Designation="Senior Software Engineer"},     
     new Employee() { EmpId = 6, Fname = "Rosh", L-name = "A", Join Date=new DateTime(2009,2,2), Age=25,Salary=10000,Designation="Software Engineer"} 
    };
Public List< Employee> EmployeeList
  {
    get
      {
        return empList;
      }
   }
Public void Update(Employee updEmployee)
  {
    Employee existing = empList.Find(p => p.EmpId == updEmployee.EmpId);
    if (existing == null)
    throw new KeyNotFoundException("Specified Employee cannot be found");
    existing.Fname = updEmployee.Fname;
    existing.Lname = updEmployee.Lname;
    existing.Age = updEmployee.Age;
   }
 
   Public void Delete(int empid)
        {
            Employee existing = empList.Find(p => p.EmpId == empid);
            empList.Remove(existing);
        }
   Public void Add(Employee new Employee)
        {
            empList.Add(new Employee
            {
                EmpId = newEmployee.EmpId,
                Fname = newEmployee.Fname,
                Lname = newEmployee.Lname,
                Age = newEmployee.Age,
                JoinDate = DateTime.Now,
                Designation = newEmployee.Designation,
                Salary = newEmployee.Salary
            });
        }
    }
} 


Step 2: Let’s start create Employee Service (simple WCF) with Service Contract, Operation Contract and Data Contract as shown below.

Interface and Implementation:

    [Service Contract ()]
    Public interface IEmployeeService
    {
        [Operation Contract]
        List< Employee > GetAllEmployeeDetails ();
 
        [Operation Contract]
        Employee Get Employee (int Id);
               
        [Operation Contract]
        Void Add Employee (Employee newEmp);
        
        [Operation Contract]
        Void UpdateEmployee (Employee newEmp);
        
        [Operation Contract]
        Void DeleteEmployee (string empId);
    }
 
     [AspNetCompatibilityRequirements (Requirements Mode= AspNetCompatibilityRequirementsMode.Allowed)]
   Public class EmployeeService: IEmployeeService 
    {        
       Public List < Employee > GetAllEmployeeDetails ()
        {
            Return EmployeeData.Instance.EmployeeList;
        }      
        Public Employee Get Employee (int id)
        {
            IEnumerable< Employee > empList = EmployeeData.Instance.EmployeeList. Where(x => x.EmpId == id);
            if (empList != null)
                Return empList.First< Employee >();
            Else
                Return null;
        }     
       Public void Add Employee (Employee newEmp)
       {
           EmployeeData.Instance.Add (newEmp);
       }       
        Public void UpdateEmployee (Employee newEmp)
        {
            EmployeeData.Instance.Update (newEmp);
        }      
         Public void DeleteEmployee (string empId)
        {
            EmployeeData.Instance.Delete (System. Convert .ToInt32 (empId));
        }
    }

Step2: This service can be hosted as normal WCF service by creating the ServiceHost object and adding endpoint with different binding. This is already explained in “Consoled Hosted WCF Service”.
As it is mention in introduction section of RESTful service, all the resource located in server side can be accessed using url. Method exposed at the server side can be call using url, to do that we need to decorate the service method with “Web Get” or “Web Invoke” attribute as mention below

[Service Contract ()]
    Public interface IEmployeeService
    {
        [WebGet (UriTemplate = "Employee")]
        [Operation Contract]
        List< Employee > GetAllEmployeeDetails ();
 
        [WebGet (UriTemplate = "Employee?id={id}")]
        [Operation Contract]
        Employee GetEmployee (int Id);
 
        [WebInvoke (Method = "POST", UriTemplate = "EmployeePOST")]
        [Operation Contract]
        Void AddEmployee(Employee newEmp);
 
        [WebInvoke (Method = "PUT", UriTemplate = "EmployeePUT")]
        [Operation Contract]
        Void UpdateEmployee(Employee newEmp);
 
        [WebInvoke (Method = "DELETE", UriTemplate = "Employee/{empId}")]
        [Operation Contract]
        Void DeleteEmployee(string empId);
    }

Step4: In the above interface declaration, you can find that we have added UriTemplate”, it is
nothing but a relative path for accessing the service method using url. These methods can be called from client application or browser by typing url as “WCf
Service url” + “Relative Path” E.g: http://localhost:8090/MyService/EmployeeService/Employee 

Step 5:Method” is another option we can add to the WebInvoke attribute to specify the mode 
of transfer like “PUT”, “POST”, or “DELETE” 

Step 6: Now we have completed with service implementation project. Let’s start with Hosting the RESTful service.

For this example we are using console application for hosting service. 

WCF framework has provided new class to host  the RESTful service i.e WebServiceHost.
By hosting the restful service with WebServiceHost host class will automatically set the binding and other configuration setting.

In the below code you can see that I have only mention url for the hosting. 

Uri httpUrl = new Uri ("http://localhost:8090/MyService/EmployeeService");
WebServiceHost host = new   WebServiceHost (typeof (MyFirstRESTfulService.EmployeeService), httpUrl);
host.Open ();            
For each (Service Endpoint se in host.Description.Endpoints)
Console.WriteLine ("Service is host with endpoint” + se.Address);
//Console.WriteLine ("ASP.Net: " + ServiceHostingEnvironment.AspNetCompatibilityEnabled);
Console.WriteLine ("Host is running... Press < Enter > key to stop");
Console.ReadLine ();


Step 7: We can access the RESTful service using browser. Just type the url in the web browser to read all the employee details



If we need to get specific employee details, pass the employee as query parameter as we mention in UriTemplate of the service.


 Step 8:Now we can start with client application. For this example we can create a console application
to read the employee information and add new employee to the server resource. Below code first read the employee details from the server and add new employee and once again it read the employee details to confirm the added resource.
 WebChannelFactory < IEmployeeService > cf =
         new WebChannelFactory< IEmployeeService >(
         new Uri("http://localhost:8090/MyService/EmployeeService"));
         IEmployeeService client = cf.CreateChannel ();
         var d = client. GetEmployee (1);
         //Load all the Employee from the server and display
        for each (Employee e in   client.GetAllEmployeeDetails() )
         {
        Console.WriteLine(string.Format("EmpID:{0}, Name:{1} {2}",e.EmpId ,e.Fname ,e.Lname ));
        }
         //Add new user
  Client. AddEmployee (new Employee () {EmpId = 11, Fname = "John", Lname = "J", Join Date = new DateTime (2010, 7, 24), Age = 34, Salary = 10000, Designation = "Software Engineer”});
        
   Console.WriteLine ("******************After adding new user ****************");
   //Load all the Employee from the server and display
   for each (Employee e in   client.GetAllEmployeeDetails() )
  {
   Console.WriteLine(string.Format("EmpID:{0}, Name:{1} {2}",e.EmpId ,e.Fname ,e.Lname ));
    }
      Console.ReadLine();
 } 


Step 9: Run the application to view the output as shown below




No comments:

Post a Comment