ASPNET Web Service

Published on July 2016 | Categories: Documents | Downloads: 116 | Comments: 0 | Views: 1266
of 12
Download PDF   Embed   Report

Comments

Content

Intel® Software Network - Build and Consume an ASP.NET Web S...

http://www.intel.com/cd/ids/developer/asmo-na/eng/20068.htm?prn=Y

Abstract
By Patrick Barnes Before the advent of Web services, other technologies and architectures existed that allowed applications to remotely call procedures exposed by other applications, typically using the TCP/IP protocol. You have undoubtedly heard of Microsoft's version of this technology, called Component Object Model* (COM*), and subsequently Distributed COM* (DCOM*). Common Object Request Broker Architecture* (CORBA*) is a competitor of COM, developed by a consortium of vendors under the aegis of the Object Management Group. Although these technologies were a breakthrough in distributed computing and served such ends well for at least five years, there were many limitations. Concerning DCOM, its two main disadvantages were: Microsoft-only: DCOM works properly only with binaries written with Microsoft languages and running on Microsoft platforms. Not Suitable for the Internet: DCOM was designed to use the TCP/IP protocol over a LAN or WAN. Firewalls present a serious problem, and performance is often poor and unreliable. Web services solve many of the problems common to DCOM. A Web service is a unit of code that publicly exposes its functionality as a URL-addressable resource. As such, any client application that conforms to open Web standards such as HTTP and the Simple Object Access Protocol (SOAP)—the main message formatting protocol, as opposed to HTTP, which is a message transmission protocol—can call a Web service, initiate a procedure, and even retrieve data in the form of an XML document. Thus, Web services take care of the two problems with DCOM and other distributed programming technologies: Non-proprietary: Open standards are governed by the World Wide Web Consortium (www.W3C.org*) and other grassroots organizations. All communication and data formatting protocols are non-proprietary, detaching this form of remote procedure calling from specific languages and platforms. Internet-savvy: Web services were designed specifically for use over the Internet via HTTP. This article shows you how to build and consume a basic ASP .NET Web service. It focuses on the steps required to build the Web service and client application that consumes it. For more theoretical or in-depth information about Web services, see the list of resources at the end of this article. Assumptions and Requirements This article assumes no prior knowledge of Web services, Visual Studio .NET*, or Visual Basic .NET*. The Web Service is built using Visual Studio .NET, although the IDE is not required to build .NET Web services. You could write the code and compile it using the Visual Basic compiler from the command line. However, this article assumes you are using Visual Studio .NET and thus makes no accommodations for other situations. Finally, you will need access to the Northwind* database shipped with Microsoft SQL Server* and the Microsoft Data Engine* (MSDE).

Creating a Web Service Project in Visual Studio .NET
Follow these steps show to create an ASP .NET Web service project in Visual Studio .NET. 1. Click Start, point to Programs, point to Microsoft Visual Studio .NET, and then click Microsoft Visual Studio .NET. 2. Click New Project. 3. Select Visual Basic Projects in the Project Types pane.

1 of 12

11/7/05 20:28

Intel® Software Network - Build and Consume an ASP.NET Web S...

http://www.intel.com/cd/ids/developer/asmo-na/eng/20068.htm?prn=Y

4. Select ASP.NET Web Service in the Templates pane. 5. In the Location box, enter the name of the Web server with the name of the project, http://ServerName (or Localhost)/intel_wsNWProducts. See Figure 1.

Figure 1. Creating the Project in Visual Studio .NET. 6. Click OK. The intel_wsNWProducts project is created and added to a Solution by the same name. Service1.asmx is open in design view. 7. Click the design surface and press F4 to access the Web service page's Properties window. 8. Set the Name property of Service1 to ProductsService. 9. In Solution Explorer, right-click the Service1.asmx file, select Rename, and rename the file Products.asmx to match the service name.

Exposing a Web Method
Functions and subroutines that you want to expose to the public over HTTP are essentially no different than non-Web service methods. The only difference is the use of the <WebMethod> attribute, as you will see. The method you will build for this article's Web service allows anyone to retrieve a list of products from the Northwind database by product category. The user types in a CategoryID, which is forwarded to the Web service. The Web service returns the products in that category. (If no category is entered by the user, all products are returned.)

2 of 12

11/7/05 20:28

Intel® Software Network - Build and Consume an ASP.NET Web S...

http://www.intel.com/cd/ids/developer/asmo-na/eng/20068.htm?prn=Y

1. In the Code Editor window right-click on Products.asmx.vb and select View Code. 2. Replace the commented lines with the following shell of a function that returns a DataSet:

Public Function GetProducts(ByVal strCategoryID As Int32) As DataSet End Function

In the next step you will add an Imports statement that lets you use shorthand notation when accessing classes in the imported namespace. A namespace is simply a logical grouping of related .NET types, such as classes, interfaces, enums, structures, and so forth. This makes it easier to work with the Base Class Library and also prevents type name conflicts. You can always access the type using a fully qualified name like this: System.Data.SqlClient.SqlConnection. The advantage of an Imports statement, however, is that you can simplify and lighten your code with the use of shorthand dot notation. Thus, if you import the System.Data.SqlClient namespace, in your code you need only type SqlConnection. 3. At the top of the page of code add the following: Imports System.Data.SqlClient Classes in the SqlClient namespace classes are optimized for use with SQL Server. If you were working with another database, you could use classes in the System.Data.OleDb. 4. Create a SqlConnection object. Add the following to the function (adjust the connection string for your setup):

Dim cn As New SqlConnection("server=(localhost);uid=sa;pwd=;database=northwind")

5. Create a SqlCommand object. This object executes SQL statements against a SQL Server database. You are passing in two arguments, the SQL statement that, at this point, returns all of the products, as well as the newly created Connection object. Add this code:

Dim cmd As New SqlCommand("select * from products",cn)

6. To support filtering the products by CategoryID, add the next few lines of code. The SQL has been built this way so that if the user doesn't enter a CategoryID, the Web service assumes that he or she wants to view all products:

If strCategoryID <> "" Then cmd.CommandText &= " where CategoryID = " & strCategoryID End If

7. Create a SqlDataAdapter object, which takes the SqlCommand object as an argument and is responsible for filling the DataSet that is returned by this method. Add this line of code:

3 of 12

11/7/05 20:28

Intel® Software Network - Build and Consume an ASP.NET Web S...

http://www.intel.com/cd/ids/developer/asmo-na/eng/20068.htm?prn=Y

Dim da As New SqlDataAdapter(cmd) 8. These last few lines of code complete the inner workings of the Web method. Add the following lines of code to create a new empty DataSet object, pass it to the SqlDataAdapter for filling, and then return the filled DataSet to the calling function:

Dim ds As New DataSet() da.Fill(ds) Return ds

9. The function is now complete, but it is not yet exposed as a public Web method. For this all you need to do is mark up the function with the <WebMethod()> attribute: <WebMethod()> Public Function GetProducts... You can also pass in a description of the Web method that will appear on the Framework-generated pages. You will be introduced to this in the next section. 10. Pass a description of the Web method as follows: <WebMethod(Description:="This method returns a DataSet containing products from the Northwind database. Not passing an argument results in all products being returned. Or you may pass a CategoryID to view only products in that category.")>

Running and Testing the Web Service
The .NET Framework makes it easy to run and test a Web service by automatically generating a set of test and information pages when you access a .NET Web service. 1. Press F5 to build and run the Web service in debug mode. After 5 or more seconds (depending on your machine, database connection, and so forth), the main Web service page created by the Framework opens in your browser.

Figure 2. The Main Web Service Page. The main Web service page contains general information about a Web service, lists the methods it exposes, and provides a link to its WSDL document. WSDL is an XML document that describes the Web service's public interface. Examining the WSDL document enables you to build a client application that can call the Web service and consume the data it returns. It is a kin to the old COM interface ontracts. 2. Click the GetProducts link to access the test page for this Web method.

4 of 12

11/7/05 20:28

Intel® Software Network - Build and Consume an ASP.NET Web S...

http://www.intel.com/cd/ids/developer/asmo-na/eng/20068.htm?prn=Y

Figure 3. Test Page for the Web Method. All test pages have an Invoke button. Because this Web method takes one argument, CategoryID, the Framework also adds a Textbox to enter a value before invoking the method. 3. Click Invoke without entering a CategoryID. A second browser window opens and displays the XML representation of the DataSet returned by this Web method. The actual data is preceded by the schema representation of the DataSet:

- <xs:schema id="NewDataSet" xmlns="" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:msdata=" urn:schemas-microsoft-com:xml-msdata">

- <xs:element name="NewDataSet" msdata:IsDataSet="true"> - <xs:complexType> - <xs:choice maxOccurs="unbounded"> - <xs:element name="Table"> - <xs:complexType> - <xs:sequence> <xs:element name="ProductID" type="xs:int" minOccurs="0" /> <xs:element name="ProductName" type="xs:string" minOccurs="0" /> <xs:element name="SupplierID" type="xs:int" minOccurs="0" /> <xs:element name="CategoryID" type="xs:int" minOccurs="0" />

5 of 12

11/7/05 20:28

Intel® Software Network - Build and Consume an ASP.NET Web S...

http://www.intel.com/cd/ids/developer/asmo-na/eng/20068.htm?prn=Y

<xs:element name="QuantityPerUnit" type="xs:string" minOccurs="0" /> <xs:element name="UnitPrice" type="xs:decimal" minOccurs="0" /> <xs:element name="UnitsInStock" type="xs:short" minOccurs="0" /> <xs:element name="UnitsOnOrder" type="xs:short" minOccurs="0" /> <xs:element name="ReorderLevel" type="xs:short" minOccurs="0" /> <xs:element name="Discontinued" type="xs:boolean" minOccurs="0" /> </xs:sequence> </xs:complexType> </xs:element> </xs:choice> </xs:complexType> </xs:element> </xs:schema> This code shows data for a single product:

- <NewDataSet xmlns=""> - <Table diffgr:id="Table1" msdata:rowOrder="0"> <ProductID>1</ProductID> <ProductName>Chai</ProductName> <SupplierID>1</SupplierID> <CategoryID>1</CategoryID> <QuantityPerUnit>10 boxes x 20 bags</QuantityPerUnit> <UnitPrice>18</UnitPrice> <UnitsInStock>39</UnitsInStock> <UnitsOnOrder>0</UnitsOnOrder> <ReorderLevel>10</ReorderLevel> <Discontinued>false</Discontinued> </Table>

4. Close the browser containing the XML data. 5. In the strCategoryID field type "2" and click Invoke. 6. Scroll through the results, verifying that only those products with CategoryID = 2 are displayed. 7. Close both browser windows.

Creating an ASP .NET Web Application to Consume the Web Service

6 of 12

11/7/05 20:28

Intel® Software Network - Build and Consume an ASP.NET Web S...

http://www.intel.com/cd/ids/developer/asmo-na/eng/20068.htm?prn=Y

You have built the Web service and are now ready to build a client application to consume it. Follow these steps to add an ASP .NET Web Application to your existing Solution. 1. In the Solution Explorer, right-click Solution 'intel_wsNWProducts', point to Add, and then click New Project. 2. Select Visual Basic Projects in the Project Types pane. 3. Select ASP.NET Web Application in the Templates pane. 4. In the Location field type "http:// localhost/intel_wsNWProductsClient". 5. Click OK. The Intel_wsNWProductsClient project is added to the Solution.

Adding Controls to a Web Form
Now you can build a Web Form containing a Textbox and Button that will allow the user to enter a CategoryID and invoke the Web service by clicking the Button. 1. You should see a blank design surface for WebForm1.aspx. (If you are not in Design View, click the Design tab below the Code Editor window.) 2. Right-click the design surface and select Properties. In the Page Layout drop-list select FlowLayout and click OK. FlowLayout is easier to use for designing and positioning form controls than the default GridLayout. 3. Click the design surface and type "CategoryID:". 4. Press CTRL + ALT + T to open the Toolbox. From the Web Forms group select and drag a Textbox to the design surface, placing it to the right of the text you just typed. 5. Press F4 to access the Textbox properties. In the Properties window, change the Columns property to 1. 6. From the Toolbox, select and drag a Button to the design surface, placing it to the right of the Textbox. 7. Press F4 to access the Button properties. In the Properties window, change the Text property to "Get Products". 8. Press Enter to move the cursor to the next line on the design surface. 9. From the Toolbox, select and drag a DataGrid to the design surface. 10. Press F4 to access the DataGrid properties. In the Properties window, below all of the properties click the Auto Format link. Select any Scheme you like and click OK.

7 of 12

11/7/05 20:28

Intel® Software Network - Build and Consume an ASP.NET Web S...

http://www.intel.com/cd/ids/developer/asmo-na/eng/20068.htm?prn=Y

Figure 4. Setting Auto Format Schemes.

Adding a Web Reference
If you have experience building applications, you are undoubtedly familiar with the concept of a reference. A reference registers a binary with the development environment so that its members can be accessed programmatically. In fact, when Visual Studio .NET created both the Web service and Web application projects, it automatically included references to the most common .NET assemblies for building each type of project. You can see a list of these assemblies by expanding References in the Solution Explorer. The concept of a Web reference is very similar. The difference is, of course, that the binary you are referencing is remote. It could be thousands of miles away on another server, hosted by a company with which you have no association. As you will see, a Web reference is merely a pointer to the Web service's WSDL document. As mentioned earlier, the WSDL document describes the Web service's public interface. The .NET Framework processes this document and generates a proxy class, which becomes like the other binaries that are locally referenced in your project. It "stands in the place of" the Web service class, allowing you to use its API as if the Web service were local instead of remote. 1. In the Solution Explorer, right-click References under Intel_wsNWProductsClient and select Add Web Reference. 2. In the Address field type "http://localhost/intel_wsNWProducts/Products.asmx". This is the URL to the main Web service page you saw earlier containing information about your Web service and a link to test the Web method. 3. Press Enter. The page appears in the left pane.

8 of 12

11/7/05 20:28

Intel® Software Network - Build and Consume an ASP.NET Web S...

http://www.intel.com/cd/ids/developer/asmo-na/eng/20068.htm?prn=Y

Figure 6. Adding a Web Reference. 4. Click Add Reference. Visual Studio .NET will now access the Web service's WSDL document over HTTP and generate a proxy class for you. Notice that a Web References node appears in the Solution Explorer, with a child localhost node. 5. It is worthwhile to examine briefly what is contained in the proxy class. In the Solution Explorer, click the View All Files icon. 6. Expand Web References | localhost | Reference.map. 7. Right-click Reference.vb and select View Code. Examine the proxy class code. Although it is beyond the scope of this article to discuss the code in detail, consider the following noteworthy points. The proxy class derives from System.Web.Services.Protocols.SoapHttpClientProtocol. This class takes care of the low-level Web service connectivity, SOAP messaging and deserialization. Much of its functionality is inherited from other classes in the same namespace. The inherited Url property maintains a reference to the Web service address. Proxy methods have been created for both the synchronous and asynchronous calling of the Web service's methods. When the XML is received back from the Web service, the proxy class takes care of deserializing it—reconstructing the DataSet object from the XML based on the schema information included in the XML stream. 8. Close Reference.vb.

Adding Code to Call the Web Method
With the Web Form controls in place, you are ready to add the code needed to invoke the Web method and display the results in the DataGrid. 1. On the design surface for WebForm1.aspx, double-click the Button to create a Click event handler. 2. In the event handler, add the following code, which creates an instance of the Web service proxy class and calls the GetProducts proxy method:

9 of 12

11/7/05 20:28

Intel® Software Network - Build and Consume an ASP.NET Web S...

http://www.intel.com/cd/ids/developer/asmo-na/eng/20068.htm?prn=Y

Dim ws As New localhost.ProductsService() DataGrid1.DataSource = ws.GetProducts(TextBox1.Text) DataGrid1.DataBind()

This is a surprisingly small amount of code, thanks entirely to the proxy class created for you. All of the complex issues involved with connecting to a Web service, creating and receiving SOAP-formatted messages, and deserializing XML are taken care of for you behind the scenes.

Running the Client Application
Running the Web application client from within Visual Studio .NET requires that you first set the startup project and start page. 1. In the Solution Explorer, right-click the intel_wsNWProductsClient project and select Set as Startup Project. 2. Right-click WebForm1.aspx and select Set As Start Page. 3. Press F5 to build and run the Solution in debug mode. 4. When the page appears in the browser, click Get Products. After a brief delay due to the Web service being "just in time" (JIT) compiled by the .NET runtime (this happens only the first time the Web service is invoked), the DataGrid displays with information about all of the Products. 5. In the Textbox type "2" and click Get Products. The DataGrid shows only those Products in the second category.

10 of 12

11/7/05 20:28

Intel® Software Network - Build and Consume an ASP.NET Web S...

http://www.intel.com/cd/ids/developer/asmo-na/eng/20068.htm?prn=Y

Figure 7. The DataGrid. 6. Close the browser.

Conclusion and Resources
Entire books have been written on Web services. Yet with this brief hands-on introduction, you should now have a basic understanding of the following: What a Web service is. Why it solves many of the key problems common to previous distributed programming technologies. How to build a Web service using Visual Studio .NET. How to build a client ASP .NET Web application to consume it. You're ahead of the game! Resources The following Web-based resources will be help you learn more about this incredible new technology that is changing the face of the Internet forever. Microsoft Developer Network (MSDN) Main Web Services Page* "XML Web Service Basics"* "Using Web Services Instead of DCOM"* "Visual Studio .NET: Build Web Applications Faster and Easier Using Web Services and XML"*

11 of 12

11/7/05 20:28

Intel® Software Network - Build and Consume an ASP.NET Web S...

http://www.intel.com/cd/ids/developer/asmo-na/eng/20068.htm?prn=Y

"Creating a .NET Web Service"*

About the Author
Patrick Barnes is a freelance Web application developer, author and consultant located in Cedar Rapids, Iowa. He specializes in n-tier development using ASP .NET, Visual Basic* .NET, SQL Server*, and XML.

The information, opinions, and recommendations in this column are provided by the Author, Patrick Barnes. Intel and its subsidiaries do not necessarily endorse or represent the accuracy of the Author's information, opinions or recommendations, and any reliance upon the Author's statements is solely at your own risk.

12 of 12

11/7/05 20:28

Sponsor Documents

Or use your account on DocShare.tips

Hide

Forgot your password?

Or register your new account on DocShare.tips

Hide

Lost your password? Please enter your email address. You will receive a link to create a new password.

Back to log-in

Close