The XML Web Service Code Model


Web services have two logical parts: the entry point (normally the .asmx file) and the code that supplies the Web service functionality (which is located in the .asmx file, in a separate code-behind file, or in separate assemblies). Building an XML Web service in ASP.NET requires either two or three basic steps:

  • Creating an .asmx file

  • Adding a @WebService directive to the file (if you’re not using Visual Studio .NET)

  • Creating the methods within the Web service

If you’ve created a new .asmx file using Visual Studio .NET, the @WebService directive is created automatically. It tells the compiler the name of the class file to use as an entry point for the Web service. The @WebService directive (not to be confused with the WebService attribute) is placed at the head of the file. Together with the .asmx file, the @WebService directive provides a URL for access to the Web service.

The @WebService Processing Directive

We mentioned in Chapter 1 that the @WebService processing directive has four attributes: language, code behind, class, and debug. This directive defines the values of the attributes within a particular .asmx file. An example directive is as follows:

<%@ WebService  language="C#"      codebehind="RecordStore.Service1.cs" debug="true" %>

We’ll now examine each of the attributes in turn.

class Attribute

The class attribute specifies which class should be exposed directly as an XML Web service. This class is automatically compiled the first time the Web service is accessed. A Web service can be made up of many classes, not all of them necessarily exposed as Web services. The class attribute is required when you use the WebService directive.

The class can also be contained within an assembly. If it is, the assembly file must be located in the bin directory, which itself must be in the Web application’s root folder. The class attribute can be any valid, fully qualified class name.

codeBehind Attribute

The codeBehind attribute specifies that a separate file should be used for the source code for compiling the Web service, when the class specified in the class attribute does not contain it. This is the same principle of code-behind as that commonly seen in Web forms, where presentational HTML is separated out from the actual ASP.NET code behind it.

language Attribute

The language attribute specifies the programming language the class was written in. You must specify this attribute if the Web service code is contained in an .asmx file. This attribute tells the compiler which language compiler should be used to compile the class. Any .NET language can be specified for this attribute, and a shortened version is often supplied. The most common abbreviations are JS for JScript .NET, VB for Visual Basic .NET, and C# for C# .NET. You can add extra languages on top of those by adding them to the machine.config file as a <compiler> element in the <compilation> section. At typical entry for the C# compiler looks like this:

<compilation debug="false" explicit="true" defaultLanguage="vb">   <compiler language="c#;cs;csharp" extension=".cs"      type="Microsoft.CSharp.CSharpCodeProvider, System, Π      Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"     warningLevel="1" />    

The compilation element sets the default language to Visual Basic .NET, so if you want to use C#, you must set the language attribute in the @WebService directive. The <compiler> element specifies the acceptable abbreviations for the language, the extension that classes written in this language should contain, and information about the assembly itself.

You can also add a list of assemblies in the <compilation> section. You specify these assemblies using an <add> element, which requires assembly, version, culture, and PublicKeyToken attributes. A typical entry for the System namespace in machine.config looks like this:

<add assembly="System, Version=1.0.3300.0, Culture=neutral,    PublicKeyToken=b77a5c561934e089"/>

The last assembly defined by an add element is as follows:

<add assembly="*"/>

This <add> element specifies any assembly name not listed, so missing assemblies can be searched for at run time.

debug Attribute

The debug attribute is by default set to false; set it to true if the code is to be compiled with debugging symbols. If it is set to false, the debugging symbols will be omitted.

Web Service Classes and Namespaces

Once you add a directive, you must expose your class to the Web by using the attributes provided in the System.Web.Services.WebService class. This class defines an optional base class for the Web service. It also allows access to common ASP.NET objects such as Application and State.

The WebService class is part of the System.Web.Services namespace. This namespace consists of classes used to transmit data from the client to the Web services. The types contained are used to map SOAP messages to method invocations. This namespace also contains the WebServiceAttribute and WebMethodAttribute classes, which we will use to expose our Web service’s functionality. These two attributes will also feature somewhere within your code when you create Web services. The WebService attribute provides a mechanism for documenting your Web service, and the WebMethod attribute exposes to the Web the particular method to be called.

The WebService Attribute

The WebService attribute is used less often than the WebMethod attribute. It is placed before the class declaration and is used primarily to set the namespace of the Web service. It takes three properties: Name, Namespace, and Description. Here is a WebService attribute that defines a namespace for the class Service1:

[WebService (Name="Record Store Web Service",     Namespace="http://www.notashop.com/wscr",      Description="A web service which exposes the "     + "stock of the record store to the web")] public class Service1 : System.Web.Services.WebService {      }

By default, ASP.NET templates don’t include a WebService attribute.

Next we’ll look at the three public properties of the WebService attribute: Name, Namespace, and Description.

Name Property

The Name property defines the name of the XML Web service. It is also reflected in the WSDL description of the service. When you use this attribute, avoid including spaces because the white space is reflected as _x0020_ in any schema names. For example, the name Record Store (instead of RecordStore) would turn up as Record_x0020_Store in your WSDL and other related XML documents.

Namespace Property

The Namespace property defines the namespace for the server; if it is not set, the namespace defaults to http://tempuri.org. This property is also reflected in the WSDL description of the service. The default namespace used in this chapter (and in the rest of this book) is http://www.notashop.com/wscr.

Description Property

The Description property provides the text to describe the XML Web service. It is also reflected in the WSDL description of the service.

The WebService attribute has no other unique public properties and methods; all other methods are inherited from the attribute or object classes.

The WebMethod Attribute

The WebMethod attribute is the attribute you use to create your Web services. By attaching a [WebMethod] header in C# to a public method or by using <WebMethod> in Visual Basic .NET, you indicate that you want to expose the functionality of that method as a Web service. In fact, methods are the only functionality you can expose using a Web service; if you try to expose gettable or settable properties, .NET will assume that they are methods and will rename them accordingly.

Once created and compiled, a Web method can be invoked by a client using the very names set up in the classes and methods on the server side. The simplest approach is to simply add a WebMethod attribute in front of your method call. You saw this in Chapter 2, with a call that takes a number and a percentage and returns the percentage:

namespace PercentService public class Service1: {     [WebMethod]     public double CalcPercent(int Percent, double Number)     {         double Value = (Number / 100) * Percent;         return Value;     } }

The Web method is then exposed and can be called from within a Windows Forms or ASP.NET Web Forms client application via the proxy class. (We’ll look at these topics in the next chapter.)

PercentService.Service1 WebProxy= new PercentService.Service1(); double Total = WebProxy.CalcPercent(25, 5);

A new instance of the Web service called WebProxy is created from the proxy class, and then the Web method is called from the proxy class, just like a normal method, along with the arguments to be passed to it.

Although we didn’t specify any properties for the WebMethod attribute in this short example, certain values are passed to the Web method by default, as you’ll soon see.

Configuring Web Methods Using Attributes

You can alter or tweak the behavior of your Web method by using the properties of the WebMethod attribute. Two of the six properties simply document the Web method; the other four change aspects of your Web service’s functionality.

The properties of attributes are specified within parentheses, as in this C# example:

[WebMethod(Description="Calculates the percentage value "     + "given a percentage and a number")]

In Visual Basic .NET, attribute properties need an extra colon before the equals operator:

<WebMethod(Description:="Calculates the percentage value " _     & "given a percentage and a number")>

Let’s take a closer look at each of these properties.

Description Property

The Description property contains a plain-text description of your Web method. This information is then reflected in the WSDL description of the service.

MessageName Property

Use the MessageName property to add the name of your Web method. This information is also reflected in the WSDL description of the service.

EnableSession Property

The EnableSession property enables the state management mechanism, allowing Web services to make use of the ASP.NET application and session objects. In ASP.NET (as in classic ASP), the server creates a single application object for each application and a number of session objects, one for each unique session opened by the client.

If this property is set to true, session state can be accessed via HTTPContext.Current.Session. It can also be accessed via a WebService.Session property if the WebService base class has been inherited. When you use sessions, the Web service sends a unique Session ID (stored in a cookie), which must be returned by the client with the next request. The session can then be identified, and the data associated with that session can be accessed on the server. (This can be done in a number of ways, which we will look at later.)

The downside of the EnableSession property is that it can decrease performance considerably. By default, it is set to false. We’ll study this property and the whole concept of session management and Web services in greater detail later in this chapter.

CacheDuration Property

The CacheDuration property sets the number of seconds that the output from a Web method will be stored in memory. The output is stored as a request/response pair, which is held in the cache. During this period of time, any further requests to the same Web method, with the same parameter values, will result in the output being sent from the cache without the Web method being invoked. Setting this property to 0, the default, disables caching of the results.

The cache stores each request and response within a hash table in memory, to reduce the amount of server resources required. Caching can be useful if you are returning data from a data source that doesn’t actually affect the contents of the data store— such as when you are requesting a stock price or when you are asking frequently for data that doesn’t change much (such as articles in an online magazine).

However, in most situations that involve a large range of possible requests, caching doesn’t improve performance greatly because the cache isn’t actually used, and a new journey is required to invoke the Web method and get back a new response. The more often the Web method is called, the larger and less efficient the hash table becomes. At other times, such as when you write to an event log, it is not possible to use the cache. The best kind of data to cache is read-only data.

TransactionOption Property

You use the TransactionOption property to set the level of support for .NET distributed transactions. Distributed transactions are a series of actions grouped into a logical whole. In .NET, transactions are supported via the Systems.EnterpriseServices namespace. As transactions take place over HTTP, a Web service can take part only as the root object of the transaction—in other words, all the components participating in the transaction must be called from one Web method.

The five possible settings for enabling the level of transaction support through TransactionOption basically boil down to two groups. The first group specifies that the Web method should not be run within the scope of the transaction and should be disabled, and the second group specifies that a new transaction is required. In each group, the individual settings don’t provide any unique functionality despite the five different names.

  • Disabled Disables transactions for the Web method.

  • NotSupported Disables transactions for the Web method.

  • Supported Disables transactions for the Web method.

  • Required Requires a new transaction to be created. The new transaction is created for the Web method.

  • RequiresNew Requires a new transaction to be created. The Web service is created within a new transaction.

The transaction releases its resources on successful completion. It can be aborted only by the throwing of an exception or the calling of the SetAbort method of the System.EnterpriseServices.ContextUtil class.

BufferResponse Property

The BufferResponse property allows the response to be kept in a memory buffer until the buffer is full or the response has been completed. If this property is set to true, the default, the entire response is buffered before it is sent to the client. This behavior helps minimize the amount of communication needed between the client and the Web server, Microsoft Internet Information Services (IIS).

A BufferResponse setting of true might not be desirable when large amounts of data are sent back by the Web method. In Chapter 2, you saw how a dataset can be sent back by a Web method; the dataset involved was relatively small, but you could see that if it had returned more than a couple of columns and rows, together with the SOAP needed to wrap it, a large amount of data would have been involved.

If you set the BufferResponse property to false, the response is sent back to the client as it is serialized, in chunks of 16 KB. You’ll generally want this property set to the default, except for users who are browsing the service via an ASP.NET client; instead of making them wait for all the data to be sent, you can show them some of the data while the page is loading.




Programming Microsoft. NET XML Web Services
Programming MicrosoftВ® .NET XML Web Services (Pro-Developer)
ISBN: 0735619123
EAN: 2147483647
Year: 2005
Pages: 172

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net