通过Web Services提供内容服务
通过Web Services提供内容服务
一、引 言
对于Web Services是什么已经如何进行简单的应用,我们已经有所了解。现在,Web内容提供商们正在充分发掘Web Services的潜力,将它作为信息发布的一个重要部件。
我们知道,许多门户网站,比如Yahoo、Excite,都提供每日更新的新闻信息、体育信息、股票信息、游戏信息、天气信息以及Email信息。但实际上,并非每个方面的内容最初都由该门户网站真正创建,它们只是订阅了其他提供特殊信息的网站的内容,然后再加工而成。现在你就不会奇怪:为什么当你浏览门户网站的这些信息时,会感觉到内容似曾相识。
提供这些特殊信息的网站被称为ICP(Internet Content Providers),也就是"Internet内容提供商"。通常,ICP除了为门户网站提供这些特殊信息外,也会为一般访问者提供这些内容。因此,如何采取有效的技术手段为外界提供信息服务,成为ICP面对的非常重要的课题。
下面我们就介绍一个可被ICP采用的用于此种信息提供的Web Services,这个Web Services将负责递送每日占星(诞生时的星位)的信息。注意,因为我们都不是占星行家,所以这里的Web Services仅仅是一个框架性的描述。要想真正地应用,还需要"占星家"的帮助哦)
二、服务器端和客户端的工作状态描述
A) 服务器端
占星的资料每日由工作人员更新,存储在叫做dailyhoro.xml的文件中,XML数据库放置于DB子目录中。
B) 客户端
客户端可以通过Web页面或者应用程序查看他们的占星信息。客户端提供Zodiac Sign信息后,Web Services接受请求进行处理,最后发送给访问者他们的每日阅读信息。
三、Web Service源代码分析
首先我们看一下这个Web Service的源代码,文件名为wshoro.asmx,它将一个含有"Zodiac Sign"的字符串作为输入参数,然后在数据库中对这个字符串信息进行搜索,如果发现了匹配信息,就返回一个包含日期的字符串和对应的预言信息。关于zodiac sign,我们只需知道它包含如下的12种命名: Aquarius, Pisces, Aries, Taurus, Gemini, Cancer, Leo, Virgo, Libra, Scorpio, Capricorn, and Sagittarius。
首先是引入必需的名字空间:
<%@ Webservice Language="C#" class="DailyHoro" %>
using System ;
using System.Web.Services ;
using System.Xml ;
using System.Data;
using System.IO ;
然后声明一个类DailyHoro,它从System.Web.Services 名字空间中延伸了WebSerice类的功能:
public class DailyHoro : WebService
{
....
.....
}
类DailHoro 包含一个公共方法GetHoro,这个方法又被标记为WebMethod属性,这表明了它可以作为一个Web Service被公开访问。GetHoro方法的输入参数是包含zodiac sign信息的字符串,然后将这个字符串传递给另外的私有方法getData,最后由getData方法返回信息给用户:
[WebMethod]
public string GetHoro(string zodiac)
{
return getData(zodiac) ;
}
getData方法在GetHoro方法中被调用。首先打开一个Filesteam文件流用于读取XML数据库文件的内容,然后使用DataSet对象从XML文件中读取数据,接着对DataSet的所有行循环操作,以找到匹配Zodiac Sign的相关信息。寻找成功后,当前日期和对应的预言内容被返回。否则,返回相应的错误信息:
private string getData(string zodiac)
{
try {
file://Create a FileStream
FileStream fin ;
fin= new FileStream(Server.MapPath("db/dailyhoro.xml"),
FileMode.Open, FileAccess.Read,FileShare.ReadWrite );
file://Create a DataSet object to contain our Database
DataSet ds = new DataSet() ;
file://Read the Xml Schema and Data from the stream to the Database file
ds.ReadXml(new StreamReader(fin)) ;
file://close the stream
fin.Close() ;
file://loop to check for the Zodiac sign provided
for(int i=0;i<12 ; i++) {
file://Check if the Zodiac sign provided by the user Equals
file://the "name" field in our Table "zodiac"
if(zodiac.Equals(ds.Tables[0].Rows[i]["name"])) {
file://If a match if found then return the Date and
file://Prediction
string pred =ds.Tables[0].Rows[i]["pred"].ToString() ;
string date = ds.Tables[0].Rows[i]["today"].ToString() ;
return date+"@"+pred ;
}
}
file://If no match found then return a error statement
return "Wrong Parameter" ;
}
catch(Exception ed) {
return "Read Error!!"+ed.ToString() ;
}
=
四、配置Web Service
配置一个Web Service就象配置其他的ASP.NET Web应用程序一样简单。对于上面所述的例子,我们要创建一个名为"horoservice"的虚拟目录,或者仅将程序文件上传到任何支持ASP.NET的服务器就可以。还请记住一点:将文件dailyhoro.xml放置到虚拟目录horoservice下的db子目录下面。
这样就配置好了Web Service。调用方式也很简单,在浏览器中输入以下地址:
http://localhost/horoservice/wshoro.asmx
五、应用Web Service
Web Service已经准备好,现在开始应用这个Web Service。
1、首先创建一个代理类(Proxy Class),它包含如何定位Web Service以及用户界面描述的信息。我们使用WebServiceUtil.exe来创建这个代理类:
WebServiceUtil
/c:proxy
/pa:http://localhost/csharp_test/oroscope/wshoro.asmx?SDL
/n:horo_service
这样就在程序运行目录下创建了文件"DailyHoro.cs"。
2、然后,将源代码进行编译,创建被客户端使用的库文件:
csc
/target:library
/r:System.dll;System.Web.Services.dll;System.Net.dll;
System.IO.dll;System.Xml.Serialization.dll
DailyHoro.cs
命令执行后,将创建一个Dll文件"DailyHoro.dll"。
3、现在开始编写客户端的Web页面文件ClientHoro.aspx。
首先引入必需的名字空间,其中名字空间horo_service包含了前面步骤中创建的代理类:
<%@ Import namespace="System" %>
<%@ Import namespace="horo_service" %>
<%@ Page Language="C#" %>
下面的代码中,gethoro_Click方法用于建立了DailyHoro类的一个实例,它包含在代理库文件中。接着调用DailyHoro类的GetHoro方法,Zodiac Sign作为输入参数被传递。返回的字符串信息被分割成日期和预言,单独地显示出来:
<html>
<head>
<script language="C#" runat="server">
private void gethoro_Click(object sender, EventArgs e) {
file://Get the Selected Item from the DropDownList
string sign = zodiac.SelectedItem.Text;
file://Create a Instance of the Proxy Class
DailyHoro dh = new DailyHoro();
file://Call the "GetHoro" method of the Web Service on the
file://Proxy Object. The Proxy object in turn communicates
file://to the Web Service. Remember the Proxy cannot do
file://anything except act as a bridge between. Your Web
file://Service and the client. It cannot replace the Web
file://Service.
string result =dh.GetHoro(sign);
file://Extract the Date from the Result
preddate.InnerHtml = "<b> Horoscope for " +
sign + " as on " + result.Substring(0,10) +
"</b>";
file://Display the Prediction
predspace.InnerHtml=result.Substring(11);
}
</script>
<title>Horoscope Service Client</title>
</head>
下面的代码用于创建下拉菜单项,其中包含了各种Zodiac Sign信息的名称。我们使用一个按钮来触发Web Service,使用2个DIV标记显示返回信息:
<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>
六、配置Web应用程序(Web Application)
现在我们通过另外一种方式Web Application来使用上面的Web Service。
1、首先将文件ClientHoro.aspx 拷贝到虚拟目录下,将代理Dll拷贝到虚拟目录下的Bin目录中。如果Bin目录不存在,就先创建它。
2、然后,编写客户端应用程序 HoroClient.cs:
/*
Compilation
csc /r:System.dll;System.Web.Services.dll;DailyHoro.dll
HoroClient,cs
*/
using System ;
using horo_service ;
file://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:");
file://Read the Input from the user
string sign = Console.ReadLine();
file://Create a instance of the Proxy Class
DailyHoro dh = new DailyHoro();
file://Make a Call on the Web Service Method "GetHoro" and
file://pass the Zodiac sign to it
string result = dh.GetHoro(sign);
Console.WriteLine("Horoscope for "+sign+" on " +
result.Substring(0,10));
file://Print the Prediction
Console.WriteLine(result.Substring(11));
Console.WriteLine("Press Enter to Exit");
Console.ReadLine();
}
}
上面的代码中包含了一个HoroClient类。类的方法Main从用户端接收输入信息Zodiac Sign,然后创建DailyHoro的实例对象,最后我们调用方法GetHorn得到预言信息。
3、最后,将HoroClient.cs进行编译:
csc /r:System.dll;System.Web.Services.dll;DailyHoro.dll
HoroClient,cs
编译成功后,生成可执行文件"HoroClient.exe",双击它开始应用Web Service。