Creating a Basic Web Service

A Simple Commerce Application

You will first create an ASP.NET Web Form that collects and validates credit card information. The Web Form allows users to enter their credit card information, and then it informs users whether the information they entered is valid. You then move the credit card validation logic into a Web service and modify the Web Form so that it calls the Web service to validate the credit card information.

Creating a Web Form

You can create a Web Form by opening Visual Studio .NET and creating a new Web Application project. Set the project type to your language of choice, and select the Web Application template. Name your project Commerce, and set the location to a URL that points to the targeted Web server, as shown here:

Visual Studio .NET creates a project on the specified Web server and places template Web application files into that directory. Included in these files is a Web Form page named WebForm1.aspx. Rename it Order.aspx, and then change the name of the class defined within Order.aspx from WebForm1 to Order by following these steps:

  1. Open the Order.aspx code-behind file by right-clicking on the filename in Solution Explorer and selecting View Code.

  2. Change the name of the WebForm1 class and its corresponding constructor to Order.

  3. In the Properties pane, change the name of the label to Status, the text of the label to Please enter your credit card information, the name of the button to PlaceOrder, and the text of the button to Place Order. After you adjust the layout and add some additional text, the Web Form should look similar to the following:

Next you provide the implementation for the Place Order button. To add an event handler for the order button, double-click it and write the following code so that when the user clicks the button, the Validate method is called to determine whether the credit card information the user entered is valid. The code will also adjust the label's text to display appropriate text to inform the user whether the credit card was valid.

public void PlaceOrder_Click(object sender. Syste.EventArgs e) {     if(Validate(TextBox1.Text, Calendar1.SelectedDate))     {         Status.Text = "Thank you for your order.";     }     else     {     Status.Text = "Credit card invalid.";     } }

Next you create the Validate method immediately following the PlaceOrder_Click method.

public bool Validate(string cardNumber, DateTime expDate) {     if(expDate >= DateTime.Today)     {         int total = 0;         int temp = 0;         char [] ccDigits = cardNumber.ToCharArray();         for(int i = 0; i < cardNumber.Length; i++)         {             if(((i+1)%2) == 0)             {                 total += int.Parse(ccDigits[i].ToString());             }             else             {                 temp = int.Parse(ccDigits[i].ToString()) * 2;                 if(temp > 9)                 {                     temp = (int)temp - 9;                 }                 total += temp;             }         }         if((total%10) ==0)         {             return true;         }         else         {             return false;         }     }     else     {         return false;     } }

The Validate method determines whether the expiration date has passed. If it has not, the Validate method uses a standard mod10 algorithm to validate the credit card number.

Now compile and test the Web application to ensure that it works as expected.

Creating a Payment Web Service

At this point, the validation functionality is embedded in the Web Form. Now I will show you how to leverage the validation functionality within other applications. For example, you might want to develop a WinForm application for running the cash registers. This application would probably need to call the same logic to validate credit cards. If you expose the validation logic as a Web service, any application that can send and receive XML over HTTP will be able to invoke the service to validate credit card information.

You have a couple of options for creating the new Web service. You can simply add the Web service to an existing application by choosing Add Web Service from the Project menu. Or you can create a new project to contain the Web service.

Recall that your intention is to have the credit card validation logic serve as a shared resource across multiple applications. It might have infrastructure and scalability requirements that differ from those of the commerce application. So, in this case you will create a separate application—a Visual Studio .NET Web service application.

First open Visual Studio .NET and select Create New Project. Set the project type to your language of choice, and select the Web Service template. Name the project Payment, and set the location to a URL that points to the targeted Web server, as shown here:

Change the name of the Service1.asmx file to CreditCard.asmx. Because it is good practice to have the class name match the name of the .asmx file, change the name of the Service1 class to CreditCard. Visual Studio .NET creates a code-behind file for the .asmx file similar to those it creates for .aspx files, so you must open CreditCard.asmx.cs to modify the class declaration. To view the code-behind file, right-click on CreditCard.asmx and choose View Code. Change the name of the Service1 class and its corresponding constructor to CreditCard.

Next cut the Validate method from the Order Web Form and paste it into the CreditCard class. Then decorate the class with the WebMethod attribute and compile the application. The WebMethod attribute is the only code required to expose the Validate method on the Web!

[WebMethod] public bool Validate(string cardNumber, DateTime expDate) {      }

The WebMethod attribute tells the ASP.NET runtime to provide all of the implementation required to expose a method of a class on the Web—including the ability to advertise the Web service's functionality in the form of Web Services Description Language (WSDL). Visual Studio .NET will use the automatically generated WSDL to create a reference to the Web service in your commerce application.

Another service that ASP.NET provides the Payment Web service is the automatic generation of documentation for the Web service and a test harness. To invoke this functionality, use a Web browser to navigate to the CreditCard.asmx file, as shown here:

Next test the Validate method using the test harness supplied with the documentation. Entering a valid credit card number and a date of 1/1/2052 produces the following results (assuming you are not reading a 50-year-old book):

<?xml version="1.0" encoding="utf-8" ?> <boolean xmlns="http://tempuri.org/">true</boolean>

As expected, the result is true. However, the XML response message is not a valid SOAP message. There are multiple ways in which an ASP.NET-hosted Web service can be called. The Web service will return a well-formed SOAP message only if the request was a SOAP message. I will discuss ASP.NET-hosted Web services in detail in Chapter 6.

Updating the Order Web Form

The next task is to switch back to the Commerce application and update the Order Web Form so that it calls the CreditCard Web service to validate the user's credit card. You first add a Web reference for the CreditCard Web service to the commerce application by using the Web Reference Wizard.

You start the wizard by choosing Add Web Reference from the Project menu. In the Address text box, enter the URL to the server that hosts your targeted Web service. Click on the link to the Payment Web service that is listed in the right pane, as shown here:

Click Add Reference. You should see the Web reference listed in Solution Explorer. Visual Studio .NET processes the WSDL metadata associated with the Payment Web service and automatically creates a proxy. You can think of WSDL as the Web services equivalent of a TypeLib. The resulting proxy allows the Web service to be treated like any other .NET class.

Next you alter the implementation of the PlaceOrder_Click method to call the Web service instead of the local Validate function. First create an instance of the CreditCard class by using the new keyword as you would with any other .NET type. Notice that the default namespace for the Web service is the name of the server on which it resides.

public void PlaceOrder_Click (object sender, System.EventArgs e) {     localhost.CreditCard cc = new localhost.CreditCard();

Finally you call the Validate method on the cc object to cause a communication exchange to occur between the client (the Order Web Form) and the CreditCard Web service.

    if(cc.Validate(TextBox1.Text, Calendar1.SelectedDate))     {         Status.Text = "Thank you for your order.";     }     else     {         Status.Text = "Credit card invalid.";     } }

If you are writing the code as you read this chapter, notice that you have full IntelliSense support for the cc object. After you type cc., the list of methods supported by the object, including the Validate method, will be shown. As soon as you type the opening parenthesis for the method, the parameters for the method will be displayed—including the .NET equivalent of the Web service's parameter types.

As you have seen, it is easy to refactor a .NET application to expose its business logic via Web services. You simply copy the local method and place it into the .asmx code-behind file for the Web service. The only code required to expose the method via HTTP is the WebMethod attribute. Once the code is compiled and deployed, any client that supports HTTP and is capable of parsing strings can call the method.



Building XML Web Services for the Microsoft  .NET Platform
Building XML Web Services for the Microsoft .NET Platform
ISBN: 0735614067
EAN: 2147483647
Year: 2002
Pages: 94
Authors: Scott Short

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