Create and Consume Web Services at Server and Client

by Colin Tong


What and Why Is Web Services

    Web Services, as known as XML Web
Services
, are units of application logic that provide data and
services to other applications using Internet (or Intranet). Applications
access Web Services via different kinds of Web protocols and data
formats such as XML, with no need to worry about how Web Services are
implemented. They can be implemented for any operation system that
supports communication over the Internet and Intranet. They are the
cornerstones of the Microsoft .NET programming model.

     Web Services can be accessed by any
language, using any component model, and running on any operating system. They
utilize HTTP as the underlying transport, which allows function requests to
pass through corporate firewalls. XML is used to format the input and output
parameters of the request, so the request is not tied to any particular
component technology or object calling convention. The Microsoft .NET Framework
makes Web Services  easy to write components that
communicate using HTTP and SOAP. 


      Web Services  are similar to
the regular services in our life.  For example, if you have a car that
needs gasoline to run, you do not need to have your own gas pump at home. All
you need to do is drive to a nearby gas station, fill up the gas tank, and you
are on your way. You have received a service from the gas station, Web
Services
are like this as well. Now, imagine that you are going to
build a web site or a Internet system for you company, you can use Web
Services’
“services” to get a complicated application. That should
lighten your work load. 

Building Web Services

      Before you start to create your Web Services,
there are some of concepts you have to know. The two most important 
things are the Simple Object Access Protocol (SOAP) and XML. SOAP is a way for
applications to communicate with one another over the Internet,
independent of platforms. Unlike Http-Get and Http-Post, only can send
name/value, but SOAP can send various rich data type, classes, objects, and
others. XML is a pared-down version of SGML, designed especially for Web
documents. It allows designers to create their own customized tags, enable the
definitions, transmission, validation, and interpret data between applications
and between organizations. SOAP relies on XML.




      Web Services relies on XML-formatted
messages to send data and receive commands. Web Services support three
stardard protocols, Http-Get, Http-Post, and SOAP. In Web Services , the
Http protocol only can be use the simple data. We do not discuss it here. All Web
Services
exmaples in this artical use SOAP communication.

       Now let’s explore how to build a Web
Service
at server. There are two ways to do so. If your Web
Service is quite simple, you can directly save it as a .asmx
file, such as TempConvertorCsharp.asmx. In some complicated
applications, especially for database related applications, I prefer to use
components. For instance, The DB Query1/2-Web Service at my .NET
tutorial, I created the classes as component first, then created a .asmx

Web Service file that called the component (to create a component,
see my .NET tutorial for details.) The whole structure of the service is
“UI-Component(Web Service classes)-Database” known as 3-tier archecturre.

       Now let’s create a Web Service that
converts degree Fahrenheit and Celsius each other using C#, and
using directly save it as .asmx.



      C# code:

1  <@ WebService Language=”C#” Class=”TempConvertor” %>
2
3 using System;
4 using System.Web.Services;
5
6 public class TempConvertor : WebService
7 {
8 [WebMethod(Description=”This method converts a degree
fahrenheit to celsius.”)]
9 public double TemptureF(double F)
10 {
11 double C = (F – 32) * (5.0/9.0);
12 return (C);
13 }
14
15 [WebMethod(Description=”This method converts a degree
celsius to fahrenheit.”)]
16 public double TemptureC(double C)
17 {
18 double F = C * (9.0/5.0) + 32;
19 return (F);
20 }
21 }


     VB.NET code:

1  <%@ WebService Language=”VB” Class=”TempConvertor” %>
2 Imports System.Web.Services
3 Public Class TempConvertor : Inherits WebService
4 <WebMethod()> Public Function TemptureF(intF as integer)
As Integer
5 dim intC as integer = (intF – 32) * (5.0/9.0)
6 Return (intC)
7 End Function
8 <WebMethod()> Public Function TemptureC(intC as integer)
As Integer
9 dim intF as integer = intC * (9.0/5.0) + 32
10 Return (intF)
11 End Function
12 End Class



       Let’s take a close look at
the C# code. First of all, on line 1 we wrote the WebService Directive
that declares this file represents a Web Service. The directive
has two attributes that are Language (C#, VB.NET
or JScript), and setting to C# in our case, and Class

that is the WebService Name , and setting to TempConvertor.
Secondly, we used (imported) the System.Web.Services namespace on
line 2. On line 3 the class TempConvertor used : WebService
(: Inherits WebService for VB) to inherit from the WebService

class. Finally, on following lines we created two Web Services
, and they are almost same as normal functions we wrote before except
the [WebMethod(…)] (<WebMethod(…)>
for VB) front each function that you want them to be Web Service
. The WebMethod has some of properties, such as BufferResponse,
CacheDuration, Description, EnableSession,
and so on. Please check
Microsoft.NET Framework Developer’s Guide for details.

       Save above file as TempConvertorCsharp.asmx.

Now the Web Service is ready to deliver to the world.

Consuming Web Services

       Consuming a Web Serviceis how a
client uses a Web Service

 from an Internet. It is easy, but not easy as filling  your gas
tank. You may follow a 4-step guide.

      1) Discovering and gathering information about
the service.
    Let’s use browser to view this .asmx
file that we just created at server as below:
      Type in http://24.156.78.145/mydotnet/webServiceLib/tempConvertor.asmx?DISCO

in your browser (please modify it in which your Web Service is), which you are
discovering this Web Service , known as Discovery. Discovery
is the process by which a client application finds a Web Service
.

     Let’s take a look at the Web Service we
just created at    

     http://24.156.78.145/mydotnet/webServiceLib/tempConvertor.asmx

Click for Full Size Version
Figure 1: Click for Full Size Version

      This page, known as HTML Description Page that
gives the details of so many items for the Web Service, and even allows
you test the methods in the service. If you click the “Service Description” on
the page or directly type in
“http://24.156.78.145/mydotnet/webServiceLib/tempConvertor.asmx?WSDL” (type in
the address in which your Web Service is) in the browser, you will see a
XML formatted file that is the way the Web Service will
be sent to any client who may use the service throught SOAP or HTTP. The WSDL

stand for Web Service Description Language. WSDL
is a general purpose XML language for describing the interface, protocol
bindings and the deployment details of network services.


      2) Generating a proxy class of the service.
    At your command prompt (I have used VS.NET command prompt
for this example.), use following command to generate a proxy class that
at client based on the web service file tempConvertorCsharp.asmx

we just create at server. 

      C:\inetpub\wwwroot\mydotnet\WebServ>wdsl
/l:C# /n:TempConvertorClientCsharp http://24.156.78.145/mydotnet/WebServiceLib/TempConvertorCsharp.asmx?WSDL


      You should see something as below.

Click for Full Size Version
Figure 2: Click for Full Size Version

       The l is short for language,
and the n is short for namespace. In our example, we valued them C#
and TempConvertorClientCsharp respectively. The used WSDL.exe that
is provided by Microsof.NET framework SDK to create the proxy class called
TempConvertor.cs that we should see at:
C:\inetpub\wwwroot\MyDotNet\WebServ\TempConvertor.cs

after we implement WSDL command. The WSDL.exe transfer
the XML format of the Temperature Convertor Web Service
through SOAP to the client. (download TempConvertor.zip below)


      3) Using the created proxy class to invoke an
available service for client self.
    To make the proxy
be a pre-compile class .dll(or exe) at your command prompt, type in:

csc /t:library /out:..\..\bin\TempConvertorClientCsharp.dll
/r:System.dll /r:System.Web.Services.dll /r:System.Xml.dll
TempConvertor.cs


and you should see something as below.


Figure 3: Click for Full Size Version

       This command was compiled the TempConvertor.cs

to TempConvertorClientCsharp.dll
class and put it into your bin/ directory. The bin/ is a very important
directory for ASP.NET application. As you might know, in the ASP technology a
component (COM) has to be registered to web server, and any updating to a
component, the server has to reboot. This processing causes so many problems to
development and web server administration. From this view, .NET has a
revolution change that a component, just as our proxy class, no long needs be
registered, all we need to do is that we just simplly save the component under
the bin/, and .NET will automatically find it. There is no server rebooting
needed after a component created or updated as well. Thanks .NET. Now, we are
ready to use the service component class.

      4) Writing an interface for a Web Service.
     All we need to do is that using (importing) the proxy
class in our ASP.NET page as below code.



1 <%@ Page Language=”VB” Debug=”true” %>

2 <%@ import Namespace=”TempConvertorClientCsharp” %>
3
4 <script runat=”server”>
5 ‘dim objTempConv as new TempConvertorClientCsharp
‘.TempConvertor
6 dim objTempConv as new TempConvertor

sub SubmitF(obj as object, ev as eventargs)
lblMessageF.Text=objTempConV.TemptureF(tbF.Text)
end sub
sub SubmitC(obj as object, ev as eventargs)
lblMessageC.Text=objTempConV.TemptureC(tbC.Text)
end sub
</script>
<!DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 4.0 Transitional//EN”>
<html>
<head>

<title>Using A Web Service</title>
<meta name=”GENERATOR” content=”Visual Studio.NET 7.0″>
</head>
<body>
<form runat=”server”>

Enter a number as Fahrenheit(F):
<asp:Textbox id=”tbF” runat=”server” />
<asp:Button id=”btSubmitF” runat=”server” text=”SubmitF”
OnClick=”SubmitF” />
<p>
Celsius(C):
<b><asp:Label id=”lblMessageF” runat=”server” /></b>
<P>

<hr>
Enter a number as Celsius(C):
<b><asp:Textbox id=”tbC” runat=”server” /></b>
<asp:Button id=”btSubmitC” runat=”server” text=”SubmitC”
OnClick=”SubmitC” />
<p>
</form>

Fahrenheit(F):
<asp:Label id=”lblMessageC” runat=”server” />
</body>
</html>


       This is easy to you if you go through from
beginning of my .NET tutorial. Only one reminder, that is: on line 2, we
imported the Web Service class to our asp.net page, which is key for this page.
If you do not like to import this way, you might remove line 2 and use the
whole name of the proxy class as line 5.

Securing Web Services

     From business, of course, you must protect your Web
Services
and only provide them to the client with your
authentication. This security measure involves using SOAP relied on XML to send
authentication information with Web Service command. You need
use SOAP header to pass along username and password
information so that only the users you choose can access the service. I am
going to list the structure of the DBQuery2-WebService with security(VB)

that I used SOAP header to secure this Web Service
at my .NET tutorial. Be attantion, this is a VB.NET code.



Namespace DBService2
Public Class Authenticator : Inherits SoapHeader
Public UserName as string
Public Password as string
End Class

Public Class DatabaseService2 : Inherits WebService
‘… some declarations …
public sHeader as Authenticator
private connstr as string = “database connection string”

<WebMethod(), SoapHeader(“sHeader”)> public function
SelectSQL(…) as DataSet
if sHeader is Nothing then
throw new Exception(“Warning: Invalid login!”)
end if

if Authenticate(sHeader.UserName, sHeader.Password) then
try
‘…processing what you want …
catch ex as OleDbException
return nothing
end try
end if
end function

private function Authenticate(strUser as string, strPw
as string) as Boolean
try
… check if the UserName and Password are authentic
return true
catch ex as OleDbException
return false
end try
end function
End Class

End Namespace




     Now we finish the whole Web Service
procedure, which is from creating to consuming.

More by Author

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Must Read