Programming Web Services with Microsoft Visual Studio .NET

I l @ ve RuBoard

Now that we've paid our dues and learned how to do things the hard way, we'll take a look at support for Web Services in Visual Studio .NET. Although the Web Services architecture is based on well-defined XML standards, the devil ”at least for the developer ”is in the details. As a result, Microsoft hopes to differentiate itself in the market for Web Services by providing tools for developers that can automate the creation, testing, and debugging of Web Services and thereby increase developer productivity. For the rest of this chapter, we'll focus on learning how to create and consume Web Services within the context of the Visual Studio .NET development environment.

Creating Web Services in Visual Studio .NET

As with other types of projects supported by Visual Studio .NET, creating a new Web Service follows the same familiar New Project Wizard paradigm. To get started, choose File, New, Project to open the New Project dialog box. Then, from the Visual C# Projects folder, select ASP.NET Web Service . We'll also give our new Web Service a distinctive name , in this case testVSWebService , and ensure that the Location parameter is set to specify our local machine at http://localhost . When we're finished, the New Project dialog box should look like Figure 11.8.

Figure 11.8. Visual Studio .NET's New Project dialog box.

Next, click OK and wait for the system to trundle through the process of populating our new project with a number of supporting files. When the process is complete, the Solution Explorer window should look like Figure 11.9.

Figure 11.9. The Solution Explorer view displays files associated with your solution and related projects.

You'll notice a lot of files here that we didn't create when hand-coding and compiling our previous Web Services using the command-line tools. Most of these files contain boilerplate Visual Studio .NET configuration data. A few, however, will warrant our attention a little later on. For now, though, let's test our Web Service to make sure everything is working properly.

Because Web Services built using Visual Studio .NET use ASP.NET's code-behind feature, we'll need to compile our application before we can view its default interface. Use of the code-behind feature has a few other implications that we'll consider in a short while. To build the project, just press Ctrl+Shift+B or choose Build, Rebuild All. Next, right-click on Service1.asmx , the default name for our new Web Service, and select View in Browser to test the service.

As you might have noticed, our new Web Service is a little thin on functionality. Conveniently, Microsoft provides a few lines of sample code that we can use to make our new service do something at least semi-useful. To view the source code associated with the service, right-click on Service1.asmx in Solution Explorer and select View Code from the pop-up menu. Next, scroll down to the bottom of the file and uncomment the following lines by removing the preceding double slash marks.

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

Rebuild the project and view it in the browser once again to test your changes. Adding your own functionality proceeds similarly in that you just have to add new methods to implement your business logic and include the [WebMethod] attribute to expose them across the Internet.

Visual Studio .NET Project Structure

After seeing all of the files listed in Solution Explorer, you might have asked yourself, "Isn't Visual Studio .NET supposed to make my life as a developer easier and less complicated?" In fact, there are a few more files that Visual Studio .NET hides from our view to reduce the amount of confusing clutter on the screen. To view them, just click the Show All Files icon in the Solution Explorer minitoolbar and then expand all of the nodes in the project. The results should look similar to Figure 11.10.

Figure 11.10. In the Solution Explorer, the Show All Files option has been enabled.

As you've seen in previous chapters, many of these files are just glue holding the Visual Studio .NET solution and its project files together. A few others store various bits of configuration data about our application that are usually modified using the Visual Studio .NET interface. The files that we don't usually need to worry about when building Web Services with Visual Studio .NET (or that aren't specific to Web Service projects) are testVSWebService.sln , Service1.asmx.resx , AssemblyInfo.cs , Web. config , Global.asax and Global.asax.cs , testVSWebService.csproj , testVSWebService.csproj.webinfo , and of course, bin\testVSWebService. dll and bin\testVSWebService.pdb .

.asmx And .asmx.cs/.asmx.vb Files

Of the remaining files, the two most important are Service1.asmx and Service1.asmx.cs . Together, these two files constitute a Web service that has been built using the code-behind approach. The code-behind approach is designed to clearly separate the browsable files accessible to users of our service (located in .asmx files) from the code that actually implements the service (located in .asmx.cs files). In practice this just means that the processing directive now lives alone in the .asmx file and is modified to point to the implementation stored in the .asmx.cs file. Let's take a look at the modified processing directive from Service1.asmx .

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

Notice that the Codebehind parameter points to the C# source file that implements our Web Service. In addition, the Class parameter indicates the specific .NET namespace and class our Web Service derives its functionality from. Now let's look at the contents of Service1.asmx.cs in a little more detail.

  using System; using System.Collections; using System.ComponentModel; using System.Data; using System.Diagnostics; using System.Web; using System.Web.Services; namespace testVSWebService {     /// <summary>     /// Summary description for Service1.     /// </summary>     public class Service1 : System.Web.Services.WebService {         public Service1() {             //CODEGEN: This call is required by the             // ASP.NET Web Services Designer             InitializeComponent();         }         #region Component Designer generated code         /// <summary>         /// Required method for Designer support - do not modify         /// the contents of this method with the code editor.         /// </summary>         private void InitializeComponent() {  }         #endregion         /// <summary>         /// Clean up any resources being used.         /// </summary>         protected override void Dispose( bool disposing ) {  }         // WEB SERVICE EXAMPLE         // The HelloWorld() example service returns the string Hello World         // To build, uncomment the following lines then         // save and build the project         // To test this Web Service, press F5 //      [WebMethod] //      public string HelloWorld() { //          return "Hello World"; //      }     } } 

The first thing to note is the inclusion of a lot of additional namespaces. This is pretty typical of tool-generated code. In this case, the namespaces relevant to Web Services and Web applications in general are included along with those necessary to enable ASP.NET's form designer.

You'll also notice that Visual Studio .NET includes a default namespace for our Web Service derived from the name of our project as well as copious comments (often in pseudo-XML format) that we can parse out into a help file if we ever get the urge. In addition, you'll find two protected methods, InitializeComponent() and Dispose() , that you'll see in most if not all ASP.NET applications built with Visual Studio .NET.

The important difference to note between our hand-coded Web Services and those generated by Visual Studio .NET is the use of System.Web.Services. WebService as a base class. By deriving from this class, our Web Service has access to the ASP.NET intrinsic objects for managing session state including the Application , Session , and Request objects. Although our simple examples don't require these services, it's important to realize that more complex Web services, especially those involving state management and session security, will need to use the services that these objects provide.

. vsdisco files

Another important file generated by Visual Studio .NET is testVSWebService.vsdisco . As of the time of this writing, Microsoft's SDK defines a .vsdisco file as "An XML-based file that contains links (URLs) to resources providing discovery information for a Web Service." Because the Disco protocol is currently in a state of flux, I'll leave it at that for now and refer you to the documentation that comes with the Microsoft .NET SDK. I certainly have my doubts as to whether what I'm looking at today when I browse a .vsdisco file will look anything at all like what you'll be seeing on your screen after the publication of this book. The important thing to realize is that Visual Studio .NET will automatically generate the documents necessary to allow potential users of your Web Services to poll your Web server and "discover" what you've made available. Of course, you can always choose not to deploy the .vsdisco file if you would like the presence of your services to remain private.

It is also important to note that while Disco and UDDI are similar in that they are both used by third parties to "discover" Web Services, they differ greatly in terms of scope. Whereas UDDI directories provide lists of services available from a range of enterprises across a range of servers, Disco is primarily designed to allow third parties to enumerate the services installed on a particular Web server.

Consuming Web Services in Visual Studio .NET

Before we close the book (or at least the chapter) on Web Services let's create a simple Web application to consume a Web Service using Visual Studio .NET. We'll start off by creating a new ASP.NET Web application called testVSWebServiceClient on our local machine. If you need a refresher on how to use the New Project Wizard to accomplish this task, refer back to the section "Creating Web Services in Visual Studio .NET."

When our ASP.NET Web application project has been created, we'll add a reference to the Web Service we want to consume by selecting Project, Add Web Reference. The resulting dialog box should look similar to that pictured in Figure 11.11.

Figure 11.11. The Add Web Reference dialog box automates the process of adding support for Web Services to your project.

As its name implies, the Add Web Reference dialog box allows you to add references to Web Services to your Visual Studio .NET projects. Conceptually, the process of adding a reference to a Web Service is almost identical to adding a reference to a type library or COM object. As with type libraries and COM objects, adding a reference to a Web Service exposes its methods for use within our application and enables the Visual Studio .NET IDE to provide us with code-completion and other productivity enhancements.

Services can be referenced by searching UDDI directories, specifying a disco file located on a local or remote server, or by providing the URL of a known service. For the purpose of this exercise, we'll choose the Web References on Local Web Server link. At this point, the list of Available References displayed will include all of the Web Services available on our local machine. From this list, select the testVSWebService.vsdisco link and then click the Add Reference button.

We'll also need some way to invoke our Web Service and to display its results. From the toolbox, drop a button and a label onto the WebForm1.aspx form designer. Next, double-click the button to edit the Button1_Click event and insert the following code to invoke the Web Service:

  localhost.Service1 myService = new localhost.Service1(); Label1.Text = myService.HelloWorld(); 

The code listed here is simple enough. The first line creates an instance of the Web Service proxy class called myService and the second line invokes its HelloWorld() method and assigns the result to the label's text property. Notice that by default the namespace of our Web Service is the URL of the server that hosts it. We can easily change this name in the Solution Explorer if we want to make it something a bit more meaningful, which is probably a good idea in production code. Also notice that after you type the service's namespace and subsequent trailing dot (that is, after typing localhost . into the IDE), code-completion kicks in and displays a list of available methods exposed by the service just as if it were a class or COM object local to our machine.

To see our client in action, build the project and then press F5 to begin execution. A simple Web form will be displayed containing the button and label we added previously. All that's left is for you to click the button and watch in awe as hundreds of thousands of lines of code churn under the hood of the OS to produce the result depicted in Figure 11.12.

Figure 11.12. A Web Application client consuming a Web Service.

Before we move on, a few additional items are worth mentioning. First, debugging Web Service and Web Service client applications using Visual Studio .NET is identical to debugging other ASP.NET applications. If you are debugging a Web Service on your local machine, it is trivial to step back and forth between client code to service code as long as both the service and client projects are located within the same Visual Studio .NET solution. In this configuration, Web Services and the applications that consume them are a true joy to work with and the productivity gains associated with using the Visual Studio .NET IDE versus the command-line tools come clearly into focus.

Also, as with other types of ASP.NET applications, deploying a Web Service from a development to a production machine can usually be accomplished just by copying the application's Web directory structure from one server to another. Another option is to use the Web Setup Project wizard to create an .msi installation package the same way you would with any ASP.NET application. Yet another option is to use the Web Hosting option available from the Visual Studio Start Page. This option is great for validating that your service will really work when accessed remotely across the Internet and is definitely useful when trying to impress your friends and coworkers.


For more information on publishing your Web Services to UDDI, see Microsoft's UDDI SDK at or visit for more information.

I l @ ve RuBoard

Asp. Net. By Example
ASP.NET by Example
ISBN: 0789725622
EAN: 2147483647
Year: 2001
Pages: 154

Similar book on Amazon © 2008-2017.
If you may any questions please contact us: