Cross-Platform Web Services Using C# & JAVA (Charles River Media Internet & Web Design)
|
ASP.NET Web Page with Visual Studio.NET
An ASP.NET page runs as a Web page on your server that is viewable with Internet Explorer. Because code runs every time an ASP.NET page loads, it is possible to call objects like any other C# program.
Open Visual Studio.NET and select Visual C# and select ASP.NET Web Application in the dialogue. Be sure to provide the application with a name that’s meaningful to you. Figure 6.14 shows the dialogue and the appropriate selections.
Visual Studio.NET creates a Web page that looks like the following.
<%@ Page language="c#" Codebehind="WebForm1.aspx.cs" AutoEventWireup="false" Inherits="SimpleASPClient2.WebForm1" %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" > <html> <head> <title>WebForm1</title> <meta name="GENERATOR" Content="Microsoft Visual Studio 7.0"> <meta name="CODE_LANGUAGE" Content="C#> <meta name="vs_defaultClientScript" content="JavaScript"> <meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5"> </head> <body MS_POSITIONING="GridLayout"> <form method="post" runat="server"> </form> </body> </html>
A lot of the information here is extraneous and can be trimmed down to save space. The meta tags are just information about the Web page and don’t really affect the code. The DOCTYPE definition simply defines the HTML used in the page, and the MS_POSITIONING attribute of the body tag is a directive for Internet Explorer that we won’t use. Thus, the code can be trimmed down to the following.
<%@ Page language="c#" Codebehind="WebForm1.aspx.cs" AutoEventWireup="false" Inherits="SimpleASPClient2.WebForm1" %> <html> <head> <title>Simple ASP.NET Web Service Client</title> </head> <body> <form method="post" runat="server"> </form> </body> </html>
The next step is to add a Web reference to the Web Service on localhost that you used in the previous sections’ examples. Go to “Project” in Visual Studio.NET and select “Add Web Reference.” Put in the URL for the WSDL file for the “SimpleStockQuote” Web Service and the reference will be built with the project. See Figure 6.11 for a description of the Web Reference dialogue in Visual Studio.NET.
Once Visual Studio.NET creates the Web reference, the code now contains an import statement that brings in the namespace for the Web Service. The code looks like the following.
<%@ Import Namespace="SimpleASPClient.localhost" %>
This imports in the localhost namespace so that when you create objects from the localhost Web Service, the definitions aren’t as long.
The second tag found in the page, Page, defines the language used, the location of the auto-generated code, and what code is inherited. Visual Studio.NET creates much of the information here from values you entered when creating the ASP.NET project. The AutoEventWireup attribute indicates whether the events on the Web page fire off when the page is first loaded. Inherits the compiler the location of the code that Visual Studio.NET created for this ASP.NET page.
After the HTML tag, the script tag appears. The attribute, runat="server", indicates to the Web server that this is a piece of code that needs to be executed on the server side. Within the script tags is that actual chunk of code that calls the Web Service.
The first step is creating a method named Submit_Click. This method will be called when someone clicks on a submit button, which is defined later. Note the arguments to the Submit_Click method (Object Src, EventArgs E) actually load the Web reference created earlier.
Next the object example gets created to call the methods in the Web Service.
Note that you don’t have to use the localhost namespace in this definition because of the import directive used earlier.
The string value, stockSymbol, receives its value from the ASP.NET control SymbolToGet. This is simply a text box dragged and dropped onto the design window in Visual Studio.NET. stockValue is defined as a string and set to a default of empty and then it receives the value back from the GetTestQuote method. Notice that the ToString() method call ensures that the value returned is a string and, thus, can be sent to the Text attribute of the Message TextBox.
The following is the complete code.
<%@ Import Namespace="SimpleASPClient.localhost" %> <%@ Page language="c#" Codebehind="WebForm1.aspx.cs" AutoEventWireup="false" Inherits="SimpleASPClient.WebForm1" %> <HTML> <script runat="server"> protected void Submit_Click(Object Src, EventArgs E) { XPlatformServices example = new XPlatformServices(); string stockSymbol = SymbolToGet.Text; string stockValue = ""; stockValue = example.GetTestQuote(stockSymbol).ToString(); Message.Text = stockValue; } </script> <body> <form runat="server"> <b>Stock Symbol:</b> <asp:TextBox Runat="server" /><br> <b>Returned:</b> <asp:Label Runat="server" /><br> <input type="submit" value="get quote" onserverclick="Submit_Click" runat="server"> </form> </body> </HTML>
Note | Note that the asp:Textbox and the asp:Label are available from the HTML tab of the “Tools” window in Visual Studio.NET. |
Figure 6.15 shows the output of the ASP.NET code in Internet Explorer. Note that by entering the symbol “C,” we got back the value “55.95,” just as in the previous Web Service consumer examples.
There’s really nothing special about the form we created to connect to our example Web Service. Thus, the example doesn’t really take advantage of the customization that can occur with an ASP.NET page being able to utilize HTML. By just adding a few HTML directives, you can customize a user’s experience with the ASP.NET page.
The following code example illustrates how you can customize the appearance in the browser by adding a few HTML tags. Note that all that has really been added is a title in the header, a table with a border and background color within the form code, and an HTML H3 definition (See Figure 6.16).
<%@ Page language="c#" Codebehind="WebForm1.aspx.cs" AutoEventWireup="false" Inherits="SimpleASPClient.WebForm1" %> <%@ Import Namespace="SimpleASPClient.localhost" %> <HTML> <head> <title>Simple ASP.NET Web Services consumer</title> </head> <script runat="server"> protected void Submit_Click(Object Src, EventArgs E) { XPlatformServices example = new XPlatformServices(); string stockSymbol = SymbolToGet.Text; string stockValue = ""; stockValue = example.GetTestQuote(stockSymbol).ToString(); Message.Text = stockValue; } </script> <body> <form runat="server"> @h3:Simple ASP.NET Consumer</h3> <table align="center" bgcolor="#FFFCC" border=1> <tr> <td><b>Stock Symbol:</b></td> <td><asp:TextBox Runat="server" /></td> </tr> <tr> <td><b>Returned:</b></td> <td><asp:Label Runat="server" /></td> </tr> </table> <input type="submit" value="get quote" onserverclick="Submit_Click" \ runat="server" NAME="Submit1"> </form> </body> </HTML>
Using an ASP.NET as a Web Services consumer provides for some easy customization for the user experience.
Using the .NET Framework SDK to Create Consumers
Just as with creating Web Services, you can use the .NET Framework SDK as a way to create Web Service consumers. Visual Studio.NET has a wide variety of features that allow you to easily create Windows and other applications, but if this version of Visual Studio is unavailable to you, the .NET Framework SDK allows you to create Web Services and Web Service consumers free of charge.
Creating the Proxy
With the SDK, you have to create the Web references, known as proxies in this case, manually. This is done by utilizing the WSDL tool and the command line C# compiler.
The first step is to use the WSDL tool to create the proxy code. Open a DOS prompt and ensure that you either execute the corvars.bat program that came with the SDK or that the DOS environment already has the appropriate environment set up for you. You can test this by executing wsdl.exe. If the DOS environment doesn’t know about WSDL, that means you need to find and execute corvars.bat.
Note that the example command assumes that your StockQuote Web Service resides at the following URL: http://localhost/XPlatform/StockQuote/Service1.asmx?wsdl
Once your DOS environment is ready, go ahead and execute the following. (Note that you want all this information to be on one line.)
wsdl.exe /l:CS /n:SDKStocks /out:stockquotes.cs http://localhost/XPlatform/StockQuote/Service1.asmx?wsdl
Table 6.1 explains the command line options for the WSDL tool.
Command Line Option | Purpose |
---|---|
/l:CS | The language of the resulting proxy is C#. |
/n:StockQuotes | Use the namespace StockQuotes in the proxy. |
/out:stockquotes.cs | The resulting source file for the proxy will be stockquotes.cs. |
Executing the command creates the stockquotes.cs file and the contents of it look like the following.
//----------------------------------------------------------------- // <autogenerated> // This code was generated by a tool. // Runtime Version: 1.0.3705.0 // // Changes to this file may cause incorrect behavior and will be // lost if // the code is regenerated. // </autogenerated> //------------------------------------------------------------------- // // This source code was auto-generated by wsdl, Version=1.0.3705.0. // namespace SDKStocks { using System.Diagnostics; using System.Xml.Serialization; using System; using System.Web.Services.Protocols; using System.ComponentModel; using System.Web.Services; /// <remarks/> [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Web.Services.WebServiceBindingAttribute (Name="XPlatformServicesSoap", Namespace="http://www.advocatemedia.com/")] public class XPlatformServices : System.Web.Services.Protocols.SoapHttpClientProtocol { /// <remarks/> public XPlatformServices() { this.Url = "http://localhost/XPlatform/StockQuote/Service1.asmx"; } /// <remarks/> [System.Web.Services.Protocols.SoapDocumentMethodAttribute ("http://www.advocatemedia.com/GetTestQuote", RequestNamespace="http://www.advocatemedia.com/", ResponseNamespace="http://www.advocatemedia.com/", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped )] public System.Double GetTestQuote(string symbol) { object[] results = this.Invoke("GetTestQuote", new object[] { symbol}); return ((System.Double)(results[0])); } /// <remarks/> public System.IAsyncResult BeginGetTestQuote(string symbol, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("GetTestQuote", new object[] { symbol}, callback, asyncState); } /// <remarks/> public System.Double EndGetTestQuote(System.IAsyncResult asyncResult) { object[] results = this.EndInvoke(asyncResult); return ((System.Double)(results[0])); } } }
You shouldn’t be intimidated by the code created for the proxy. An automated process creates this code and it isn’t meant for you to modify or use directly.
Tip | You should never modify this code. Let the WSDL tool do that for you because the code gets overwritten every time the tool executes. Thus, you would lose your changes. |
Now that you created the proxy code, it needs to be compiled so that the application or Web page can utilize it. You compile it from the command line, as shown in the following example. Note that the line breaks are present to make it easier for you to read.
csc /t:library /out:XPlatform.dll /r:system.dll /r:system.weservices.dll /r:system.xml.dll stockquotes.cs
Remember that in order to use the C# command line compiler, csc, you either need to have the appropriate environment already set up or you need to execute corvars.bat. The command line options are very important in this step and Table 6.2 summarizes them.
Command Line Option | Purpose |
/t:library | Tells the compiler you want to create a dll. |
/out:Xplatform.dll | Sets the name of the dll. |
/r:system.dll | Has the dll reference the system.dll library. This is the manual equivalent of adding a Web Reference in Visual Studio.NET. |
Because you don’t have Visual Studio.NET’s Graphical User Interface (GUI) to handle many of these details, you must use the command line options to handle many of the details. In this case, you need to tell the compiler to create a library, the name of the dll you create, and any references the proxy needs.
Now that you have a proxy, you need to put it in such a place that your consumers can see it. This is usually the bin directory under your wwwroot for ASP.NET pages. For example, on the author’s machine the path is c:\Inetput\wwwroot\bin. For a C# executable, the reference is made while the executable is being compiled. Thus, it doesn’t have to reside in any special place.
The code that comes at the top of the ASP.NET page is much simpler than that created by Visual Studio.NET. Visual Studio does a lot of code generation for each project, and we just don’t need this here. All you have at the beginning of this page is a definition to explain that the code is written in C# and an import of the namespace created when the WSDL tool was used. Other than those two small details, the code is the same as our previous examples and executes the same.
<%@ Page language="c#" %> <%@ Import Namespace="SDKStocks" %> <html> <script runat="server"> protected void Submit_Click(Object Src, EventArgs E) { XPlatformServices example = new XPlatformServices(); string stockSymbol = SymbolToGet.Text; double value = 0; string stockValue = ""; stockValue = example.GetTestQuote(stockSymbol).ToString(); lblMessage.Text = stockValue; } </script> <body> <form runat="server"> <b>Stock Symbol:</b> <asp:TextBox Runat="server"/><br> <b>Returned:</b> <asp:Label Runat="server"/><br> <input type="submit" value="get quote" onserverclick="Submit_Click" runat="server"/> </form> </body> </html>
Just by simply pointing your browser to this ASP.NET page on your system, the code compiles.
C# Client Compiled with Framework SDK
No example of a Web Services consumer would be complete without creating an executable client. C# makes it very easy to create such a client.
The following code is a simple command line tool to call the example Web Service. The beginning of the code calls the System namespace and then it defines the class XPlatformTest. The program uses the default constructor and goes right into defining the Main method. Two strings are defined to handle the value passed to the Web Service and then the result. Next the example object is created using the SDKStocks.XPlatformServices. Remember that SDKStocks is the namespace defined when you used the WSDL tool. The XPlatformServices is the class you defined in the Web Service code. Then the string myResult gets the result of the GetTestQuote method call. Note that this only works if the ToString()method is used as well. Finally, the myResult variable is written to the command line. The program simply echos 55.95 to the command line.
using System; public class XPlatformTest { public static void Main() { String mySymbol = "C"; String myResult = ""; SDKStocks.XPlatformServices example = new SDKStocks.XPlatformServices(); myResult = example.GetTestQuote(mySymbol).ToString(); Console.WriteLine(myResult); } }
To build the executable, you still have to reference the proxy dll created earlier. You just need to refer to it at compile time and the following example assumes that the dll is in the same directory. Notice that you only need to use the /r option to compile in the reference in order for the executable to use the information in the proxy.
csc /r:SDKStocks.dll XPlatformTest.cs
This creates XPlatformTest.exe, which when run from the command line, returns 55.95.
|