Web Service ?? Shouldn't that be Windows Service (Win Services) ? Hmmm... Nopes its Web Services !! With the introduction of the new .NET platform there has been a creation of "Web Services". So one more type of service to learn, understand --- yep but one thing its pretty easy to learn and master. So what is a Web Service ? The simple answer to that would be a, "A Web Service is a Application running as a service delivered over the Web". If I was to break up this statement there are few points which get highlighted.
1) A Web Service is a Application.
2) To be more precise its a Application running as a Service (like Windows Services in Windows 2000) . So one thing is cleared that once deployed a Web Service will run in the Background.
3) "Delivered over the Web" - This statement say's a lot of things about Web Services. Firstly Web Services are URL addressable i.e. You can call (invoke) it from your browser by typing the path to the Service e.g.
"http://localhost/myservice.asmx" . If you think a bit more deeper over the point "Delivered over the Web" and if you know a bit about the Protocols used over the Web you can easily make out that Web Services have to use either of the 2 protocols widely used on the Internet "HTTP or FTP". Since FTP is to transfer files to using it is out of question , hence no prizes for guessing that Web Services use HTTP protocol for communication with its clients. That means you do not need any special software to host and run your Web Services, your normal Web Server will be able to serve your Web Services...(there you save your precious time and Brain in learning that new Server first that runs your application !!). As stated above Web Services uses HTTP for communication with its clients, this is a very big advantage over other remote services like DCOM , RMI etc which have their own Object -Specific Protocols.
The Web Service interface can be defined strictly in terms of Messages Web Service Accepts and Generates. This lead to a conclusion that Web Services talk with its clients with Messages. Due to XML being the Internets Favorite of describing Data, Microsoft has used XML extensively in Web Services. The Messages transferred to/fro from the Web Service are in XML format. Another standard used to access a Object remotely is SOAP (Simple Object Access Protocol). Web Services use SOAP encoded XML messages to communicate. Does that mean you have to learn XML and SOAP ?? Not exactly, that's the beauty of Web Services which leads to some people calling it as having "Black - Box" functionality. What they mean is that you can code and use Web Service with out know how exactly the Web Service is implemented i.e. You will never need to worry about how the messages get coded into SOAP and XML and how they are transferred to it clients.
A very important point that many of you might have already understood would be that the Clients (consumers) of the Web Service could be from any platform, Object model and Programming Language. As long as they can understand and generate SOAP encoded XML messages , You guessed that, didn't you ?. This solves a big problem of application interoperability being experienced today's programmers.
Future of Web Service ?, will all my applications get converted to Web Services ? Impact of Web Services ? Hey, hey hold on a second... I am just 20 and still getting a gist of how the Programming World Functions !! It would be better if you ask those questions to seasoned developers, having a experience of 10-20 years out there who would let you and Me know, of this technology's future? As for me, I am all excited and can find many applications for it in the present Web scenario. One such field I think where Web Services could be a major boon would be in the field of "Content Providers" , as I call them. If you are a regular browser of many "Consumer Oriented Portals" which provide daily updates of News, Sports, Stocks, Games, Weather, E-mail, .... and not to forget Horoscopes (That's what I look up every day to count my chances of emerging as a good programmer :) )!!! The point I want to make here is that you will find that many of these "Consumer Oriented Portals" actually do not create original content in all the sections. They subscribe to some other Portals which provide specialized information on that section, that's the reason why if you surf many such portals you will find that the content of some of their columns like Sports, Weather etc are the same. Such portals which offer specialized information are called as "Content Providers", since they provide specialized content to other Portals as well as to general surfers directly.
I have tried here to outline a hypothetical Web Service which such Content Providers could use. Guess what I will be delivering as Content through my Web Service? ........ Ahmmm Horoscopes ........ .
Yep this is that my sample service would deliver, Daily Horoscopes. Since I am not a astrologer I will not provide accurate readings nor will I be updating it daily.... :) but still I will try to give it by best shot !
A) Server Side ("Content Provider Side")
The horoscopes will be updated Daily by the staff. The daily horoscopes will be stored in a XML file called dailyhoro.xml.
B) Clients ("Content Consumers")
The clients can view their Horoscopes through Web Pages or through Applications. They will provide the Zodiac sign and the Web Service will process their request and send them their daily readings.
Download The Code (horoservice.zip)
Time to kick up some real code. First we will see the code for the Web Service. This Service is pretty simple, it takes a string containing the "Zodiac Sign" as a input parameter. Then it looks up its database for the prediction for the "Zodiac Sign" the client entered. If a match if found then it returns the user a string containing the Date for which the horoscope is along with the prediction for the supplied sign. Just incase you did not know there 12 zodiac signs Namely - "Aquarius, Pisces, Aries, Taurus, Gemini, Cancer, Leo, Virgo, Libra, Scorpio, Capricorn, Sagittarius". What is your Zodiac Sign ??? Mine is encoded in this example if you look carefully and you will know!
1) wshoro.asmx :- The Horoscope Web Service
<%@ Webservice Language="C#" class="DailyHoro" %>
using System ;
using System.Web.Services ;
using System.Xml ;
using System.IO ;
//Only Public classes are exposed to the clients. All the classes that
//you want to expose to the Web Service should derive from
//In my example the class "DailyHoro" derives from the class
public class DailyHoro : WebService
//All the methods you want to expose to the Web Service should
//also be public methods.
//To make the method available to the Clients you have to mark the
//method as "[WebMethod]"
//only the marked methods will be available to the clients
//This method has one Input parameter as a String containing the Zodiac
//sign name of the Sign for which the client wants the Horoscope.
//In return we send the client the current date and the prediction.
public string GetHoro(string zodiac)
//We give a call to our private method which does all the data collection and sends
//the Current Date and prediction of the sign requested
//We return the data to the client
return getData(zodiac) ;
//A Private method which takes the "Zodiac" sign as input and returns a
//string containing the current date and the Prediction for that sign.
//Since I am using XML as the Database, this method first reads the Data
//from the XML file, Then it searches for the specified sign in the database
private string getData(string zodiac)
//Declare a FileStream
FileStream fin ;
//Set the Various parameters on the File stream.
//It is also to declaring "FileShare.ReadWrite"
//which will allow other users too to read this file
//Also the System Admins will have access to update the File.
fin= new FileStream(Server.MapPath("db/dailyhoro.xml"),
FileMode.Open, FileAccess.Read,FileShare.ReadWrite );
//Create a DataSet object to contain our Database
DataSet ds = new DataSet() ;
//Read the XmlSchema and Data from the stream
ds.ReadXml(new StreamReader(fin)) ;
//close the stream
//loop to check for the Zodiac sign provided
//We check up to 12, ??? any answers why ??
//Didn't get it may be it too much coffee ..
//There are only 12 Zodiac signs -Remember!!!
for(int i=0;i<12 ; i++)
//Check if the Zodiac sign provided by the user Equals
//the "name" field in our Table "zodiac"
//If a match if found then return the Date and
string pred =ds.Tables.Rows[i]["pred"].ToString() ;
string date = ds.Tables.Rows[i]["today"].ToString() ;
return date+"@"+pred ;
//If no match found then return a error statement
return "Wrong Parameter" ;
//catch any error and inform the user a error has occurred
//in the Web Service
//You will not do this in real implementation
//Keep the user guessing or send him some understandable message
//like service down etc..
return "Read Error!!"+ed.ToString() ;
That's It !!! Saw how easy it is to write a Web Service. You don't even have to think how the Service will listen for incoming clients or the communication will take place between the Service and its Clients. Save the file as "wshoro.asmx". Web Services are stored with the extension ".asmx".
Web Service Deployment
To deploy a Web Service is as simple as deploying any other ASP.NET Web Application. In our example create a Virtual Directory on your computer if you are using a "localhost" Server, or simply upload your files to any server supporting ASP.NET. Remember to place the "dailyhoro.xml" file in a directory called "db" in the virtual directory. Now you web Service is deployed. to call it just type the URL of the Web Service in to your browser. The page that you see is auto generated by the .NET runtime. It gives some information about the Web Service.
Since your web service is ready you can now proceed with writing clients to consume your service.
1) Proxy Class :
In order for the client to use the Web Service it should have knowledge of how the Web Service is implemented and how to call it etc. But I said before that you can talk to Web Services with out knowing how they are implemented? You are right but theoretically the client cannot know automatically about the Web Service. Hence all Web Services automatically generate a XML document with SDL(Service Description Language) grammar to describe itself. In our example say if you have installed the Web Service in a Virtual Directory called "myservice" then you can get the SDL of the service by calling the following URL in your browser "http://localhost/myservice/wshoro.asmx?SDL". This will generate a XML file and display it in your browser. The Displayed file is the SDL of the Web Service.
The .NET SDK has a tool called "WebServiceUtil". This tool takes the SDL of a Web Service as a input and uses Reflection to generate a Proxy Class that is similar to the Web Service. To create a proxy class for our Horoscope Example use
WebServiceUtil /c:proxy /pa:http://localhost/myservice/wshoro.asmx?SDL /n:horo_service Where "/c:proxy" --prompts the Utility to make a Proxy class. "/pa:http://localhost/myservice/wshoro.asmx?SDL" --is the full URL to the SDL. Remember the SDL of the Web Service and not the Web Service. So you can also save the SDL of the Web Service to your Computer and use it for creating a Proxy.
"/n:horo_service" --is to specify the Namespace to create for the Proxy Class.
This will generate a file "DailyHoro.cs" in the directory you called WebServiceUtil. This file contains the source code which defines the Web Service in C#.
Now compile this Source code to generate a Library that we can use in our clients. The library generation command will be.
csc /target:library /r:System.dll;System.Web.Service.dll;System.Xml.Serialization.dll DailyHoro.cs
Note that you have to reference all the above Assemblies to create your Proxy Library. The above code will generate a Dll "DailyHoro.dll" . With this you have successfully created your Proxy Library and now you can easily write up clients to use your Web Service.
2) ClientHoro.aspx -The Web Page Client
Are you awake ??? Grab a cup of coffee since we are on a part which many of you might be knowing well by now. We are going to write a ASP.NET Web page which will consume the Web Service I have just written.
<%@ Import namespace="System" %>
<%@ Import namespace="horo_service" %>
<%@ Page Language="C#" %>
<script language="C#" runat="server">
private void gethoro_Click(object sender, EventArgs e)
//Get the Selected Item from the DropDownList
string sign = zodiac.SelectedItem.Text ;
//Create a Instance of the Proxy Class
DailyHoro dh = new DailyHoro() ;
//Call the "GetHoro" method of the Web Service on the Proxy Object
//The Proxy object inturn communicates to the Web Service
//Remember the Proxy cannot do anything except act as a bridge between
//your Web Service and the client. It cannot replace the Web Service.
string result =dh.GetHoro(sign) ;
//Extract the Date from the Result
preddate.InnerHtml="<b> Horoscope for "+sign+" as on "+result.Substring(0,10)+"</b>" ;
//Display the Prediction
<title>Horoscope Service Client</title>
<form runat="server" >
<table border="1" width="60%" cellpadding="1" cellspacing="2">
<td colspan=2> <b> Select your Zodiac Sign</b></th>
<asp:DropDownList id="zodiac" runat="server">
<td colspan="2" >
<asp:Button onClick="gethoro_Click" Text="Fetch !" runat="server" /></td>
<td colspan="2"><div id="preddate" runat="server" /></td>
<td colspan="2"><div id="predspace" runat="server" /></td>
Deploy the Web Application
To deploy the above Web Page is similar to deploying any ASP.NET Page. Copy the File ClientHoro.aspx to your Virtual Directory. Also remember to copy the Proxy Dll to your "Bin" directory located in the Virtual Directory. If a "/bin" directory does not exist then create it in your Virtual Directory . Wasn't that easy to consume the Web Service. Also since the Input is returned in the form of a string you can format that data to suit to your needs.
2) HoroClient.cs:- The Horoscope Web Service Consuming Console Client
/* the Horoscope Web Srevice COnsumer Console Client
csc /r:System.dll;System.Web.Services.dll;DailyHoro.dll HoroClient,cs
using System ;
using horo_service ;
//A class which consumes the Web Service
public class HoroClient
public static void Main(string argv)
Console.WriteLine("Welcome to Horoscope Client") ;
Console.Write("Enter you Zodiac Sign:") ;
//Read the Input from the user
string sign = Console.ReadLine() ;
//Create a instance of the Proxy Class
DailyHoro dh = new DailyHoro() ;
//Make a Call on the Web Service Method "GetHoro" and
//pass the Zodiac sign to it
string result = dh.GetHoro(sign) ;
Console.WriteLine("Horoscope for "+sign+" on "+result.Substring(0,10)) ;
//Print the Prediction
Console.WriteLine("Press Enter to Exit") ;
Compile this code and you will get the Executable "HoroClient.exe" which consumes our Web Service. Run the file to use the service.
If you have gone through the article you will find that Writing and Consuming Web Services is very easy. Also in case of our "Content Providers" Example Web Service can be very useful since the consumers take the responsibility of how to format the Code. Also one useful point for the consumers is that they have to write the code only once. In our examples the Consumer Portals have to just write the code once, The content gets updated every time the content gets updated on the Web Service.
Have you got some extra coffee send it over to me ... my coffee is over and I am dam sleepy (so if there are any errors in the code do let me know :) )!!!!!!
Points to Remember
1) Web Services are Applications Delivered over the Web.
2) Web Services use HTTP protocol to communicate with its client.
3) Web Services use SOAP encoded XML messages to communicate with its clients.
4) Web Service clients can be anything from Web Pages to Applications to Devices only criteria being the client can understand the and communicate over HTTP in SOAP encoded XML messages.
5) SDL is the description of a Web Service generated automatically for all Web Services.
6) If you are using the .NET platform to create a Client then use "WebServiceUtil.exe" to create a Proxy class from the SDL of the Web Service.
7) Once you have the Proxy class code, compile it into a Library.
8) Use the Proxy class Library in your Clients to call methods upon a Web Service.
9) If you Have any Questions , Comments or Suggestions feel free to contact me at firstname.lastname@example.org . Or visit my shack at http://learncsharp.cjb.net .
10) Hey if someone really implements this service for the public then please do let me know, since I would have but I don't have the resources yet ....