Create A Simple Web Service

eb Services allow your business objects over HTTP. You can create a very simple Web Service in relatively few steps.

Web Services enable client applications to communicate to server components over the internet using the HTTP protocol. Web Services are requested over HTTP by HTTP-GET, HTTP-POST, or HTTP-SOAP. The most functional access method is HTTP-SOAP access. The SOAP access formats requests and responses from client to server with messages using XML for formatting the message contents.

To write a Web Service, you create a text file with an .asmx extension. You must add a directive at the top of the page to specify the Web Service language, the class that implements the Web Service, and optionally the assembly containing the implementation. The assembly is required if you do not include the Web Service class inside of your ASMX file. The assembly needs to be in the /bin directory underneath the Web application that contains the Web Service.

For the class that is either embedded in the Web Service file, *.asmx, or in a separate file, *.cs, you must determine which methods in your class are exposed to Web Service clients. To expose methods in a class to Web Service clients, you must apply the WebService attribute to a public method.

CREATE A SIMPLE WEB SERVICE

CREATE A SIMPLE WEB SERVICE

D Open a new document in your text editor.

< Set the Language in the directive.

L-> Give the WebService class a name.

'—0 Create an alias for the System namespace.

m Create an alias for the System.Web.Service namespace.

D Open a new document in your text editor.

< Set the Language in the directive.

L-> Give the WebService class a name.

'—0 Create an alias for the System namespace.

m Create an alias for the System.Web.Service namespace.

TYPE THIS:

<%@ WebService Language="C#" using System;

using System.Web.Services;

Class="SinpleWebService_ai" %>

public class SimpleWebService_ai : WebService {

[WebMethod] public string GetRandomDailyGoal() { Random randomNumber = new Random (); int intNumberOfGoals = 3; string stringGoal = "";

int intRandomNumber = randomNumber.Next(intNumberOfGoals); switch(intRandomNumber){ case 0:

Drink 8 glasses of water."; break;

stringGoal case 1:

stringGoal = "Exercise for 30 minutes.' case 2:

stringGoal = "Call your Mom."; break; default:

goto case 2;

return stringGoal;

break;

RESULT:

A Web Service that will generate a random daily goal each time the service is requested.

Q Create the

SimpleWebService class as a WebService.

□ Create a WebMethod by placing the attribute before the method declaration.

-0 Add a public method that returns a string variable.

I Set the return value for the function.

— Save the file to the Web server with an .asmx extension.

TEST A WEB SERVICE

After you create your Web Service, you can test it. aSp.NET automatically generates pages for testing a Web Service when the Web Service ASMX file is requested with your Web browser. You can use these pages to see what is returned from the Web Service.

You do not need to create any additional pages for testing out a simple Web Service. Simply request the Web Service file — *.asmx— with your Web browser. The first page that you see displays the Web Service class name and all of the Web methods that are available for that Web Service class. You can click the Web Method name that you want to test. The next page displays an Invoke button that you can use to call the Web Method. If you have parameters for the Web Method, you will see a text box for entering each parameter value. After you click Invoke, another instance of Internet Explorer opens, and the XML that is generated from the request displays the results. If you do not have a Web Service to test, see page 152.

TEST A WEB SERVICE

TEST A WEB SERVICE

D Open a Web browser and navigate to the Web Service file.

-■ The WebMethod appears '—0 Scroll down the page to as a hyperlink. view samples of a SOAP, r- ,. , , , ,. , HTTP Get, and HTTP Post

^ Cllck the hyperllnk. request and response for the

Web Service.

D Open a Web browser and navigate to the Web Service file.

-■ The WebMethod appears '—0 Scroll down the page to as a hyperlink. view samples of a SOAP, r- ,. , , , ,. , HTTP Get, and HTTP Post

^ Cllck the hyperllnk. request and response for the

Web Service.

You can create a custom test page if you have special testing needs. The following is a Web page that you can use to create a custom testing page. The response from the Web Service will remain in the same Web browser window.

TYPE THIS:

RESULT:

A test page that is very similar to the automatically generated test page for a Web Service.

—Q Click the Invoke button.

■ The HTTP Post response appears.

—Q Click the Invoke button.

■ The HTTP Post response appears.

USING A PARAMETER TTH A WEB SERVICE

For most of your Web Services, you will want to pass parameters when invoking a Web Service method. These parameters give the method context to the Web client's specific needs from the Web Service. For example, a Web Service client can make a request for its goals for the next three months. Parameters that would be useful in this Web Service request are the customer's ID and the time frame for requesting goals (the next three months).

Creating a Web Service that accepts data for a parameter requires the same steps that it takes to create a Web Service without parameters. However, in the function declaration for the Web Method, you must specify information on the parameter type and parameter name for each parameter needed to invoke the method. After you do this, you can use the data passed to the Web Service by referencing it by the parameter name.

Testing a Web Service method that has parameters is very similar to testing a method without parameters. The only difference is that the test page will include labeled text boxes for each parameter that is specified on the Web Service method.

USING A PARAMETER WITH A WEB SERVICE

B^ Untitled - Notepad

-|S|x|

File Edit Format Help

1 <%@ WebService Language="C#" C las s=|"ParameterWeb Service]" %> _±J|

using System;

using System. Web.Servi ces;

1 public class|ParameterWebService|: WebService {

z\

D Open the WebServices Template.aspx template from the Code Templates directory.

0 Rename the class to ParameterWebService.

D Open the WebServices Template.aspx template from the Code Templates directory.

0 Rename the class to ParameterWebService.

^0 Create a WebMethod with a parameter in the function signature.

□ Use the parameter the caller passes to the WebMethod for formatting the welcome statement.

^0 Create a WebMethod with a parameter in the function signature.

□ Use the parameter the caller passes to the WebMethod for formatting the welcome statement.

WORK WITH WEB SERVICES

You can create a Web Service method by leveraging other methods in the class that implement the Web Service. The following sample demonstrates this concept in a Web Service class (refer to this book's CD-ROM for an expanded example).

TYPE THIS:

public class ParameterWebService_ai : WebService {

[WebMethod] public string GetRandomGoal(string stringGoalTimeLength) { stringGoalTimeLength = stringGoalTimeLength.ToUpper(); if (stringGoalTimeLength != "DAILY" & stringGoalTimeLength != "YEARLY")

stringGoalTimeLength = "DAILY"; string stringGoal = "";

int intRandomNumber = 1; // Replace this with random number.

if (stringGoalTimeLength == "DAILY")

stringGoal = DailyGoal(intRandomNumber); else if (stringGoalTimeLength == "YEARLY") stringGoal = YearlyGoal(intRandomNumber);

return stringGoal;

public string YearlyGoal (int intRandomNumber) { string stringGoal = "Yearly Goals"; return stringGoal;

public string DailyGoal (int intRandomNumber) { string stringGoal = "Daily Goal"; return stringGoal;

RESULT:

A Web Service that will give a goal based on the time frame provided. This Web Service method will utilize other methods in the Web Service class.

0 Save the file and request it from the Web server.

Q Fill in your name for the parameter.

^O Click the Invoke button.

■ The parameterized welcome message appears.

TURN AN ARRAY ROM A WEB SERVICE

You can return more complex data types from your Web Services. For example, you can return arrays from a Web Service. Having the ability to return arrays from a Web Service enables you to pass back to the client a dynamic number of return values. With arrays, the return values will all be of the same data type, such as strings, integers, and so on.

To return an array from a Web Service, you need to first create a Web Service file containing a Web Method. The Web Method must define the array for the return type. In the Web Method, write the code that populates the array and specifies the return as the newly created array. When you test the Web Service, the array is designated by the

ArrayOfDataType element, and each member in the array will be a child element specified by the name of the data type. For example, the return that is an array of strings would generate the following XML:

<ArrayOfString>

<string>First string member</string> <string>Second string member</string> <string>Third string member</string> </ArrayOfString>

With this returned array, the client can work with the returned array to present the data in the client application. Note that arrays are zero based. Therefore, the first member of the array will be accessed with arrayName[0].

RETURN AN ARRAY FROM A WEB SERVICE

RETURN AN ARRAY FROM A WEB SERVICE

D Open the WebServices Template.asmx template from the Code Templates directory.

0 Rename the class to ArrayWebService.

'—0 Create a WebMethod that Q Create a string array returns a string array. variable for holding the goals.

D Open the WebServices Template.asmx template from the Code Templates directory.

0 Rename the class to ArrayWebService.

'—0 Create a WebMethod that Q Create a string array returns a string array. variable for holding the goals.

TYPE THIS:

<%@ WebService Language="C#" Class="ArrayWebService_ai" %> using System;

using System.Web.Services;

public class ArrayWebService_ai : WebService { [WebMethod]

public string[] GetGoals(int intNumberOfGoals) { if (intNumberOfGoals > 3) intNumberOfGoals = 3; if (intNumberOfGoals < 1) intNumberOfGoals = 1; string[] stringarrayGoals = new string[intNumberOfGoals]; stringarrayGoals[0] = "Regular exercise at the gym (3 days a week)";

if (intNumberOfGoals == 2 | intNumberOfGoals ==3) stringarrayGoals[1] = "A patient better driver";

if (intNumberOfGoals == 3)

stringarrayGoals[2] = "Keep in contact with old friends";

return stringarrayGoals;

RESULT:

An array of goals. The number of goals returned is dependent on the number the client provides.

^0 Read the goals into the 0 Return the string array.

array.

Note: The array is zero based.

Q Save the file and test the Web Service.

-■ The Web Service returns an array.

Note: The ArrayOfString element is used.

Note: Nested string elements are used for the string array.

TURN AN ENUMERATED YPE FROM A WEB SERVICE

Returning enumerations from a Web Service is useful when you have a set of fixed values for a variable. For example, you can define an enumeration to classify the types of goals a user can set in your application.

First you must add the definition of the enumeration into your Web Service file. After creating the enumeration, you can use the enumeration name as the return type for your Web Method. To return an enumeration, you can use the name of the enumeration and the desired member to return, separated by a period. For example, you can return the Travel member from the GoalType enumeration by using return GoalType.Travel.

To create an enumeration, you can set constant values for each enumeration or let the value for the constant be created automatically. For client applications that use Web Services with enumerations, you need to determine if the client application needs to work with the enumeration by its name or value. If you work with the enumeration by name, you need to define the enumeration in the client application to be able to access the value for the enumeration. If the client application is not aware of the enumeration, you will pass back the enumeration's value.

RETURN AN ENUMERATED TYPE FROM A WEB SERVICE

RETURN AN ENUMERATED TYPE FROM A WEB SERVICE

D Open the WebServices Template.aspx template from the Code Templates directory.

0 Rename the class to EnumeratedTypeWebService.

Create a public enumeration for the GoalType.

□ Create three enumerated types.

D Open the WebServices Template.aspx template from the Code Templates directory.

0 Rename the class to EnumeratedTypeWebService.

Create a public enumeration for the GoalType.

□ Create three enumerated types.

WORK WITH WEB SERVICES

Instead of returning the enumeration by name, you can return the constant value for the enumeration.

TYPE THIS:

<%@ WebService Language="C#" Class="EnumeratedTypeWebService_ai" %>

using System;

using System.Web.Services;

public enum GoalType{ Career = 1, Educational = 2,

Travel = 3

public class EnumeratedTypeWebService_ai : WebService { [WebMethod]

public int GetGoalTypeConstantValue(GoalType goaltypeMember) { return (int) goaltypeMember;

RESULT:

This Web Service takes in an enumeration member and returns its constant value. For example, when you test this with "Travel" for the goaltypeMember, the response is 3.

L-0 Add a WebMethod that returns the GoalType enumeration.

Q Return the value for a specific enumeration.

H Save the file and test the Web Service.

■ The GoalType element and value appear.

L-0 Add a WebMethod that returns the GoalType enumeration.

Q Return the value for a specific enumeration.

H Save the file and test the Web Service.

■ The GoalType element and value appear.

Was this article helpful?

0 0

Post a comment