Microsoft KB Archive/815671

= How to use XML in connected and disconnected ADO.NET applications in Visual C++ =

Article ID: 815671

Article Last Modified on 5/13/2007

-

APPLIES TO


 * Microsoft Visual C++ 2005 Express Edition
 * Microsoft Visual C++ .NET 2003 Standard Edition
 * Microsoft SQL Server 2000 Standard Edition
 * Microsoft ADO.NET 1.1

-







For a Microsoft Visual Basic .NET version of this article, see 307224.



For a Microsoft Visual C# version of this article, see 815672.



IN THIS TASK

 * SUMMARY
 * Requirements
 * Create an XML Web Service by using ASP.NET
 * Create a disconnected ADO.NET Windows application
 * Test the disconnected ADO.NET Windows application
 * Create a connected ADO.NET Windows application
 * Test the connected ADO.NET Windows application
 * REFERENCES



SUMMARY
XML is a fundamental part of Microsoft ADO.NET and XML Web Services. This article describes how to use XML in connected and disconnected ADO.NET applications:
 * Connected ADO.NET applications can query Microsoft SQL Server to return an XML result and then use the XmlReader class to iterate through the rows of XML data.
 * Disconnected ADO.NET applications can use a DataSet object to pass data in XML format between the different tiers in a distributed system.

This article describes how to use Microsoft ASP.NET to write an XML Web service that queries a database and returns a DataSet object in XML format to the client. The client application loads the XML data in a local DataSet object and binds it to a DataGrid control. If the user changes any data, the client application posts a DiffGram to the XML Web service. The DiffGram indicates which rows are inserted, modified, or deleted. The XML Web service uses the DiffGram to update the database.

In this article, you also write a connected ADO.NET application for reporting purposes. This application uses an XmlReader class to display current information in the database.

back to the top

Requirements
This article assumes that you are familiar with the following topics:
 * Microsoft Visual C++ .NET or Microsoft Visual C++ 2005 syntax
 * ADO.NET principles
 * ASP.NET principles
 * XML concepts

back to the top

Create an XML Web service by using ASP.NET
 Start Visual Studio .NET or Visual Studio 2005, and then create a new ASP.NET Web Service project in Visual C++. In the Location box, type C:\test\, type ProductsService in the Name box, and then click OK. On the View menu, click Server Explorer. In Server Explorer, right-click Data Connections, and then click Add Connection. Set the properties in the Data Link Properties dialog box as follows: <ol style="list-style-type: lower-alpha;"> Select or enter a server name: </li> Enter logon information: <ul> User name= </li> Password= </li></ul>

Where  is the name of your SQL Server server, where   is your user name, and where   is your password.</li> Select the database on the server: Northwind </li></ol> </li> Click OK, type your password again in the SQL Server Login dialog box, and then click OK.</li> In Server Explorer, expand the following nodes: <ul> Data Connections</li> YourSQLSERVERName.Northwind.dbo</li> Tables</li></ul> </li> Drag the Products table to the designer. Click Include password in the warning dialog box.

This action adds a SqlConnection object to your application to enable connections to the Northwind database. It also adds a SqlDataAdapter object to encapsulate queries and modifications to the Products table.</li> On the Data menu, click Generate Dataset.</li> Click New, and then name the new DataSet ProductsDataSet.</li> Click Add this DataSet to the designer, and then click OK.

This creates a typed DataSet class that is named ProductsDataSet (based on the Products table in the database) and creates a DataSet object that is named productsDataSet1.</li>  View the code for the class, and then add the following method. This XML Web service method queries the Products table and returns a DataSet object in XML format to the client. public: [WebMethod] String __gc* GetProductsData { // Query database, and fill the DataSet with the result. sqlDataAdapter1->Fill(productsDataSet1->Products); // Write the DataSet to a string in XML format. System::IO::StringWriter * sw = new System::IO::StringWriter; productsDataSet1->WriteXml(sw); // Return the XML string to the client. return sw->ToString; } Note You must add the common language runtime support compiler option (/clr:oldSyntax) in Visual C++ 2005 to successfully compile the previous code sample. To add the common language runtime support compiler option in Visual C++ 2005, follow these steps: <ol style="list-style-type: lower-alpha;"> Click Project, and then click  Properties.

Note  is a placeholder for the name of the project.</li> <li>Expand Configuration Properties, and then click General.</li> <li>Click to select Common Language Runtime Support, Old Syntax (/clr:oldSyntax) in the Common Language Runtime support project setting in the right pane, click Apply, and then click OK.</li></ol>

For more information about the common language runtime support compiler option, visit the following Microsoft Web site:

/clr (Common Language Runtime Compilation)

http://msdn2.microsoft.com/en-us/library/k8d11d4s.aspx

These steps apply to the whole article. </li> <li> Add another XML Web service method. The following method receives a DiffGram from a client and updates the database with the changes that are defined in the DiffGram: public: [WebMethod] void UpdateProductsData(String * Diff) { //Read the XML DiffGram into the DataSet object in the XML Web service. System::IO::StringReader * sr = new System::IO::StringReader(Diff); productsDataSet1->ReadXml(sr, XmlReadMode::DiffGram);

// Use the SqlDataAdapter object to update the database accordingly. sqlDataAdapter1->Update(productsDataSet1->Products); } </li> <li>Build the XML Web service.</li></ol>

back to the top

Create a disconnected ADO.NET Windows application
<ol> <li>In Visual Studio .NET or in Visual Studio 2005, create a new Windows Forms Application (.NET) project in Visual C++, and then name it UseProducts.</li> <li>In the Location box, click any folder on your computer, and then click OK.</li> <li>Add a DataGrid control, a RichTextBox control, and a Button control to the Windows Form designer.</li> <li>Change the names and the text of the 3 buttons as follows: </li> <li>Drag a DataSet object to the form. In the Add DataSet dialog box, click Untyped dataset, and then click OK.

You use this DataSet object as a local store for the data that the XML Web service returns.</li> <li>On the Project menu, click Add Web Reference.</li> <li>In the Address box, type http://localhost/ProductsService/ProductsService.asmx, click Go to, and then click Add Reference.

This generates a proxy class that is named ProductsServiceClass. By using this class, you can run methods on the ProductsService XML Web service.</li> <li> Define a click event handler for the Get Data button. Add the following code to the method to request data from the XML Web service and display it in the DataGrid object: // Create a proxy object that is ready to invoke the XML Web service method. localhost::ProductsServiceClass * svc = new      localhost::ProductsServiceClass;

// Invoke the XML Web service method to get Products data in XML format. String * strXml = svc->GetProductsData;

// Display XML data in the text box to show what it looks like. richTextBox1->Text = strXml;

// Read the XML data into the local DataSet. System::IO::StringReader * sr = new System::IO::StringReader(strXml); dataSet1->ReadXml(sr); dataSet1->AcceptChanges;

// Bind the DataGrid to the DataSet to display the data. dataGrid1->DataSource = dataSet1->Tables->get_Item(0)->DefaultView;           </li> <li> Define a click event handler for the Save Data button. Add the following code to the method to send an XML DiffGram to the XML Web service. The XML DiffGram tells the XML Web service what data has changed: // Write the DataSet data as an XML DiffGram string. System::IO::StringWriter * sw = new System::IO::StringWriter; dataSet1->WriteXml(sw, XmlWriteMode::DiffGram);

// Display the XML DiffGram in the text box to show what it looks like. richTextBox1->Text = sw->ToString;

// Create a proxy object that is ready to invoke the XML Web service method. localhost::ProductsServiceClass * svc = new localhost::ProductsServiceClass;

// Invoke the XML Web service method to save Products data. svc->UpdateProductsData(sw->ToString); </li> <li> Define a click event handler for Process Data. Add the following code to load the DataSet object data in an XmlDataDocument object. In this way, you can use XML techniques (such as XPath) to process the data: // Load DataSet data in an XmlDataDocument object (for DOM manipulation). System::Xml::XmlDataDocument * doc = new System::Xml::XmlDataDocument(dataSet1->Copy);

// Create an XPathNavigator object that is ready to use XPath. System::Xml::XPath::XPathNavigator * nav = doc->CreateNavigator;

// Evaluate an XPath expression. Object * obj = nav->Evaluate(&quot;count(//*[local-name='UnitPrice'])&quot;); MessageBox::Show(String::Concat(&quot;Total price for products: $&quot;, obj->ToString ));

// Obtain the names of all products that cost more than $50. System::Xml::XPath::XPathNodeIterator * iter = nav->Select(String::Concat(&quot;//*[local-name='ProductName']&quot;, &quot;[../*[local-name='UnitPrice'] > 50]&quot;));

//Display product names in the text box. richTextBox1->Clear; while (iter->MoveNext) { richTextBox1->AppendText(String::Concat(&quot;ProductName: &quot;, iter->Current->Value->ToString , &quot;\n&quot;) ); } </li> <li>Build the disconnected Windows application.</li></ol>

back to the top

Test the disconnected ADO.NET Windows application

 * 1) Run the disconnected Windows application.
 * 2) Click Get Data to retrieve data through the XML Web service. The retrieved data appears in XML format in the text box, and appears in tabular format in the DataGrid object.
 * 3) Modify the data in the DataGrid object, and then insert new rows.
 * 4) Click Save Data to save the changes back to the database through the XML Web service.
 * 5) Click Process Data to process the DataSet as XML.

A message box displays the total price of all products. The text box displays the name of each product that costs more than 50 dollars.
 * 1) Close the disconnected Windows application.

back to the top

Create a connected ADO.NET Windows application
<ol> <li>In Visual Studio .NET or in Visual Studio 2005, create a new Windows Application (.NET) project in Visual C++, and then and name it ReportProducts.</li> <li>In the Location list box, click any folder on your computer, and then click OK.</li> <li> View the code for the application. Add two using statements before the start of the class to simplify your code: using namespace System::Data::SqlClient; // For SqlConnection and SqlCommand using namespace System::Xml; // For XmlReader and XmlConvert </li> <li>In the Windows Form designer, add a ListBox control and a Button control to your form.</li> <li> Define a click event handler for the button. Add the following code to the method to connect to the Northwind database and to obtain product data in XML format by using the FOR XML AUTO clause: SqlConnection * cn = new SqlConnection(&quot;data source=localhost;initial catalog=Northwind;integrated security=SSPI;persist security info=True;packet size=4096&quot;); SqlCommand * cmd = new SqlCommand(&quot;SELECT ProductName, UnitPrice FROM Products FOR XML RAW&quot;, cn); cn->Open; XmlReader * r = cmd->ExecuteXmlReader; </li> <li> Add the following code after the previous code to use the XmlReader object to loop through the rows of XML data: while( r->Read) { String * name = r->GetAttribute(&quot;ProductName&quot;); double price = XmlConvert::ToDouble(r->GetAttribute(&quot;UnitPrice&quot;)); listBox1->Items->Add(String::Concat(name, &quot;, $&quot; , price.ToString)); } </li> <li> After you finish reading the data, close the XmlReader object and the database connection by using the following code: r->Close; cn->Close;                </li> <li>Build the connected Windows application.</li></ol>

back to the top

Test the connected ADO.NET Windows application

 * 1) Run the ReportProducts application.
 * 2) Click the button on the form. The list box displays the name and price for all products.
 * 3) Verify that the data reflects the changes that you made when you ran the disconnected Windows application earlier.

back to the top

<div class="references_section">