Creating a Web Service

I l @ ve RuBoard

So much for all the theory. How does this work in practice? The obvious thing to do next is to create a simple Web service and see how it works.

A Simple Web Service

An ASP.NET-based Web service is defined in an ASMX file. This file is similar to the ASPX files found in ASP.NET Web applications in that it can contain a mixture of ASP.NET directives (embedded in <%@ %> tags) and executable code. The main difference between an ASMX file and an ASPX file is that the ASMX file is not intended to contain any static markup. (An ASPX file will usually contain HTML as well as code.) This means that the whole ASMX file, excluding the directives, will be treated as executable code, so you do not have to enclose it in code render blocks or script tags.

Defining the Web Service

Let's say we want to create a Web service based on the simple form of the Feeds ­HowMany method. The first thing we need to do is create a file with the ASMX extension. This file must contain a Web service directive ( <%@ WebService %> ) that provides information about the Web service:

 <%@WebServiceLanguage="VJ#" Class="SimpleEnquiry" %> 

As with the ASP.NET <%@ Page %> directive, the <%@ WebService %> directive defines the language in which the code on the page is written. It also defines a class to be used to service requests . This brings up another difference between Web services and other ASP.NET Web applications. ASP.NET Web applications that use the <%@ Page %> directive define a class from which they inherit. (The runtime creates a new class based on this inherited functionality and the various controls and tags defined in the ASPX file.) In the case of Web services, the code you supply is all that's needed to define and implement the service, so no new class is created. The class that handles requests for the Web service can be defined in the current file or can be held in a separate assembly in the bin directory of the virtual directory containing the Web service, or in the Global Assembly Cache (GAC). As you'll see later, you can use code-behind for Web services as well.

Implementing the Web Service

Your Web service must send and receive SOAP messages encoded in XML, so you might expect to have to write a lot of "plumbing" code to implement a Web service. However, to create a simple XML Web service based on ASP.NET, all you do is write a class in J# that implements the methods you want to expose as part of your Web service. You then tag each method you want to expose with the WebMethod attribute ( System.Web.Services.WebMethodAttribute ), as shown here:

 /**@attributeWebMethodAttribute()*/ publicintFeedsHowMany(intdiameter, System.Stringshape,System.Stringfilling) 

This attribute tells the ASP.NET runtime that you want to make this method visible as part of your Web service. Any methods that you want to expose must have public visibility, but the opposite is not true ” public methods are not automatically exposed as part of your Web service; only those labeled with the WebMethod attribute are.

The parameters of this version of the method are a little different from before. Earlier versions of this method, described in the previous chapters, used int values for the shape and filling. These values were defined as constants in two other J# classes. This FeedsHowMany method will be exposed using WSDL, so it uses strings (such as "square" ) to transmit this information because it is simpler than exposing the two other classes. The mapping of types and passing of nonstandard types are discussed later in the chapter. The complete SimpleEnquiry class is shown in the SimpleEnquiry.asmx sample file.

SimpleEnquiry.asmx
 <%@WebServiceLanguage="VJ#" Class="SimpleEnquiry" %> importSystem.Web.Services.*; publicclassSimpleEnquiry { /**@attributeWebMethodAttribute()*/ publicintFeedsHowMany(intdiameter, Stringshape,Stringfilling) { BooleanfruitFilling=(filling.Equals("fruit"))?true:false; doublemunchSizeFactor=(fruitFilling?2.5:1); intnumConsumers=(int)(diameter*munchSizeFactor); returnnumConsumers; } } 
Testing the Web Service

You can place this ASMX file into any IIS virtual directory that allows scripts to be executed, and it will be identified and interpreted correctly. As with ASPX files, the .asmx suffix is defined as being associated with Windows\Microsoft.NET\Framework\< .NETVersion >\aspnet_isapi.dll, so files with this suffix will be passed to the ASP.NET runtime to be processed . Once the file has been placed in a suitable directory, you can access it directly from a browser using its standard URL. If you have installed the sample RawWebServices project on your local machine, you can access the XML Web service using the URL http://localhost/RawWebServices/SimpleEnquiry.asmx . This will display the page shown in Figure 17-2.

Figure 17-2. Using the default URL for an ASP.NET-based Web service in a Web browser to display information about the service

What's happening here is that the ASP.NET runtime is working out that this is not really a request to use the service. Using the basic page URL will issue a simple HTTP GET request for the page. This request contains no Web service information, so it will be interpreted as a browser-based request for information about the service. In response to such a browser-based request, ASP.NET will generate the HTML page shown in Figure 17-2. Most of this Web page tells you to use a valid namespace in your XML Web service description, but we'll ignore this for now and discuss it later. For the time being, concentrate on the FeedsHowMany bulleted hyperlink on the left side., When you click this hyperlink, it will take you to the test page for the FeedsHowMany method, as shown in Figure 17-3.

Figure 17-3. Testing your Web services using a Web browser

There's more to the test page than you can see in the figure ”namely, protocol descriptions for the method. The protocol exchanges are discussed later ”for now, you just need to know that the ASP.NET runtime makes this service accessible over raw HTTP (using either POST or GET methods) as well as SOAP. As you can see, this test page allows you to enter values for the three parameters. We filled these out with typical values (for a 10-inch round fruit cake). When you click the Submit button, the values will be sent to the Web service using the HTTP GET method, as you can see if you examine the HTML that defines the form containing the three parameter input fields:

 <formtarget="_blank" action= 'http://localhost/RawWebServices/SimpleEnquiry.asmx/FeedsHowMany' method="GET"> 

In the case of requests that use HTTP GET or POST , you encode the target method by appending it to the Web service URL. The submission in this case uses GET , so the parameter values are simply encoded and appended to the URL. The result of sending these values to the Web service is shown in Figure 17-4.

Figure 17-4. The result of submitting a test through the SimpleEnquiry Web service test page

Compilation and Dependencies

You've probably noticed that we haven't touched a compiler yet. Chapter 16 described ASP.NET's automatic compilation mechanism. If you create an XML Web service based on ASP.NET, this automatic compilation will also be performed on ASMX files. You can find the compiled version of SimpleEnquiry.asmx in a subdirectory named after the host virtual directory, under the folder \Windows\Microsoft.NET\Framework\< .NETVersion >\Temporary ASP.NET Files. If you look, you'll find two pairs of XML files and DLL assemblies. One of the DLL assemblies is the compiled version of the SimpleEnquiry class. The associated XML file (SimpleEnquiry.asmx.< a number >.xml) specifies the name of the assembly containing SimpleEnquiry , plus the source code file on which it depends:

 <preserveassem="2szhq2zu" type="SimpleEnquiry" hash="14e3044cee7"> <filedepname="c:\inetpub\wwwroot\RawWebServices\SimpleEnquiry.asmx" /> </preserve> 

The other assembly and its associated XML file relate to the generation of WSDL for this service (as discussed later in the chapter).

The Web service shown is simple, with many loose ends and unanswered questions (which we'll cover in the rest of the chapter). The first question to answer is how you can create such a Web service using Visual Studio .NET.

Creating a Web Service Using Visual Studio .NET

Visual Studio .NET is intended to simplify the creation of all types of .NET applications, including XML Web services. When you create an XML Web service in Visual Studio .NET, you're essentially creating an ASP.NET application with a few variations. To create an XML Web service in Visual Studio .NET, select the Visual J# ASP.NET Web Service template in the New Project dialog box, as shown in Figure 17-5.

Figure 17-5. Selecting an ASP.NET Web service in the Visual Studio .NET New Project dialog box

The project wizard will create a skeleton XML Web service that contains the following items:

  • All of the artifacts you would associate with a standard ASP.NET Web application, including Global.asax, Web.config, AssemblyInfo.jsl, references to standard libraries, and a new virtual directory under IIS in which to house the files.

  • A Web service ASMX file. By default, this file is called Service1.asmx.

  • A discovery (VSDISCO) file. This is a skeleton file to be used as part of the DISCO Web service discovery protocol.

You've already seen the ASP.NET application files, and discovery is covered in Chapter 18, so we'll focus now on the Web service file itself. The contents of Service1.asmx are similar to those of SimpleEnquiry.asmx (shown earlier), except Service1.asmx is set up automatically to use the code-behind model:

 <%@WebServiceLanguage="VJ#" Codebehind="Service1.asmx.jsl" Class="CakeEnquiryService.Service1" %> 

Tip

In Visual Studio, if you double-click on the Service1.asmx file, you'll see a design screen. To view and edit the actual file, right-click on the file, choose Open With from the shortcut menu, and select Source Code (Text) Editor.


The design screen offers you a hyperlink to the code view of the Web service. The default code provided is contained in the sample file Service1.asmx.jsl (shown below) that's contained in the sample CakeCatalogService project. The structure of the file is similar to an ASP.NET Page subclass. The project has various standard packages imported by default, and the class is placed in a package that matches the project name. A constructor is provided, and some initialization and closedown code is defined in the #region generated by the component designer. At first sight, this last part might seem strange . A Web service has no user interface, so why do you need the services of the component designer? Although a Web service class will have no need for visual controls, such as buttons and text boxes, you can still drop nongraphical controls onto the Web Forms designer surface for an ASMX file. These controls are accessible in the code-behind, and you can set their properties using the Property sheet in Visual Studio .NET.

Service1.asmx.jsl
 packageCakeEnquiryService; importSystem.*; importSystem.Collections.*; importSystem.ComponentModel.*; importSystem.Data.*; importSystem.Diagnostics.*; importSystem.Web.*; importSystem.Web.Services.*; /** *SummarydescriptionforService1. */ publicclassService1extendsSystem.Web.Services.WebService { publicService1() { //CODEGEN:ThiscallisrequiredbytheASP.NETWebServicesDesigner InitializeComponent(); } #regionComponentDesignergeneratedcode /** *RequiredbytheWebServicesDesigner */ privateIContainercomponents=null; /** *RequiredmethodforDesignersupport-donotmodify *thecontentsofthismethodwiththecodeeditor. */ privatevoidInitializeComponent() { } /** *Cleanupanyresourcesbeingused. */ protectedvoidDispose(booleandisposing) { if(disposing&&components!=null) { components.Dispose(); } super.Dispose(disposing); } #endregion /** *WEBSERVICEEXAMPLE *TheHelloWorld()exampleservicereturnsthestringHelloWorld *Tobuild,uncommentthefollowinglinesthensaveandbuildtheproject *Totestthiswebservice,pressF5 */ ///**@attributeWebMethod()*/ //publicSystem.StringHelloWorld() //{ //return "HelloWorld"; //} } 

From the standpoint of Web services, two points are of primary interest:

  • The class inherits from System.Web.Services.WebService . As you saw earlier, this is not a prerequisite for a Web service class, but using WebService as your superclass gives you direct access to ASP.NET intrinsic objects such as Server , Session , Application , and Context . All other intrinsic objects, namely Cache , Error , Request , and Response , are available through the Context object (as are Server , Session , and Application ). If you choose to not inherit from WebService , you can still get hold of the Context object using the static HttpContext.get_Current method.

  • Because Web services have largely been developed by users of curly bracket languages (Java, C++, C#), the obligatory HelloWorld method is predefined, complete with the WebMethod attribute. In the true spirit of developers across the world, you can uncomment this method and adapt it to your own purposes!

    Note

    The need to work your way through the Context object to obtain the Request and Response objects is intentional. You should not access the Request and Response data directly because it forms part of the underlying Web service interaction. You can generally retrieve any information you need without having to access the Request . Similarly, you return data to the client by using method return values rather than the Response object.


I l @ ve RuBoard


Microsoft Visual J# .NET (Core Reference)
Microsoft Visual J# .NET (Core Reference) (Pro-Developer)
ISBN: 0735615500
EAN: 2147483647
Year: 2002
Pages: 128

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