Developing a Simple Concatenate Web Service


From the File menu select New Project. The dialog box with different types of projects will be displayed, as shown in Figure E-5. Select ASP.NET Web service from the Visual C# Projects and type the location of the localhost Web server (or the name of the IIS Web server on which to host the XML Web service). After typing the location, press the OK button. Visual Studio automatically creates the necessary files and references to support a Web service. After you press OK, the IDE displays the .asmx file in Design View (since XML Web services are inherently nonvisual, you cannot drag and drop controls or other visual elements in Design View). Click the link Click here to switch to code view in the Design View to add the code to the Web service. [1]

[1] The project created by Visual Studio has commented-out code already provided for a simple "Hello World" Web service. To implement that Web service, just uncomment the code, then build and run.

Figure E-5. Creating a Concatenate ASP.NET Web application project.

graphics/efig05.gif

When the project is created, the Web service has the name Service1.asmx . Rename the Service1.asmx file in the Solution Explorer Concatenate.asmx . The addressable entry point for the Web service is specified by the .asmx file Concatenate.asmx . The implementation for the methods that the Web service provides is in the file Concatenate.asmx.cs . To view the .asmx file, right-click the .asmx file in the Solution Explorer and select Source Code (Text) Editor in the Open With dialog box, and then click Open, as shown in Figure E-6.

Figure E-6. Open With dialog box.

graphics/efig06.gif

Use the following URL to access the program: http://localhost/Security/AppendixE/Concatenate/Concatenate.asmx .

Concatenate.asmx and Concatenate.asmx.cs

The code of the Concatenate.asmx file has just the following WebService directive:

 <%@ WebService Language="c#" Codebehind="Concatenate.asmx.cs" Class="Concatenate.Service1" %> 

The code of Concatenate.asmx.cs file is as follows .

[View full width]
 
[View full width]
using System; using System.Collections; using System.ComponentModel; using System.Data; using System.Diagnostics; using System.Web; using System.Web.Services; namespace Concatenate { [WebService(Namespace="http://www.phptr.com", Description="A Simple Web Service.", graphics/ccc.gif Name="Concatenation")] public class Service1 : System.Web.Services.WebService { public Service1() { InitializeComponent(); } //Component Designer generated code protected override void Dispose(bool disposing) { } //If you add "WebMethodAttribute" to a method in a Web //service then it makes the method callable from a remote //client. [WebMethod (Description="Web Service which provides Concatenation functionality.")] public string Concatenate(string s1, string s2) { string s3="Concatenated String ="; return s3+s1+s2; } } }
TESTING CONCATENATE WEB SERVICE

Even without creating a client for your Web service, you can view and test it by employing ASP.NET. After creating the Concatenate Web service in Visual Studio .NET, just click the Run button to view the IE (Internet Explorer) test page. [2] Figure E-7 shows the IE test page, which lists all the available Web service methods. (In our example, only one, Concatenate , is available.)

[2] The Internet Explorer test page is an automatically created HTML page with which you can execute and test a Web service's methods and review its WSDL document.

Figure E-7. The Internet Explorer test page for the Concatenate Web service.

graphics/efig07.gif

Now, let us test our Web service by clicking the link Concatenate in the IE test page. Figure E-8 shows the test page that is displayed when you click the link. This test page has two sections. The first part consists of two textboxes and an Invoke button that allows you to run the Concatenate Web service method without needing to create a client. The second part consists of a list of different protocols (HTTP POST, HTTP GET, and SOAP) you can employ to connect with the Web service and a description for each message format. If you press the Invoke button, the result is displayed inside a new browser window in the XML format, as shown in Figure E-9.

Figure E-8. Invoking Concatenate Web service method.

graphics/efig08.gif

Figure E-9. The result from Concatenate Web service method in XML format.

graphics/efig09.gif

SERVICE DESCRIPTION

If you click the Service Description link, WSDL is displayed that defines the service description of that Web service, as shown in Figure E-10. A WSDL document can be logically divided into two sections:

  • Abstract definitions: Types, messages, and port types

  • Concrete definitions: Bindings and services

Figure E-10. Viewing the Concatenate Service Description (WSDL document).

graphics/efig10.jpg

WSDL Element: type

This element provides the definition for the datatypes in a SOAP message. The <types> element contains an XSD schema. For example, the <types> section in the WSDL file of the concatenate Web service defines the following types:

  • Concatenate is used when SOAP invokes the Web service.

  • ConcatenateResponse is used when the SOAP Web service invocation returns. Concatenate has two elements, s1 and s2, which are defined with the XSD type's string.

WSDL Element: message

The <message> section offers a description of the message.

WSDL Element: portType

The <portType> section describes the service interfaces of the operations that the Web service supports. If there had been more Web methods in the Web service, there would have been more operation elements allied with the portType .

WSDL Element: service

The <service> section describes the URL of the Web service on the server.

WSDL Element: binding

The <binding> section defines the data encodings and protocols to be used for each operation.

Later, we discuss how to consume the developed Web service. Now, let us study in detail the WebService directive and the System.Web.Services namespace.

@ WebService Directive

To declare a Web service, place the WebService directive at the top of a file with an .asmx extension.

 <%@ WebService class="Service1" Language="cs" %> 

The WebService directive indicates the class implementing the Web service and the programming language used in the implementation. The essential attributes of the WebService directive include the following:

Class attribute: This attribute indicates the class with Web service implementation. It can be set to a class that exists in the same file as in our previous example or within a separate file placed in the Bin folder under the directory where .asmx is situated.

Language attribute: This attribute indicates the programming language used to create the Web service. You can develop Web services in any .NET-compatible language, such as C#, Visual Basic.NET, and JScript.NET.

Codebehind attribute: If the implementation of the Web service resides in a code-behind file, then this Codebehind attribute specifies the file.

If the implementation of the Web service resides in an assembly, then declare as follows:

 <%@ WebService Language="cs" Class="Class Name, Assembly Name" %> 

System.Web.Services Namespace

The System.Web.Services namespace consists of the classes that facilitate development and use of Web services. Let us investigate the classes in System.Web.Services namespace in detail. Table E-1 shows the classes in the System.Web.Services namespace.

Table E-1. Classes in System.Web.Services Namespace

Item

Details

WebServiceAttribute (Optional)

May be used to add more information to Web services, such as a string describing its functionality.

WebService (Optional)

Delineates the base class for Web services if you want to use common ASP.NET objects such as Server, Session, User , Context , and Application .

WebMethodAttribute

If you add this attribute to a method in a Web service, it makes the method callable from a remote client.

WebServiceAttribute

You can use the WebServiceAttribute to add information to a Web service. It is optional. This is used in the service description and the service help page of the Web service. The attribute is not required for a Web service to be published and executed. Table E-2 shows the instance properties of the WebServiceAttribute class .

Table E-2. Instance Properties of the WebServiceAttribute Class

Properties

Description

Description

Provides descriptive comments about the Web services.

Name

Provides the name for the ASP.NET Web service.

Namespace

Provides the default XML namespace for the Web service.

In our first example, Concatenate.asmx , you may notice these properties in the code and in the program output as follows.

  • Description : "A Simple Web Service."

  • Name : "Concatenation"

  • Namespace : http://www.phptr.com

The default value of the namespace is http://tempuri.org/ for Web services that are under development, but published Web services should use a more permanent namespace. It is highly suggested that this default namespace should be personalized before the Web service is made publicly consumable. This is important because the Web service needs to be distinguished from other Web services. To apply the WebService attribute, insert the WebService attribute before the class declaration and set the Namespace and Description properties. Separate multiple properties with a comma.

[View full width]
 
[View full width]
[WebService(Namespace="http://www.phptr.com", Description="A Simple Web Service.", graphics/ccc.gif Name="Concatenation")] public class Service1 : System.Web.Services.WebService { //Implementation }

When you run the Concatenate program without the WebService attribute, you can see more details concerning the need for the WebService attribute in the test page.

WebService Class

System.Web.Services.WebService class is an optional base class for Web services, which provides access to common ASP.NET objects such as Session, Server, Application, Context , and User . You can derive Web services directly from System.Object , but, by default, Web services created using Visual Studio .NET automatically derive from the WebService base class. If you create a Web service without deriving from the WebService class, then you cannot access the ASP.NET objects. If the Web service does not inherit from the WebService base class, it can access the ASP.NET intrinsic objects from System.Web.HttpContext.Current . Let's scrutinize the properties of the WebService class. Table E-3 shows the properties of the WebService Class.

Table E-3. Properties of the WebService Class

Properties

Description

Application

Gets the Application object for the current HTTP request.

Context

Gets the ASP.NET HttpContext for the current request, which encapsulates all HTTP-specific contexts used by the HTTP server to process Web requests .

Server

Gets the HttpServerUtility for the current request.

Session

Gets the HttpSessionState instance for the current request.

User

Gets the ASP.NET server User object, which can be used to authenticate a given user.

WebMethod Attribute

If you want to expose your public method as part of the Web service, add the WebMethod attribute to that public method. The WebMethod attribute provides the following properties:

  • BufferResponse

  • Description

  • MessageName

  • CacheDuration

  • EnableSession

  • TransactionOption

WEBMETHOD ATTRIBUTE: BUFFERRESPONSE

The BufferResponse property of the WebMethod attribute facilitates buffering of responses before they are sent to the client for a Web service method. If this property value is true, then it serializes the response of the Web service method into a memory buffer until either the response is completely serialized or the buffer is full. After the response is buffered, it is returned to the Web service client over the network. The default value is true. The buffering technique improves performance by reducing the communication between the worker process and the IIS process. If you set this property to false, ASP.NET buffers the response in 16-KB chunks . If you don't need to place the whole contents of the response in the memory, or if the Web service method returns large amounts of data to the client, then you might set this property to false. SOAP extensions are disabled for the Web service method if this property value is false.

 [WebMethod(BufferResponse=false)] Public string GetData() { // Implementation code } 
WEBMETHOD ATTRIBUTE: DESCRIPTION

You can make use of the Description property of the WebMethod attribute to provide a name for the Web method which is to be published. It is optional. This is used in the service description and the service help page of the Web service.

The default value is String.Empty . In the following example the string "Web Service which provides Concatenation functionality" is used to describe the Web service method, and the same can be used in the WSDL file, as shown in Figure E-10.

 [WebMethod (Description="Web Service which provides Concatenation functionality.")] public string Concatenate(string s1, string s2)      {        string s3="Concatenated String =";        return s3+s1+s2;      } 
WEBMETHOD ATTRIBUTE: MESSAGENAME

The MessageName property of the WebMethod attribute facilitates a unique name to the overloaded or polymorphic methods. The MessageName property can be used to alias method or property names . To exemplify this property, let's look at a simple add Web service that has three methods.

 [WebMethod (Description="Add two floats.")]  public float Add(float s1, float s2)  {    return s1+s2;  } [WebMethod (Description="Add two integers.")]  public int Add(int s1, int s2)  {    return s1+s2;  } [WebMethod (Description="Add three integers.")]  public int Add (int s1, int s2, int s3)  {    return s1+s2+s3;  } 

The program compiles nicely without a problem. But if you request the Web service, you come across the following errors for overload and polymorphic methods, respectively.

System.Exception: Both Int32 Add(Int32, Int32) and Single Add(Single, Single) use the message name 'Add'. Use the MessageName property of the WebMethod custom attribute to specify unique message names for the methods.

System.Exception: Both Int32 Add(Int32, Int32, Int32) and Int32 Add(Int32, Int32) use the message name 'Add'. Use the MessageName property of the WebMethod custom attribute to specify unique message names for the methods.

If you alter the program as follows, using the MessageName property, the program runs smoothly.

 [WebMethod(Description="Add two Floats.",MessageName="Add2Floats")] public float Add (float s1, float s2) { return s1+s2;} [WebMethod (Description="Add two integers.",MessageName="Add2Integers")] public int Add (int s1, int s2) { return s1+s2;} [WebMethod (Description="Add three integers.",MessageName="Add3Integers")] public int Add (int s1, int s2, int s3) { return s1+s2+s3;} 

You can see that the WSDL description names are unique now.

CACHING IN ASP.NET WEB SERVICE

You can incorporate the caching behavior to an ASP.NET Web service by setting the CacheDuration property of the WebMethod attribute as follows.

 [WebMethod(CacheDuration=30)] 

The value of the CacheDuration property indicates how many seconds ASP.NET should cache the results. You should set the CacheDuration property of the WebMethod attribute to any value greater than zero. The default value of CacheDuration property is zero.

TRANSACTION IN ASP.NET WEB SERVICE

You can incorporate the transaction behavior (new transaction) of an ASP.NET Web service by setting the transaction property of the WebMethod attribute as follows.

  1. Add a reference to System.EnterpriseServices.dll .

  2. Use the TransactionOption property of the WebMethod attribute

     [WebMethod(TransactionOption=TransactionOption.RequiresNew)] 

System.EnterpriseServices.dll namespace contains methods and properties that expose the distributed transaction model found in COM+ services. If an exception is thrown during the execution of the transaction process in a Web service method, the transaction is automatically aborted (using the SetAbort method of the System.EnterpriseServices.ContextUtil class). If no exception happens, then the transaction is automatically committed (using the SetComplete method of the System.EnterpriseServices.ContextUtil class). The TransactionOption property of the WebMethod attribute specifies how a Web service method participates in a transaction. Table E-4 shows TransactionOption enumeration members .

Table E-4. TransactionOption Enumeration Members

Item

Description

Disabled

Ignore any transaction in the current context.

NotSupported

Create the component in a context with no governing transaction.

Required

Share a transaction if one exists; create a new transaction if necessary.

RequiresNew

Create the component with a new transaction regardless of the state of the current context.

Supported

Share a transaction if one exists.

The TransactionOption property can be set to any of the TransactionOption enumeration values. But the TransactionOption enumeration of a Web service method has only two possible behaviors.

  • Doesn't participate in a transaction ( Disabled, NotSupported, Supported ).

  • Creates a new transaction ( Required, RequiresNew ).

The default value is TransactionOption.Disabled .

Session Management

The EnableSession property of the WebMethod attribute facilitates session state for a Web service method. The basic steps are as follows:

  • Add a reference to the System.Web.Services namespace.

  • Set the EnableSession property of the WebMethod attribute to true as below.

You can access the stored information in the Session object if you set this property to true.

 [WebMethod(EnableSession=true)] public String SessionCount() { // Code } 


.NET Security and Cryptography
.NET Security and Cryptography
ISBN: 013100851X
EAN: 2147483647
Year: 2003
Pages: 126

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