Tuesday, February 19, 2013

Web Services and standard web protocols

Web Services and standard web protocols

Web services gain more popularity from last few years in developers and companies. So there are good reasons to understand internals of Web Services.


What are Web Services?
 
Web Service is an application designed to directly interact with other applications all over the world on internet. It describes a standardized way of integrating web based applications. Web services allow different applications from different sources to communicate with each other.
 
Web Services provides an important way for business to communicate with clients and with each other. It provides business logic processes and data through a programmatic interface instead of any traditional user interface. User interface is then added to this application interface to provide specific functionality to users. The basic purpose of Web Service is to provide some functionality from the owner to its clients so that they can use it.
Web Services publish their methods to the world and these methods, when invoked, perform some actions and provide some data in result. Web services sometimes called Application Services.
 
Independent of Operating System and Language
 
Web Services are XML based applications that use XML to communicate with other applications so Web Services are independent of Operating System and Programming Language.  An application using a Web Service is not concerned about the operating system or programming language of that Web Service as all communication is in XML. For example, A Web Service created in Java can be used by an application created in Visual Basic or Windows application can be called by a UNIX application.
 
 
Web Services Protocols
 
Web services use XML based web protocols that include HTTP, XML, SOAP, WSDL and UDDI. XML is used to tag the data, SOAP is used to transfer data, WSDL is used to describe available Web Services and UDDI is used to list the available Web Services.
 
HTTP
 
Hypertext Transfer Protocol (HTTP) is the standardized protocol of communication on the internet by the World Wide Web Consortium (W3C). It is responsible for requesting and transmitting data over the internet. It provides safe recognition of network web server and encrypted communication.
 
XML
 
Extensible Markup Language (XML) is the markup language that is designed to transport and store data in a format that is readable by both human and machine. It enables the transmission, validation and interpretation of data between applications. . XML is used to tag, format and display the data. It allows developers to create their own customized tags. It mainly designed for documents but it is extensively used in Web Services. It is the most common markup language in which the information is written.
 
SOAP
 
Simple Object Access Protocol (SOAP) is the XML based protocol to transfer the data in Web Services. It is the language and platform independent protocol that allows applications in Web Services to communicate via standard internet HTTP. It is the center piece of Web Services and complements all other protocols (XML, WSDL and UDDI). In a simple way, we can say that SOAP is the way in which web services method calls are translate into XML format and sent via HTTP and it allows applications to exchange information over HTTP. SOAP is standardized and recommended by W3C.
 
WSDL
 
Web Services Description language (WSDL) is a standard format to describe and locate web services. It is the XML based language that UDDI uses for Web Services. Every client application that is connected to Web Service can read the WSDL to determine what functions are available on the Web Service. Any special data types are embedded in the WSDL. URL from which Web Service methods can be accessed and communication protocols used by web services are also in the WSDL file. So it contains every detail to allow users to build client applications to use Web Services. WSDL is the W3C recommendation.
 
UDDI
 
Universal Description, Discovery and Integration (UDDI) is the web based directory or registry for listing web services. It enables businesses to list themselves on the internet and discover each other. It allows clients to find Web Services to use them. It is a public library where we can publish Web Services and inquire about Web Services. UDDI includes several ways to find Web Services that client needs to built their application.
 
UDDI registry manages information about service providers and service implementations. Service providers can use UDDI to publicize web services they offer and service clients can use UDDI to discover Web Services according to their requirements. UDDI is based on XML and SOAP standards.
 
 
Criticism on Web Services
 
Web services are often criticized because of security issues. It is the application to application interaction instead of human-application interaction. Issues like authentication, privacy and data integrity are main concerns when using Web Services. Another criticism on Web Services is the complexity in Web Services.
 
 
Benefits of Web Services
 
Although there are some criticisms on Web services but benefits of Web Services have overpowered these criticisms. The communication between applications is easier with Web Services. Information distribution to different clients and consumers is relatively simple task for companies. Web services can be reused when needed and from the past few years there is rapid development in Web Services. 
 
SOAP is a standard for exchanging XML-based messages over a computer network, normally using HTTP.
Purpose of using SOAP:
For many Web services, you need only a combination of XML, HTTP, and an application-specific message protocol. To be sure, SOAP has its uses. But, in my opinion, SOAP’s role is overstated in the early stages of a Web service’s development. Using SOAP for the wrong tasks can easily hijack a Web service development project, because SOAP introduces a large set of problems that are orthogonal to the challenges of building a Web service. SOAP-related issues tend to consume the majority of the development effort.

The most common purpose of Web services today is to exchange XML data. For instance, more than 200 Web services listed on XMethods share that purpose. The classic examples of a stock quote service, weather service, or postal code lookup service are all about sending an XML query message, and receiving an XML reply. That pattern dominates more complex Web services as well: the UDDI registry service or the Liberty Alliance single sign-on and identity federation Web services are all defined in terms of XML-based query-response message exchanges.

At best, SOAP introduces a level of indirection to such XML message exchanges by embedding an XML message in a SOAP envelope. Since the SOAP envelope can carry metadata about the original XML message, such as processing instructions, the envelope can aid a Web service in processing that message. At worst, SOAP makes it difficult, if not impossible, to verify the validity of an XML message traversing between two Web services.
Example:
Here is an example of how a client might format a SOAP message requesting product information from a fictional warehouse web service. The client needs to know which product corresponds with the ID DEVASP123:

<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
   <soap:Body>
     <getProductDetails xmlns="http://warehouse.example.com/ws">
       <productID> DEVASP123</productID>
     </getProductDetails>
   </soap:Body>
 </soap:Envelope> 

Here is how the warehouse web service might format its reply message with the requested product information:

<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
   <soap:Body>
     <getProductDetailsResponse xmlns="http://warehouse.example.com/ws">
       <getProductDetailsResult>
         <productName>Toptimate 3-Piece Set</productName>
         <productID> DEVASP123</productID>
         <description>3-Piece luggage set. Black Polyester.</description>
         <price>96.50</price>
         <inStock>true</inStock>
       </getProductDetailsResult>
     </getProductDetailsResponse>
   </soap:Body>
 </soap:Envelope>


How to create and use a Web Service in ASP.NET Visual Studio 2010
 
What is Web Service?
Web Service is an application that is designed to interact with other applications on the internet. Web Services allow a server to expose its functionality that clients can utilize. Web services can publish their methods or messages to the world and these methods, when invoked, perform some action and return some data or result.
Web services allow different applications from different sources to communicate with each other. As all communication in a web service is in XML so it is independent of language, platform and protocol.
 
Create a Web Service

To create a web service in visual studio 2010, follow these steps:
  1. Open New Project
  2. Select .NET Framework 3.5
  3. Select ASP.NET Web Service Application in web either in Visual C# or in Visual Basic
  4. A HelloWorld web method is already in the Service1 class. Write another web method in class Service1 as below

    C#

    [WebMethod]
    public int AddNumbers(int firstNum, int secondNum) {
                int thirdnum = firstNum + secondNum;
                return thirdnum;
     }
     
    VB.NET

    <WebMethod()> _
    Public Function AddNumbers(ByVal firstNum As Integer, ByVal secondNum As Integer)   As Integer
                Dim thirdnum As Integer = firstNum + secondNum
                Return thirdnum
    End Function
     
  5. See web service in browser and copy the URL to add reference of the service when you have to use the service. Select Web Method to see result in XML.

Use Web Service
 
When a web service is created the next step is to use this service. It is also called consuming the Web Service.
 
To use a web service, follow these steps in visual studio 2010:
 
  1. Open New Web Site
  2. Select .NET Framework 3.5
  3. Create an ASP.NET Empty Website either in Visual Basic or Visual C#
  4. Right click on the Website in Solution Explorer
  5. Select Add Service Reference
  6. Select Advanced option in Add Service Reference window
  7. Select Add Web Reference in Service Reference Settings
  8. Enter the copied URL in Add Web Reference window
  9. Change the Web reference name and click Add Reference
  10. Import namespace for the Web Service

    C#
     
    using WebServiceTest;
     
    VB.NET

    Imports WebServiceTest
     
  11. Now drag and drop two labels in aspx page and write below code in Page_Load method of code behind file. Create the instance of the Service1 class and call the method of that class.

    <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>

    <br />

     
    <asp:Label ID="Label2" runat="server" Text="Label"></asp:Label>

     


  12.  
  13. Write below code in Page_Load method of code behind file. Create the instance of the Service1 class and call the method of that class.

    C#

    Service1 service = new Service1();
    Label1.Text = service.HelloWorld();
    int num = service.AddNumbers(3, 4);
    Label2.Text = "The result is: " + num.ToString();

    VB.NET

    Dim service As New Service1()
    Label1.Text = service.HelloWorld()
    Dim num As Integer = service.AddNumbers(3, 4)
    Label2.Text = "The result is: " & num.ToString()
     
  14. View website in browser, you will see the result of both web methods of Web Service
A web Service created in any ASP.NET language can be consumed in application written in any other ASP.NET language.

How to bind data to Web Service and use this Web Service in ASP.NET


Web Services are created to bind data because these are used by consumers to work with data. You can see articles on DevASP.NET about Web Services. In this article, I will show you simple example of data binding to web service. This data binding procedure can be complex but this example is just for learning purposes.
Follow below steps to create a web service and bind data to it.
  1. Create New Web Site in Visual Studio 2010
  2. Select .NET Framework 3.5
  3. Select ASP.NET Web Service either in Visual C# or in Visual Basic
  4. Add a Class and rename it as ProductsClass
  5. Import namespaces in ProductsCass
    C#
     
    using System.Data;
    using System.Data.SqlClient;
     
    VB.NET
     
    Imports System.Data
    Imports System.Data.SqlClient
     
     
  6. Write below function in ProductsClass to get data
     
    C#
     
    public static DataSet ProductsData() {
        string sqlQuery = "Select * From Products";
        string connString = "Data Source=Local;Initial Catalog=NORTHWND;Integrated Security=True";
        SqlConnection connection = new SqlConnection(connString);
        SqlCommand command = new SqlCommand(sqlQuery, connection);
        SqlDataAdapter da = new SqlDataAdapter(command);
        DataSet ds = new DataSet();
        da.Fill(ds);
        return ds;
    }
     
    VB.NET
     
    Public Shared Function ProductsData() As DataSet
        Dim sqlQuery As String = "Select * From Products"
        Dim connString As String = "Data Source=Local;Initial Catalog=NORTHWND;Integrated Security=True"
        Dim connection As New SqlConnection(connString)
        Dim command As New SqlCommand(sqlQuery, connection)
        Dim da As New SqlDataAdapter(command)
        Dim ds As New DataSet()
        da.Fill(ds)
        Return ds
    End Function
     
    As you can see I have used Products table of NORTHWIND database. This function returns DataSet. I have written a query and set connection to my Server. Then I have created a SqlCommand object by passing query and connection as parameters. Then I have created a SqlDataAdapter object, a DataSet object and fill DataSet object with SqlDataAdapter object.
     
  7. Open Service.cs file and import namespace
     
    C#
    using System.Data;
     
    VB.NET

    Imports System.Data
     
  8. Now write below function in Service.cs file
     
    C#
     
    [WebMethod]
    public DataSet GetProducts() {
        DataSet ds = ProductsClass.ProductsData();
        return ds;
    }
     
    VB.NET
     
    <WebMethod()> _
    Public Function GetProducts() As DataSet
        Dim ds As DataSet = ProductsClass.ProductsData()
        Return ds
    End Function
     
    This function in our Web Service code file returns DataSet. I have created a DataSet object and assigned the data of ProducsData() function of ProductsClass. We will call this method to get data in our consumer web site.
     
  9. See this Web Service in browser and copy the URL of Web Service. We need this URL for service reference to consume this Web Service.
 Now follow below steps to consume this Web Service and get data from this Web Service function.
  1. Open New Web Site
  2. Create an ASP.NET Empty Website either in Visual Basic or Visual C#
  3. Right click on the Website in Solution Explorer
  4. Select Add Service Reference
  5. Select Advanced option in Add Service Reference window
  6. Select Add Web Reference in Service Reference Settings
  7. Enter the copied URL in Add Web Reference window
  8. Change the Web reference name as DataBindWebService and click Add Reference
  9. Import namespace for the Web Service
    C#
     
    using DataBindWebService;
     
    VB.NET
     
    Imports DataBindWebService
     
  10. Drag and Drop a GridView in aspx page
     
     
    <asp:GridView ID="GridView1" runat="server">
     
    </asp:GridView>
     
  11. Write below code in Page_Load method of code behind file
     
    C#

    protected void Page_Load(object sender, EventArgs e) {
        Service service = new Service();
        GridView1.DataSource = service.GetProducts();
        GridView1.DataBind();
    }
     
    VB.NET

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Dim service As New Service
        GridView1.DataSource = service.GetProducts()
        GridView1.DataBind()
    End Sub
     
    Create a new instance of Web Service and call the GetProducts() method. Bind the data to GridView.
     
  12. View website in browser, you will see the result of data bound Web Service method.
 

 

1 comment:

  1. Hi there, awesome site. I thought the topics you posted on were very interesting. I tried to add your RSS to my feed reader and it a few. take a look at it, hopefully I can add you and follow.

    MCX Brokerage

    ReplyDelete