2.5. Using a Web Service as a Data Source

Problem

You want to use a web service as the data source for a client application.

Solution

Create a web service that returns a DataSet to a client, and then invoke the web service from the client to retrieve the DataSet.

The XML web service code contains one method:

LoadOrders( )

Creates a DataSet containing all Orders and Order Details data from Northwind. A DataRelation is created relating the tables. The DataSet is returned by the method.

The client-side code instantiates the web service class and calls the LoadOrders( ) method to create a DataSet containing the Orders and Order Details data from Northwind. The default view of the Orders table is bound to a data grid on the form.

The C# code for the XML web service is shown in Example 2-4.

Example 2-4. File: NorthwindServiceCS.asmx.cs

// Namespaces, variables, and constants using System; using System.ComponentModel; using System.Web.Services; using System.Configuration; using System.Data; using System.Data.SqlClient; public const String ORDERS_TABLE = "Orders"; public const String ORDERDETAILS_TABLE = "OrderDetails"; public const String ORDERID_FIELD = "OrderID"; public const String ORDERS_ORDERDETAILS_RELATION = "Order_OrderDetails_Relation"; // . . . [WebMethod] public DataSet LoadOrders( ) { DataSet ds = new DataSet( ); SqlDataAdapter da; // Fill the Order table and add it to the DataSet. da = new SqlDataAdapter("SELECT * FROM Orders", ConfigurationSettings.AppSettings["DataConnectString"]); ...

Get ADO.NET Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.