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

ASP .NET Web Developer s Guide - Mesbah Ahmed, Chris Garrett

.pdf
Скачиваний:
38
Добавлен:
24.05.2014
Размер:
7.32 Mб
Скачать

340 Chapter 7 • Introduction to ADO.NET: A Simple Address Book

Figure 7.22 (A, B, and C) Delete Syntax

Figure 7.22A T-SQL

DELETE

FROM <table name>

WHERE <primary key> = <id>

Figure 7.22B Delete Syntax for Access

DELETE *

FROM <table name>

WHERE <primary key> = <id>

Notice that T-SQL does not use the asterisk between the DELETE and the FROM keywords, and Access does.

Figure 7.22C Deleting a Particular Address in T-SQL

CREATE PROC usp_tblAddress_del(@AdrsID INT)

AS

DELETE FROM [dbo].[tblAddress]

WHERE [AdrsID] = @AdrsID

The Delete method of our DAL is simple after we have completed the methods earlier in the chapter.The finished code for the Delete Method is in Figure 7.23 (A and B).

Figure 7.23 (A and B) Calling the Delete Stored Procedure

Figure 7.23A C#.NET (cs\CDalAddress.cs)

public void Delete(Int32 AdrsID)

{

string strSQL = "EXEC usp_tblAddress_del " + AdrsID; SqlCommand oCmd = new SqlCommand(strSQL, oConn); oCmd.CommandType = CommandType.Text;

try

{

if (oConn.State == ConnectionState.Closed)

Continued

www.syngress.com

Introduction to ADO.NET: A Simple Address Book • Chapter 7

341

Figure 7.23A Continued

{

oConn.Open();

}

oCmd.ExecuteNonQuery();

}

catch (Exception oErr)

{

throw oErr;

}

}

Figure 7.23B VB.NET (vb\CDalAddress.vb)

Public Sub Delete(ByVal AdrsID As String)

Dim oCmd As SqlCommand

Dim strSQL As String

strSQL = "EXEC usp_tblAddress_del " & AdrsID oCmd = New SqlCommand(strSQL, oConn) oCmd.CommandType = CommandType.Text

Try

If oConn.State = ConnectionState.Closed Then

oConn.Open()

End If oCmd.ExecuteNonQuery()

Catch oErr As Exception

Throw New Exception(oErr.ToString)

End Try

End Sub

The code to call the Delete Stored procedure is similar to the first method you used to select the records by their ID. Again, the ExecuteNonQuery tells ADO.NET that you are not interested in returning any rows and to close the connection when you are done.This requires less overhead for the data provider.

www.syngress.com

342 Chapter 7 • Introduction to ADO.NET: A Simple Address Book

Summary

Microsoft has put a lot effort into .NET, and it shows in the 2500-plus objects that they have provided you in the .NET Framework. ADO.NET continues the tradition of ADO simplifying data access, while allowing for more flexible and powerful solutions than ever. Microsoft has added much power to ADO.NET, and provided clear ties to classic ADO that enable the veteran ADO programmer to easily move into the new environment.

We have gone over the changes in ADO.NET from classic ADO and talked about the new architecture.We discussed that ADO.NET was based on XML and how this compared to the proprietary protocol that classic ADO was based on.We talked about the rich support for XML and that it is part of the native architecture of ADO.NET.We discussed the fact that the Recordset no longer exists, and that it has been replaced with two objects that offer more than the Recordset ever could have: specifically, the DataSet, which can hold more than one result set for a data provider.We discussed the disconnected nature of the ADO.NET architecture and made great use of the DataReader object in our Address Book example.

We went into great detail about the configuration of a connection string, and where to keep this valuable piece of information. Specifically, by adding the <appSettings> node to the web.config file, and using the <add> tag, you can create a ConfigurationSettings variable that can be accessed globally in the Web application.We discussed the differences in the connection strings of the two major namespaces for data access. More to the point, we said that OleDB connection strings really haven’t changed, but that if you are using the SqlConnection object, then you will need to remove the Provider attribute, or ADO.NET will raise an exception.

We introduced you to the Data Access Layer concept, and created a sample application the used the DAL to insert data using Embedded SQL statements, and Stored procedures.We used the System.Data.SqlTypes and the SqlDbTypes enumeration, and discussed that they are related, but have very different uses, such as the System.Data.SqlTypes namespace provider objects that are used to create SQL Server-compatible variables in our code, and then use the SqlDbTypes enumeration to specify the data type of a Parameter object for a command.

We showed you the ease in which operations can be performed using the various namespaces.We created the strConnection property of our DAL, and demonstrated the ease in which you can change from OleDbConnections to SqlConnections by declaring new variables and changing the connection string.

www.syngress.com

Introduction to ADO.NET: A Simple Address Book • Chapter 7

343

Solutions Fast Track

Understanding the Changes in ADO.NET

;ADO.NET is not ActiveX Data objects for ported to .NET, but an entirely new class of data access technologies.

;ADO.NET makes extensive use of XML, with rich support for consuming and creating XML documents.

;The Recordset has been removed, and new and more powerful objects have been provided.The DataSet is an in-memory relational database with support for multiple result sets from multiple data sources.

;ADO.NET is connectionless by nature, and does not maintain a connection to the data source.

Creating Connection Strings

;The first step to connecting to a data source, after choosing the Managed Provider, is to create the connection string.

;The connection string is a list of key/value pairs that the Connection object will parse; it will use the information to find the Data Source, authenticate, and establish a connection. Depending on the namespace used, the connection string will vary a little.

Connecting to a Database: Exercise

;Introduce the concept of the Data Access Layer, or DAL, as the data tier of a multi-tier application architecture.

;Create the correct Connection string for your data provider, and place it in a safe place such as the web.config file.

;The connection string for a SqlConnection is different than the connection string for an OleDbConnection; specifically, the SqlConnection does not allow for a Provider attribute.

;Provide the minimum database permissions to the user.

www.syngress.com

344 Chapter 7 • Introduction to ADO.NET: A Simple Address Book

Browsing a Database: Exercise

;Use stored procedures as much as possible, for both security and for performance.

;Use a DataReader instead of a DataSet to return data from a Method in VB.NET or C#.NET.

;Bind data of the DataReader to a DataList, DataGrid, or DataRepeater.

;Return only the rows and columns you need.

Adding to a Database: Exercise

;Use parameterized stored procedure to insert data, and return the identity of the new record in MS SQL.

;Use Dynamic SQL to add records in Access, and you can still use the @@IDENTITY to return the identity that the database gave the new record.

;Use the ExecuteNonQuery() to improve performance.

Updating a Database: Exercise

;Use parameterized stored procedures to update data using the primary key to identify the row to update.

;Use ExecuteNonQuery() to improve performance.

Deleting from a Database: Exercise

;Do not forget the Where clause!

;Use ExecuteNonQuery() to improve performance.

www.syngress.com

Introduction to ADO.NET: A Simple Address Book • Chapter 7

345

Frequently Asked Questions

The following Frequently Asked Questions, answered by the authors of this book, are designed to both measure your understanding of the concepts presented in this chapter and to assist you with real-life implementation of these concepts. To have your questions about this chapter answered by the author, browse to www.syngress.com/solutions and click on the “Ask the Author” form.

Frequently Asked Questions

Q: Where is the best place to put the connection string?

A:In this chapter, we put our samples in the web.config file.This provides a central point to administer the connection strings, and allows for a reasonable level of security.You should guard the web.config from prying eyes regardless of where the connection string is.You really have a lot of options for placing the connection string.You can put the connection string in an encrypted in a file, custom object, and so on.The best place really depends on your environment, the applications purpose, and the level of security desired.

Q: Can I reuse a connection?

A:Yes, connections can be reused. Remember to test for state before you do, as ADO.NET may close the connection if it thinks it is not being used.You cannot use a connection twice at the same time. It would not be wise to open a connection at the application level, as you could very easily end up with simultaneous attempts to use the same connection.

Q:In SQL Server, which data type is more suitable for a primary key, INT, BIGINT or a uniqueidentifier?

A:Generally speaking, the INT going to be sufficient. An INT can hold between –2,147,483,648 and 2,147,483,648.That is a lot of records. If you were to seed an identity column with –2,147,483,648 negative number and insert one record a second, it would take 136 years to use all of them up. If you need more than that, then BIGINT is an alternative, but uniqueidentifier would probably be more appropriate.The other good use for the uniqueidentifier is to keep disconnected records from colliding with one another.This is often an issue with replication, and the uniqueidentifier is the method used to prevent it.

www.syngress.com

346 Chapter 7 • Introduction to ADO.NET: A Simple Address Book

Q:How can I add a record to Access and return the ID of the new record in the same call?

A:Yes, you can. Access 2002 with ADO.NET supports the @@IDENTITY function.This function returns the last identity that was written in your session.This ensures that the identity value that you got was not from another user’s session.

Q:How can I add a record to Microsoft SQL Server and return the ID of the new record in the same call?

A:The technique for returning the identity in SQL server is much the same as for Access; however, you have a couple of other options.You can return the identity as a return value.You can create an output parameter that is populated after the insert.You can also select the @@IDENTITY and return a record to the caller.The latter is not the most efficient way.The return value and the output parameter are comparable; however, the return value is limited to a data type of integer, while the output value can be any data type that SQL Server supports.

www.syngress.com

Chapter 8

Using XML in the

.NET Framework

Solutions in this chapter:

An Overview of XML

Processing XML Documents Using .NET

Reading and Parsing Using the XmlTextReader Class

Writing an XML Document Using the XmlTextWriter Class

Exploring the XML Document Object Model

Querying XML Data Using XPathDocument and XPathNavigator

Transforming an XML Document Using XSLT

Working with XML and Databases

;Summary

;Solutions Fast Track

;Frequently Asked Questions

347

348 Chapter 8 • Using XML in the .NET Framework

Introduction

The Extensible Markup Language (XML) is the latest offering in the world of data access. Microsoft has been actively supporting this language since its conception. XML provides a universal way for exchanging information between organizations. Its structure makes it perfect for online applications and working with data residing on the local or remote data sources.

Like Hypertext Markup Language (HTML), XML is a tag-based markup language. Many other technologies, such as browsers, JavaScript,VBScript, Dynamic HTML (DHTML), and Cascading Style Sheets (CSS), were developed to support the HTML documents. Similarly, XML cannot be singled out as a stand-alone technology. It is actually a family of a growing set of technologies and frameworks.The major members of this family are XML parsers, Extensible Stylesheet Language Transformations (XSLT), XPath, XLink, Simple API for XML (SAX), Schema Generators, and Document Object Model (DOM), just to name a few.

Please take note that ADO.NET is not coded in XML but that ADO.NET revolves around XML. Some readers may confuse the terms. Microsoft has integrated the XML technology in its .NET Framework rather tightly.The core foundation of the entire ADO.NET architecture is built upon XML.The ADO.NET itself is not coded in XML; however, it provides the facilities to apply various existing and emerging XML technologies to manipulate data and information.The System.XML namespace offers perhaps the richest collection of classes for generating, transmitting, processing, and storing information via XML. In this chapter, we will first have a brief introduction to the structural components of an XML document.Then we will look into the architecture of the XML objects in the .NET Framework. Finally, we will study several major XML.NET objects with many examples.

An Overview of XML

XML is fast becoming a standard for data exchange in the next generation’s Internet applications. XML allows user-defined tags that make XML document handling more flexible than HTML, the conventional language of the Internet. Since XML is the heart and soul of ADO.NET, sound knowledge of XML is imperative for developing applications in ASP.NET.The following section touches on some of the basic concepts of XML.

www.syngress.com

Using XML in the .NET Framework • Chapter 8

349

What Does an XML Document Look Like?

The idea behind XML is surprisingly simple.The major objective is to organize information in such a way so that human beings can read and comprehend the data and its context; also, the document itself is technology and platform independent. Consider the following text file:

F10 Shimano Calcutta 47.76

F20 Bantam Lexica 49.99

Obviously, it is difficult to understand exactly what information the above text file contains. Now consider the XML document shown in Figure 8.1.The code is available in the Catalog1.xml file on the accompanying CD.

Figure 8.1 Example XML Document (Catalog1.xml)

<?xml version="1.0"?>

<!— Chapter8\Catalog1.xml —> <Catalog>

<Product>

<ProductID>F10</ProductID> <ProductName>Shimano Calcutta </ProductName> <ListPrice>47.76</ListPrice>

</Product>

<Product>

<ProductID>F20</ProductID> <ProductName>Bantam Lexica</ProductName> <ListPrice>49.99</ListPrice>

</Product>

</Catalog>

The above document is the XML’s way of representing data contained in a product catalog. It has many advantages. It is easily readable and comprehendible, it is self-documented, and it is technology independent. Most importantly, it is quickly becoming the universally acceptable data container and transmission format in the current information technology era.Well, welcome to the exciting world of XML!

www.syngress.com