28
Developing Web Applications Using Microsoft ® Visual Studio ® 2008

Developing Web Applications Using Microsoft ® Visual Studio ® 2008

Embed Size (px)

Citation preview

Developing WebApplications Using

Microsoft® VisualStudio® 2008

Module 5: Accessing Data with Microsoft ADO.NET and Visual Studio 2008

• Overview of ADO.NET

• Connecting to a Database

• Accessing Data

• Accessing Multiple Tables

Lesson: Overview of ADO.NET

• What Is ADO.NET?

• The ADO.NET Object Model

• DataSets and DataReaders

• Accessing Data with ADO.NET

What Is ADO.NET?

ADO.NET provides a set of classes for working with data. ADO.NET is:

• An evolutionary, more flexible successor to ADO

• A system designed for disconnected environments

• A programming model with advanced XML support

• A set of classes, interfaces, structures, and enumerations that manage data access in the .NET Framework

The ADO.NET Object Model

DataSet

DataTableDataTable

ODBCData Provider

ODBCData Provider

SQL ServerData ProviderSQL Server

Data ProviderOLE DB .NET Data ProviderOLE DB .NET Data Provider

OracleData Provider

OracleData Provider

ODBC sources

SQL Server 7.0 (and later)

OLEDB sources(SQL Server 6.5)

Oracle sources

DataSets and DataReaders

DataSet DataReader

Read/write access to data Read-only

Includes multiple tables from different databases

Based on one SQL statement from one database

Disconnected Connected

Bind to multiple controls Bind to one control only

Forward and backward scanning of data Forward-only

Slower access Faster access

Supported by Visual Studio 2008 Designer Manually coded

Database Client makes request

Create a SqlDataSource

Client manipulates the data

Update the data

Use the SqlDataSource to open a database connection, update the database, and close the connection

Accessing Data with ADO.NET

GridView Control

GridView Control

ClientClient

Web serverWeb

serverSqlDataSource

Return the data to the client

11

22

33

44

55

66

Lesson: Connecting to a Database

• Generating a Connection by Using Server Explorer

• The DataAdapter Object Model

• Generating a DataSet

• Creating a Connection Programmatically

• In Server Explorer, right-click Data Connections, and then click Add Connection.

• Configure the connection

Generating a Connection by Using Server Explorer

CommandCommand CommandCommand CommandCommand CommandCommand

The DataAdapter Object Model

SELECT

SelectCommand UpdateCommand InsertCommand DeleteCommand

DataAdapter

UPDATE INSERT DELETEDatabase

DataSetDataSet

ConnectionConnection

Generating a DataSet

• Creating a DataSet

• Filling the DataSet

[Visual Basic]Dim myDataSet As _ New DataSet()

[Visual Basic]Dim myDataSet As _ New DataSet()

[Visual C#]DataSet myDataSet = new DataSet();

[Visual C#]DataSet myDataSet = new DataSet();

[Visual Basic]myDataAdapter1.Fill(ds)myDataAdapter2.Fill(ds)

[Visual Basic]myDataAdapter1.Fill(ds)myDataAdapter2.Fill(ds)

[Visual C#]myDataAdapter1.Fill(ds);myDataAdapter2.Fill(ds);

[Visual C#]myDataAdapter1.Fill(ds);myDataAdapter2.Fill(ds);

Creating a Connection Programmatically

• Creating a SqlConnection instance

• Setting connection string parameters

Connection timeout

Data source

Initial catalog

Integrated security

Password

Persist security info

Provider

User ID

[Visual Basic] Dim connectionString As String = "data source=localhost; " & _ "initial catalog=northwind; integrated security=true"Dim connection As New SqlConnection(connectionString)

[Visual Basic] Dim connectionString As String = "data source=localhost; " & _ "initial catalog=northwind; integrated security=true"Dim connection As New SqlConnection(connectionString)

[Visual C#]string connectionString = "data source=localhost; " + "initial catalog=northwind; integrated security=true";SqlConnection connection = new SqlConnection(connectionString);

[Visual C#]string connectionString = "data source=localhost; " + "initial catalog=northwind; integrated security=true";SqlConnection connection = new SqlConnection(connectionString);

Lesson: Accessing Data

• Binding Data to Controls by Using the IDE

• Creating a Command Object

• Creating a DataReader

• Retrieving Data by Using a DataReader

• Creating a DataSet

• Displaying a DataSet in a List-Bound Control

• Handling Errors

• Add a GridView control to the Web Form

• Bind the GridView control to a SqlDataSource control that contains the connection and query information

•SqlDataSource properties:

ConnectionString. The connection string to connect to the database.

ProviderName. The database type.

•GridView properties:

Columns. The set of columns to be shown in the control

DataSourceID. The control ID of a data source

Binding Data to Controls by Using the IDE

Creating a Command Object

•ExecuteReader. Returns a DataReader object

•ExecuteScalar. Returns a single scalar value object

•ExecuteNonQuery. Executes a command that does not return any rows

•ExecuteXmlReader. Returns an XmlReader object

[Visual C#] myCommand.Connection.Open();SqlDataReader myDataReader = myCommand.ExecuteReader();// Process the results.myCommand.Connection.Close();

[Visual C#] myCommand.Connection.Open();SqlDataReader myDataReader = myCommand.ExecuteReader();// Process the results.myCommand.Connection.Close();

[Visual Basic]myCommand.Connection.Open() Dim myDataReader As SqlDataReader = myCommand.ExecuteReader() ' Process the results.myCommand.Connection.Close()

[Visual Basic]myCommand.Connection.Open() Dim myDataReader As SqlDataReader = myCommand.ExecuteReader() ' Process the results.myCommand.Connection.Close()

Creating a DataReader

Create and open the database connection

Create a Command object

Create a DataReader from the Command object

Call the ExecuteReader method

Use the DataReader object

11

22

33

44

55

Close the DataReader object

Close the Connection object

66

77

Retrieving Data by Using a DataReader

• Call Read for each record Returns false when there are no more records

• Access fields Parameter is the ordinal position or name of the field Get functions give best performance

• Close the DataReader

• Close the connection

[Visual Basic]Do While myDataReader.Read() text &= myDataReader(1) text &= myDataReader ("field") text &= myDataReader.GetDateTime(2)Loop

[Visual Basic]Do While myDataReader.Read() text &= myDataReader(1) text &= myDataReader ("field") text &= myDataReader.GetDateTime(2)Loop

[Visual C#]while (myDataReader.Read()) { text += myDataReader[1]; text += myDataReader["field"]; text += myDataReader.GetDateTime(2);}

[Visual C#]while (myDataReader.Read()) { text += myDataReader[1]; text += myDataReader["field"]; text += myDataReader.GetDateTime(2);}

Creating a DataSet

• Create and populate a DataSet with DataTable objects

Fill method executes the SelectCommand

• Access a DataTable

[Visual Basic]Dim myDS As New DataSet()myDA.Fill(myDataSet, _ "Authors")

[Visual Basic]Dim myDS As New DataSet()myDA.Fill(myDataSet, _ "Authors")

[Visual C#]DataSet myDS = new DataSet();myDA.Fill(myDataSet, "Authors");

[Visual C#]DataSet myDS = new DataSet();myDA.Fill(myDataSet, "Authors");

[Visual Basic]myDS.Tables( _ "Authors").Rows.Count...Dim row As DataRowDim text As StringFor Each row in myDS.Tables("Authors").Rows

text &= r(1)text &= r("LastName")

Next

[Visual Basic]myDS.Tables( _ "Authors").Rows.Count...Dim row As DataRowDim text As StringFor Each row in myDS.Tables("Authors").Rows

text &= r(1)text &= r("LastName")

Next

[Visual C#]myDataSet.Tables[ "Authors"].Rows.Count;...string text = "";foreach(DataRow row in myDS.Tables["Authors"].Rows){

text += row[1];text += row["LastName"];

}

[Visual C#]myDataSet.Tables[ "Authors"].Rows.Count;...string text = "";foreach(DataRow row in myDS.Tables["Authors"].Rows){

text += row[1];text += row["LastName"];

}

Displaying DataSet Data in List-Bound Controls

• Set the properties

• Fill the DataSet, then call the DataBind method

[Visual Basic]myDataAdapter.Fill(myDataSet)employeesList.DataBind()

[Visual Basic]myDataAdapter.Fill(myDataSet)employeesList.DataBind()

[Visual C#]myDataAdapter.Fill(myDataSet)employeesList.DataBind();

[Visual C#]myDataAdapter.Fill(myDataSet)employeesList.DataBind();

Property Description

DataSource The DataSet containing the data

DataMember The DataTable in the DataSet

DataTextField The field in the DataTable that is displayed

DataValueField The field in the DataTable that becomes the value of the selected item in the list

[Visual Basic]Catch ex1 As System.Data.SqlClient.SqlException Select Case ex1.Number ... Case 18452 errorsLabel.Text = errorsLabel.Text & _ ("Invalid user name") ... End SelectEnd Try

[Visual Basic]Catch ex1 As System.Data.SqlClient.SqlException Select Case ex1.Number ... Case 18452 errorsLabel.Text = errorsLabel.Text & _ ("Invalid user name") ... End SelectEnd Try

Handling Exceptions

• Connection will not open

Connection string is invalid

Server or database not found

Login failed

[Visual C#]catch (System.Data.SqlClient.SqlException ex1){ switch(ex1.Number) { ... case 18452: errorsLabel.Text = errorsLabel.Text + ("Invalid user name"); break; ... }}

[Visual C#]catch (System.Data.SqlClient.SqlException ex1){ switch(ex1.Number) { ... case 18452: errorsLabel.Text = errorsLabel.Text + ("Invalid user name"); break; ... }}

•DataAdapter cannot create a DataSet

Invalid SQL syntax

Invalid table or field name

Lesson: Accessing Multiple Tables

• Storing Data From Multiple Tables

• Creating Relationships

• Programmatically Navigating Between Tables by Using Relationships

[Visual C#]ordersDataAdapter = new SqlDataAdapter ("select * from Orders", connection2);customersDataAdapter.Fill(myDataSet, "Orders");

[Visual C#]ordersDataAdapter = new SqlDataAdapter ("select * from Orders", connection2);customersDataAdapter.Fill(myDataSet, "Orders");

[Visual Basic]ordersDataAdapter = new SqlDataAdapter _ ("select * from Orders", connection2)customersDataAdapter.Fill(myDataSet, "Orders")

[Visual Basic]ordersDataAdapter = new SqlDataAdapter _ ("select * from Orders", connection2)customersDataAdapter.Fill(myDataSet, "Orders")

Storing Data From Multiple Tables

• Add the first table

• Add the subsequent table(s)

OrdersCustomers

DataSet

[Visual C#]customersDataAdapter = new SqlDataAdapter ("select * from Customers", connection1);customersDataAdapter.Fill(myDataSet, "Customers");

[Visual C#]customersDataAdapter = new SqlDataAdapter ("select * from Customers", connection1);customersDataAdapter.Fill(myDataSet, "Customers");

[Visual Basic]customersDataAdapter = new SqlDataAdapter _ ("select * from Customers", connection1)customersDataAdapter.Fill(myDataSet, "Customers")

[Visual Basic]customersDataAdapter = new SqlDataAdapter _ ("select * from Customers", connection1)customersDataAdapter.Fill(myDataSet, "Customers")

connection1 connection2

[Visual C#]DataRelation coDataRelation;DataColumn parentColumn, childColumn;

parentColumn = myDataSet.Tables["Customers"].Columns["CustomerID"];childColumn = myDataSet.Tables["Orders"].Columns["CustomerID"];cODataRelation = new DataRelation("CustomerOrders", parentColumn, childColumn);myDataSet.Relations.Add(cODataRelation);

[Visual C#]DataRelation coDataRelation;DataColumn parentColumn, childColumn;

parentColumn = myDataSet.Tables["Customers"].Columns["CustomerID"];childColumn = myDataSet.Tables["Orders"].Columns["CustomerID"];cODataRelation = new DataRelation("CustomerOrders", parentColumn, childColumn);myDataSet.Relations.Add(cODataRelation);

Creating Relationships

• Identify parent column

• Identify child column

• Create DataRelation

Orders table

Customers table

DataSet

parentColumn

childColumn

DataRelation

[Visual Basic]Dim cORelation As DataRelationDim parentColumn As DataColumn, childColumn As DataColumn

parentColumn = _myDataSet.Tables("Customers").Columns("CustomerID")childColumn = _ myDataSet.Tables("Orders").Columns("CustomerID")cODataRelation = New DataRelation("CustomerOrders" _ , parentColumn, childColumn)myDataSet.Relations.Add(cODataRelation)

[Visual Basic]Dim cORelation As DataRelationDim parentColumn As DataColumn, childColumn As DataColumn

parentColumn = _myDataSet.Tables("Customers").Columns("CustomerID")childColumn = _ myDataSet.Tables("Orders").Columns("CustomerID")cODataRelation = New DataRelation("CustomerOrders" _ , parentColumn, childColumn)myDataSet.Relations.Add(cODataRelation)

Programmatically Navigating Between Tables by Using Relationships

Customers Orders

GetChildRows

GetParentRowDataSet

[Visual Basic] ds.Tables(index).Rows(index).GetChildRows("relation")ds.Tables(index).Rows(index).GetParentRow("relation")

[Visual Basic] ds.Tables(index).Rows(index).GetChildRows("relation")ds.Tables(index).Rows(index).GetParentRow("relation")

[Visual C#]ds.Tables[index].Rows[index].GetChildRows("relation");ds.Tables[index].Rows[index].GetParentRow("relation");

[Visual C#]ds.Tables[index].Rows[index].GetChildRows("relation");ds.Tables[index].Rows[index].GetParentRow("relation");

Lab: Accessing Data with Microsoft ADO.NET and Visual Studio 2008

• Exercise 1: Connecting to the Doctors Database

• Exercise 2: Paging and Selection in a GridView Control

• Exercise 3: Implementing a SqlDataReader

• Exercise 4: (If Time Permits) Viewing Doctors from All Cities

Logon information

Virtual machine 2310C-LON-DEV-08

User name Student

Password Pa$$w0rd

Estimated time: 45 minutes

Lab Scenario

Medicalmedical.aspxMedicalmedical.aspx

BenefitsHome PageDefault.aspx

BenefitsHome PageDefault.aspx

Life Insurancelife.aspxLife Insurancelife.aspx

Retirementretirement.aspxRetirementretirement.aspx

Dentistsdental.aspxDentistsdental.aspx

Doctorsdoctors.aspx Doctorsdoctors.aspx

Logon Pagelogin.aspxLogon Pagelogin.aspx

Registrationregister.aspxRegistrationregister.aspx

Prospectusprospectus.aspxProspectusprospectus.aspx XML Web

ServiceDentalService1.asmx

XML Web ServiceDentalService1.asmx

Page Headerheader.ascxPage Headerheader.ascx

Lab Web Application

User ControlnameDate.ascxUser ControlnameDate.ascx

Menu ComponentBenefits.cs or Benefits.vbMenu ComponentBenefits.cs or Benefits.vb

Master PagebenefitsMaster.masterMaster PagebenefitsMaster.master

LINQ to SQLClassesDoctors.dbml

LINQ to SQLClassesDoctors.dbml

ASPState

DentistsDoctorsXML Files

Web.config

TempDB

Lab Review

Review Questions

• How can you add a connection to a database?

• What controls are created when you drag a table from Server Explorer to a Web page?

• How can you enable paging for a GridView control?

• How can you add a select column to a GridView control?

• When you use Connection and SqlDataReader objects, what must you do?

Module Review and Takeaways

• Review Questions

• Real-World Issues and Scenarios

• Best Practices