2002-09-13 13:17
Providing Content Through Web Services
Saurabh Nandu
May 09 2001
Introduction
We have seen what Web Services are and a Sample Web Service,
Stock Quotes, in my previous articles on .NET101 (please refer to these two
articles if you need detailed information on Web Services and the tools used).
Content Providers will see Web Services as a major component that will change
the way they distribute information.
Many Portals like Yahoo and Excite
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, these Portals actually do not create original content for all the
sections. They subscribe to some other Portals which provide specialized
information. 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 look the
same.
Web sites which offer such specialized information are called
"Content Providers", since they provide specialized content to Portals as well
as to general surfers.
I have outlined a hypothetical Web Service which
such Content Providers could use. Guess what I will be delivering as Content
through my Web Service? Horoscopes !
This article will walk through building a sample service that would deliver, Daily Horoscopes. Since I am not a astrologer I will not provide accurate readings nor will I be updating it daily.
Design Considerations
A) Server Side (Portal)
The horoscopes will be updated
Daily by the staff. The daily horoscopes will be stored in a XML file called
dailyhoro.xml. The XML database will be placed in a DB
subfolder.
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.
Implementation
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 is found then it returns a string containing the Date for which the horoscope applies, along with the prediction for the supplied sign. Just incase you did not know there are 12 zodiac signs Namely - "Aquarius, Pisces, Aries, Taurus, Gemini, Cancer, Leo, Virgo, Libra, Scorpio, Capricorn, and Sagittarius". You ca write the code in any text editor and save it as wshoro.asmx .
<%@ Webservice Language="C#" class="DailyHoro"
%>
using System ;
using System.Web.Services ;
using
System.Xml ;
using System.Data;
using System.IO ;
First import the necessary Namespaces.
public class DailyHoro :
WebService
{
....
.....
}
We declare a class DailyHoro which extends the WebService class from the System.Web.Services Namespace.
[WebMethod]
public string GetHoro(string
zodiac)
{
return getData(zodiac) ;
}
The class DailHoro contains a public method GetHoro, which is marked with the WebMethod Attribute to indicate it will be available publicly as a Web Service. This method takes a string containing as the zodiac sign as the input parameter and passes it to another private method getData. The information returned by the getData method is returned to the user.
private string getData(string zodiac)
{
try
{
//Create a
FileStream
FileStream fin ;
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 Xml Schema and Data from the stream to the Database
file
ds.ReadXml(new StreamReader(fin))
;
//close the stream
fin.Close() ;
//loop to check for the
Zodiac sign provided
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(zodiac.Equals(ds.Tables[0].Rows[i]["name"]))
{
//If
a match if found then return the Date and
//Prediction
string pred =ds.Tables[0].Rows[i]["pred"].ToString()
;
string date = ds.Tables[0].Rows[i]["today"].ToString()
;
return date+"@"+pred ;
}
}
//If no match found then return a error statement
return "Wrong Parameter"
;
}
catch(Exception ed)
{
return "Read
Error!!"+ed.ToString() ;
}
}
The getData method gets called from the GetHoro method.
A FileStream is open to read the XML Database file. Then the DataSet object is
used to read the data from the XML file. Next, there is a loop through all the
rows of the DataSet to find the match for the Zodiac sign. Once a match is
found, the Current date along with the prediction is returned. If no match is
found or an error occurs then a relevant message is returned.
Web Service Deployment
Deploying a Web Service is as simple as deploying any other
ASP.NET Web Application. For our example create a Virtual Directory on your
computer named "horoservice" or simply upload the files to any server supporting
ASP.NET.
Remember to place the "dailyhoro.xml" file in a directory
called "db" which should reside in the horoservice virtual directory.
Now your web Service is deployed. To call it just type the URL of the
Web Service into your browser i.e http://localhost/horoservice/wshoro.asmx.
Using the Web Service (Consumers)
Since your web service is ready you can now proceed with writing clients to consume your service.
Proxy Class
The first step in creating a client is creating a Proxy Class that contains the information on how to locate the web service and the interface description. We use the WebServiceUtil.exe tool to create a Proxy class.
WebServiceUtil
/c:proxy
/pa:http://localhost/csharp_test/oroscope/wshoro.asmx?SDL
/n:horo_service
This will create a file "DailyHoro.cs" in the directory from
which you ran the tool.
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.Services.dll;System.Net.dll;
System.IO.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". Paste the commands in a single command line.
ClientHoro.aspx -The Web Page Client
Now let's step through the code of a ASP.NET client which will consume the Horoscope Web Service.
<%@ Import namespace="System" %>
<%@ Import
namespace="horo_service" %>
<%@ Page Language="C#" %>
Import the necessary Namespaces. Remember to import the horo_service Namespace too, which contains the Proxy class which we generated in the earlier step.
<html>
<head>
<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 in turn 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
predspace.InnerHtml=result.Substring(11);
}
</script>
<title>Horoscope Service
Client</title>
</head>
In the above code snippet, the gethoro_Click method creates a instance of the class DailyHoro which resides in our proxy library. next the GetHoro method of the DailyHoro class is called and the Zodiac sign is passed as an input parameter. The returned string is split and the date and prediction are displayed separately.
<body>
<center>
<form
runat="server" >
<table border="1" width="60%"
cellpadding="1"
cellspacing="2">
<tr>
<td
colspan=2> <b> Select your Zodiac
Sign</b></th>
</tr>
<tr>
<td>
<asp:DropDownList
id="zodiac"
runat="server">
<asp:ListItem>aquarius</asp:ListItem>
<asp:ListItem>pisces</asp:ListItem>
<asp:ListItem>aries</asp:ListItem>
<asp:ListItem>taurus</asp:ListItem>
<asp:ListItem>gemini</asp:ListItem>
<asp:ListItem>cancer</asp:ListItem>
<asp:ListItem>leo</asp:ListItem>
<asp:ListItem>virgo</asp:ListItem>
<asp:ListItem>libra</asp:ListItem>
<asp:ListItem>scorpio</asp:ListItem>
<asp:ListItem>capricorn</asp:ListItem>
<asp:ListItem>sagittarius</asp:ListItem>
</asp:DropDownList>
</td>
</tr>
<tr>
<td colspan="2" >
<asp:Button
onClick="gethoro_Click" Text="Fetch !"
runat="server" /></td>
</tr>
<tr>
<td
colspan="2"><div id="preddate" runat="server"
/></td>
</tr>
<tr>
<td colspan="2"><div id="predspace" runat="server"
/></td>
</tr>
</table>
</form>
</center>
</body>
</html>
The above code is the rest of the code which makes the ASP.NET page. It includes a dropdownlist containing the names of various Zodiac signs, a button which triggers the Web Service and two DIV's to display the returned value.
Deploying the Web Application
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.
Console Client
HoroClient.cs: The Horoscope Web Service Consuming
Console Client
Now, we will see how to build a Console Application which
consumes our Horoscope Web Service.
/*
Compilation
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(result.Substring(11));
Console.WriteLine("Press Enter to Exit");
Console.ReadLine();
}
}
In the above example we have a class HoroClient. The Main method of this class takes the Zodiac Sign input from the user and instantiates a object of the type DailyHoro (Contained within the Proxy Library). Next, we call the GetHoro method to get the prediction and display it to the user.
Deployment
Compile this code and to get the Executable "HoroClient.exe" which consumes our Web Service. Run the file to use the Web Service.