A web service is a network-based function that can be obtained by web applications through web network protocols. Web service development mainly includes the following three aspects:
Create web service
Create proxy server
Use web services
A web service is a web application. Its basic form is a class containing multiple methods that can be called by other applications. It also uses a hidden code structure such as an ASP.NET web page, but it does not have a user interface.
To better understand this concept let's create a web service that provides stock price information. Clients of the service can look up related names and prices through a stock's tag. To simplify this example, we set the stock price to a fixed value and save it in a two-dimensional list. This web service contains three methods:
A default HelloWorld method
A GetName method
A GetPrice method
Take the following steps to create the service:
Step (1) : Select File -> New -> Web Site in Visual Studio, and then select ASP.NET Web Service.
Step (2) : A web service file named Service.asmx and its code are hidden, and Service.cs will be created in the App_Code path of this project.
Step (3) : Change the file names to StockService.asmx and StockService.cs.
Step (4) : The .asmx file simplifies a WebService instruction as follows:
<%@ WebService Language="C#" CodeBehind="~/App_Code/StockService.cs" Class="StockService" %>
Step (5) : Open the StockService.cs file. The code generated in this file is the basic code of the Hello World service. The default web service code is as follows:
using System; using System.Collections; using System.ComponentModel; using System.Data; using System.Linq; using System.Web; using System.Web.Services; using System.Web.Services.Protocols; using System.Xml.Linq ; namespace StockService { // <summary> // Summary description for Service1 // <summary> [WebService(Namespace = "http://tempuri.org/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] [ToolboxItem(false)] // 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 Service1 : System.Web.Services.WebService { [WebMethod] public string HelloWorld() { return "Hello World"; } } }
Step (6) : Modify the code in the file to add a two-dimensional pointer that stores the string of each stock's label, name and price, and write two web methods to obtain stock information as follows;
using System; using System.Linq; using System.Web; using System.Web.Services; using System.Web.Services.Protocols; using System.Xml.Linq; [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 StockService : System.Web.Services.WebService { public StockService () { //Uncomment the following if using designed components //InitializeComponent(); } string[,] stocks = { {"RELIND", "Reliance Industries", "1060.15"}, {"ICICI", "ICICI Bank", "911.55"}, {"JSW", "JSW Steel", "1201.25"}, {"WIPRO", "Wipro Limited", "1194.65"}, {"SATYAM", "Satyam Computers", "91.10"} }; [WebMethod] public string HelloWorld() { return "Hello World"; } [WebMethod] public double GetPrice(string symbol) { //it takes the symbol as parameter and returns price for (int i = 0; i < stocks.GetLength(0); i++) { if (String.Compare(symbol, stocks[i, 0], true) == 0) return Convert.ToDouble(stocks[i , 2]); } return 0; } [WebMethod] public string GetName(string symbol) { // It takes the symbol as parameter and // returns name of the stock for (int i = 0; i < stocks.GetLength(0); i++) { if (String.Compare(symbol, stocks[i, 0], true) == 0) return stocks[i, 1]; } return "Stock Not Found"; } }
Step (7) : Running the web service application gives a web service test page where we can test the service methods.
Step (8) : Click on a method name to confirm whether it is running correctly.
Step (9) : To detect the GetName method, provide one of the defined stock tags. If correct, the name of the relevant stock will be returned.
To use this web service, we create a website under the same solution (Solution). Just right-click the solution name in the solution manager. The web page called by the web service should have a control management to display the return result and two control buttons, one for returning and another for starting the call to the service.
The file content of the web application is as follows:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="wsclient._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> Untitled Page </title> </head> <body> <form id="form1 " runat="server"> <div> <h3>Using the Stock Service</h3> <br /> <br /> <asp:Label ID="lblmessage" runat="server"></asp:Label> <br /> <br /> <asp:Button ID="btnpostback" runat="server" onclick="Button1_Click" Text="Post Back" /> <asp:Button ID="btnservice" runat="server" onclick="btnservice_Click" Text="Get Stock" /> </div> </form> </body> </html>
The code for the web application is as follows:
using System; using System.Collections; using System.Configuration; using System.Data; using System.Linq; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.HtmlControls ; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Xml.Linq; //this is the proxy using localhost; namespace wsclient { public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { lblmessage.Text = "First Loading Time: " + DateTime.Now.ToLongTimeString } else { lblmessage.Text = "PostBack at: " + DateTime.Now.ToLongTimeString(); } } protected void btnservice_Click(object sender, EventArgs e) { StockService proxy = new StockService(); lblmessage.Text = String.Format("Current SATYAM Price:{0}", proxy.GetPrice("SATYAM").ToString()); } } }
A proxy server refers to a replacement for web service code. Before using the web service, we must create a proxy server. This proxy server is registered by the client application. The client application then implements the call to the web service as if it were using a native method.
The proxy server will make the call and send the call to the server in the appropriate format as a SOAP request. SOAP supports the Simple Object Access Protocol. This protocol is suitable for web service data exchange.
When the server responds and returns a SOAP packet to the client, the proxy server presents everything to the client application.
Before calling the web service using btnservice_click, the web application should be added to the application. This will transparently create a proxy class that can be used by the btnservice_click event.
protected void btnservice_Click(object sender, EventArgs e) { StockService proxy = new StockService(); lblmessage.Text = String.Format("Current SATYAM Price: {0}", proxy.GetPrice("SATYAM").ToString()) ; }
Take the following steps to create a proxy:
Step (1) : Right-click on the web application entry in Solution Explorer and select 'Add Web Reference'.
Step (2) : Select 'Web Services in this solution' and the stock service reference we wrote will be returned.
Step (3) : Click on the service to open the test page. When creating the proxy, it defaults to 'localhost'. Of course, you can also rename it. Click 'Add Reference' to add a proxy to the client application.
Add the following statement to your code to include the agent:
using localhost;