Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

C# ПІДРУЧНИКИ / c# / MS Press - Msdn Training Programming Net Framework With C#

.pdf
Скачиваний:
173
Добавлен:
12.02.2016
Размер:
16.87 Mб
Скачать

Module 16 (Optional): Using Microsoft ADO.NET to Access Data

33

 

 

 

Demonstration: Calling Stored Procedures

Topic Objective

To introduce the demonstration.

Lead-in

In this demonstration, you will see how to call stored procedures both with and without parameters.

*****************************ILLEGAL FOR NON-TRAINER USE******************************

In this demonstration, you will see how to create and call stored procedures with and without parameters.

Run the Visual Studio .NET StoredProcedure project from the following location:

<install folder>\Democode\Mod16\Demo16.3

Tip You can examine the database tables and stored procedures by using the

Server Explorer window Data Connections entries.

To create and execute a stored procedure that returns the product names of all the entries in the Products table, click the Load Product Names button.

Typing a name in the text box that is labeled Enter Product Name allows you to click on the Load Product Data button. This button creates and executes a stored procedure that takes the product name as an input parameter and returns all the fields of that product.

To create and execute a stored procedure that has an output parameter, which gets set to the number of products in the database’s Products table, click the

Get Number of Products button.

34

Module 16 (Optional): Using Microsoft ADO.NET to Access Data

Lab 16: Using ADO.NET to Access Data

Topic Objective

To introduce the lab.

Lead-in

In this lab, you will create an XML Web service and a Windows form that reads and updates database records by using ADO.NET.

*****************************ILLEGAL FOR NON-TRAINER USE******************************

Explain the lab objectives.

Objectives

 

 

After completing this lab, you will be able to:

 

! Use the rapid application design facilities of Visual Studio .NET to create an

 

XML Web service whose methods can be used to read and update a

 

database by using ADO.NET.

 

! Use Visual Studio .NET rapid application design facilitates to create a

 

Windows Forms application that displays and enables a user to update a

 

DataGrid control that is bound to a DataSet. The DataSet is obtained and

 

updated by using an XML Web service.

 

Lab Setup

Only solution files are associated with this lab. The solution files for this lab are in the folder <installfolder>\Labs\Lab16\Solution.

Module 16 (Optional): Using Microsoft ADO.NET to Access Data

35

 

 

 

Scenario

This lab is based on the Visual Studio .NET Framework SDK Walkthrough: Creating a Distributed Application. In this lab, you will create a multi-tiered, distributed application.

The application consists of three logical tiers: data, business object, and user interface. The data tier is a SQL Server database. The business object tier handles the tasks of accessing the data and distributing it to the clients. The user interface tier consists of a Windows-based application.

You will create the Authors XML Web service and the Windows Client Application. The following diagram shows the architecture of the distributed application:

As part of the distributed application, you will build a simple data application with look-up and update functionality. You will create an XML Web service to retrieve data from the Authors table in the SQL Server Pubs sample database. You will also build a Windows-based client application to display the results of the query by the XML Web service. The communication between the client and the XML Web service is handled by using HTTP and XML.

For this lab, the data has already been generated and is available in the Pubs sample database. Therefore, you will begin by creating the business object, the XML Web service, followed by building the Windows Form user interface.

Estimated time to complete this lab: 60 minutes

36

Module 16 (Optional): Using Microsoft ADO.NET to Access Data

Exercise 1

Creating the Middle-Tier Business Object

In this exercise, you will create a business object that runs on a Web server. You will implement the business object as an XML Web service that holds the data connections and dataset definition.

After first creating an ASP.NET Web Service project in Visual Studio .NET, you will use the Visual Studio .NET design environment to add a data connection, a data adapter, and a dataset class definition to the XML Web service. You will add two methods to the XML Web service: GetAuthors, which returns a dataset from the database, and UpdateAuthors, which updates the database with changes from the user.

!Create a ASP.NET Web Service project

1.Open Visual Studio .Net and on the File menu, click New, and then click Project to display the New Project dialog box.

2.In the Project Types pane, click Visual C# Projects, and then select

ASP.NET Web Service in the Templates pane.

3.In the Location box, type the name of the Web server, http://localhost/AuthorsWebService. The dimmed Name box will now contain the text: AuthorsWebService. Click OK.

4.The AuthorsWebService project is added to the solution. The Component Designer for Service1.asmx appears in the development environment. In this component, you will create a connection to the data store and obtain an instance of the data by using a dataset. In Solution Explorer, double-click

Service1.asmx.

5.In the Properties window, set the Name property of Service1 to AuthorsService.

6.In Solution Explorer, right-click the Service1.asmx file, click Rename, and rename the file AuthorsService.asmx, to match the service name.

!Create a database connection and data adapter

1.If Server Explorer is not visible, on the View menu, click Server Explorer.

2.In Server Explorer, right-click the Data Connections node and on the shortcut menu, click Add Connection.

3.In the Connection tab of the Data Link Properties dialog box, type the name of the SQL Server where the pubs database is installed: (local)\NETSDK

Select Use Windows NT Integrated security for the logon information.

4.Select the pubs database from the list. Click Test Connection to validate the information that you provided, and then click OK to establish the connection.

A new node appears in the Data Connections node of Server Explorer.

5.In Server Explorer, expand the node for the new connection node and then expand the Tables node.

Module 16 (Optional): Using Microsoft ADO.NET to Access Data

37

 

 

 

6.Find the authors node and expand it to show the fields in the authors table.

7.Using CTRL+Click, select the au_id, au_lname, au_fname, and city fields.

8.Drag these fields from Server Explorer onto the design surface.

A SqlConnection that is paired with a SqlDataAdapter appears in the designer. A connection has now been created to the database, with the transfer of information to be handled by the SqlDataAdapter. These components are configured to move a dataset with the selected fields of the authors table in and out of the database.

! Configure Integrated Windows authentication

1.Start the Internet Information Services tool. It can be run from the Start button, Control Panel, Performance and Maintenance, Administrative Tools.

2.Expand the node for your server.

3.Expand the Default Web Site node.

4.Right-click the node for AuthorsWebService and click Properties.

5.Click the Directory Security tab.

6.Click the Edit button in the Anonymous access and authentication control section, click the Edit button.

7.Clear the Anonymous access check box.

8.Select the Integrated Windows authentication check box. Click OK to return to the AuthorsWebService Properties and click OK again. You have now configured your XML Web service directory.

9.Returning to the project in Visual Studio, in Solution Explorer, doubleclick the Web.config file.

10.Add the following tag on the line after the <system.web> tag to configure integrated security for your XML Web service.

<identity impersonate="true"/>

! Create a dataset class definition

1.In Solution Explorer, double-click the AuthorsService.asmx file to open it in the designer.

2.On the Data menu, click Generate DataSet. In the Generate Dataset dialog box, select New and name the dataset authors1. Do not select the

Add this dataset to the designer check box. Click OK.

Note A dataset schema file, authors1.xsd, is created and added to the project. This schema file contains a class definition for authors1. This class, which inherits from DataSet, contains a typed dataset definition for the authors table.

3.On the File menu, click Save All.

38Module 16 (Optional): Using Microsoft ADO.NET to Access Data

!Add methods to the XML Web service

1.In Solution Explorer, double-click AuthorsService.asmx, if it is not already open in the designer.

2.On the View menu, click Code.

3.Add a method named GetAuthors to deliver a dataset to the client.

This method creates a new authors1 dataset, and fills it by using the SqlDataAdapter that is based on the authors table. The method then returns the dataset:

The following code shows the method:

[WebMethod]

public authors1 GetAuthors()

{

authors1 authors = new authors1(); sqlDataAdapter1.Fill(authors); return authors;

}

4.Add a method named UpdateAuthors to propagate changes from the client back to the database.

This method has an authors1 dataset parameter (authorChanges) that contains the changed data and updates the database through the SqlDataAdapter.Update method. The Update method accepts the changes in the dataset. The dataset is returned to the client. The client then uses this returned dataset to update its own instance of the authors1 dataset.

The following code shows the method:

[WebMethod]

public authors1 UpdateAuthors(authors1 authorChanges)

{

if (authorChanges != null)

{

sqlDataAdapter1.Update(authorChanges); return authorChanges;

}

else

{

return null;

}

}

Note In a production application, you would add error checking and exception handling to these methods.

5.On the File menu, click Save All.

6.On the Build menu, click Build Solution.

7.To test the XML Web service, in the Solution Explorer right-click

AuthorsService.asmx and click View in Browser. In the browser, click

GetAuthors and in the resulting GetAuthors page, click the Invoke button. You should see the list of authors displayed as XML.

Module 16 (Optional): Using Microsoft ADO.NET to Access Data

39

 

 

 

Exercise 2

Creating a Windows User Interface

In this exercise, you will create a Windows Forms client application. The application consists of one Windows Form that contains a reference to AuthorsWebService. The data in the database is displayed in a DataGrid control when a Load button on the form is clicked.

To implement the display of data in the DataGrid, you call the XML Web service’s GetAuthors method. The DataGrid control enables direct editing of the data, with changes being passed directly to the underlying dataset.

In addition to a Load button, the form has a save button. The code for this button calls the XML Web service's UpdateAuthors method to save the changes back to the database.

! Create the Windows application

1.Open Visual Studio .NET and on the File menu, click New, and then click Project to display the New Project dialog box.

2.Select Visual C# Projects in the Project Types pane, then select Windows Application in the Templates pane.

3.Name the project AuthorsWinClient.

4.In the Location box, type the name of the Starter folder:

<install folder>\Labs\Lab16\Starter

5.Click OK.

The AuthorsWinClient project is created and Form1 is automatically added to the project and appears in the Windows Forms Designer.

6.Add a reference to the XML Web service project that you created earlier.

a.In Solution Explorer, expand the AuthorsWinClient node, right-click the References node, and on the shortcut menu, click Add Web Reference.

b.In the Address box at the top of the Add Web Reference dialog box, type the following and then press ENTER:

http://localhost/AuthorsWebService/AuthorsService.asmx

This is the location of the XML Web service file of your ASP.NET Web Service project.

c.Click Add Reference.

You can now create an instance of the authors1 dataset in your application.

40Module 16 (Optional): Using Microsoft ADO.NET to Access Data

!Add the controls to the form

1.Drag a DataGrid control from the Windows Forms tab of the Toolbox onto the form.

2.Drag a Button control from the Windows Forms tab of the Toolbox onto the form. Set the button's Name property to LoadData and its Text property to Load.

3.Drag a second Button control from the Windows Forms tab of the Toolbox onto the form. Set the button's Name property to SaveData and its Text property to Save.

4.Drag a DataSet object from the Data tab of the Toolbox onto the form. In the Add DataSet dialog box, select Typed dataset and then select

AuthorsWinClient.localhost.authors1 from the Name list. Click OK.

This action creates a DataSet object in the component tray that is based on the authors1 dataset class definition.

5.Select the DataSet control and set the Name property to AuthorData.

6.Select the DataGrid control and select AuthorData from the DataSource property list. Select authors from the DataMember property list.

The column headings of the DataGrid are set to the Authors table column names.

You may want to adjust the width of the form and the DataGrid control to accommodate all of the column headings. The user can then avoid having to scroll horizontally to view all of the columns in the DataGrid.

!Add code for the LoadData and SaveData buttons

1.On the View menu, click Designer. Double-click the button that is labeled Load to create an empty event handler for the Click event. Add the following code to the LoadData_Click method:

private void LoadData_Click(

object sender, System.EventArgs e)

{

AuthorsWinClient.localhost.AuthorsService ws = new AuthorsWinClient.localhost.AuthorsService(); ws.Credentials = System.Net.CredentialCache.DefaultCredentials; AuthorData.Merge(ws.GetAuthors());

}

XML Web service methods are called by first creating an instance of the service class, and then calling the service methods. In this case, the GetAuthors method is called. The dataset returned is merged with the

AuthorData dataset.

Module 16 (Optional): Using Microsoft ADO.NET to Access Data

41

 

 

 

2.On the View menu, click Designer. Double-click the button labeled Save to create an empty event handler for the Click event. Add the following code to the SaveData_Click method:

private void SaveData_Click(

object sender, System.EventArgs e)

{

if (AuthorData.HasChanges())

{

AuthorsWinClient.localhost.AuthorsService ws = new

AuthorsWinClient.localhost.AuthorsService(); ws.Credentials = System.Net.CredentialCache.DefaultCredentials; AuthorsWinClient.localhost.authors1 diffAuthors =

new AuthorsWinClient.localhost.authors1(); diffAuthors.Merge(AuthorData.GetChanges()); ws.UpdateAuthors(diffAuthors); AuthorData.Merge(diffAuthors);

}

}

If there are changes in the dataset, a new dataset of type authors1 is created to hold just the changed data. This dataset is then passed to the XML Web service's UpdateAuthors method. The dataset is returned with the changes accepted, and the AuthorData dataset is updated to reflect these new changes.

! Run the application

1.On the File menu, click Save All.

2.In Solution Explorer, right-click AuthorsWinClient, and click Set as StartUp Project.

3.Press CTRL+F5 to run the application.

A window is displayed that contains an empty table with headers from the authors table in the pubs database.

4.Click Load to populate the table. Make some changes to the data, and then click Save.

You can click Load again to see that the changes that you made were stored in the database. Also, close and reopen the application. The next time you click Load, you will see that your changes have persisted.

42

Module 16 (Optional): Using Microsoft ADO.NET to Access Data

" Accessing Data with DataReaders

Topic Objective

To introduce the topics in this section.

Lead-in

Another method of accessing data from a data source is to use

DataReaders.

!Creating a DataReader

!Reading Data from a DataReader

!Using DataSets vs. DataReaders

*****************************ILLEGAL FOR NON-TRAINER USE******************************

The benefit of using a DataSet is that it gives you a disconnected view of the database. For long running applications, this is often the best approach. For Web applications, developers usually perform short and simple operations with each request, such as displaying data. For such operations, developers do not have to maintain a DataSet object. In such cases, you can use a DataReader.

Choosing a DataReader or a DataSet

When deciding whether your application should use a DataReader or a DataSet, you should consider the type of functionality that your application requires. Use a DataSet when you need to do any of the following:

!Remote data between tiers or from an XML Web service.

!Interact with data dynamically such as binding to a Windows Forms control or combining and relating data from multiple sources.

!Cache data locally in your application.

!Provide a hierarchical XML view of relational data and use tools like an XSL Transformation or an XML Path Language (XPath) Query on your data.

For more information, see XML and the DataSet in the .NET Framework SDK documentation.

!Perform extensive processing on data without requiring an open connection to the data source, which frees the connection to be used by other clients.

Соседние файлы в папке c#