Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Consuming RESTFul service using .NET

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 770
    Comment on it

    Asp.net provides a client application call by making HTTP requests across the Web. Asp.net enables to create custom Web services or WCF services.Such type architectural style consuming services is called RESTful serviecs.

    RESTful service

    REST stands for Representational State Transfer. REST is an architectural style of huge networked software. REST concentrated data objects or resources, addressed and stressing the easy exchange of information.

    REST an architectural style to building distributed client applications and Resource-Oriented Architecture (ROA) . Resources are implement uniform interfaces using standard HTTP method as GET,POST,PUT, and DELETE. Uniform Resource Identifier (URI) to identify and located them.

    REST is not a particular technology or platform. Its simply a way to design a work. Architectural style of WCF Services is commonly known RESTful services.

    WCF Services

    1. Endpoints are each network protocol.
    2. Based on the Remote Procedural Call (RPC).
    3. Added service reference in the client applications.

    RESTFul Services

    1. By using HTTP request/response messages can be connect over Web .
    2. Based on the Remote Procedural Call (RPC).
    3. Without add the service reference in the client applications

    *Web Services AND WCF*

    Web Service

    A web service is a web-based functionality accessed using HTTP protocols across the web to be used by the web applications. A client application uses this service by calling Hypertext Transfer Protocol (HTTP) requests across the Web. Using Asp.net, we can create custom Web Services and call these services from any client applications. Web Services are platform independent programming language, they send and receive data using Simple Object Access Protocol (SOAP) messages.

    Simply we can understand webservices as :

    Webservices provide some functionality or developed program or services by internet using SOAP protocol. In this services client can add up( by calling these function or add references ) their developing program or project.

    WCF

    WCF stands for Windows Communication Foundation. WCF combined programming to implement , deployment service-oriented architecture (SOA). WCF concentrated computing have isolated consumers. Consume multiple services as well as services can be consumed by multiple clients.

    WCF simply work's same as webservices but In WCF communication is two sided here client can also send message to WCF services.

    Web Services V/s WCF Services

    1) Web services application are developed to send and receive messages using the Simple Object Access Protocol (SOAP) over HTTP. The structure of the messages can be defined using an XML Schema. To serialized the. NET Framework objects and the technology can automatically generate meta data to describe Web services in the Web Services Description Language (WSDL).

    But WCF services are developed to send and receive messing using many formats and conveyed any transport protocol. SOAP is used by default format. The structure of the messages can be defined using an XML Schema. There are various options for serializing the messages . WCF can automatically generate metadata to describe applications built using the technology in WSDL and it also provides generating clients for those applications from the WSDL. Sending messages using not only HTTP, but also used TCP, other network protocols. Switch message protocols with minimal effort. To support hosting services on Supporting to security, transactions , reliability, sending messages using different formats .

    2) Webservices is XmlSerializer. The XmlSerializer to translate data represented by .NET Framework types to XML for transmission or from a service and translate data received as XML into .NET Framework objects. Defined the complex data types an ASP.NET service. Use requires the definition of .NET Framework classes that theXmlSerializer to serialize and form XML.

    But WCF is DataContractSerializer. The DataContractAttribute is signify zero or more types fields or properties to be serialized. The theDataMemberAttribute to defined to a particular field or property to be serialize. The DataContractAttribute can be use to a class or structure. The DataMemberAttribute can be use to a field or a property. Data contracts in WCF are serialized into XML using DataContractSerializer.

    3) Webservices are less perfection as compare WCF DataContractSerializer.

    4) Webservice attributes to use the XmlSerializer do not defined which fields or properties of the type are serialized into XML. In wcf DataMemberAttribute for use with the DataContractSerializer shows explicitly which fields or properties are serialized. Therefore, data contracts are explicit contracts about the structure of the data that an application is to send and receive.

    5) Webservices XmlSerializer can only translate the public members of a .NET object into XML. But wcf DataContractSerializer can translate the members of objects into XML regardless of the access modifiers of those members.

    6) Webservices classes that implement the IDictionary interface, such as Hashtable, cannot be serialized into XML. But wcf can translate into XML types like Hashtable that implement the Idictionary interface.

    Simple RESTFul Service Creation

    First Step:

    Create a new WCF project using VisulStudio2013 .Naming project is RestfulExp.

    alt text

    Second Step:

    The existing Iservice1.cs & Service1.svc files delete first. Now create IRESTfullexp.cs & RESTfull.cs files.

    alt text

    Third Step:

    Separately created Student class in the Iservice.cs and write a simple member for this entity. Write code below:

     [DataContract]
       public class Student
      {
              [DataMember]
              public string ID;
    
              [DataMember]
              public string stdClass;
    
             [DataMember]
             public string Roll;
       }    
    

    Student class and its members decorated with [DataContract] & [DataMember] usingSystem.Runtime.Serialization namespace.

    [DataContract] Which can be DataContractSerializable over the network.

    [Datamember] [Datamember] property can be serializable & the class must be decorated with [DataContract] .

    Fourth Step:

    Create a interface IRESTfullexp and create some methods with [ServiceContract] and its members [OperationContract].Namespace should be System.ServiceModel.

      public interface IRestfullexp
        {
            [OperationContract]
            Student CreateStudent(Student createPerson);
    
            [OperationContract]
            List<student> GetAllStudent();
    
            [OperationContract]
            Student GetAStudent(string id);
    
            [OperationContract]
            Student UpdateStudent(string id, Student updateStudent);
    
            [OperationContract]
            void DeleteStudent(string id);
    
        }     
    

    [ServiceContract] - Service contract defined class or interface to the client applications. It contain one or more methods. Here these method defined [OperationContract].

    [OperationContract] - Method defines an operation that is part of a service contract in an application. Therefore only the method decorated with [OperationContract].And class of this method must be decorated with[ServiceContract].

    Fifth Step:

    The normal code RESTful services as WCF services. RESTful services works under HTTP protocol. WebGet and WebInvoke are important attributes. Include System.ServiceModel.Web namespace .

    Operation:

    Logical WebGet operation is receiving the information from a service operation and called by the REST programming . WebGet attribute is applied to a service operation in add OperationContract and associates the operation with a UriTemplate using the HTTP protocol Get.

    Logical WebInvoke operation raises a service option and called by the REST programming . The WebInvoke attribute is applied to a service operation in addition to the OperationContract and associates the operation with a UriTemplate as well as an underlying transport verb that represents an invocation where transport verb as HTTP POST,PUT, or DELETE. WebInvoke has a Method to allows specifying different types of HTTP methods as POST,PUT or DELETE.The default Method is POST.

    [ServiceContract] 
       public interface IRestfullexp
       {   
        //Posting operation  
         [OperationContract]
    
        [WebInvoke(UriTemplate = "", Method = "POST")]
    
        Student CreateStudent ( Student createStudent );
    
        //Getting Information  Operation
    
         [OperationContract]
         [WebGet(UriTemplate = "")]
    
        List GetAllStudent ();
    
        [OperationContract]
    
        [WebGet(UriTemplate = "{id}")]
    
        Person GetAStudent (string id);
    
       //update Operation
    
        [OperationContract]
    
        [WebInvoke(UriTemplate = "{id}", Method = "PUT")]
    
       Student UpdateStudent (string id, Student updateStudent );
    
       //Delete record Operation
    
        [OperationContract]
    
        [WebInvoke(UriTemplate = "{id}", Method = "DELETE")]
    
        void DeleteStudent (string id);
    
    
          }   
    The modified code for IRESTfullexp interface,WebGet & WebInvoke attributes decorates for methods available in the IRESTfullexp interface.
       Student CreateStudent(Student createStudent);
    
        //insert operation,  WebInvoke HTTP POST 
    
        List GetAllStudent ();
    
        Student GetAPerson(string id);
    
       // retrieve the information, WebGet (HTTP Get)
    
        Student UpdateStudent (string id, Student updateStudent );
    
        // updates the available information,  HTTP PUT 
    
        void DeleteStudent (string id);
    
        // deletes  WebInvoke HTTP DELETE 
    

    Sixth Step :

    The IRESTfullexp in the RESTfull class and complete the requirements. Code is following:

    public class RESTfull:IRESTfullexp
    
    {
        List student = new List();
    
        int studentCount = 0;
    
        public Student CreateStudent(Student createStudent)
    
        {
            createStudent.ID = (++studentCount).ToString();
    
            student.Add(createStudent);
    
            return createStudent;
    
        }
    
        public List  GetAllStudent()
    
    
    {
                return student.ToList();
    
    }
    
        public Student GetAStudent(string id)
    {
    
    return student.FirstOrDefault(e => e.ID.Equals(id));
    
    }
    
        public Student UpdatePerson(string id, Student updateStudent)
    {
           Student p = student.FirstOrDefault(e => e.ID.Equals(id));
    
           p.stdClass = updateStudent.stdClass;
    
            p.Roll = updateStudent.Roll;
    
            return p;
    
        }
    
        public void DeleteStudent(string id)
    
        {
            student.RemoveAll(e => e.ID.Equals(id));
    
        }
    
    
    }

    We can run also compatibility mode. Using AspNetCompatibilityRequirements attributes have RESTService class.

    [AspNetCompatibilityRequirements (RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]

    [ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]

        [AspNetCompatibilityRequirements
        (RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    

    [ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]

    public class RESTfull : IRestfullexp
    {
        //Put Code Part
       . . . . . .
    }

    RESTfull class added with ServiceBehavior attribute, This defined internal behavior of a service operation.

    Seventh Step :

    For host RESTFul service application need to be modification for running the RESTService. Insert the code in Web.Cogfig :

     
    
    < serviceHostingEnvironment aspNetCompatibilityEnabled="true" >
    < /serviceHostingEnvironment >
        < standardEndpoints >
          < webHttpEndpoint >
            < standardEndpoint name="" helpEnabled="true" 
            automaticFormatSelectionEnabled="true "> < /standardEndpoint  >
          <  /  webHttpEndpoint >
        < /  standardEndpoints >
      < /system.serviceMode l>
    
    

    Insert the code in Global.Cogfig :

        RouteTable.Routes.Add(new ServiceRoute
        ("RestService", new WebServiceHostFactory(), typeof(RESTSerivce)));   
    

    Eighth Step :

    Run it. Open in the explorer and address bar contain the base address of RESTFul service. As http://localhost:5678/ or http://localhost:XXXX/ etc

    The Routingprefix name RestService ,it dependent the global.asax file code .

    http://localhost:XXXX/RestService ( It is basically URI of the Get operation).

    http://localhost:XXXX/restservice/help It displays the help content for RestFulexp.

    Finish here creating and hosting the RESTFul services. To consume this RESTFulexp service next topic.

    alt text

    AddReference RESTFULL service (Consuming )

    Step 1

    Open new console application to RESTFulExp .Using language Visual C# or Visual Basic,.NET Framework , WCF Name ,RestfulExp

    Step 2

        do
    {
    try
    {
        string content;
    
        Console.WriteLine("Method name:");
    
        string Method = Console.ReadLine();
    
        Console.WriteLine("Enter Address:");
    
        string uri = Console.ReadLine();
    
        HttpWebRequest req = WebRequest.Create(uri) as HttpWebRequest;
    
        req.KeepAlive = false;
    
        req.Method = Method.ToUpper();
    
        if (("POST,PUT").Split(',').Contains(Method.ToUpper()))
    
        {
    
            Console.WriteLine("Write XML FilePath:");
    
            string FilePath = Console.ReadLine();
    
            content = (File.OpenText(@FilePath)).ReadToEnd();
    
    
            byte[] buffer = Encoding.ASCII.GetBytes(content);
    
            req.ContentLength = buffer.Length;
    
            req.ContentType = "text/xml";
    
            Stream PostData = req.GetRequestStream();
    
            PostData.Write(buffer, 0, buffer.Length);
    
            PostData.Close();
    
        }
    
        HttpWebResponse resp = req.GetResponse() as HttpWebResponse;
    
        Encoding enc = System.Text.Encoding.GetEncoding(1252);
    
        StreamReader loResponseStream = 
        new StreamReader(resp.GetResponseStream(), enc);
    
        string Response = loResponseStream.ReadToEnd();
    
        loResponseStream.Close();
    
        resp.Close();
    
        Console.WriteLine(Response);
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.Message.ToString());
    }
    
    Console.WriteLine();
    
    Console.WriteLine("Are you sure to continue?");
    
    
    } 
    while (Console.ReadLine().ToUpper() == "Y");
    

    Step 3

    Before running the RESTFulExp application, Fill address

    alt text

    After Fill address click Go. Then you find service name. Click Ok button . Your service successfully added.

    Enjoy you have added WCF REST Sevices in your Application. You can download doc file designed screen shot running program.

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: