Friday 16 November 2012

Web services Example

This article will explain you everything about Web Services in .Net, so lets get started with Web Service

What is Web Service?
  • Web Service is an application that is designed to interact directly with other applications over the internet. In simple sense, Web Services are means for interacting with objects over the Internet.
  • Web Service is
    • Language Independent
    • Protocol Independent
    • Platform Independent
    • It assumes a stateless service architecture.
  • We will discuss more on web service as the article proceed. Before that lets understand bit on how web service comes into picture.

Example of Web Service
  • Weather Reporting: You can use Weather Reporting web service to display weather information in your personal website.
  • Stock Quote: You can display latest update of Share market with Stock Quote on your web site.
  • News Headline: You can display latest news update by using News Headline Web Service in your website.
  • In summary you can any use any web service which is available to use. You can make your own web service and let others use it. Example you can make Free SMS Sending Service with footer with your companies advertisement, so whosoever use this service indirectly advertise your company... You can apply your ideas in N no. of ways to take advantage of it.

Web Service Communication
Web Services communicate by using standard web protocols and data formats, such as
  • HTTP
  • XML
  • SOAP



Web Services Communication Protocols 
Advantages of Web Service Communication
Web Service messages are formatted as XML, a standard way for communication between two incompatible system. And this message is sent via HTTP, so that they can reach to any machine on the internet without being blocked by firewall.

Terms which are frequently used with web services
  • What is SOAP?
    • SOAP are remote function calls that invokes method and execute them on Remote machine and translate the object communication into XML format. In short, SOAP are way by which method calls are translate into XML format and sent via HTTP.
  • What is WSDL?
    • WSDL stands for Web Service Description Language, a standard by which a web service can tell clients what messages it accepts and which results it will return.
    • WSDL contains every details regarding using web service
      • Method and Properties provided by web service
      • URLs from which those method can be accessed.
      • Data Types used.
      • Communication Protocol used.
  • What is UDDI?
    • UDDI allows you to find web services by connecting to a directory.
  • What is difference between Disco and UDDI?
    • Disco is Microsoft's Standard format for discovery documents which contains information about Web Services, while UDDI is a multi-vendor standard for discovery documents which contains information about Web Services.
  • What is Web Service Discovery Tool (disco.exe) ?
    • The Web Services Discovery Tool (disco.exe) can retrieve discovery information from a server that exposes a web service.
  • What is Proxy Class?
    • A proxy class is code that looks exactly like the class it meant to represent; however the proxy class doesn't contain any of the application logic. Instead, the proxy class contains marshalling and transport logic.
    • A proxy class object allows a client to access a web service as if it were a local COM object.
    • The Proxy must be on the computer that has the web application.
  • What is Web Service Description Language Tool (wsdl.exe)?
    • This tool can take a WSDL file and generate a corresponding proxy class that you can use to invoke the web service.
    • Alternate of generating Proxy class through WSDL.exe is you can use web reference. Web Reference automatically generate a proxy classes for a web service by setting a web reference to point to the web service.
    • Advantage of using Web Reference as compare to using WSDL.exe Tool is you can update changes done in web service class easily by updating web reference, which is more tedious task with WSDL.exe tool.
  • Testing a Web Service?
    • You can test web service without building an entire client application.
      • With Asp.net you can simply run the application and test the method by entering valid input paramters.
      • You can also use .Net Web Service Studio Tool comes from Microsoft.

Example of Creating Web Service in .Net
This Web Service will retrieve CustomerList Country Wise and return as dataset to client application for display.
Step1: Create a Web Service Application by File > New > Web Site > Asp.net Web Services
Named the web service, for example here i have choosen name "WSGetCustomerCountryWise"

Step2: Rename the default Service.asmx file to proper name, you also need to switch design view and change the class name with the same name you use to rename the service.asmx.
For example, "WSGetCustomerCountryWise.asmx" and switch to design view and change the class="Service" to class="WSGetCustomerCountryWise"

Step3: Rename the Service.CS File to proper name, you need to change the class name and constructor name too.
For example, "WSGetCustomerCountryWise.CS" and switch to code view and change the class and constructor name to "WSGetCustomerCountryWise"

After three steps your solution explorer looks as shown in figure





using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Xml;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
// [System.Web.Script.Services.ScriptService]
public class Service : System.Web.Services.WebService
{
    public Service () {

        //Uncomment the following line if using designed components
        //InitializeComponent();
    }

    [WebMethod]
    public string HelloWorld(string message) {
        return "Hello World"+message;
    }

    [WebMethod]
    public int Add(int a,int b)
    {
        return a + b;
    }

    [WebMethod]
    public XmlElement GetUserDetails(string empname)
    {
        SqlConnection con = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=D:\WebSite\Webservices1\App_Data\Database.mdf;Integrated Security=True;User Instance=True");
        con.Open();
        SqlCommand cmd = new SqlCommand("select * from Emp where EmpName like @EmpName +'%'" , con);
        cmd.Parameters.AddWithValue("@EmpName",empname);
        cmd.ExecuteNonQuery();
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        // Create an instance of DataSet.
        DataSet ds = new DataSet();
        da.Fill(ds);
        con.Close();
        // Return the DataSet as an XmlElement.
        XmlDataDocument xmldata = new XmlDataDocument(ds);
        XmlElement xmlElement = xmldata.DocumentElement;
        return xmlElement;
    }
}



  Now  Build Web Service and Run the Web Service for testing by pressing F5 function key.






By pressing "Invoke" button will generate XML File.

So you are done creating web service application.

Example of Testing Web Service in .NetThis Web Service will display the information which had been retrieved from Remote computer by accessing public method "GetCustomerCountryWise".

 Create Web Site :

1. To create new Web Site project, choose New from File menu, then choose Web Site as shown below.



2. Choose ASP.NET Web Site. Name the project and click OK

Second Step: Add web Reference

After creating the Web Site project, it’s time to add a web reference for our web service.
1. In the solution explorer, right click the project node, choose Add Web Reference

2. A new window with Add Web Reference title will be opened.
In the URL field, insert the URL for the web service. In this tutorial as I mentioned before I’ll use the test published web services form Extentrix. “Extentrix Web Services 2.0 – Application Edition”
After clicking the Go button you will see the web services APIs.

3. Set a name for your web service reference in the web reference name field and click Add Reference



Aspx page:

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <asp:Label ID="lblhello" runat="server"></asp:Label><br />
    sum is:<asp:Label ID="lbladd" runat="server"></asp:Label>   <br />
   
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" />
   
    </div>
    <asp:GridView ID="GridView1" runat="server">
    </asp:GridView>
    </form>
</body>
</html>


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using System.Xml;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            localhost.Service newobj = new localhost.Service();

            lblhello.Text = newobj.HelloWorld("My Name is siva");

            lbladd.Text = newobj.Add(5, 4).ToString();          

            BindUserDetails("");
        }
    }  
      
    private void BindUserDetails(string Empname)
    {
        localhost.Service objUserDetails = new localhost.Service();
        DataSet dsresult = new DataSet();
        XmlElement exelement = objUserDetails.GetUserDetails(Empname);
        if (exelement != null)
        {
            XmlNodeReader nodereader = new XmlNodeReader(exelement);
            dsresult.ReadXml(nodereader, XmlReadMode.Auto);
            GridView1.DataSource = dsresult;
            GridView1.DataBind();
        }
        else
        {
            GridView1.DataSource = null;
            GridView1.DataBind();
        }
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        BindUserDetails(TextBox1.Text);
    }

}

No comments:

Post a Comment