The original article comes from :http://www.codeproject.com/Articles/14957/Web-Services-in-C-and-Net
Web Services provide the most flexible infrastructure for creating distributed computing applications. A web service in its simplest form is an object oriented class residing on a web server, and allowing remote clients to invoke its methods. Prior to web services, programmers have relied on sockets, RPC (Remote Procedure Calls), distributed COM (DCOM), and RMI (Remote Method Invocation) technologies to create distributed applications. The major problem with the above solutions is that either they are difficult to program (e.g., sockets), or require both the client and server side to be using the same technology (e.g., DCOM is mostly windows based, and RMI is Java based requiring both the client and server programs to be written in Java). The web services architecture overcomes these limitations. The following are the main motivations behind the development of web services.
- The client and the web service can be remote from each other.
- The client and the web service can use a totally different operating system or programming language.
- The web service can be made available through firewalls that allow port 80 but block other ports.
The above goals are easily accomplished by having the client and the web service use XML (or Http Get/Post protocols for simple type of parameters in method calls) to invoke methods on the service and receive back results. The format of XML used in invoking a web service is a W3C standard known as SOAP (Simple Object Access Protocol).
Here are some of the characteristics of a web service.
- Web services do not contain any user interface, and are mainly a class or classes exposing some useful methods to a client.
- A web server is used to host the web service which uses port 80 to make the web service available to clients.
- The methods of a web service can be invoked either by Http Get, or Http Post, or using SOAP.
- Http Get/Post techniques are used when the method parameters and results are simple data types. However, for passing back and forth structures and class objects in method parameters, SOAP is the solution. .Net provides HttpGetClientProtocol, HttpPostClientProtocol and SoapHttpClientProtocol classes for using Get, Post or SOAP protocols in the client code.
- The client of a web service can either be a web browser, a web application or a desktop application (e.g., a windows form application).
- All clients to a web service require a proxy (very similar to proxy in RPC or DCOM or RMI). The job of proxy is to marshal the parameters and results in method calls to a web service.
- The client code simply invokes an object of the proxy class (which has same methods and their signatures as the methods in the web service), and calls the proxy methods. The proxy, serializes the method calls to the web service using either Http Get/Post or SOAP, and also deserializes the results back to the client.
- If the client is a web browser, or a web application, the proxy code is downloaded from the web server hosting the web service. If the client application is a desktop application. The proxy code has to be generated in advance and resides on the client.
- Since web services reside on the web server and are accessed by clients using Http (SOAP is also using Http to send back and forth XML packets) which is a stateless protocol, maintaining state between method calls is possible through application or session objects.
- The client of a web service should be able to locate (discovery) and find out the prototypes of methods (description) in web service. For this purpose, the web service provides a discovery file and a description (wsdl format) file that lists all the public methods and their prototypes in XML format. Web services can be registered with a UDDI (Universal Description, Discovery and Integration) server which can act as the yellow pages for web services.
- The web service methods can use any .Net primitive data type (e.g., int, float, Double, string, DateTime, Decimal, Boolean, Object) in parameters or return values. Arrays and ArrayLists can also be used. User defined classes or structures used in parameters or return types require special XML streaming in using SOAP.
Web Services in .Net have a file extension of .asmx. It is possible to type all the class code in an asmx file using a simple editor like notepad. Visual Studio uses the code behind technique for creating web services. The benefit of the code behind technique in general is that it separates the user interface from the underlying code. However, in case of web services, since there is no user interface, the code behind technique has the advantage that the class code is precompiled in advance. It is possible to create a web service where all the code is written in the .asmx file which will get compiled on its first access by the user.
A web service class is usually derived from System.Web.Services.WebService class. Each public method of the web service class that needs to be made available as a web service will be marked with an attribute of [WebMethod].
Creating a simple Web Service Using C#:
Create an ASP.NET Web Service type project. Name the project StInfo
Change the default name of the file from Service1.asmx to StInfo.asmx. Web services in .Net have files with an extension of .asmx.
Type the following code in the StInfo.asmx.cs file.
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Web;
using System.Web.Services;
namespace StInfo
{
/// <summary>
/// Summary description for Service1.
/// </summary>
public class StInfo : System.Web.Services.WebService
{
string [,] students =
{
{"062987","Andrew", "Anserson","3.45","CS"},
{"062988","Jessica", "Johnson","3.75","CS"},
{"062989","Monica", "Marker","3.15","EE"},
{"062990","Michael", "Jordan","2.45","MBA"},
{"062991","Sally", "Simpson","3.12","EE"},
{"062987","Mark", "Mathews","2.85","CS"},
{"062987","Sara", "Sorenson","3.52","MBA"}
};
public StInfo()
{
//CODEGEN: This call is required by the ASP.NET Web Services Designer
InitializeComponent();
}
#region Component Designer generated code
//Required by the Web Services Designer
private IContainer components = null;
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent(){ }
protected override void Dispose( bool disposing )
{
if(disposing && components != null)
{
components.Dispose();
}
base.Dispose(disposing);
}
#endregion
[WebMethod]
public string GetFirstName(string StID)
{
// return first name for a given student ID
for (int i = 0; i < students.GetLength(0);i++)
{
if (String.Compare(StID,students[i,0],true) == 0)
return students[i,1];
}
return "Student does not exist with this ID";
}
[WebMethod]
public string GetLastName(string StID)
{
// return first name for a given student ID
for (int i = 0; i < students.GetLength(0);i++)
{
if (String.Compare(StID,students[i,0],true) == 0)
return students[i,2];
}
return "Student does not exist with this ID";
}
[WebMethod]
public float GetGPA(string StID)
{
// return first name for a given student ID
for (int i = 0; i < students.GetLength(0);i++)
{
if (String.Compare(StID,students[i,0],true) == 0)
return float.Parse(students[i,3]);
}
return 0;
}
[WebMethod]
public string GetMajor(string StID)
{
// return first name for a given student ID
for (int i = 0; i < students.GetLength(0);i++)
{
if (String.Compare(StID,students[i,0],true) == 0)
return students[i,4];
}
return "Student does not exist with this ID";
}
[WebMethod]
public string[] GetAllStudents()
{
// return first name for a given student ID
string [] sts = new string[students.GetLength(0)];
for (int i = 0; i < students.GetLength(0);i++)
{
sts[i]=students[i,0];
}
return sts;
}
}
}
Even though the Visual Studio does not show the contents of the asmx file, you can view it by opening it in notepad. For example, the contents of StInfo.asmx look as:
<%@ WebService Language="c#" Codebehind="StInfo.asmx.cs" class="StInfo.StInfo" %>
As you can see, the main job of the asmx file is to indicate that first of all, it is a web service using C# and to identify the code behind file (StInfo.asmx.cs in above case).
Choose Build->Build Solution to compile the web service. If there are no errors, you can test the web service by either choosing Debug-> Start, or directly typing http://localhost/StInfo/StInfo.asmx in the browser.
You will see the following screen.
If you click on the link GetLastName, you will see the following page which has a simple form that can be filled out to find out the student last name corresponding to the student ID (the form uses the Http GET method).
Similarly, you can test the GetAllStudents link. When you click on the invoke button, you will see the following result.
The page that shows the Invoke button also gives hints about how you can use the SOAP or Http POST protocols to invoke the web service methods, and the general form of the request and response headers for these protocols. For example, to invoke the GetLastName method using SOAP, the format of request response headers is:
SOAP
The following is a sample SOAP request and response. The placeholders shown need to be replaced with actual values.
<SPAN style="COLOR: black">POST /stinfo/stinfo.asmx HTTP/1.1<o:p></o:p>
<SPAN style="COLOR: black">Host: localhost<o:p></o:p>
<SPAN style="COLOR: black">Content-Type: text/xml; charset=utf-8<o:p></o:p>
<SPAN style="COLOR: black">Content-Length: <SPAN style="COLOR: darkblue">length<SPAN style="COLOR: black"><o:p></o:p>
<SPAN style="COLOR: black">SOAPAction: "http://tempuri.org/GetLastName"<o:p></o:p>
<SPAN style="COLOR: black"><o:p> </o:p>
<SPAN style="COLOR: black"><?xml version="1.0" encoding="utf-8"?><o:p></o:p>
<SPAN style="COLOR: black"><soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"><o:p></o:p>
<SPAN style="COLOR: black"><SPAN style="mso-spacerun: yes"> <soap:Body><o:p></o:p>
<SPAN style="COLOR: black"><SPAN style="mso-spacerun: yes"> <GetLastName xmlns="http://tempuri.org/"><o:p></o:p>
<SPAN style="COLOR: black"><SPAN style="mso-spacerun: yes"> <StID><SPAN style="COLOR: darkblue">string<SPAN style="COLOR: black"></StID><o:p></o:p>
<SPAN style="COLOR: black"><SPAN style="mso-spacerun: yes"> </GetLastName><o:p></o:p>
<SPAN style="COLOR: black"><SPAN style="mso-spacerun: yes"> </soap:Body><o:p></o:p>
<SPAN style="COLOR: black"></soap:Envelope><o:p></o:p>
<SPAN style="COLOR: black">HTTP/1.1 200 OK<o:p></o:p>
<SPAN style="COLOR: black">Content-Type: text/xml; charset=utf-8<o:p></o:p>
<SPAN style="COLOR: black">Content-Length: <SPAN style="COLOR: darkblue">length<SPAN style="COLOR: black"><o:p></o:p>
<SPAN style="COLOR: black"><o:p> </o:p>
<SPAN style="COLOR: black"><?xml version="1.0" encoding="utf-8"?><o:p></o:p>
<SPAN style="COLOR: black"><soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"><o:p></o:p>
<SPAN style="COLOR: black"><SPAN style="mso-spacerun: yes"> <soap:Body><o:p></o:p>
<SPAN style="COLOR: black"><SPAN style="mso-spacerun: yes"> <SPAN style="mso-spacerun: yes"> <GetLastNameResponse xmlns="http://tempuri.org/"><o:p></o:p>
<SPAN style="COLOR: black"><SPAN style="mso-spacerun: yes"> <GetLastNameResult><SPAN style="COLOR: darkblue">string<SPAN style="COLOR: black"></GetLastNameResult><o:p></o:p>
<SPAN style="COLOR: black"><SPAN style="mso-spacerun: yes"> </GetLastNameResponse><o:p></o:p>
<SPAN style="COLOR: black"><SPAN style="mso-spacerun: yes"> </soap:Body><o:p></o:p>
<SPAN style="COLOR: black"></soap:Envelope><o:p></o:p>
To use POST method for invoking the GetLastName method, the format of request response headers is:
The following is a sample HTTP POST request and response. The placeholders shown need to be replaced with actual values.
<SPAN style="COLOR: black">POST /stinfo/stinfo.asmx/GetLastName HTTP/1.1<o:p></o:p>
<SPAN style="COLOR: black">Host: localhost<o:p></o:p>
<SPAN style="COLOR: black">Content-Type: application/x-www-form-urlencoded<o:p></o:p>
<SPAN style="COLOR: black">Content-Length: <SPAN style="COLOR: darkblue">length<SPAN style="COLOR: black"><o:p></o:p>
<SPAN style="COLOR: black"><o:p> </o:p>
<SPAN style="COLOR: darkgreen">StID<SPAN style="COLOR: black">=<SPAN style="COLOR: darkblue">string<SPAN style="COLOR: black"><o:p></o:p>
<SPAN style="COLOR: black">HTTP/1.1 200 OK<o:p></o:p>
<SPAN style="COLOR: black">Content-Type: text/xml; charset=utf-8<o:p></o:p>
<SPAN style="COLOR: black">Content-Length: <SPAN style="COLOR: darkblue">length<SPAN style="COLOR: black"><o:p></o:p>
<SPAN style="COLOR: black"><o:p> </o:p>
<SPAN style="COLOR: black"><?xml version="1.0" encoding="utf-8"?><o:p></o:p>
<SPAN style="COLOR: black"><string xmlns="http://tempuri.org/"><SPAN style="COLOR: darkblue">string<SPAN style="COLOR: black"></string><o:p></o:p>
Using POST method to Invoke the Web Service Methods:
Using notepad, create a simple ASP page as shown below.
<% @LANGUAGE=VBSCRIPT %>
<% 'StInfoPost.asp – ASP client for StInfo web service %>
<HTML>
<HEAD>
<TITLE> StInfo Client </TITLE>
</HEAD>
<BODY>
<H2> StInfo Web Service Client Using Post </H2>
<HR>
<PRE>
<FORM method=POST ACTION="/stinfo/stinfo.asmx/GetLastName">
Student ID: <INPUT NAME="StID" SIZE="6" MAXLENGTH="6">
<INPUT TYPE=SUBMIT VALUE="Get Last Name" name="btnSubmit">
</FORM>
<FORM method=POST ACTION="/stinfo/stinfo.asmx/GetAllStudents">
<INPUT TYPE=SUBMIT VALUE="Get All Students" name="btnSubmit">
</FORM>
</PRE>
<HR>
</BODY>
</HTML>
You can test the invocation of GetLastName and the GetAllStudents web service methods by clicking on the two buttons in the form.
Using SOAP to Invoke the Web Service:
The easiest way to using SOAP to invoke a web service is by creating a proxy dll and registering it with the client application. The proxy does all the marshalling and serialization/deserialization of parameters and returns to/from a web service. The proxy has all the exposed methods in a web service and to the client it appears as if the call to the web service method is a local call. The proxy makes all the appropriate SOAP packets when invoking a method on the web service.
ASP.NET Web Service Client:
To understand the creation and use of proxy dlls, create a new ASP.NET web application. Name the project StInfoClient.
Change the name of Webform1.aspx file to StInfoClient.aspx.
Creating the Proxy: The wsdl utility program can generate the source code for the proxy of a given web service. For example, the following command will generate a file called StInfo.cs for the StInfo web service.
The above StInfo.cs file needs to be compiled into a dll and copied into the bin directory of the client ASP.NET application.
The easiest solution to the above tasks is to create a bat file and run the bat file to generate the source code for the proxy dll, compile the dll and move it to the bin directory.
Using Notepad, create a bat file called StInfoProxy.bat. I stored the file in the c:\InetPub\wwwroot\StInfoClient\ProxyCode folder.
rem StInfoProxy.bat
rem bat file for creating StInfo Proxy dll
rem
rem generate the proxy source code
wsdl /l:cs http://localhost/StInfo/StInfo.asmx?wsdl
rem
rem compile the proxy dll
csc /out:StInfoProxy.dll /t:library /r:System.dll,System.web.dll,System.web.services.dll StInfo.cs
rem
rem Copy the dll to the bin directory of Client App
copy StInfoProxy.dll c:\InetPub\wwwroot\StInfoClient\bin
Run the above file from the DOS or Command prompt (from the ProxyCode folder).
Back to the ASP.NET Client Project – StInfoClient:
By right clicking on the references link in the StInfoClient project (in the project explorer), add a reference to the newly created StInfoProxy.dll in the bin folder of this project. Because this dll uses the WebServices, you also need to add a reference to the System.Web.Services.dll.
Add a Label to the StInfoClient.aspx page. Set its text property to “Client for StInfo Web Service”.
Add a panel to the StInfoClient.aspx file. Put a table on it with 4 rows and two columns. Add labels and text boxes to each of the table cells as shown below. Give IDs of txtFirstName, txtLastName, txtMajor and txtGPA to the four text boxes in the panel. Also add a drop down list box server control to the page. Give it a name of ddlStudents. Set the AutoPostBack property of ddlStudents to true.
The important code in the StInfoClient.aspx.cs file that you will be typing is shown below in bold.
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
namespace StInfoClient
{
/// <summary>
/// Summary description for WebForm1.
/// </summary>
public class WebForm1 : System.Web.UI.Page
{
StInfo st = new StInfo();
protected System.Web.UI.WebControls.Label Label1;
protected System.Web.UI.WebControls.Label Label2;
protected System.Web.UI.WebControls.Panel pnlStudent;
protected System.Web.UI.WebControls.Label Label3;
protected System.Web.UI.WebControls.Label Label4;
protected System.Web.UI.WebControls.TextBox txtMajor;
protected System.Web.UI.WebControls.TextBox txtGPA;
protected System.Web.UI.WebControls.Label Label5;
protected System.Web.UI.WebControls.Label Label6;
protected System.Web.UI.WebControls.TextBox txtFirstName;
protected System.Web.UI.WebControls.DropDownList ddlStudents;
protected System.Web.UI.WebControls.TextBox txtLastName;
private void Page_Load(object sender, System.EventArgs e)
{
// Put user code to initialize the page here
if (!IsPostBack)
{
string []sts = st.GetAllStudents();
ddlStudents.Items.Clear();
foreach(string SID in sts)
ddlStudents.Items.Add(SID);
}
}
#region Web Form Designer generated code
override protected void OnInit(EventArgs e)
{
// CODEGEN: This call is required by the ASP.NET Web Form Designer.
InitializeComponent();
base.OnInit(e);
}
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.ddlStudents.SelectedIndexChanged += new System.EventHandler(this.ddlStudents_SelectedIndexChanged);
this.Load += new System.EventHandler(this.Page_Load);
}
#endregion
private void ddlStudents_SelectedIndexChanged(object sender, System.EventArgs e)
{
txtFirstName.Text = st.GetFirstName(ddlStudents.SelectedItem.Text);
txtLastName.Text = st.GetLastName(ddlStudents.SelectedItem.Text);
txtMajor.Text = st.GetMajor(ddlStudents.SelectedItem.Text);
txtGPA.Text = (st.GetGPA(ddlStudents.SelectedItem.Text)).ToString();
}
}
}
Build the StInfoClient application. If there are no errors, you can test the web service client by typing http://localhost/StInfoClient/StInfoClient.aspx in the browser, as shown below.
You can find out the description of the methods in a web service by typing the following URL: http://localhost/StInfo/StInfo.asmx?wsdl
Theoretically speaking, a web service created in .Net does not have to inherit from the WebService class. However, the benefit of inheriting from the WebService class is that you get access to the Application, Session, User and Context objects. If you do not inherit from the WebService class, then you can still get access to the above objects from the HttpContext.Current collection, e.g., you can add two methods to the StInfo web service class. These methods are called GetUniversityName and SetUniversityName and both use the Session object. Note that the session object is not enabled by default for a web service method, you have to enable it explicitly for the method by the WebMethod property of EnableSession=true.
[WebMethod(EnableSession=true)]
public string GetUniversityName()
{
// if this class is not derived from WebService class
// then we can obtain Session, Application, User
// and Context objects as shown below
// Application object is HttpApplicationState class
// Note that you have to explicitly enable
// the session for a web service as the default
// is disabled for a method.
try
{
System.Web.SessionState.HttpSessionState sess;
sess = HttpContext.Current.Session;
if (sess["UniversityName"] != null)
return sess["UniversityName"].ToString();
else
return "No University Name Set in Session";
}
catch (Exception e)
{
return e.Message;
}
}
[WebMethod(EnableSession=true)]
public string SetUniversityName(string uName)
{
// if this class is not derived from WebService class
// then we can obtain Session, Application, User
// and Context objects as shown below
// Note that you have to explicitly enable
// the session for a web service as the default
// is disabled for a method.
try
{
System.Web.SessionState.HttpSessionState sess;
sess = HttpContext.Current.Session;
Session["UniversityName"]=uName;
return ("University Name Set to " + uName);
}
catch(Exception e)
{ return e.Message;}
}