Vous êtes sur la page 1sur 10

Building XML Web Services Using C# and ASP.

NET
The term "web service" refers to a form of a component that can be used remotely over the web.
Web services are invoked remotely using SOAP or HTTP-GET and HTTP-POST protocols. Web
services are based on XML and return an "answer" to the client in XML format. Web services have
all the advantages of components plus many more. The most significant benefits include:

• Language and platform independence: Web services can be built and consumed on
any operating system just as long as that operating system supports the SOAP protocol
and XML.
• Automatic upgrade: Unlike components, if a web service requires an update, that update
is propagated to all applications consuming that web service immediately. This is because
the actual methods and properties for the web service are invoked from the web server
remotely, meaning that each function contained within a web service appears as a "black
box" to a client: they aren't concerned with the way the function does its job, just as long
as it returns the expected result.

Commonly Used Jargon


As with all new technologies, web services come with a lot of associated jargon. Here's a list of
some terms that you'll come across as you begin your journey down the web services highway:

UDDI
Well, this isn't the case at the moment, but I'm pretty sure that in the future there will be
thousands of web services on the Internet. The question is how are we going to find the web
services we are looking for? UDDI (Universal Description, Discovery and Integration) is the
answer to that question. UDDI is a registry that provides a place for a company to register its
business and the services that it offers. People or businesses that need a service can use this
registry to find a business that provides the service. The UDDI server serves as yellow pages to
WebServices.
When you search for a web service using UDDI's web service or web browser, UDDI returns a
listing of web services that matched your criteria. This list is returned in the form of a DISCO or
WSDL document.

WSDL
WSDL (Web Services Description Language) is a language that describes a web service. It
contains information such as where you can find the web service, methods and properties that it
supports, its data types, and the protocol used to communicate with the web service. WSDL is
based on the XML format and it's used to create proxy objects. Basically, without a WSDL
document, developers wouldn't be able to use web services simply because they wouldn't know
which methods and properties they support and also which communication method any particular
web service supports.

DISCO
DISCO (Abbreviated from discovery) is a list of WSDL documents. DISCO is used to group
common web services together. DISCO documents are also in XML format.

SOAP
SOAP (Simple Object Access Protocol) is a protocol to transport data to and from the web server,
mostly using HTTP. It is in XML format and allows you to transport a variety of data types used in
.NET. As an alternative to SOAP, we can use HTTP-GET and HTTP-POST, which will be covered later
in the article. These protocols return the output in a non-SOAP format; however this output is still
in XML format.
Usage Syntax
In this section we'll build a simple web service to demonstrate the fundamentals of web service
building. Our web service will contain just one method called HelloWorldMethod.
HelloWorldMethod returns a string, "Hello World". We'll add modifications to this web service as
we learn more about the available features of web services.

The following code shows the most basic web service:

<%@ WebService Language="C#" class="HelloWorld"%>

using System.Web.Services;

public class HelloWorld : WebService


{
[WebMethod]
public string HelloWorldMethod()
{
return "Hello World";
}
}

Copy the code above into your favorite text editor and save the file into the virtual directory we
created above as HelloWorld.asmx.

[Note] The file extension for a web service is .asmx. [End Note]

You can now access our HelloWorld web service in your browser by visiting
http://localhost/HelloWorld/HelloWorld.asmx.

You should see a page that looks like this:

This web page is automatically built by IIS using the WSDL of our web service. You can change
how this page looks but that's out of the scope for this article. You can view the raw WSDL by
clicking on the link to "Service Description", which will forward you to the WSDL for our web
service, which looks something like this:

As you can see, the WSDL shows where you can find the web service (URI) and other useful
information including the methods that we have created in our web service.
Now that we've built the web service, we need to be able to use it. On the main web service page,
you can see the method that we've created. If you click on the method, it will forward you to this
page:

If our method actually took a parameter, we would be given a text box for us to enter its value
into. However, because our method doesn't take any parameters only the invoke button is
provided, which will run the method and display the returned output as XML. This page is
especially useful for testing purposes during the development and also to allow consumers to
check if the web service is what they expected it to be.

When you click on the invoke button, you'll get the following result:
If you examine the XML then you will see that "Hello World" was returned between a <string>
tag. As you've probably guessed by now, the tags name specifies the data type of the returned
value. Another thing to note is "http://tempuri.org/". This is the default namespace assigned to
our web service, and unless we change the attribute using the web service attribute, it will display
this URI as the namespace of our future web services as well.

Let's now look at the code that made our web service:

<%@ WebService Language="C#" class="HelloWorld"%>

Like any other ASP.NET page, web services also support directives. This just tells the compiler
that the C# language is used and that the HelloWorld class contains methods and properties
which should be exposed.

public class HelloWorld : WebService

This line is very important. It tells the .NET compiler that our HelloWorld class inherits from the
WebService base class, which contains everything that's required to make our class a web
service.

[WebMethod]

This line is written just before the method, and it's a C# attribute that indicates to IIS and the
.NET compiler that the following method is to be exposed and web callable. The rest of the code is
simple C#, so you shouldn't have any trouble with it.

Web Service Attribute


Almost all the time when you're developing for the "real" world, you'll want to provide a
description for your web services. You might also want to change the default namespace and give
your web service a different name. All of these can be changed using WebService attributes. You
can add an attribute and its appropriate properties just before the class declaration, like this:

[WebService(Name="Hello World", Description="Hello World Application developed by James


Yang", Namespace="devArticles")]

public class HelloWorld : WebService

When you view the web service page now, it will look like this:
Notice how the name has changed from HelloWorld to Hello World. The description attribute that
we specified is also shown. The instructions on how to change the namespace attribute are gone
as well, and the namespace is also changed.
The biggest change however, is on the deletion of all of the instructions and template descriptions
for the web service. IIS and the compiler assume that by specifying a namespace, our web
service is no longer in the development stages and therefore removes unnecessary developer
information for us.

Web Method Attribute


Attributes can also be added to each method individually. The available properties are:
• Description
• EnableSession
• MessageName
• TransactionOption
• CacheDuration
• BufferResponse

If you change the line

[WebMethod]

to

[WebMethod(Description ="Hello World Method")]

... then you will see the following change on our web service page:

Back to the web method attributes, MessageName is simply an alias for the method. This is
particularly useful for parameter-overloaded methods, as requests through a browser cannot
display two methods with the same name. The CacheDuration property sets the amount of time
that the data will be cached for. This property is an integer and therefore it must contain a whole
numeric value. The BufferResponse property is a Boolean property. If set to true, output is
buffered and only transmitted once.

The TransactionOption property allows us to specify how transactions will be supported in this
method. The available options are:
• Disabled - Ignores any transaction in the current context.
• Notsupported - Creates the component in a context with no governing transaction.
• Supported - Shares a transaction, if one exists.
• Required - Shares a transaction if one exists and creates a new transaction if necessary.
• RequiredNew - Creates the component with a new transaction, regardless of the state of
the current context.

The EnableSession property is a Boolean property and allows us to enable sessions (this requires
the use of the proxy object). Without the proxy object, this web property cannot be implemented
as the property is discarded as soon as the value is assigned to it. Without a proxy object, only
one request is allowed per session, and assigning a value to the property itself is a request and
therefore the session is ended just after.

Web Properties
A web property can be created like this:

string _property;

public string HelloWorldProperty


{
[WebMethod(EnableSession=true)]
get
{
return _property;
}
[WebMethod(EnableSession=true)]
set
{
_property = value;
}
}

Notice how the EnableSession property of our WebMethod attribute is set to true. If you open up
your web service page again, then you will see that get and set have been implemented as two
separate methods:

Protocols
ASP.NET supports three different protocol types:
• HTTP-GET
• HTTP-POST
• SOAP
When we pass a parameter on the web services page that we looked at earlier, we're actually
passing the value using the HTTP-GET protocol. You can see this from the URL of the returned
page, for example:

http://ws1/helloworld/helloworld.asmx/HelloWorldMethod?

"?" is used to pass values with the HTTP_GET protocol. We can pass parameters on the web
service web page if we modify the showPost flag of defaultwsdlhelppagegenerator.aspx to true,
which located in the c:\winnt\system32\Microsoft.NET\Framework\[Version] directory.

One important thing to notice here is that the two methods shown above return the result in XML
format and not SOAP. Results returned as XML can be used in an application by treating the data
as an XML document, but there is a better way to use web services. Its called SOAP.

SOAP is a 3rd generation protocol that can be used to communicate with web services. It's actually
composed of lightweight XML that's dedicated to the transportation of data structures information
and the actual data itself. SOAP is sent using the HTTP-POST protocol:

POST /helloworld/helloworld.asmx HTTP/1.1


Host: ws1
Content-Type: text/xml; charset=utf-8
Content-Length: length goes here
SOAPAction: "devArticles/HelloWorldMethod"

<?xml version="1.0" encoding="utf-8"?>


<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/">
<soap:Body>
<HelloWorldMethod xmlns="devArticles" />
</soap:Body>
</soap:Envelope>

Every SOAP message has an Envelope, a Header (optional) and Body (SOAP message in XML
Format).

SOAP Message format

SOAP Envelop defines the content of the message.


SOAP header (optional) contains header information.
SOAP body contains call and response information.

Advantages of SOAP
Before the advent of web services and .Net, technologies like DCOM, CORBA and RMI were used
for network communication. But these technologies are vendor specific and interoperability
between them was quite complex. Remote procedure calls (RPC) was used for communication
between technologies like DCOM and CORBA, but HTTP was not designed for this. RPC calls are
(mostly non-compatible and) less secure and firewalls/proxy servers will normally block this kind
of traffic. Most of the corporate networks use proxy/firewalls that allow only HTTP requests. Web
sites too allow mostly HTTP traffic through port 80. All Internet browsers and servers support
HTTP. So HTTP is generally a better way to communicate between applications. SOAP
accomplishes this.

.NET understands SOAP and behind the scenes it organizes the resultant data into the right type
of application defined data for us. For example, if we use a proxy object to invoke our web service
then SOAP is automatically used. If the web service returns a string, then .NET extracts this value
and assigns it to a new string object. This string object can then be used in our applications,
without even knowing that SOAP was handling the web service request for us!

SOAP and the web service session actually allow us to create an instance of our web service and it
automatically calls the appropriate methods for us behind the scenes. This process is called XML
Serialization.

For example, if we setup a proxy object for the HelloWorld web service that we created earlier, we
could use the following code to invoke it:

HelloWorld hw = new HelloWorld


hw.HelloWorldProperty = "Property Value";
Console.WriteLine (hw.HelloWorldProperty);
hw.HelloWorldMethod();

Generate a Proxy class for the Web Service


The .NET SDK simplifies the process of creating Web Service clients by providing the Web Services
Description Language (wsdl.exe) utility. This utility generates proxy source code for an existing
Web Service

wsdl /l:CS /protocol:SOAP http://localhost/OIDServer/OIDServer.asmx?WSDL

The above command creates a proxy for the OIDServer web service from the WSDL document
obtained from the URL http://localhost/OIDServer/OIDServer.asmx?WSDL. The proxy uses SOAP
as its protocol to talk to the web service and is generated as a C# source file. The wsdl.exe utility
can also take a WSDL file as input instead of a URL pointing to the location where the WSDL can
be obtained. We can compile the C# source file into a dynamic link library (DLL) and then add a
reference to this DLL to any project you want to create.

csc /t:library /r:System.Web.Services.dll /r:System.Xml.dll OIDServer.cs

Web Service Type Marshalling:


Web Service Type Marshalling is the process of moving different data types over the web. Various
data types can be passed to and back from Web Service methods. As the XML Web services
implementation is built on top of the XML Serialization architecture it supports lots of data types.
The code samples below provide examples for marshalling the following types: String, Array,
Class, Integer and Dataset.

Integer
//This WebMethod will take two integer arguments and return the result as an int.

[WebMethod]
public int Add (int A, int B)
{
return A+B;
}

String
//This WebMethod will take no arguments and return the result as a string.
[WebMethod]
public string HelloWorld()
{
return "Hello Lloyd";
}

Class
//This WebMethod will take no arguments and return the result as a class.

[WebMethod]
public Person GetMyRecord ()
{
Person s= new Person ();
s.Name ="Lloyd Almeida";
s.age ="1.5";
s.Address ="1036 san Jacinto drive";
return s;
}

Integer Array

//This WebMethod will take no arguments and return the result as an array of int.

[WebMethod]
public int[] MyMarks()
{
int i;
int [] Marks = new int [5];
for (i=0;i<5;i++)
{
Marks[i]=3*20;
}
return Marks;
}

Dataset
//This WebMethod will take no arguments and return the result as a Dataset.
// This WebMethod reads the windows eventlog and constructs an XML message in a file and then
// writes the message from the file to a Dataset.

[WebMethod()]
public DataSet ReadEventLog()
{
DataSet ds = new DataSet(); // Creating DataSet objects
EventLog aLog = new EventLog();
AppLog.Log = "Application"; //Reading only Application logs
AppLog.MachineName = "."; // Local machine

string str="<?xml version='1.0' ?>";


str=str+"<MSG>";

foreach (EventLogEntry entry in AppLog.Entries)


{
str = str +"<Msg>";
str=str + "<Type>"+entry.EntryType+"</Type>";
str =str+"<Date>"+entry.TimeWritten.ToString()+"</Date>";
str =str +"<Source>"+entry.Source+"</Source>";
str =str+"<Description>"+entry.Message.ToString()+"</Description>";
str=str+"</Msg>";
}
str=str+"</MSG>";
FileStream fs = new FileStream("c:\\Raga.xml" , FileMode.Create, FileAccess.ReadWrite);

//Now let's put some text into the file using the StreamWriter
StreamWriter sw = new StreamWriter(fs);
sw.WriteLine(str);

sw.Flush();
sw.Close();

ds.ReadXml("c:\\raga.xml");

return ds;
}
The Windows EventLog returned from ReadEventLog WebMethod as a dataset looks like this:

Web Services Capabilities


This part of the article ends with some fast facts on web services capability. The following table
depicts a web services capability matrix:

Capability Web services


Invoke single method on a stateless object Yes
Invoke multiple methods on a stateful object No
Have all clients invoke methods on the same server side object No
Pass through firewalls Yes
Uses HTTP for communication Yes
Uses raw TCP socket for communication No
Use IIS as host Yes
Allow custom host No
Uses SOAP-compliant formatting of data Yes
Uses smaller binary formatting of data No
Retrieve partial copy of data from complex object Yes
Retrieve complete copy of complex object No

Vous aimerez peut-être aussi