.NET Data Access Architecture Guide

xiaoxiao2021-03-06  72

.NET Data Access Architecture Guide

Related Links

Patterns & Practices INDEX

Application Architecture for .NET: Designing Applications and Services

Alex Mackman, Chris Brooks, Steve Busby, Ed Jezierski, Jason Hogg, Roberta Leibovitz (Modilated Computation) And Colin Campbell (Mode) Microsoft Corporation

October 2001

Updated June 2003

Summary: This document provides guidelines for implementing an ADO.NET-based data access layer in a multi-tier .NET-based application It focuses on a range of common data access tasks and scenarios, and presents guidance to help you choose the most. ApproPriate Approaches and Techniques.

Introduction

If you are designing a data access layer for a .NET-based application, you should use Microsoft® ADO.NET as the data access model. ADO.NET is feature rich and supports the data access requirements of loosely coupled, multitier Web applications and Web Services. AS WITHER Feature-Rich Object Models, ADO.NET OFFERS A Number of Ways To Solve A Particular Problem.

The .NET Data Access Architecture Guide provides information to help you choose the most appropriate data access approach. It does this by describing a wide range of common data access scenarios, providing performance tips, and prescribing best practices. This guide also provides answers to frequently asked questions, such as: Where is the best place to store database connection strings How should I implement connection pooling How should I work with transactions How should I implement paging to allow users to scroll through large numbers of records????

This guide focuses on the use of ADO.NET to access Microsoft SQL Server ™ 2000 by using the SQL Server .NET data provider, one of the two providers shipped with ADO.NET. Where appropriate, this guide highlights any differences that you need to be aware of when you use the OLE DB .NET data provider to access other OLE DB-aware data sources.For a concrete implementation of a data access component developed using the guidelines and best practices discussed in this document, see the Data Access Application Block ..................

The .Net Data Access Architecture Guide Includes The Following Sections:

Introducing ADO.NET

· Managing Database Connections

Error Handling

Performance

· Connecting Through FireWalls

Handling blobs

Performing Database Updates with DataSets

· Using strongly Typed DataSet Objects

· Working with Null Data Fields

Transactions

· Data Paging

Who Should Read this Document

This document provides guidelines for application architects and enterprise developers who want to build .NET-based applications. Read this document if you are responsible for designing and developing the data tier of a multitier .NET-based application.

What You Must Know

To use this guide to build .NET-based applications, you must have experience developing data access code using ActiveX® Data Objects (ADO) and / or OLE DB, as well as SQL Server experience. You must understand how to develop managed code for THE .NET Platform, And You Must Be Aware The ADO.NET DATA Access Model Introduces. For more information, see http://msdn.microsoft.com/net.what's new

.

As INDICATEDITED, SOME OF THE Content In this Guide Applies Specify To The Microsoft Visual Studio® 2003 Development System and the .NET Framework SDK VERSION 1.1.

Download the .NET DATA Access Architecture Guide

Click to Download The .NET Data Access Architecture Guide from The Ms.com Download Center Center

Introducing ADO.NET

ADO.NET is the data access model for .NET-based applications. It can be used to access relational database systems such as SQL Server 2000, Oracle, and many other data sources for which there is an OLE DB or ODBC provider. To a certain extent, ADO.NET represents the latest evolution of ADO technology. However, ADO.NET introduces some major changes and innovations that are aimed at the loosely coupled-and inherently disconnected-nature of Web applications. For a comparison of ADO and ADO. Net, See the msdn article "ADO.NET for the ado program" AT http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dndotNet/html/adonetprogmsdn.asp.

One of the key changes that ADO.NET introduces is the replacement of the ADO Recordset object with a combination of the DataTable, DataSet, DataAdapter, and DataReader objects. A DataTable represents a collection of rows from a single table, and in this respect is similar to the Recordset. A DataSet represents a collection of DataTable objects, together with the relationships and constraints that bind the various tables together. in effect, the DataSet is an in-memory relational structure with built-in XML support.One of the key characteristics of the DataSet is that it has no knowledge of the underlying data source that might have been used to populate it. It is a disconnected, stand-alone entity used to represent a collection of data, and it can be passed from component to component THROUGH THE VARIOUS. IT CAN Also Be Serialized AS An XML Data Stream, Which Makes It Ideally Suited for Data Transfer Between Herogeneous Platforms. ADO.NET USES The DA TAADAPTER Object To Channel Data To and from The DataSet and The Underlying Data Source. The DataApter Object Also Provides Enhanced Batch Update Features Previously Associated with the recordset.

Figure 1 Shows The Full DataSet Object Model.

Figure 1.1. DataSet Object Model

.NET DATA Providers

ADO.NET DATA ON The Services of .Net Data Providers. These Provide Access to the underlying Data Source, And The Comprise Four Key Objects (Connection, Command, DataReader, And DataAptapter).

Currently, ADO.NET ships with two categories of providers:. Bridge providers and native providers Bridge providers, such as those supplied for OLE DB and ODBC, allow you to use data libraries designed for earlier data access technologies Native providers, such as the. SQL Server and Oracle providers, typically offer performance improvements due, in part, to the fact that there is one less layer of abstraction. · The SQL Server .NET Data Provider. This is a provider for Microsoft SQL Server 7.0 and later databases. It .

Always Use this provider when Connect To SQL Server 7.0 OR SQL Server 2000.

· The Oracle .NET Data Provider. The .NET Framework Data Provider for Oracle enables data access to Oracle data sources through Oracle client connectivity software. The data provider supports Oracle client software version 8.1.7 and later.

· The OLE DB .NET Data Provider. This is a managed provider for OLE DB data sources. It is slightly less efficient than the SQL Server .NET Data Provider, because it calls through the OLE DB layer when communicating with the database. Note that this provider does not support the OLE DB provider for Open Database Connectivity (ODBC), MSDASQL. for ODBC data sources, use the ODBC .NET Data Provider (described later) instead. for a list of OLE DB providers that are compatible with ADO. Net, see http://msdn.microsoft.com/library/en-us/cpguidnf/html/cpconadonetproviders.asp.

Other .NET DATA Providers Currently In Beta Testing Include:

· The ODBC .NET Data Provider. The .NET Framework Data Provider for ODBC uses native ODBC Driver Manager (DM) to enable data access by means of COM interoperability. · A managed provider for retrieving XML from SQL Server 2000. The XML for SQL Server Web update 2 (currently in beta) includes a managed provider specifically for retrieving XML from SQL Server 2000. for more information about this update, see http://msdn.microsoft.com/library/default.asp?url=/nhp /Default.asp?contentid=28001300.

For a more detailed overview of the different data providers, see ".NET Framework Data Providers" in the.NET Framework Developer's Guide, at http://msdn.microsoft.com/library/default.asp?url=/library/en -us / cpguide / html / cpconadonetproviders.asp.

Namespace Organization

The Types (Classes, Structs, ENUMS, AND SO ON) Associated with each .NET DATA PROVIDER ARE LOCATED in Their Own Namespaces:

· System.data.sqlclient. Contains The SQL Server .NET Data Provider Types.

· System.Data.OracleClient. Contains the Oracle .NET DATA PROVIDER

• System.Data.OLDB. Contains The OLE DB .NET DATA Provider Types.

· System.Data.odbc. Contains the ODBC .NET DATA Provider Types.

• System.Data. Contains Provider-Independent Types Such as The Dataset and DataTable.

Within its associated namespace, each provider provides an implementation of the Connection, Command, DataReader, and DataAdapter objects. The SqlClient implementations are prefixed with "Sql" and the OleDb implementations are prefixed with "OleDb." For example, the SqlClient implementation of the Connection object is SqlConnection, and the OleDb equivalent is OleDbConnection. Similarly, the two incarnations of the DataAdapter object are SqlDataAdapter and OleDbDataAdapter, respectively.In this guide, the examples are drawn from the SQL Server object model. Although not illustrated here, similar features Are Available in Oracle / OLEDB and ODBC.

Generic Programming

If you are likely to target different data sources and want to move your code from one to the other, consider programming to the IDbConnection, IDbCommand, IDataReader, and IDbDataAdapter interfaces located within the System.Data namespace. All implementations of the Connection, Command, DataReader, And DataAdapter Objects Must Support these Interfaces.

For More Information About Implementing .NET DATA Providers, See http://msdn.microsoft.com/library/en-us/cpguidnf/html/cpconimplementingnetDataProvider.asp.

It should also be noted that both the OLE DB and ODBC bridging providers are alternatives if an application uses a single object model to access multiple databases. In this situation, it is important to consider the application's need for flexibility, and the extent to which database -Specific Functionality Is Required, in Comparison With the application's need for perform.

Figure 2 illustrates the data access stack and how ADO.NET relates to other data access technologies, including ADO and OLE DB. It also shows the two managed providers and the principal objects within the ADO.NET model.Figure 1.2. Data access stack

For more information about the evolution of ADO to ADO.NET, see the article "Introducing ADO : Data Access Services for the Microsoft .NET Framework" in the November 2000 issue of MSDN Magazine, at http://msdn.microsoft.com/ MSDNMAG / ISSUES / 1100 / Adoplus / Default.aspx.

Stored Procedures vs. Direct SQL

Most code fragments shown in this document use SqlCommand objects to call stored procedures to perform database manipulation. In some cases, you will not see the SqlCommand object because the stored procedure name is passed directly to a SqlDataAdapter object. Internally, this still results in the Creation of a Sqlcommand Object.

You Should Use Stored Procedures Instead of Embedded SQL Statements for a Number of Reasons:

· Stored Procedures Generally Result In Improved Performance Because The Database Can Optimize The Data Access Plan Used by The Procedure and Cache It for Subsequent Reuse.

· Stored Procedures Can Be Individually Secured Wtemed Permissions to Execute A Stored Procedure WITHOUT HAVING ANY Permissions on the underlying table.

· Stored Procedures Result in Easier Maintenance Because It is generally Easier To Modify A Stored Procedure Than It Is To Change A HARD-CODED SQL Statement Withnin a Deployed Component.

· Stored procedures add an extra level of abstraction from the underlying database schema. The client of the stored procedure is isolated from the implementation details of the stored procedure and from the underlying schema. · Stored procedures can reduce network traffic, because SQL statements can be EXECUTED IN BATCHES Rather Than Sending Multiple Requests from The Clivity.

. The SQL Server online documentation strongly recommends that you do not create any stored procedures using "sp_" as a name prefix because such names have been designated for system stored procedures SQL Server always looks for stored procedures beginning with sp_ in this order:

1. Look for the Stored Procedure in The Master Database.

2. Look for The Stored Procedure Based On Any Qualifiers Provided (Database Name Or Owner).

3. Look for the Stored Procedure, USING DBO As The Owner if An Owner is not specific.

Properties vs. constructor arguments

You can set Specific Property Values ​​of Ado.net Objects Either Through Constructor Arguments or by Directly Setting The Properties. For Example, The Following Code Fragments Are Functionally Equivalent.

// Use constructor arguments to configure command Object

SQLCommand cmd = new sqlcommand ("Select * from products", conn);

// the Above line is functionally equivalent to the folload

// Three Lines Which Set Properties Explicitly

SQLCommand cmd = new sqlcommand ();

cmd.connection = conn;

cmd.commandtext = "SELECT * from Products";

From a performance perspective, there is negligible difference between the two approaches because setting and getting properties against .NET objects is more efficient than performing similar operations against COM objects.The choice is one of personal preference and coding style. The explicit setting of properties does , HOWEVER, Make The Code Easier To Comprehend (Particularly if you are not familiar with the ado.net object model) and Easier to debug.

Note In the past, developers of the Microsoft Visual Basic® development system were advised to avoid creating objects with the "Dim x As New ..." construct. In the world of COM, this code could result in the short circuit of the COM object creation .

Managing Database Connections

Database connections represent a critical, expensive, and limited resource, particularly in a multitier Web application. It is imperative that you manage your connections correctly because your approach can significantly affect the overall scalability of your application. Also, think carefully about where to store connection Strings. You NEED A Configurable and Secure Location.

When Managing Database Connections and Connection Strings, You Should Strive TO:

Help Realize Application Scalability by Multiplexing a Pool of Database Connections Across Multiple Clients.

· Adopt A Configurable and High Performance Connection Pooling Strategy.

· Use Windows Authentication When Accessing SQL Server.

· Avoid Impersonation in the Middle Tier.

· Store Connection Strings Securely.

· Open Database Connections Late and Close Them Early.

This section discusses connection pooling and will help you choose an appropriate connection pooling strategy. This section also considers how you should manage, store, and administer your database connection strings. Finally, this section presents two coding patterns that you can use to help ensure that Connections Are Closed Reliably and return to the connection pool.

USING Connection POOLING

Database connection pooling allows an application to reuse an existing connection from a pool instead of repeatedly establishing a new connection with the database. This technique can significantly increase the scalability of an application, because a limited number of database connections can serve a much larger number of CLIENTS. THIS TECHNIQUE Also Improves Performance, Because The Significant Time Required To Establish A New Connection Can Be Avoided.

Data access technologies such as ODBC and OLE DB provide forms of connection pooling, which are configurable to varying degrees. Both approaches are largely transparent to the database client application. OLE DB connection pooling is often referred to as session or resource pooling.

For a general discussion of pooling within Microsoft Data Access Components (MDAC), see "Pooling in the Microsoft Data Access Components," at http://msdn.microsoft.com/library/en-us/dnmdac/html/pooling2.asp .

ADO.NET DATA Providers Provide Transparent Connection Pooling, The Exact Mechanics of Which Vary for Each Provider. This Section Discusses Connection POOLINGIN

· The SQL Server .Net Data Provider

· The Oracle .NET Data Provider

· The OLE DB .NET DATA Provider · The ODBC .NET DATA PROVIDER

Pooling with the SQL Server .NET DATA Provider

If you are using the SQL Server .NET Data Provider, use the connection pooling support offered by the provider. It is a transaction-aware and efficient mechanism implemented internally by the provider, within managed code. Pools are created on a per application domain basis And pools are not destroyed unloded.

You can use this form of connection tooling transparently, but you sell be aware of how pools are management and of the various configuration options you can use to fine-tune connection poolings.

In many cases, the default connection pooling settings for the SQL Server .NET data provider may be sufficient for your application. During the development and testing of your .NET-based application, it is recommended that you simulate projected traffic patterns to determine if modifications To The Connection Pool Size Are Required.

Developers building scalable, high performance applications should minimize the amount of time a connection is used, keeping it open for only as long as it takes to retrieve or update data. When a connection is closed, it is returned to the connection pool and made available For Reuse. in this case, the actual connection; however, the agent, if connection tooling is disabled, the actual connection to the database will be closed.

Developers should be careful not to rely on the garbage collector to free connections because a connection is not necessarily closed when the reference goes out of scope. This a common source of connection leaks, resulting in connection exceptions when new connections are requested.Configuring SQL Server .NET DATA Provider Connection Pooling

You can configure connection pooling by using a set of name-value pairs, supplied by means of the connection string. For example, you can configure whether or not pooling is enabled (it is enabled by default), the maximum and minimum pool sizes, And The Amount of Time That A Queued Request To Open A Connection Can Block. The Following IS An Example Connection String That Configures The maximum and minimum pool sizes.

"Server = (local); integrated security = sspi; data = northwind;

Max pool size = 75; min pool size = 5 "

When a connection is opened and a pool is created, multiple connections are added to the pool to bring the connection count to the configured minimum level. Connections can be subsequently added to the pool up to the configured maximum pool count. When the maximum count is Reached, New Requests to Open A Connection Are Queued for a configurable duration.

Choosing pool size

Being able to establish a maximum threshold is very important for large-scale systems that manage the concurrent requests of many thousands of clients. You need to monitor connection pooling and the performance of your application to determine the optimum pool sizes for your system. The optimum Size Also Depends on The Hardware on Which You Are Running SQL Server.

During development, you might want to reduce the default maximum pool size (currently 100) to help find connection leaks.If you establish a minimum pool size, you will incur a small performance overhead when the pool is initially populated to bring it to that level , although the first few clients that connect will benefit. Note that the process of creating new connections is serialized, which means that your server will not be flooded with simultaneous requests when a pool is being initially populated.

For more details about monitoring connection pooling, see the Monitoring Connection Pooling section in this document. For a complete list of connection pooling connection string keywords, see "Connection Pooling for the .NET Framework Data Provider for SQL Server" in the.NET Framework Developer's Guide, at http://msdn.microsoft.com/clibrary/default.asp?url=/library/en-us/cpguide/html/cpconconnectionPoolingForsqlservernetDataProvider.asp.

More information

WHEN Using SQL Server .NET Data Provider Connection Pooling, Be aware of the Following:

· Connections are pooled through an exact match algorithm on the connection string. The pooling mechanism is even sensitive to spaces between name-value pairs. For example, the following two connection strings will result in two separate pools because the second contains an extra space character .

· SqlConnection conn = new SQLCONNECTION

· "Integrated Security = SSPI; Database = Northwind");

Conn.open (); // pool a is created

·

· SQLCONMECTION CONN = New SqlConnection

· "Integrated Security = SSPI; Database = Northwind"); · conn.open (); // pool b is create (extra spaces in string)

· The connection pool is divided into multiple transaction-specific pools and one pool for connections not currently enlisted in a transaction. For threads associated with a particular transaction context, a connection from the appropriate pool (containing connections enlisted with that transaction) is returned. This Makes Working with Enlisted Connections a Transparent Process.

Pooling with the ole db .NET Data Provider

The OLE DB .NET DATA Provider Pools Connections By Using The Underlying Services of Ole DB Resource Pool, you have a number of options for configuring resource poibility:

· You can use the connection string to configure, enable, or disable resource pooling.

.

You can Programmatically Configure Resource Pooling.

To Circumvent Registry-Red Deployment Issues, Avoid Using The Registry To Configure Ole DB Resource Pool.

For More Details About Ole DB Resource Pooling, See "Resource Pool" in Chapter 19, "Ole DB Services" of The Ole DB Programmer's Reference, at http://msdn.microsoft.com/library/default.asp?url=/ Library / en-US / OLEDB / HTM / OLPRCORE_CHApter19.ASP.

Managing Connection Pooling with Pooled Objects

As Windows DNA developers, you were encouraged to disable OLE DB resource pooling and / or ODBC connection pooling and use COM object pooling as a technique to pool database connections There are two primary reasons for this.:

· Pool Sizes and thresholds can be explicitly configured (in the COM CATALOG). The Pooled Object Approach Can Outperform Native Pooling By A Factor of Two.

However, because the SQL Server .NET Data Provider uses pooling internally, you no longer need to develop your own object pooling mechanism (when using this provider). You can thus avoid the complexities associated with manual transaction enlistment.

You might want to consider COM object pooling if you are using the OLE DB .NET Data Provider to benefit from superior configuration and improved performance. If you develop a pooled object for this purpose, you must disable OLE DB resource pooling and automatic transaction enlistment ( For example, by incruding "OLE DB Services = -4" in the connection string). You Must Handle Transaction EnListment Wtem Pooled Object Implementation.

Monitoring Connection Pooling

To Monitor Your Application's Use of Connection Pooling, You Can Use The Profiler Tool Tool That Ships With SQL Server, or The Performance Monitor Tool That Ships with the Microsoft Windows® 2000 Operating System.

To Monitor Connection Pooling with SQL Server Profiler

1. Click Start, Point To Programs, Point To Microsoft SQL Server, And The Click Profiler To Start Profiler.

2. On The File Menu, Point To New, And The Click Trace.

3. Supply Connection Details, and the Click OK.

4. In The Trace Properties Dialog Box, Click The Events Tab.

5. In the Selected event classes list, ensure that the Audit Login and Audit Logout events are shown beneath Security Audit. To make the trace clearer, remove all other events from the list.6. Click Run to start the trace. You will see Audit Login Events WHEN Connections Are Established and Audit Logout Events When Connections Are Closed.

To Monitor Connection Pooling with Performance Monitor

1. Click Start, Point To Programs, Point To Administrative Tools, And The Click Performance To Start Performance Monitor.

2. Right-Click The Graph Background, And the Click Add Counters.

3. In The Performance Object Drop-Down List, Click SQL Server: General Statistics.

4. In The List That Appears, Click User Connections.

5. Click Add, And The Click Close.

Managing security

Although database connection pooling improves the overall scalability of your application, it means you can no longer manage security at the database. This is because to support connection pooling, the connection strings must be identical. If you need to track database operations on a per user Basis, Consider Adding a Parameter Through Which You CAN Pass The User Identity and Manually Log User Actions In The Database. You NEED To Add this Parameter To Each Operation.

Using Windows Authentication

You Should Use Windows Authentication When Connecting to SQL Server Because IT Provides a Number of Benefits:

· Security is Easier To Manage Because You Work with a Single (Windows) Security Model Rather Than The Separate SQL Server Security Model.

· You Avoid Embedding User Names and Passwords In Connection Strings. User Names and Passwords Are Not Passed over the network in clear text.

· Logon Security Improves Through Password Expiration Periods, Minimum Lengths, And Account Lockout After Multiple Invalid Logon Requests.

More information

WHEN You Use Windows Authentication To Access SQL Server, Use The Following Guidelines:

· Consider performance tradeoffs. Performance tests have shown that it takes longer to open a pooled database connection when using Windows authentication as compared to using SQL Server authentication. The .NET runtime version 1.1 has reduced the margin by which SQL Server security outperforms Windows authentication, But SQL Server Authentication is Still Faster.

However, although Windows authentication is still more expensive, the performance reduction is relatively insignificant in comparison to the time it takes to execute a command or stored procedure. As a result, in most cases the security benefits of using Windows authentication outweigh this slight performance degradation Before Making a Decision, Assess The Performance Requirements of Your Application.

· Avoid impersonation in the middle tier. Windows authentication requires a Windows account for database access. Although it might seem logical to use impersonation in the middle tier, avoid doing so because it defeats connection pooling and has a severe impact on application scalability.

To Address This Problem, Consider Impersonating a Limited Number of Windows Accounts (Rather Than The Authenticated Principal) with each account representing a particular role.

For example, you can use this approach:. · Create two Windows accounts, one for read operations and one for write operations (Or, you might want separate accounts to mirror application-specific roles For example, you might want to use one account. For internet users and another for internal operators and / or administrators.)

· Map Each Account to a SQL Server Database Role, And Establish The Necessary Database Permissions for Each Role.

· Use Application Logic in your data access layer to determine Which Windows Account to Impersonate Before You Perform A Database Operation.

Note Each account must be a domain account with Internet Information Services (IIS) and SQL Server in the same domain or in trusted domains. Or, you can create matching accounts (with the same name and password) on each computer.

· Use TCP / IP for your network library. SQL Server 7.0 and later support Windows authentication for all network libraries. Use TCP / IP to gain configuration, performance, and scalability benefits. For more information about using TCP / IP, see the Connecting Through FireWalls Section in this document.

For General Guidance On Developing Secure Asp.Net and Web Applications, Refer to The Following Microsoft Patterns & Practices Guides:

· Volume I, Building Secure ASP.NET Applications: Authentication, Authorization, and Secure Communication, Available At http://www.microsoft.com/practices

· Volume II, Improving Web Application Security: Threats and CounterMeasures, Which Will Be Available At http://www.microsoft.com/practices

Storing Connection Strings

To store database connection strings, you have a variety of options with different degrees of flexibility and security. Although hard coding a connection string within source code offers the best performance, file system caching ensures that the performance degradation associated with storing the string externally in the file system is negligible. The extra flexibility provided by an external connection string, which supports administrator configuration, is preferred in virtually all cases.When you are choosing an approach for connection string storage, the two most important considerations are security and ease of configuration, Closely Followed by Performance.

You Can Choose Among The Following Locations for Storing Database Connection Strings:

· In an application configure file; for example, web.config for an asp.net web application

· In a universal data link (UDL) file (Supported Only by the Ole DB .NET DATA Provider)

· In the windows registry

· In a custom file

· In the com catalog, by using construction "(for serviced components only)

By using Windows authentication to access SQL Server, you can avoid storing user names and passwords in connection strings. If your security requirements demand more stringent measures, consider storing the connection strings in encrypted format.

For ASP.NET Web Applications, Storing The Connection Strings in Encrypted Format With Web.config File Represents A Secure and Configurable Solution.

Note You can set the Persist Security Info named value to false in the connection string to prevent security-sensitive details, such as the password, from being returned by means of the ConnectionString property of the SqlConnection or OleDbConnection objects.The following subsections discuss how to use the various options to store connection strings, and they present the relative advantages and disadvantages of each approach. This will allow you to make an informed choice based on your specific application scenario.

Note The Configuration Application Management Block Allows You To Manage Configuration Settings-from Database Connections to Complex Hierarchical Data. For more information, see http://msdn.microsoft.com/practices.

Using XML Application Configuration Files

You can use the element to store a database connection string in the custom settings section of an application configuration file This element supports arbitrary key-value pairs, as illustrated in the following fragment.:

Value = "server = (local); integrated security = sspi; database = northwind" />

Note The Element Appears Under The Element and not directly under .

Advantages

· Ease of Deployment. The Connection String is Deployed Along With The Configuration File Through Regular .NET Xcopy Deployment.

· Ease of Programmatic Access. The appsettings Property of The ConfigurationSettings Class Makes Reading The Configured Database Connection String An Easy Task At Run Time.

· Support of dynamic update (ASP.NET only). If an administrator updates the connection string in a Web.config file, the change will be picked up the next time the string is accessed, which for a stateless component is likely to be the Next Time aclient Uses The Component To Make A Data Access Request.disadvantages

· Security. Although the ASP.NET Internet Server Application Programming Interface (ISAPI) dynamic-link library (DLL) prevents clients from directly accessing files with a .config file extension and NTFS permissions can be used to further restrict access, you might still want TO Avoid Storing The deTails in clear text on a Front-End Web Server. For added security, Store The Connection String In Encrypted Format in The Configuration File.

More information

· You can retrieve custom application settings by using the static AppSettings property of the System.Configuration.ConfigurationSettings class This is shown in the following code fragment, which assumes the previously illustrated custom key called DBConnStr.:

· Use system.configuration;

Private string getDBaseConnectionstring ()

{

· Return ConfigurationSettings.AppSettings ["dbconnstr"];

}

· For more information about configuring .NET Framework Applications, See http://msdn.microsoft.com/library/en-us/cpguidnf/html/cpconconfiguringnetFrameworkApplications.asp.

USING UDL Files

The OLE DB .NET Data Provider supports Universal Data Link (UDL) file names in its connection string. You can pass the connection string by using construction arguments to the OleDbConnection object, or you can set the connection string by using the object's ConnectionString property. Note The SQL Server .NET Data Provider Does Not Support Udl Files in Its Connection String. Therefore, this approach is available to you. Only if you are using the ole db .NET DATA Provider.

For the OLE DB Provider, TO Reference A Udl File with the connection string, use "file name = name.ud."

Advantages

· Standard Approach. You might already be used UDL Files for Connection String Management.

Disadvantages

Performance. Connection Strings That Contain Udls Are Read and PaSed Each Time The Connection is Opened.

..................... ..

· SqlClient Does NOT Support Udl Files. This approach is not supported by the SQL Server .NET DATA Provider, Which You Use to Access SQL Server 7.0 and later.

More information

· To support administration, make sure that administrators have read / write access to the UDL file and that the identity used to run your application has read access. For ASP.NET Web applications, the application worker process runs by using the SYSTEM account by default , although you can override this by using the element of the machine-wide configuration file (Machine.config). you can also impersonate, optionally with a nominated account, by using the element of the Web.config file .................................... ...Clakens.

· For more information about these and other security-research asp.net features, see "Authentication in asp.net: .Net Security Guidance," At http://msdn.microsoft.com/library/en-us/dnbda/html /autHaspdotNet.asp.

Using the windows registry

You Can Also Use a Custom Key In The Windows Registry to Store The Connection String, Althei This Is Not Recommended Due To Deployment Issues.

Advantages

.

· Ease of Programmatic Access. .Net Classes Are Available To Support Reading Strings from The Registry.

Disadvantages

......................

USING a CUSTOM FILE

You can use a custom file to store the connection string. However, this technique authenticed.advantages

None.

Disadvantages

· Approach Requires extra coding and forces you to deal explicitly with concurrency ss.

· Deployment. The file must be copied along with the other ASP.NET application files. Avoid placing the file in the ASP.NET application directory or subdirectory to prevent it from being downloaded over the Web.

USING Construction Arguments and the COM Catalog

You can store the database connection string in the COM catalog and have it automatically passed to your object by means of an object construction string. COM will call the object's Construct method immediately after instantiating the object, supplying the configured construction string.

Note this Approach Works Only for Servic Components. Consider it Other Services, Such As Distributed Transaction Support Or Object Pool.

Advantages

Administration. An Administrator Can Easily Configure The Connection String By Using The Component Services MMC Snap-in.

Disadvantages

· SECURITY. THE COM CATALOG IS Considered A Non-Secure Storage Area (Although You CAN Restrict Access With COM ROLES) AND Theerefore Must Not Be Used To Maintain Connection Strings In Clear Text.

· Deployment. Entries in the COM catalog must be deployed along with your .NET-based application. If you are using other enterprise services, such as distributed transactions or object pooling, storing the database connection string in the catalog presents no additional deployment overhead, because the COM catalog must be deployed to support those other services. · Components must be serviced. You can use construction strings only for serviced components. You should not derive your component's class from ServicedComponent (making your component serviced) simply to enable construction strings.

Important It is critical to secure connection strings. With SQL authentication, the connection contains a user name and password. If an attacker exploits a source code vulnerability on the Web server or gains access to the configuration store, the database will be vulnerable. To prevent . this, connection strings should be encrypted For descriptions of different methods available to encrypt plaintext connection strings, see Improving Web Application Security: Threats and Countermeasures, which will be available at http://www.microsoft.com/practices.

More information

· For more information about how to configure a .NET Class for Object Construction, See How to Enable Object Construction for a .NET Class in The Appendix.

· For more information about it.........................................

· For General Guidance On Developing Secure Asp.Net and Web Applications, Refer to the Following Microsoft Patterns & Practices Guides:

· Volume I, Building Secure ASP.NET Applications: Authentication, Authorization, and Secure Communication, available at http://www.microsoft.com/practices· Volume II, Improving Web Application Security: Threats and Countermeasures, which will be available at http://www.microsoft.com/practices

Connection USAGE PATTERNS

Irrespective of the .NET DATA Provider You Use, You Must Always:

· Open A Database Connection As Late As Possible.

· Use the connection for as short a period as possible.

· Close the connection as soon as possible. The connection is not returned to the pool until it is closed through either the Close or Dispose method. You should also close a connection even if you detect that it has entered the broken state. This ensures that IT is returned to the pool and marked as invalid. The Object Pool, Looking for Objects That Have Been Marked AS Invalid.

To guarantee that the connection is closed before a method returns, consider one of the approaches illustrated in the two code samples that follow. The first uses a finally block. The second uses a C # using statement, which ensures that an object's Dispose method is called .

The Following Code Ensures That a finally block closes the connection. Note That The Approach Works for Both Visual Basic .Net and C # Because Visual Basic .NET Supports structured exception handling.

Public void dosomework ()

{

SqlConnection Conn = New SqlConnection (Connectionstring);

Sqlcommand cmd = new sqlcommand ("commandproc", conn;

cmd.commandtype = commandtype.storedProcedure;

Try

{

Cn.open ();

cmd.executenonquery ();

Catch (Exception E)

{

// Handle and log Error

}

Finally

{

CONN.CLOSE ();

}

}

.

Public void dosomework ()

{

// USING Guarantees That Dispose Is Called on Conn, Which Will

// close the connection.

Using (SqlConnection Conn = New SqlConnection (Connectionstring))

{

Sqlcommand cmd = new sqlcommand ("commandproc", conn;

Fcmd.commandtype = commandtype.storedProcedure;

Cn.open ();

cmd.executequery ();

}

}

You Can Also Apply This Approach To Other Objects-for Example, SqldataReader or OLEDBDataReader-Which Must Be Closed Before with The Current Connection.

Error Handling

ADO.NET errors are generated and handled through the underlying structured exception handling support that is native to the .NET Framework. As a result, you handle errors within your data access code in the same way that you handle errors elsewhere in your application. Exceptions CAN Be detected and handled through standard .NET Exception Handling Syntax and Techniques.

.................................

.NET EXCEPTIONS

The .NET data providers translate database-specific error conditions into standard exception types, which you should handle in your data access code. The database-specific error details are made available to you through properties of the relevant exception object.

All .NET exception types ultimately are derived from the base Exception class in the System namespace. The .NET data providers throw provider-specific exception types. For example, the SQL Server .NET Data Provider throws SqlException objects whenever SQL Server returns an error condition . Similarly, the OLE DB .NET Data Provider throws exceptions of type OleDbException, which contain details exposed by the underlying OLE DB provider.Figure 3 shows the .NET data provider exception hierarchy. Notice that the OleDbException class is derived from ExternalException, the base .

Figure 1.3. .NET DATA Provider Exception Hierarchy

Catching and handling .NET Exceptions

To handle data access exception conditions, place your data access code within a try block and trap any exceptions generated by using catch blocks with the appropriate filter. For example, when writing data access code by using the SQL Server .NET Data Provider, you should Catch Exceptions of Type Sqlexception, As Shown In The Following Code:

Try

{

// Data Access Code

}

Catch (SQLException Sqlex) // More Specific

{

}

Catch (Exception EX) // Less Specific

{

}

If you provide more than one catch statement with differing filter criteria, remember to order them from most specific type to least specific type. That way, the most specific type of catch block is executed for any given exception type.

This Sqlexception Class Exposed Properties That Contain Details of the Exception Condition. Thase Include:

· A Message Property That Contains text describing the error.

· A Number property that contains the error number, which uniquely identifies the type of error. · A State property that contains additional information about the invocation state of the error. This is usually used to indicate a particular occurrence of a specific error condition. For Example, IF a Single Stored Procedure CAN Generate The Same Error from More Than One Line, The State Should Be Used to Identify The Specific Occurrence.

........................................

The Following Code Fragment Illustrate Now To Handle A SQL Server Error Condition By Using The SQL Server .NET DATA Provider:

Using system.data;

Using system.data.sqlclient;

Using system.diagnostics;

//Method Exposed by a data access layer (dal) Component

Public String getProductName (int Productid)

{

SqlConnection conn = null;

// Enclose All Data Access Code forin a Try Block

Try

{

CONN = New SqlConnection

"Server = (local); Integrated Security = SSPI; Database = Northwind");

Cn.open ();

SQLCommand cmd = new SQLCommand ("LookuppproductName", Conn;

cmd.commandtype = commandtype.storedProcedure;

Cmd.Parameters.Add ("@ ProductID", ProductId;

Sqlparameter parampn =

CMD.Parameters.Add ("@ ProductName", SqldbType.varchar, 40);

PARAMPN.DIRECTION = parameterDirection.output;

cmd.executenonquery ();

// the finally code is executed before the method Returns

Return parampn.value.tostring ();

}

Catch (SQLEXCEPTION SQLEX)

{

// Handle Data Access Exception Condition // Log Specific Exception Details

LOGEXCEPTION (SQLEX);

// Wrap the Current Exception in A More Relevant

// Outer Exception and Re-Throw the New Exception

Throw new dalexception

"Unknown ProductID:" ProductId.toString (), SQLEX);

}

Catch (Exception EX)

{

// Handle Generic Exception Condition.

Throw EX;

}

Finally

{

IF (conn! = null) conn.close (); // EnsuRES connection is closed

}

}

// Helper Routine That Logs Sqlexception Details To The

// Application Event Log

Private void logxception (SQLEXCEPTION SQLEX)

{

Eventlog el = new eventlog ();

El.Source = "CustomApplog";

String strmessage;

StrMessage = "Exception Number:" SQLEX.NUMBER

"(" SQLEX.Message ") HAS Occurred";

El.writentry (StrMessage);

FOREACH (SQLERROR SQLE IN SQLEX.ERRORS)

{

StrMessage = "Message:" SQLE.MESSAGE

"Number:" SQLE.NUMBER

"Procedure:" SQLE.Procedure

"Server:" SQLE.Server

"Source:" Sqle.Source

"State:" Sqle.State

"Severity:" SQLE.CLASS

"LINENUMBER:" SQLE.LINENUMBER;

El.writentry (StrMessage);

}

}

Within the SqlException catch block, the code initially logs the exception details by using the LogException helper function. This function uses a foreach statement to enumerate the provider-specific details within the Errors collection and records the error details to the error log. The code within the catch block then wraps the SQL Server-specific exception within an exception of type DALException, which is more meaningful to the callers of the GetProductName method. The exception handler uses the throw keyword to propagate this exception back to the caller.More Information

· For a full list of membrate of the sqlexception class, see http://msdn.microsoft.com/library/en-us/cpref/html/frlrfsystemDatasqlclientsqlexceptionMemberstopic.asp.

· For further guidance about developing custom exceptions, logging and wrapping .NET exceptions, and using various approaches to exception propagation, see http://msdn.microsoft.com/library/default.asp?url=/library/en-us/ DNBDA / HTML / ExceptDotNet.asp.

Generating Errors from Stored Procedures

Transact-SQL (T-SQL) provides a RAISERROR (note the spelling) function, which you can use to generate custom errors and return them to the client. For ADO.NET clients, the SQL Server .NET Data Provider intercepts these database errors And Translates Them to Sqlerror Objects.

. ,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,

Raiserror ('Unknown Product ID:% S', 16, 1, @ProductID)

In this example, a substitution parameter is used to return the current product ID as part of the error message text. Parameter two is the message severity, and parameter three is the message state.More Information

· To avoid hard coding message text, you can add your own message to the sysmessages table by using the sp_addmessage system stored procedure, or by using the SQL Server Enterprise Manager. You can then reference the message by using an ID passed to the RAISERROR function . The message.

· Raiserror (50001, 16, 1, @ProductID)

· For Full Details Relating to the Raiserror Function, Look Up Raiserror In The SQL Server Books Online INDEX.

Using Severity Levels Appropriately

Choose your error severity levels carefully and be aware of the impact of each level. Error severity levels range from 0 to 25 and are used to indicate the type of problem that SQL Server 2000 has encountered. In client code, you can obtain an error's severity ..................... ..

Table 1. Error Severity Levels-Impact and Meaning

Severity Level

Connectionis closed

Generat Qlexception

Meaning

10 and Below

NO

NO

Informational Messages That Do Not Necessarily Represent Error Conditions.

11-16

NO

YES

Errors That Can Be corrected by the user-for example, by retrying the Operation with meansded data.

17-19

NO

YES

Resource or system errors.

20-25

YES

YES

Fatal System Errors (Including Hardware Errors). Client's Connection is Terminated.Controlling Automatic Transactions

The SQL Server .NET Data Provider throws a SqlException for any error encountered with a severity greater than 10. When a component that is part of an automatic (COM ) transaction detects a SqlException, the component must ensure that it votes to abort the transaction. .

For more information.

Retrieving INFORMATIONAL MESSAGES

Severity Levels of 10 and Lower Are Used to Represent Informational Messages and Do Not Cause A SQLException To Be Raised.

To Retrieve Informational Messages:

......................... ..

· Public Delegate Void SqlinFomessageEventhandler (Object Sender,

· SQLINFOMESSAGEVENTARGS E);

Message data is available through the SqlInfoMessageEventArgs object passed to your event handler. This object exposes an Errors property, which contains a set of SqlError objects-one per informational message. The following code fragment illustrates how to register an event handler that is used to log INFORMATIONAL MESSAGES.

Public String getProductName (int Productid)

{

SqlConnection conn = null;

Try

{

CONN = New SqlConnection

"Server = (local); integrated security = sspi; database = northwind"); // register a message event handler

Conn.infomessage = New SqlinfomessageEventHandler (MessageEventhandler);

Cn.open ();

// setup Command Object and Execute IT

.

}

Catch (SQLEXCEPTION SQLEX)

{

// log and handle exception

.

}

Finally

{

IF (conn! = null) conn.close ();

}

}

// Message Event Handler

Void MessageEventHandler (Object Sender, SqlinfubessageEventArgs E)

{

Foreach (SQLERROR SQLE IN E.Error)

{

// log sqlerror proties

.

}

}

Performance

This section introduces a number of common data access scenarios, and for each one, provides details about the most high-performance and scalable solution in terms of ADO.NET data access code. Where appropriate, performance, functionality, and development effort are compared. This Section Considers The Following Functional Scenarios:

· Retrieving a result set and itrating through the retrieved rows.

· Retrieving a single row with a specified primary key.

· RETRIEVING A SINGLE ITEM From A Specified Row.

. Checking to see WHETICULAR KEY EXISTS. THIS A VARITION OF THE SINGLE ITIKUP SCENARIO IN WHICH A Simple Boolean Return IS SUFFICIENT.

Retrieving Multiple Rows

In this scenario, you want to retrieve a tabulated set of data and iterate through the retrieved rows to perform an operation. For example, you might want to retrieve a set of data, work with it in disconnected fashion, and pass it to a client application as an XML document (perhaps through a Web service). Alternatively, you might want to display the data in the form of a HTML table.To help determine the most appropriate data access approach, consider whether you require the added flexibility of the ( disconnected) DataSet object, or the raw performance offered by the SqlDataReader object, which is ideally suited to data presentation in business-to consumer (B2C) Web applications. Figure 4 shows the two basic scenarios.

Note The SqldataAdapter Used to Populate A DataSet InterNally Uses A SqlDataReader To Access The Data.

Figure 1.4. Multiple Row Data Access Scenarios

Comparing the options

You Have The Following Options When You Retrieve Multiple Rows from a data source:

· Use a sqldataadapter Object to generate a dataset or dataable.

· Use a SqldataReader to Provide a Read-Only, Forward-Only Data Street.

• Use an XmlReader to Provide a Read-Only, Forward-Only Data Stream of XML Data.

The choice between SqlDataReader and DataSet / DataTable is essentially one of performance versus functionality The SqlDataReader offers optimum performance;. The DataSet provides additional functionality and flexibility.

Data binding

All three of these objects can act as data sources for data-bound controls, although the DataSet and DataTable can act as data sources for a wider variety of controls than the SqlDataReader. This is because the DataSet and DataTable implement IListSource (yielding IList), whereas the SqlDataReader implements IEnumerable. A number of WinForm controls capable of data binding require a data source that implements IList.This difference is due to the type of scenario for which each object type is designed. The DataSet (which includes the DataTable) is a Rich, Disconnected Structure Suited to Both Web and Desktop (Winform) Scenarios. The Data Reader, on The Other Hand, IS Optimized for Web Applications That Require Optimized Forward-Only Data Access.

Check The Data Source Requirements for The Particular Control Type That You Want To Bind To.

Passing Data Between Application Tiers

The DataSet provides a relational view of the data that can optionally be manipulated as XML, and allows a disconnected cached copy of the data to be passed between application tiers and components. The SqlDataReader, however, offers optimum performance because it avoids the performance and memory overhead associated with the creation of the DataSet. Remember that the creation of a DataSet object can result in the creation of multiple sub-objects-including DataTable, DataRow, and DataColumn objects-and the collection objects used as containers for these sub-objects.

Using a dataset

Use a dataset populate by a SqldataAdapter Object when:

· You Require a Disconnected Memory-Resident Cache of Data, SO That You Can Pass It To Another Component Or Tier Wtem Application.

You Require An in-Memory Requered Of The Data for XML or Non-XML Manipulation. You are Working With Data Retrieved from Multiple Data Sources, Such As Multiple DataBases, Tables, or Files.

......................

YOU Want to Perform Data Binding Against A Control That Requires A Data Source That Supports ILIST.

Note for Detailed Information, See "Designing Data Tier Components and Passing Data THROUGH TIERS" on the msdn web site at http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnbda/ HTML / boagag.asp.

More information

If you use a sqldataadapter to generate a dataset or datatable, Note The Following:

· You do not need to explicitly open or close the database connection. The SqlDataAdapter Fill method opens the database connection and then closes the connection before it returns. If the connection is already open, Fill leaves the connection open.

IF You Require The Connection For Other Purposes, Consider Opening It Prior To Calling The Fill Method. You Can Thus Avoid Unnecessary Open / Close Operations and Gain A Performance Benefit.

· Alth You can repeately use the Same Sqlcommand Object to Execute The Same Command Multiple Times, Do Not Reuse The Same Sqlcommand Object To Execute Different Commands.

· For a code Sample That Shows How To Use a Sqldataadapter to Populate A DataSet or DataTable, See How To Use A SqldataAdapter To Retrieve Multiple Rows in The Appendix.

Using a SqldataReader

Use a SqldataReader Obtained by Calling The ExecuteReader Method Of The Sqlcommand Object When: · You Are Dealing with Large Volumes of Data-Too Much to Maintain in a Single Cache.

You want to reduce the memory footprint of your application.

You want to avoid the object des.taset.

· You Want to Perform Data Binding with a Control That Supports A Data Source That Implements IENUMERABLE.

· You wish to streamline and optimize your data access.

· You are reading rows containing binary large object (BLOB) columns. You can use the SqlDataReader to pull BLOB data in manageable chunks from the database, instead of pulling all of it at once. For more details about handling BLOB data, see the Handling Blobs section in this document.

More information

If you use the sqldatareader, Note The Following:

· The underlying connection to the database remains open and cannot be used for any other purpose While The Data Reader is Active. Call Close on The SqlDataReader as soon as possible.

· There can be Only One Data Reader Per Connection.

· You can close the connection explicitly when you finish with the data reader, or tie the lifetime of the connection to the SqlDataReader object, by passing the CommandBehavior.CloseConnection enumerated value to the ExecuteReader method. This indicates that the connection should be closed when the SqlDataReader is closed.

· When accessing data by using the reader, use the typed accessor methods (such as GetInt32 and GetString) if you know the column's underlying data type because they reduce the amount of type conversion required when you read column data. · To avoid unnecessary data being pulled from server to client, if you want to close the reader and discard any remaining results, call the command object's Cancel method before calling Close on the reader. Cancel ensures that the results are discarded on the server and are not pulled unnecessarily to the client . Conversely, Calling Close on The Data Reader Causes The Reader To Unnecessarily Pull The Remaining Results To Empty The Data Stream.

· If you want to obtain output or return values ​​returned from a stored procedure and you are using the ExecuteReader method of the SqlCommand object, you must call the Close method on the reader before the output and return values ​​are available.

· For a code Sample That Shows How To Use a SqldataReader, See How To Use A SqldataReader To Retrieve Multiple Rows in The Appendix.

Using an XmlReader

Use an Xmlreader Obtained by Calling The Executexmlreader Method of The SqlCommand Object When:

You want to process the retrieved Data As XML, But you do not want to incote The Performance Overhead of Creating A DataSet and do Not Require A Disconnected Cache of Data.

· You want to exploit the functionality of the SQL Server 2000 FOR XML clause, which allows XML fragments (that is, XML documents with no root element) to be retrieved from the database in a flexible manner. For example, this approach lets you specify PRECISE Element Names, WHETER AN Element OR Attribute-Centric Schema Should Be Bu Returned with The XML Data And So ON.MORE Information

If you use the xmlreader, Note The Following:

· The connection must remain open while you read data from the XmlReader. The ExecuteXmlReader method of the SqlCommand object currently does not support the CommandBehavior.CloseConnection enumerated value, so you must explicitly close the connection when you finish with the reader.

· For a code sample what shows how to use one.................

Retrieving a Single Row

In this scenario, you want to retrieve a single row of data that contains a specified set of columns from a data source. For example, you have a customer ID and want to look up related customer details, or you have a product ID and want TO RETRIEVE PRODUCT INFORMATION.

Comparing the options

If you want to perform data binding with a single row retrieved from a data source, you can use a SqlDataAdapter to populate a DataSet or DataTable in the same way that is described in the Multiple Row Retrieval and Iteration scenario discussed previously. However, unless you Spectable Require Dataset / DataTable Functionality, You Should Avoid Creating these Objects.

If You NEED TO RETRIEVE A SINGLE ROW, Use Open of the Following Options:

· Use stiled procedure output parameters .. Use a sqldatarader object.

Both options avoid the unnecessary overhead of creating a result set on the server and a DataSet on the client. The relative performance of each approach depends on stress levels and whether or not database connection pooling is enabled. When database connection pooling is enabled, performance tests Have Shown The Stored Procedure Approach To Outperform The SqldataReader Approach by Nearly 30 Percent Under High-Stress Conditions (200 Simultaneous Connections).

USING Stored Procedure Output Parameters

Use Stored Procedure Output Parameters Want To Retrieve A Single Row from a Multitier Web Application Where You Have Enabled Connection Pool.

More information

For a code Sample That Shows How To Use Stored Procedure Output Parameters, See How to Use Stored Procedure Output Parameters to Retrieve A Single Row In The appendix.

Using a SqldataReader

Use a sqldatarader when:

.................... ..

· You are not using connection pooling With connection pooling disabled, the SqlDataReader is a good option under all stress conditions;. Performance tests have shown it to outperform the stored procedure approach by around 20 percent at 200 browser connections.

More information

If you use a sqldatareader, Note The Following:

· If you know your query only returns a single row, use the CommandBehavior.SingleRow enumerated value when calling the ExecuteReader method of the SqlCommand object. Some providers such as the OLE DB .NET Data Provider use this hint to optimize performance. For example, this provider performs binding by using the IRow interface (if it is available) rather than the more expensive IRowset. This argument has no effect on the SQL Server .NET Data Provider. · If your SQL Server command contains output parameters or return values, they Will Not Be Available Until The DataReader Is Closed.

· When using the SqlDataReader object, always retrieve output parameters through the typed accessor methods of the SqlDataReader object, for example GetString and GetDecimal. This avoids unnecessary type conversions.

· .NET Framework Version 1.1 Includedes An Additional DataReader Property Called Hasrows, Which Enables You To Dermine If The DataReader Has Returned Any Results Before Reading from It.

· For a code Sample That Shows How To Use A SqldataReader Object To Retrieve A Single Row, See How To Use A SqldataReader To Retrieve A Single Row In The Appendix.

Retrieving a Single Item

In this scenario, you want to retrieve a single item of data. For example, you might want to look up a single product name, given its ID, or a single customer credit rating, given the customer's name. In such scenarios, you will Generally Not Want to Incur The Overhead of a Dataset Or Even A DataTable When Retrieving A Single Item.

You might also want simply to check whether a particular row exists in the database. For example, as a new user registers on a Web site, you need to check whether or not the chosen user name already exists. This is a special case of the Single Item Lookup, But in this case, a Simple Boolean Return Is Sufficient.comParing the Options

Consider The Following Options When You Retrieve A Single Item of Data from A Data Source:

· Use The Executescalar Method of A Sqlcommand Object with a stored procedure.

· Use a stored procedure output or return parameter.

· Use a sqldatareader object.

The ExecuteScalar method returns the data item directly because it is designed for queries that only return a single value. It requires less code than either the stored procedure output parameter or SqlDataReader approaches require ..

From a performance perspective, you should use a stored procedure output or return parameter because tests have shown that the stored procedure approach offers consistent performance across low and high-stress conditions (from fewer than 100 simultaneous browser connections to 200 browser connections).

More information

When Retrieving a Single Item, Be aware of the following:

· IF a Query Normally Returns Multiple Column and / or Rows, Executing It Through ExecuteQuery Will Return Only The First Column of The First Row.

· For a code Sample That Shows How To Use Executescalar, See How To Use Executescalar to Retrieve A Single Item in the appendix.

· For a code sample that shows how to use a stored procedure output or return parameter to retrieve a single item, see How To Use a Stored Procedure Output or Return Parameter To Retrieve a Single Item in the appendix. · For a code sample that shows How To Use a SqldataReader Object To Retrieve A Single Item, See How To Use A SqldataReader To Retrieve A Single Item in the appendix.

Connecting Through FireWalls

You will often want to configure Internet applications to connect to SQL Server through a firewall. For example, a key architectural component of many Web applications and their firewalls is the perimeter network (also known as DMZ or demilitarized zone), which is used to isolate Front-End Web Servers from Internal Networks.

Connecting to SQL Server through a firewall requires specific configuration of the firewall, client, and server. SQL Server provides the Client Network Utility and Server Network Utility programs to aid configuration.

Choosing a network librage

Use the SQL Server TCP / IP network library to simplify configuration when connecting through a firewall. This is the SQL Server 2000 installation default. If you are using an earlier version of SQL Server, check that you have configured TCP / IP as the default network Library on Both The Client and The Server by Using The Client Network Utility and Server Network Utility, Respective.

In addition to the configuration benefit, Using the TCP / IP Library Results Means That You:

Benefit from Improved Performance with High Volumes of Data And Improved Scalability.

· Avoid Additional Security Issues Associated with named pipes.

You must configure the client and server computers for TCP / IP. Because most firewalls restrict the set of ports through which they allow traffic to flow, you must also give careful consideration to the port numbers that SQL Server uses.Configuring the Server

Default instances of SQL Server listen on port 1433. UDP port 1434 is also used to allow SQL clients to locate other SQL servers on their network. Named instances of SQL Server 2000, however, dynamically assign a port number when they are first started. Your network administrator will not want to open a range of port numbers on the firewall; therefore, when you use a named instance of SQL Server with a firewall, use the Server Network Utility to configure the instance to listen on a specific port number Your administrator. .

Note The source port that the client network library uses is dynamically assigned in the range 1024-5000. This is standard practice for TCP / IP client applications, but it means your firewall must allow traffic from any port within this range. For more information about The Ports That SQL Server Uses, See Microsoft Knowledge Base Article 287932, "INF: TCP Ports Needed for Communication TO SQL Server Through A Firewall."

Dynamic Discovery of Named INSTANCES

If you change the default port number That SQL Server Listens ON, Configure your client to connect to this port. For details, see the configuring the client section

If you change the port number for your default instance of SQL Server 2000, failure to modify the client will result in a connection error. If you have multiple SQL Server instances, the latest version of the MDAC data access stack (2.6) employs dynamic discovery and uses a User Datagram Protocol (UDP) negotiation (through UDP port 1434) to locate the named instances. Although this might work in a development environment, it is unlikely to work in a live environment because the firewall will typically block the UDP negotiation traffic .To Circumvent this, Always Configure your client to connect to the configured destination port number.

Configuring the client

You Should Configure The Client To Use TCP / IP Network Library To Connect To SQL Server, and You Should Ensure That The Client Library Uses The Correct Destination Port Number.

Using the TCP / IP Network Library

You can configure the client by using the SQL Server Client Network Utility In some installations, you might not have this utility installed on the client (for example, your Web server) In this case, you can do either of the following..:

· Specify the network library by using the "Network Library = dbmssocn" name-value pair supplied through the connection string. The string "dbmssocn" is used to identify the TCP / IP (sockets) library.

Note When Using The SQL Server .NET Data Provider, The Network Library Setting Uses "dbmsoCN" by default.

· Modify the registry on the client machine, to establish TCP / IP as the default library For more information about configuring the SQL Server network library, see HOWTO:. Change SQL Server Default Network Library Without Using Client Network Utility (Q250550) .Specifying a Port

IF Your Instance of SQL Server IS Configured to Listen ON A Port Other Than The Default 1433, You Can Specify The Port Number To Connect To By:

USING The Client Network Utility.

· Specifying the port number with the "server" or "data source" name-value pair sales. Use a string with the folload format:

· "Data Source = Servername, Portnumber"

Name ServerName Might Be An IP Address OR Domain Name System (DNS) Name. For Optimum Performance, Use An IP Address To Avoid A DNS Lookup.

Distributed Transactions

If you have developed serviced components that use COM distributed transactions and the services of the Microsoft Distributed Transaction Coordinator (DTC), you might also need to configure your firewall to allow DTC traffic to flow between separate DTC instances, and between the DTC and resource managers Such as SQL Server.

For More Information About Opening Ports for the DTC, See Info: Configuring Microsoft Distributed Transaction Coordinator (DTC) To Work Through A Firewall.

Handling blobs

Today, many applications need to deal with data formats such as graphic and sound-or even more elaborate data formats, such as video-in addition to more conventional character and numeric data. There are many different types of graphic, sound, and video formats . From a storage perspective, however, they can all be thought of as lumps of binary data, typically referred to as binary large objects, or BLOBs.SQL Server provides the binary, varbinary, and image data types to store BLOBs. Despite the name , BLOB data can also refer to text-based data. for example, you might want to store an arbitrarily long notes field that can be associated with a particular row. SQL Server provides the ntext and text data types for this purpose.

In General, For Binary Data Less Than 8 Kilobytes (KB), Use The Varbinary Data Type. For binary data exceeding this size, use image. Table 2 Highlights The Main Features of Each Data Type.

Table 2. Data Type Features

Data Type

Size

Description

binary

Ranges from 1 to 8,000 bytes. Storage Size IS Specified Length Plus 4 bytes.

Fixed-Length Binary Data

Varbinary

Ranges from 1 to 8,000 bytes. Storage Size Is Actual Length of Supplied Data Plus 4 Bytes.

Variable-Length Binary Data

Image

Variable-Length Binary Data from 0 to 2 Gigabytes (GB).

Large-size, Variable-Length Binary Data

TEXT

Variable-Length Data from 0 to 2 GB.

Character Data

NText

Variable-Length Data from 0 to 2 GB.

Unicode Character Data

Note Microsoft® SQL Server ™ 2000 supports the ability to store small to medium text, ntext, and image values ​​in a data row. The feature is best used for tables in which the data in text, ntext, and image columns is usually read or Written in one unit and most the text, ntext, and image data. more information can be bound in the sql server books online under "Text in row" .where to store blob data

SQL Server 7.0 and later have improved the performance of working with BLOB data stored in the database. One of the reasons for this is that the database page size has increased to 8 KB. As a result, text or image data less than 8 KB no longer needs to be stored in a separate binary tree structure of pages, but can be stored in a single row. This means that reading and writing text, ntext, or image data can be as fast as reading or writing character and binary strings. Beyond 8 KB, A Pointer Is Maintained with The Row, And The Data Itself Is Held in a Binary Tree Structure of Separate Data Pages-with an INEVITABLE PERFORMANEPACT.

For More Information About Forcing Text, Ntext, and Image Data To Be Stored In A Single Row, See The "Using Text and Image Data" Topic in SQL Server Books Online.

A commonly used alternative approach to handling BLOB data is to store the BLOB data in the file system, and store a pointer (preferably a Uniform Resource Locator [URL] link) in a database column to reference the appropriate file. For versions earlier than SQL Server 7.0, Storing Blob Data External To The Database In The File System CAN IMPROVE Performance.

However, improved BLOB support in SQL Server 2000, coupled with ADO.NET support for reading and writing BLOB data, makes storing BLOB data in the database a feasible approach.Advantages of Storing BLOB Data in the Database

Storing Blob Data in The Database Offers a Number of Advantages:

· It is easier to keep the blob data synchronized with the remaining items in the rot.

· BLOB DATA IS backed Up with the database. Having a single storage system can eat administration.

· BLOB DATA CAN BE Accessed Through XML Support in SQL Server 2000, Which Can Return A Base 64-Encoded Representation of The Data In The XML Stream.

· SQL Server Full Text Search (FTS) operations can be performed against columns that contain fixed or variable-length character (including Unicode) data. You can also perform FTS operations against formatted text-based data contained within image fields-for example, Microsoft Word or Microsoft Excel Documents.

Disadvantages of Storing Blob Data in The Database

Carefully Consider What Resources Might Be Better Stored On A Database. Good Examples Are Image That ArePically Reference Via Http Href. This is Because:

· Retrieving An Image from a Database Incurs Significant Overhead Compared to use used the file system.

• Disk Storage on Database Sans IS Typically More Expensive Than Storage on Disks Used in Web Server Farms.

Note A well thought out metadata strategy can remove the need for resources such as images, movies, and even Microsoft Office documents to be stored in the database. The metadata could be indexed and include pointers to resources stored on the file system.Writing BLOB Data To the database

.

Public void storePicture (String FileName)

{

// read the file into a byte array

Using (filestream fs = new filestream (filename, filemode.open, fileaccess.read)

{

Byte [] imagedata = new byte [fs.length];

fs.read (imagedata, 0, (int) fs.length);

}

Using (SqlConnection Conn = New SqlConnection (Connectionstring))

{

Sqlcommand cmd = new SQLCOMMAND ("StorePicture", CONN);

cmd.commandtype = commandtype.storedProcedure;

Cmd.Parameters.Add ("@ filename", filename;

CMD.Parameters ["@ filename"]. Direction = parameterdirection.input;

Cmd.Parameters.Add ("@ blobdata", sqldbtype.image);

CMD.Parameters ["@ blobdata"]. Direction = parameterdirection.input;

// store the byte array within the image field

CMD.Parameters ["@ blobdata"]. value = imagedata;

Cn.open ();

cmd.executenonquery ();

}

}

Reading Blob Data from The Database

When creating a SqlDataReader object through the ExecuteReader method to read rows that contain BLOB data, use the CommandBehavior.SequentialAccess enumerated value. Without this enumerated value, the reader pulls data from the server to the client one row at a time. If the row contains a BLOB column, this might represent a large amount of memory. by using the enumerated value, you have a finer degree of control because the BLOB data will be pulled only when referenced (for example, by means of the GetBytes method, which you can Use to control the number of bytes read. this is illustrate in the following code Fragment.// Assume Previously Established Command and Connection

// the command selects the Image column from the table

Cn.open ();

Using (SqlDataReader Reader = cmd.executeReader (Commandbehavior.SequentialAracse))

{

Reader.Read ();

// Get Size of Image Data-Pass Null As the byte Array Parameter

Long Bytesize = Reader.getbytes (0, 0, NULL, 0, 0);

// allocate byte array to hold image data

Byte [] imagedata = new byte [bytesize];

Long BytesRead = 0;

INT CURPOS = 0;

While (bytesRead

{

// chunksize is an Arbitrary Application Defined Value

BYTESREAD = Reader.getbytes (0, Curpos, ImageData, Curpos, Chunksize);

Curpos = chunksize;

}

}

// Byte Array 'ImageData' Now Contains Blob from Database

Note Using CommandBehavior.SequentialAccess requires you to access column data in a strict sequential order. For example, if the BLOB data is in column 3, and you also require data from column 1 and column 2, you must read columns 1 and 2 prior to READING 3.

Performing Database Updates with DataSets

The architecture for performing database updates has changed significantly with the introduction of ADO.NET. ADO.NET has been designed to better facilitate development of multitier applications that scale to large database sizes and large numbers of clients. This has had some important consequences, in particular: · ADO.NET applications usually segregate application logic on the client from business and data integrity computations on the middle and database tiers In practical terms, this means that the typical application will have more of a batch or transactional nature with fewer (but. Larger) Between Client Application and Database.

· ADO.NET Applications Have More Control (In Comparison to Ado and ITS Predecessors) over exactly how updates are processed.

· ADO.NET allows applications to propagate changes by means of stored procedures that are stored in the backend database, instead of directly manipulating a row of a database table. This is a recommended practice.

Update usage patterns

The process of using ado.net to update data from a DataSet Can Be Outlined As Follows:

1. Create a DataAdapter Object and Fill A DataSet Object with the results of a database query. The data will be cached locally.

2. Make changes to the local dataset object. These Changes, And Insertions to One or more Tables in The Locally Cached DataSet.

3. Initialize the DataAdapter update-related properties. This step configures exactly how updates, deletions, or insertions will be processed. Since there are several ways to handle this, recommended approaches are discussed below in "Initializing DataAdapters for Update." 4. Invoke the DataAdapter Update method to submit the pending changes. Each of the changed records of the locally cached DataSet will be processed. (Records with no changes will be automatically ignored by the Update method.)

5. Handle Exceptions Thrown by the DataAdapter Update Method. Exceptions Arise When The Requested Changes Cannot Be Made In The Database.

(There is one other way to perform updates. You can directly execute a SQL update query using the ExecuteNonQuery method. This technique is appropriate when you want to update specific rows programmatically, without using a DataSet object.)

Initializing DataAdapters for Update

In ado.net, you must add your owned for subsmitting database updates to the dataadapter object. There all three Ways of doing this:

.

.

.

It is recommended that you supply your own updating logic. To save time, you can use the Data Adapter Configuration Wizard, but if you do, try not to generate the logic at run time. Do not rely on CommandBuilder objects unless you have to because your performance will suffer and you can not control the updating logic the objects generate. In addition, a CommandBuilder will not help you submit updates using stored procedures.You can use CommandBuilder with applications that dynamically generate data access logic, such as reporting or data extraction tools .................

Using stored procedures

Using stored procedures for updates allows the administrator of your database to implement more granular security than is available with dynamic SQL, as well as more sophisticated data integrity checks. For example, the stored procedure might insert an entry into an audit log as well as perform the requested update. Stored procedures can provide the best performance as well because of offline query optimization performed within the database on stored procedures. Finally, the insulation between the database structure and the application that stored procedures provide allows for easy maintenance.

Because ADO.NET applications that use stored procedures provide many benefits and are no more difficult to implement than those that make changes directly to the database, this approach is recommended in nearly every case. The exception to this is if you must work with multiple back Ends or A Database, Such as Microsoft Access, That Doesn't Support Them. In Those Cases, Use Query-based Updates.

Managing concurrency

The DataSet object is designed to encourage the use of optimistic concurrency for long-running activities, such as when you are remoting data and when users are interacting with data. When submitting updates from a DataSet to the database server, there are four main approaches to Managing Optimistic Concurrency: · Including Only The Primary Key Column

· Including all column in the where clause

· Including Unique Key Column and The TimeStamp Columns

· Including Unique Key Column and The Modified Column

.

Including Only The Primary Key Column

This option creates a situation where the last update overrides all previous changes. The CommandBuilder does not support this option, but the Data Adapter Configuration Wizard does. To use it, go to the Advanced Options tab and clear the Use Concurrency check box.

This approach is not a recommended practice because it allows users to unknowingly overwrite other users' changes. It is never advisable to compromise the integrity of another user's update. (This technique is appropriate only for single-user databases.)

INCLUDING All Column in The Where Clause

This option prevents you from overwriting changes made by other users between the time your code fetches the row and the time your code submits the pending change in the row. This option is the default behavior of both the Data Adapter Configuration Wizard and the SQL code generated By The Sqlcommandbuilder.

This approach is not a recommended Practice for the Following Reasons:

· If an additional column is added to the table, the query will need to be modified. · In general, databases do not let you compare two BLOB values ​​because their large sizes make these comparisons inefficient. (Tools such as the CommandBuilder and the Data Adapter Configuration Wizard SHOULD NOT INCLUDE BLOB Columns in The Where Clause.)

COMPARING All Columns Wtemns in An Updated Row Create Excessive Overhead.

Including Unique Key Column and The TimeStamp Column

With this option, the database updates the timestamp column to a unique value after each update of a row. (You must provide a timestamp column in your table.) Currently, neither the CommandBuilder nor the Data Adapter Configuration Wizard supports this option.

Including Unique Key Column and The Modified Column

In general, this option is not recommended because errors may result if your application logic relies on out-of-date data fields or even fields that it does not update. For example, if user A changes an order quantity and user B changes the unit Price, IT May Be Possible for the Order Total (Quantity Multiplied By Price) to be incorrectly Calculate.

Correctly Updating Null Fields

When fields in a database do not contain data values, it is often convenient to think of these empty fields as containing a special null value. However, this mental picture can be the source of programming errors because database standards require special handling for null values.

The core issue with null fields is that the ordinary SQL = operator will always return false if one or both of the operands is a null value. The operator IS NULL is the only correct way to check for the presence of a null field in a SQL query.If your application uses the technique described above to manage concurrency by specifying a WHERE clause, you must include explicit IS nULL expressions wherever it is possible that a field could be null. For example, the following query will always fail if OldLastName is null :

Set lastname = @newlastname where studentid = @studentid and

Lastname = @OLDLASTNAME

The Query Should Be Rewritten As:

Set lastname = @newlastname where (studentid = @studentID) and

(LastName = @oldlastname) or

(OldLastName Is Null and lastname is null))

......................... ...CRIPLITRATORSTIC.

More information

A Complete Treatment of Database Updates Can Be Found in David Sceppa's Microsoft ADO.NET (Microsoft Press, 2002), ChapterS 11 and 12.

USING STRONGLY TYPED DATATIT OBJECTS

. Strongly typed DataSet objects present database tables and columns as objects and properties Access is performed by name, not by indexing into a collection This means you can recognize the difference between strongly typed and untyped DataSet objects in the way you access the fields.:

String n1 = mydataset.tables ["students"]. Rows [0] ["studentname"]; // untyped

String n2 = mydataset.students [0] .studentname; // strongly typed

There Are Several Benefits To Use Strongly Typed DataSet Objects:

· The code required to access................................ ..

· The Compiler CaCCH Strongly Typed DataSet Type Mismatch ErrorS. It is better to detect Type Errors At Compile Time Than At Run Time.

When to Use strongly Typed DataSet

Strongly typed DataSets are useful because they make application development easier and less error-prone. This is especially true for the client side of a multitiered application where the focus is on graphical user interfaces and data validation that require many field access operations.

However, strongly typed DataSets can be cumbersome if the database structure changes, for example when field and table names are modified. In this case, the typed DataSet class has to be regenerated and all dependent classes must be modified.

It is possible to use both strongly typed and untyped approaches in the same application. For example, some developers use strongly typed DataSets on the client side and untyped records on the server. The.Merge method of the strongly typed DataSet can be used to import Data from an Undyped DataSet.

Generating DataSet Classes

Both the .NET Framework SDK and Visual Studio.NET provide utilities for helping you generate the necessary DataSet subclasses. The .NET Framework SDK involves using a command-line tool and writing code. The Visual Studio .NET method, obviously, relies on the Visual Studio .Net Development Environment and Doesn't Require You to Open A Command Window.

Regardless of how the DataSet class is generated, the new class must also be deployed to all tiers that reference that typed DataSet. (This is not a typical scenario, but it is important to consider if passing a typed DataSet across tiers by using remoting. ) Using the .net framework utility

The .NET Framework SDK includes a command-line utility called the XML Schema Definition Tool that helps you generate class files based on XML schema (.xsd) files. Use this utility in conjunction with the DataSet object's WriteXmlSchema method to translate your untyped DataSet into a strongly type type dataset.

The Following Command Illustrates How To Generate A Class File from an XML Schema File. Open a Command Window and Type:

C: /> xsd mynewclass.xsd / d

The first parameter in the command is the path to the XML schema file. The second parameter indicates that the class you want to create is derived from the DataSet class. By default, the tool generates Visual C # .NET class files, but it can also GENERATE VISUAL BASIC .NET CLASSIT Files BY Adding The Appropriate Options. To list the Tool's Available Options, Type:

XSD /?

ONCE You'VE CREATED YOUR New Class File, add it to your project. You can now create an instance of your strong typed dataset class, as shown in the following visual c # .NET CODE SNIPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPP

Mynewclass DS = new mynewclass ();

Using Visual Studio .NET

To generate a strongly typed DataSet in Visual Studio .NET, right-click in the form designer window, and then click Generate Dataset. This creates an .xsd (XML Schema Definition) file, as well as a class file, and then adds them to your project. Be sure that one or more DataAdapters have been added to your Windows form before doing this. Note that the class file is hidden. to see it, click the Show All Files button located in the toolbar of the Solution Explorer window. The class file is associated with the .xsd file.To add relations to a strongly typed DataSet, open the XML Schema Designer by double-clicking the schema file in the Solution Explorer window, and then right-click the table to which you want to Add a constraint. on The Shortcut Menu, Click Add New RELATION.

An alternative method for generating a strongly typed DataSet in Visual Studio .NET is to right-click the project in the Project Explorer, choose Add Files, and then select dataset. A new .xsd file will be created. From there you can use Server Explorer to Connect to a Database and Drag Table (s) ONTO The XSD File.

Working with Null Data Fields

Here Are A Few Tips To Help You Correctly Use Null Field Values ​​in The .NET Data Architecture:

Always Set The Value of a Null Field Using The System.dbnull Class. Do Not Use The Null Value Provided by C # Or Visual Basic .NET. For example:

Rowstudents ["nickname"] = dbnull.value // Correct!

· Strongly typed DataSets contain two additional methods per DataRow-one to check if a column contains a null value, and another to set the column value to null These are shown in the following code fragment.:

· IF (tds.rowstudnt [0] .isphonenonull ()) {....} · Tds.rowstudent [0] .SETPHONENONONULL ()

· Always use the IsNull method of the DataRow class (or the strongly typed equivalent given in the previous bullet) to test for null values ​​from a database. This method is the only supported way to test for null database values.

· If it is possible that a data field contains a null value, be sure to test for it (with the IsNull method) before using the value in a context that expects a non-null value. A typical example of this is Integer-valued Data Fields That May Be Null. Note That The .NET Run Time Integer DataType Does NOT INCLUDE The NULL VALUE. Here is an esample:

· INT i = rowstudent ["zipcode"]; // throws exception if null!

· Use the nullValue annotation of a strongly typed DataSet .xsd file to configure how null values ​​from a database are mapped By default, an exception is thrown;. However, for more fine-grained control, you can configure the class to replace the null Value with a specified value, so as string.empty.

Transactions

Virtually all commercially oriented applications that update data sources require transaction support Transactions are used to ensure the integrity of a system's state contained within one or more data sources by providing the four basic guarantees of the well known ACID acronym:. Atomicity, consistency, isolation, And durability.

For Example, Consider a Web-Based Retail Application That Processes Purchase Orders. Each Order Requires Three Distinct Operations That Involve Three Database Updates:

..........................

· A New Order Must Be Added to the Orders Database.

It is essential that these three distinct operations be performed as a unit and in an atomic fashion. They must all succeed, or none of them must succeed-any alternative would compromise data integrity. Transactions provide this and other guarantees.

For further background recapation.com, see http://msdn.microsoft.com/library/en-us/cpguidnf/html/cpContransactionProcessingFundamentals.asp.

THERE A Number of Approaches That You Can Adopt To Incorporate Transaction Management Into Your Data Access Code. Each Approach Fits Into One of Two Basic Programming Models:

MANUAL Transactions. You Write Code That Uses The Transaction Support Features of Either ado.net or transact-sql directly in Your Component Code or Stored Procedures, respective.

· Automatic (COM ) transactions. You add declarative attributes to your .NET classes that specify the transactional requirements of your objects at run time. This model allows you to easily configure multiple components to perform work within the same transaction.

Both techniques can be used to perform local transactions (that is, transactions performed against a single resource manager such as SQL Server 2000) or distributed transactions (that is, transactions performed against multiple resource managers located on remote computers), although the automatic transaction model Great Simplifies Distributed Transaction Processing.

You might be tempted to use automatic (COM ) transactions to benefit from an easier programming model. This benefit is particularly apparent in systems where you have many components that perform database updates. In many scenarios, however, you should avoid the additional overhead and performance Reduction model .this section sections guidance to help you choose the MOST Approrate Model Based on your particular application scenario.

Choosing a Transaction Model

Prior to choosing a transaction model, you should consider whether or not you require transactions at all Transactions are the single most expensive resource consumed by server applications, and they reduce scalability when used unnecessarily Consider the following guidelines governing the use of transactions..:

..............

· Keep Transactions As Short As Possible to Minimize The Amount of Time That You Hold Database Locks.

NEVER Place a Client in Control of Transaction Lifetime.

· DON '' USE A Transaction for An Individual SQL Statement. SQL Server Automatical Runs Each Statement As An Individual Transaction.

Automatic vs. Manual Transactions

Although the programming model is somewhat simplified for automatic transactions, particularly when multiple components are performing database updates, manual local transactions are always significantly faster because they do not require interaction with the Microsoft DTC. This is true (although the performance degradation is reduced) even if you are using automatic transactions against a single local resource manager (such as SQL Server), because a manual, local transaction avoids any unnecessary interprocess communication (IPC) with the DTC.Use manual transactions when:

· You are Performing a Transaction Against A Single Database.

Use Automatic Transactions When:

· You Require a Single Transaction to SPAN Multiple Remote Databases.

· You Require A Single Transaction To Encompass Multiple Resource Managers-for Example, A Database and A Windows 2000 Message Queuing (Formerly Known AS MSMQ) Resource Manager.

Note Avoid Mixing Your Transaction Models. Use one or the other.

In application scenarios in which performance is deemed sufficient, it is reasonable to opt for automatic transactions (even against a single database) to simplify the programming model. Automatic transactions make it easy for multiple components to perform operations that are part of the same transaction.

USING MANUAL Transactions

With manual transactions, you write code that uses the transaction support features of either ADO.NET or Transact-SQL directly in your component code or stored procedures, respectively. In most cases, you should opt for controlling transactions in your stored procedures because this approach Offers superior encapsulation

ADO.NET supports a transaction object that you can use to begin a new transaction and then explicitly control whether it should be committed or rolled back. The transaction object is associated with a single database connection and is obtained by the BeginTransaction method of the connection object . Calling this method does not implicitly mean that subsequent commands are issued in the context of this transaction. You must explicitly associate each command with the transaction, by setting the Transaction property of the command. You can associate multiple command objects with the transaction object, ThereBy Grouping Multiple Operations Against The Single Database IN A Single Transaction.

.

More information

· The default isolation level for an ADO.NET manual transaction is Read Committed, which means that the database holds shared locks while data is being read, but data can be changed before the end of the transaction. This can potentially result in non-repeatable reads, or phantom data. You can change the isolation level by setting the transaction object's IsolationLevel property to one of the enumerated values ​​defined by the IsolationLevel enumerated type. · You must give careful consideration to choosing an appropriate isolation level for your transactions. The tradeoff is one of data consistency versus performance. The highest isolation level (Serialized) offers absolute data consistency, but at the price of overall system throughput. Lower isolation levels can make an application more scalable, but at the same time, increase the possibility of errors Resulting from data inconsistency. for systems this read data Most of the time, and write data Rarely, Lower Isolation Levels Might Be Appropriate.

· For Valuable Information About Choosing An Appropriate Transaction Isolation Level, See The Microsoft Press® Book Inside SQL Server 2000, by Kalen delaney.

Performing Manual Transactions with stored procedures

You can also control manual transactions directly by using Transact-SQL statements in your stored procedures. For example, you could perform transactional operations by using a single stored procedure that employs Transact-SQL transaction statements such as BEGIN TRANSACTION, END TRANSACTION, and ROLLBACK TRANSACTION .

More information

· If required, you can control the transaction isolation level by using the SET TRANSACTION ISOLATION LEVEL statement in the stored procedure. Read Committed is the SQL Server default. For more information about SQL Server isolation levels, see Isolation Levels within the "Accessing and Changing Relation Data "section of SQL Server Books Online. · For a code sample that shows how to perform transactional updates using Transact-SQL transaction statements, see How to Perform Transactions With Transact-SQL in the appendix.

Using Automatic Transactions

Automatic transactions simplify the programming model because they do not require that you explicitly begin a new transaction or explicitly commit or abort the transaction. However, the most significant advantage of automatic transactions is that they work in conjunction with the DTC, which allows a single transaction to span multiple distributed data sources. In a large-scale distributed application, this advantage can be significant. Although it is possible to manually control distributed transactions by programming the DTC directly, automated transactions drastically simplify the task and are designed for component-based systems For Example, IT IS Easy to Declarative Configure Multiple Components to Perform Work That Comprises a Single Transaction.

Automatic transactions rely on the distributed transaction support features provided by COM , and as a result, only serviced components (that is, components that are derived from the ServicedComponent class) can use automatic transactions.

To Configure a class for Automatic Transactions:

· Derive the class from the ServicedComponent class located within the System.EnterpriseServices namespace. · Define the transaction requirements of the class by using the Transaction attribute. The value supplied from the TransactionOption enumerated type determines how the class will be configured in the COM catalog. Other Properties That Can Be Established with this Attribute Include The Transaction Isolation Level and Time-Out.

· To avoid explicitly having to vote in the transaction outcome, you can annotate methods with the AutoComplete attribute. If these methods throw an exception, the transaction will be aborted automatically. Note that you can still directly vote toward transaction outcome if required. For further Details, see the determining Transaction Outcome section Later in this document.

More information

· For more information about com automatic Transactions, Search for "Automatic Transactions Through COM " within the Platform SDK Documentation.

· For An Example of a Transactional .NET Class, See How To Code a Transactional .NET Class in The Appendix.

Configuring Transaction Isolation Levels

The transaction isolation level for COM version 1.0-that is, COM running on Windows 2000-is Serialized. Although this offers the highest degree of isolation, such protection comes at the cost of performance. The overall throughput of your system is reduced because the resource managers (typically databases) involved must hold both read and write locks for the duration of the transaction. During this time, all other transactions are blocked, which can have a significant impact on your application's ability to scale.COM version 1.5, which ships with Microsoft Windows .NET, allows the transaction isolation level to be configured in the COM catalog on a per component basis. The setting associated with the root component in the transaction determines the isolation level for the transaction. in addition, internal subcomponents that are part of The Same Transaction Stream Must Not Have a Transaction Level Higher Than That Defined by The Root Component. if DO, An Error Will Result Whe n the subcomponent is instantiated.

For .NET managed classes, the Transaction attribute supports the public Isolation property. You can use this property to declaratively specify a particular isolation level, as illustrated in the following code.

[Transaction (TransactionOption.supported, Isolation = TransactioniSolationledLevel.Readcommitted)]

Public Class Account: ServicedComponent

{

.

}

More information

· For more information about configurable transaction isolation levels and other Windows .NET COM enhancements, see the MSDN Magazine article, "Windows XP: Make Your Components More Robust with COM 1.5 Innovations" at http://msdn.microsoft.com/msdnmag/ Issues / 01/08 / COMXP / Default.aspx.determining Transaction Outcome

The outcome of an automatic transaction is governed by the state of the transaction abort flag, together with the consistent flags, in the context of all transactional components in a single transaction stream. Transaction outcome is determined at the point that the root component in the transaction Stream is deactivated (AND Control is returned to the caller). This Is Illustrate In Figure 5, Which Shows A Classic Bank Funds Transfer Transaction.

Figure 1.5. Transaction stream and context

The outcome of the transaction is determined when the root object (in this example, the Transfer object) is deactivated, and the client's method call returns. If any of the consistent flags within any context are set to false, or if the transaction abort flag IS set to true, the underlying physical dtc transaction is aborted.

You Can Control Transaction Outcome from a .Net Object in One of Two Ways:

· You can annotate methods with the AutoComplete attribute, and let .NET automatically place your vote governing the outcome of the transaction. With this attribute, if the method throws an exception, the consistent flag is automatically set to false (which ultimately causes the transaction to abort). If the method returns without throwing an exception, the consistent flag is set to true, which indicates that the component is happy for the transaction to commit. This is not guaranteed because it depends on the votes of other objects in the same TRANSABORT METIC SETCOMPLETE OR SETABORT METHOD OF THE CONTEXTUTIL CLASS, Which Sets The Consistent Flag To True Or False, Respective.

SQL Server errors with a severity greater than 10 result in the managed data provider throwing exceptions of type SqlException. If your method catches and handles the exception, be sure to either manually vote to abort the transaction, or for methods flagged as [AutoComplete], Ensure That The Exception is propagated to the caller.

[AutoComplete] Methods

For Methods Marked with the AutoComplete Attribute, Do Either of the Following:

· Propagate The Sqlexception Back Up The Call Stack.

Wrap the Sqlexception in an Outer Exception and Propagate That To the Caller. You might Want to Wrap The Exception in an Exception Type That Is More Meaningful to the Caller.

Failure to propagate the exception will result in the object not voting to abort the transaction, despite the database error. This means that other successful operations made by other objects sharing the same transaction stream might be committed.

The following code catches a SqlException and then propagates it directly to the caller. The transaction will ultimately abort because this object's consistent flag will automatically be set to false when it is deactivated. [AutoComplete]

Void someMethod ()

{

Try

{

// Open the connection, and perform Database Operation

.

}

Catch (SQLEXCEPTION SQLEX)

{

LOGEXCEPTION (SQLEX); // Log the Exception Details

Throw; // Rethrow the Exception, Causeing the consistent

// flag to be set to false.

}

Finally

{

// Close The Database Connection

.

}

}

NON- [AutoComplete] Methods

For methods not marked with the autocplete attribute, you must:

· Call Contextutil.Setabort WTHIN The Catch Block to vote to abort the transaction. This sets the consistent flag to false.

Call ContextUtIl.SetComplete if An Exception Doesn't '' occur to vote to commit the transaction. This set The consistent flag to true (ITS default state).

The Following Code Illustrates this approach.

Void someharmthod ()

{

Try

{

// Open the connection, and perform Database Operation

.

Contextutil.setComplete (); //manually vote to commit the transport

}

Catch (SQLEXCEPTION SQLEX)

{

LOGEXCEPTION (SQLEX); // Log the Exception Details

Contextutil.Setabort (); // manally vote to abort the transaction

// Exception is Handled At this point and is not propagated to the caller

}

Finally

{

// Close The Database Connection

.

}

}

Note If you have multiple catch blocks, it is easier to call ContextUtil.SetAbort once at the start of a method, and call ContextUtil.SetComplete at the end of the try block. In this way, you do not need to repeat the call to ContextUtil.SetAbort within every catch block. The setting of the consistent flag determined by these methods has significance only when the method returns.You must always propagate exceptions (or wrapped exceptions) back up the call stack because this makes the calling code aware that the transaction will fail. This allows the calling code to make optimizations. For example, in a bank funds transfer scenario, the transfer component could decide not to perform the credit operation if the debit operation has already failed.

If you set the consistent flag to false and then return without throwing an exception, the calling code has no way of knowing that the transaction is bound to fail. Although you could return a Boolean value or set a Boolean output parameter, you should be consistent And throw an exception to indeption. this Leads to cleaner and more consistent code with a standard approach to error handling.

Data Paging

Paging through data is a common requirement in distributed applications. For example, the user might be presented with a list of books where it would be prohibitive to display the entire list at once. The user will want to perform familiar activities on the data, such .

. T..............

Comparing the options

The Options for Data Paging Are:

Using the Fill Method of the SqldataAdapter to Fill A Dataset With A Range of Results from a Query · Using Ado Through COM Interoperability and use a Server-Side Cursor

Using Stored Procedures To Implement Data Paging Manually

The Best Option for Paging Your Data IS Dependent on The Factors listed Below:

· Scalability Requirements

Performance Requirements

· NetWork Bandwidth

· Database Server Memory and Power

· Middle-Tier Server Memory and Power

Number of rows returned by a query you want to page

Size of Your Data Pages

Performance tests have shown that the manual approach using stored procedures offers the best performance across a wide range of stress levels. However, as the manual approach performs its work on the server, server stress levels can become a significant issue if a large proportion of your Site's FunctionAlity Relies Upon Data Paging Functionality. To Ensure That This Approach Suits your particular Environment, You Should Test All Options Against Your Specific Requirements.

The Various Options Are Discussed Below.

Using the Fill Method of SqlDataAdapter

AS Previously Discussed, The SqldataAdapter IS Used To Fill A DataSet with Data from A Database. One of the overloaded Fill Methods (Shown In The Following Code) Takes Two Integer Index Values.

Public Int Fill

DataSet DataSet,

Int StartRecord,

Int MaxRecords,

String Srctable

);

The startRecord value indicates the zero-based index of the start record. The maxRecords value indicates the number of records, starting from startRecord, to copy into the new DataSet.Internally, the SqlDataAdapter uses a SqlDataReader to execute the query and return the results. The SqlDataAdapter reads the results and creates a DataSet based on the data read from the SqlDataReader. The SqlDataAdapter copies all of the results through startRecord and maxRecords into a newly generated DataSet and discards the results that it does not need. This means that a lot Of Unnecessary Data Could Potentially Be Pulled Across The Network To The Data Access Client, Which Is The Primary Drawback to this approach.

For example, if you have 1,000 records and want records 900 through 950, the first 899 records are still pulled across the network and discarded on the client side. This overhead would probably be minimal for small result sets, but could be significant when you page THROUGH LARGER SETS OF DATA.

USING ADO

Another option for implementing paging is to use COM-based ADO to do the paging. The primary motivation behind this option is to gain access to server-side cursors, which are exposed through the ADO Recordset object. You can set the Recordset cursor location to adUseServer. If your OLE DB provider supports it (SQLOLEDB does), this will result in the use of a server-side cursor. You can then use this cursor to navigate to the starting record directly without having to pull all of the records across the NetWork to the data access client code.

There Are Two Primary DrawBacks to this approach:

· In most cases, you will want to translate the records returned in the Recordset object into a DataSet for use in your client managed code. Although OleDbDataAdapter does overload the Fill method to take an ADO Recordset object and translate that into a DataSet, there is no facility to start and end with a particular record. The only realistic option is to move to the start record in the Recordset object, loop through each record, and manually copy the data to a new manually generated DataSet. It is possible that doing this , particularly through the overhead of COM Interop calls, will more than negate the benefits of not pulling extra data across the network, especially for small DataSet (s). · During the time it takes to pull the data that you want from the server, You Hold Open A Connection and a Server-Side Cursor. Cursors Are Typically An Expensive Resource To Open and Maintain on A Database Server. Althought Might Increase Your PE RFORMANCE, IT IS Also Likey to Diminish Your Scalability by Consuming Valuable Resources ON The Server for Extended Periods of Time.

USING a Manual Implementation

The final option discussed in this section for paging through your data is to manually implement paging functionality for your application through the use of stored procedures. For tables that contain a unique key, you can implement the stored procedure relatively easily. For tables without a unique Key (and You Shouldn't Have Many of Those), The Process Is More Complicated.

Paging against a Table with a unique key

If your table contains a unique key, you can use the key in a WHERE clause to create a result set starting from a specific row. This, coupled with the SET ROWCOUNT statement or the SQL Server TOP statement used to restrict the size of the result Set, Provides An Effective Paging Mechanism. This Approach Is Illustrate In The Following Stored Procedure: Create Procedure GetProductSpaged

@LastProductId Int,

@PageSize Int

AS

Set rowcount @PageSize

SELECT *

From product

Where [Standard Search Criteria]

And Productid> @LastProductID

Order by [criteria That Leaves Productid Monotonically Increasing]

Go

The Caller of this Stored Procedure Simply Maintains The LastProductid Value and increments OR Decrements It by The Chosen page size Between Successive Calls.

Paging Against a Table without a unique key

If the table through which you want to page does not have a unique key, consider adding one-for example, by using an identity column. This will enable you to implement the paging solution discussed previously.

IT Is Still Possible to Implement An Effective Paging Solution for a Table with No Unique Key, As Long As You Can Generate Uniqueness by Combining Two or More Other Fields That Are Part of The Result Set.

For Example, Consider The Following Table:

COL1

COL2

COL3

Other columnsç

A

1

W

ç

A

1

X

ç

A

1

Y

ç

A

1

Z

ç

A

2

W

ç

A

2

X

ç

B

1

W

ç

B

1

X

ç

With this table, it is possible to generate uniqueness by combining Col1, Col2, and Col3. As a result, you can implement a paging mechanism by using the approach illustrated in the following stored procedure.

Create Procedure RetrievedataPaged

@LastKey Char (40),

@PageSize Int

AS

Set rowcount @PagesizesEct

COL1, Col2, Col3, Col4, Col1 Col2 Col3 As Keyfield

From SampleTable

Where [Standard Search Criteria]

And Col1 Col2 Col3> @LastKey

Order By Col1 ASC, Col2 ASC, Col3 ASC

Go

.

Although the manual implementation increases the strain placed on the database server, it avoids passing unnecessary data over the network. Performance tests have shown this approach to work well across a range of stress levels. However, depending on how much of the work of your site involves data paging functionality, performing manual paging on the server might impact the scalability of your application. you should run performance tests in your own environment to find the optimum approach for you specific application scenario.

Appendix

How to enable Object Construction for a .NET Class

You Can Enable a .NET Managed Class for Object Construction By Using Enterprise (COM ) Services).

To Enable a .NET Managed Class

1. Derive Your Class from The ServicedComponent Class Located in The System.EnterpriseServices Namespace.

2. Using system.enterprises;

3. Public Class DataAccessComponent: ServicesDComponent

4. Decorate your class with the ConstructionEnabled attribute, and optionally specify a default construction string. This default value is held in the COM catalog. Administrators can use the Component Services Microsoft Management Console (MMC) snap-in to maintain the value.

5. [Constructionenabled (Default = "default DSN")] 6. Public Class DataAccessComponent: ServicesDComponent

7. Provide an overridden implementation of the virtual Construct method. This method is called after the object's language-specific constructor. The construction string maintained in the COM catalog is supplied as the single argument to this method.

8. Public override void construct (String ConstructionString)

9. {

10. // Construct Method Is Called Next After Constructionor.

11. // The configured dsn is support as the single argument

12.}

13. Provide a strong name for the assembly by signing it through the AssemblyKey file or AssemblyKeyName attribute. Any assembly registered with COM services must have a strong name. For more information about strong-named assemblies, see http://msdn.microsoft. COM / library / en-us / cpguidnf / html / cpconworkingwithstrongly-namedassemblies.asp.

14. [Assembly: AssemblyKeyFile ("Dataservices.snk")]]

15. To support dynamic (lazy) registration, use the assembly-level attributes ApplicationName and ApplicationActivation to specify the name of the COM application used to hold assembly components and the application's activation type, respectively For more information about assembly registration, see http.: //msdn.microsoft.com/library/en-us/cpguidnf/html/cpconregisteringservicedComponents.asp.

16. // The ApplicationName Attribute Specifies The Name of The Name of Thae

17. // COM Application Which Will Hold Assembly Components

18. [Assembly: ApplicationName ("Dataservices")]]]]

19.

20. // The applicationActivation.ActivationOption Attribute Specifies21. // Where assembly company

22. // Library: Components Run in The Creator's Process

23. // Server: Components Run in a System Process, DLLHOST.EXE

24. [Assembly: ApplicationActivation]]

The Following Code Fragment Shows A Servic Component Called DataAccessComponent, Which Uses COM Construction Strings To Obtain A Database Connection String.

Using system;

Using system.enterprises;

// the applicationname attribute specifies the name of the name

// COM Application Which Will Hold Assembly Components

[Assembly: ApplicationName ("Dataservices")]]]

// the applicationActivation.ActivationOption Attribute Specifies

// WHERE Assembly Components Are Loaded ON Activation

// Library: Components Run in The Creator's Process

// Server: Components Run in a System Process, Dllhost.exe

[assmbly: ApplicationActivation (ActivationOption.Library)]

// sign the assembly. The snk key file is created Using the THE

// sn.exe utility

[Assembly: askEMBLYKEYFILE ("Dataservices.snk")]]

[Constructionenabled (default = "default dsn")]

Public Class DataAccessComponent: ServicesDComponent

{

PRIVATE STRING CONNECTIONSTRING;

Public DataAccessComponent ()

{

// Constructor is Called On Instance Creation

}

Public override void construct (String ConstructionString)

{

// Construct Method Is Called Next After Constructionor.

// the configured dsn is supplished as the single argument

THIS.CONNECTIONSTRING = ConstructString;

}

}

How to use a sqldataadapter to Retrieve Multiple Rows

The following code illustrates how to use a SqlDataAdapter object to issue a command that generates a DataSet or DataTable It retrieves a set of product categories from the SQL Server Northwind database.using System.Data.;

Using system.data.sqlclient;

Public DataTable RetrieverowswithDataTable ()

{

Using (SqlConnection Conn = New SqlConnection (Connectionstring))

{

Cn.open ();

SQLCommand cmd = new SQLCommand ("DatretrieveProducts", Conn;

cmd.commandtype = commandtype.storedProcedure;

SqlDataAdapter Adapter = New SqldataAdapter (CMD);

DataTable DataTable = New DataTable ("Products");

Adapter .fill (DataTable);

Return DataTable;

}

}

To Use a sqladapter to generate a dataset or dataable

1. CREATE A SQLCOMMAND OBJECT TO INVOKE The Stored Procedure and Associate This with a SqlConnection Object (Shown) or Connection String (Not Shown).

2. Create a new sqldataadapter Object and associate it with the sqlcommand object.

3. CREATE A DATATABLE (OR OPTIONALLY, A DATASET) Object. Use a constructor argument to name the datable.

4. Call The Fill Method of The SqldataAdapter Object To Populate Either The Dataset OR DataTable with The Retrieved Rows.

How to use a sqldatareader to retrieve multiple Rows

The SqlDataReader Approach To Retrieve Multiple Rows Is Illustrate In The Following Code Fragment.

Using system.io;

Using system.data;

Using system.data.sqlclient;

Public SqlDataReader RetrieverowswithDataReader ()

{

SqlConnection conn = new SQLCONNECTION

"Server = (local); Integrated Security = SSPI; Database = Northwind");

Sqlcommand cmd = new sqlcommand ("DATRETRIEVEPRODUCTS", CONN); cmd.commandtype = commandType.StoredProcedure;

Try

{

Cn.open ();

// generate the reader. ComMMandbehavior.closeConnection Causes the

// the connection to be closed when the reader object is closed

Return (cmd.executeReader (CMMANDBEHAVIOR.CLOSECONNECONNECONNECONNECONNECONNECONNECONNECTION);

}

Catch

{

CONN.CLOSE ();

Throw;

}

}

// Display the Product List sale the console

Private void displayproducts ()

{

SqldataReader Reader = RetrieverowswithDataReader ();

Try

{

While (Reader.Read ())

{

Console.writeline ("{0} {1} {2}",

Reader.GetInt32 (0) .tostring (),

Reader.getstring (1));

}

}

Finally

{

Reader.close (); // Also Closes The Connection Due To The Connection Due To

// Commandbehavior Enum Used Whenrating The Reader

}

}

To Retrieve Rows with a SqldataReader

1. CREATE A SQLCOMMAND OBJECT Used to Execute The Stored Procedure and Associate It With a SqlConnection Object.

2. Open the Connection.

3. Generate a SqldataReader Object by calling the executeReader Method of a SqlCommand Object.

4. To read the data from the stream, call the Read method of the SqlDataReader object to retrieve rows and use the typed accessor methods (such as the GetInt32 and GetString methods) to retrieve the column values.

5. WHEN You Finish with the reader, Call ITS Close Method.

How to use an xmlreader to retrieve multiple rows

You can use the SqlCommand object to generate an XmlReader object, which provides forward-only, stream-based access to XML data. The command (usually a stored procedure) must generate an XML-based result set, which for SQL Server 2000 usually consists Of a select statement with a valid for xml clause. The following code fragment illustrates this approach: public void retrieveandDisplayRowsWithXMLReader ()

{

Using (SqlConnection Conn = New SqlConnection (Connectionstring))

{;

Sqlcommand cmd = new sqlcommand ("DATRETRIEVEPRODUCTSXML", CONN);

cmd.commandtype = commandtype.storedProcedure;

Try

{

Cn.open ();

XmlTextReader XReader = (XMLTextReader) cmd.executexmlreader ();

While (XReader.Read ())

{

IF (XReader.name == "Products")

{

String stroutput = xreader.getattribute ("productID");

Stroutput = ""

Stroutput = xreader.getattribute ("productname");

Console.writeLine (stroutput);

}

}

XReader.close (); // XmlTextReader Does Not Support Idisposable So It Can't Be

// used within a using keyword

}

}

The Following Code Uses The Following Stored Procedure:

Create Procedure DatretrieveProductsXML

AS

Select * from products

For xml auto

Go

To Retrieve XML Data with An XmlReader

.

2. Call the ExecuteXmlReader method of the SqlCommand object and assign the results to a forward-only XmlTextReader object. This is the fastest type of XmlReader object that you should use when you do not require any XML-based validation of the returned data.3 . Read The data by using the read method of the xmltextreader object.

How To Use Stored Procedure Output Parameters to Retrieve A Single Row

You can call a stored procedure that returns the retrieved data items within a single row by means of named output parameters. The following code fragment uses a stored procedure to retrieve the product name and unit price for a specific product contained in the Products table in the Northwind Database.

Void getProductDetails (int products)

Out String ProductName, Out Decimal Unitprice

{

Using (SqlConnection Conn = New SqlConnection)

"Server = (local); integrated security = sspi; database = northwind"))

{

// set up the command Object used to execute the stored proc

SQLCommand cmd = new SQLCommand ("DatgetProductDetailsSpoutput", CONN)

cmd.commandtype = commandtype.storedProcedure;

// establish stored proc parameters.

@ProductID Int Input

@ProductName Nvarchar (40) Output

@Unitprice Money Output

// Must Explicitly Set The Direction of Output Parameters

Sqlparameter paramprodid =

Cmd.Parameters.Add ("@ProductID", ProductID;

Paramprodid.direction = parameterdirection.input;

Sqlparameter paramprodname =

CMD.Parameters.Add ("@ProductName", SqldbType.varchar, 40);

ParamProdname.direction = parameterDirection.output;

Sqlparameter paramunitprice =

CMD.Parameters.Add ("@unitprice", sqldbtype.money); paramunitprice.direction = parameterdirection.output;

Cn.open ();

// Use ExecutenonQuery to run the commit.

// Alth No Rows Are Returned Any Mapped Output Parameters

// (and potentially returnes) Are Populate

cmd.executenonquery ();

// Return Output Parameters from stored Proc

ProductName = paramprodname.value.toString ();

Unitprice = (decimal) paramunitprice.value;

}

}

To Retrieve A Single Row with Stored Procedure Output Parameters

1. CREATE A SQLCOMMAND OBJECT AND ASSOCIATE IT WITH A SQLCONNECTION OBJECT.

2. Set up the stored procedure parameters by calling the Add method of the SqlCommand's Parameters collection. By default, parameters are assumed to be input parameters, so you must explicitly set the direction of any output parameters.

Note It is Good Practice to Explicitly Set The Direction of All Parameters, Including Input Parameters.

3. Open the Connection.

4. Call The ExecutenonQuery Method of The Sqlcommand Object. This Populates The Output Parameters (AND Potentially a return value).

5. Retrieve The Output Parameters from the appropriate Sqlparameter Objects by using the value.

6. Close The Connection.

The Preceding Code Fragment Invokes The Following Stored Procedure.

Create Procedure DatgetProductDetailsspoutput

@ProductID INT,

@ProductName Nvarchar (40) Output,

@Unitprice Money Output

AS

SELECT @ProductName = ProductName,

@Unitprice = Unitprice

From product

Where productid = @ProductID

Go

How to use a sqldatareader to retrieve a single row

You can use a SqlDataReader object to retrieve a single row, and specifically the desired column values ​​from the returned data stream. This is illustrated in the following code fragment.void GetProductDetailsUsingReader (int ProductID,

Out String ProductName, Out Decimal Unitprice

{

Using (SqlConnection Conn = New SqlConnection)

"Server = (local); integrated security = sspi; database = northwind"))

{

// set up the command Object used to execute the stored proc

Sqlcommand cmd = new sqlcommand ("DatgetProductDetailsReader", CONN);

cmd.commandtype = commandtype.storedProcedure;

// establish stored proc parameters.

@ProductID Int Input

Sqlparameter paramprodid = cmd.parameters.add ("@ProductID", ProductID;

Paramprodid.direction = parameterdirection.input;

Cn.open ();

Using (SqlDataReader Reader = cmd.executeReader ())

{

IF (Reader.Read ()) // Advance to the One and Only Row

{

// Return Output Parameters from Returned Data Stream

ProductName = Reader.getstring (0);

Unitprice = reader.getDecimal (1);

}

}

}

}

TO RETURN A SINGLE ROW with A SQLDATAREADER OBJECT

1. Establish The Sqlcommand Object.

2. Open the Connection.

3. Call The ExecuteReader Method of The SqldataAder Object.

4. Retrieve Output Parameters through the Typed Accessor Methods of the TypedArEader Object-in this case, getString and getDecimal.

The Preceding Code Fragment Invokes The Following Stored Procedure.

CREATE Procedure DatgetProductDetailsReader

@ProductID Int

AS

Select ProductName, Unitprice from Products

Where productid = @ProductID

Go

How to Use ExecuteScalar to Retrieve a Single ItemThe ExecuteScalar method is designed for queries that return only a single value. In the event of the query returning multiple columns and / or rows, ExecuteScalar returns only the first column of the first row.

The Following Code Shows How To Look Up The Product Name for a Specific Product ID:

Void getProductNameexecutescalar (int Productid, Out String ProductName)

{

Using (SqlConnection Conn = New SqlConnection)

"Server = (local); integrated security = sspi; database = northwind"))

{

Sqlcommand cmd = new SQLCOMMAND ("LookuppproductNamescalar", Conn;

cmd.commandtype = commandtype.storedProcedure;

Cmd.Parameters.Add ("@ ProductID", ProductId;

Cn.open ();

ProductName = (string) cmd.executescalar ();

}

}

To Use Executescalar To Retrieve A Single Item

1. Establish a SqlCommand Object to Call A Stored Procedure.

2. Open the Connection.

3. Call The Executescalar Method. Notice That Method Returns An Object Type. This Contains The Value of The First Column Retrieved and Must Be Cast To The Appropriate Type.

4. Close The Connection.

The Following Code Uses The Following Stored Procedure:

Create Procedure LookuppproductNamescalar

@ProductID Int

AS

SELECT TOP 1 ProductName

From product

Where productid = @ProductID

Go

How to use a stored procedure Output or return parameter to Retrieve A Single Item

You CAN Look Up A Single Value by Using A Stored Procedure Output Or Return Parameter. Use of an output parameter is illustrate in The Following Code:

Void getProductNameusingsingsPoutPut (int ProductId, Out String ProductName)

{

Using (SqlConnection Conn = New SqlConnection)

"Server = (local); integrated security = sspi; database = northwind"))

{

Sqlcommand cmd = new SQLCommand ("LookuppproductNamesPoutput", CONN);

cmd.commandtype = commandtype.storedProcedure;

SQLParameter paramprodid = cmd.parameters.add ("@ productID", productID;

Paramprodid.direction = parameterdirection.input;

Sqlparameter parampn =

CMD.Parameters.Add ("@ ProductName", SqldbType.varchar, 40);

PARAMPN.DIRECTION = parameterDirection.output;

Cn.open ();

cmd.executenonquery ();

ProductName = parampn.value.tostring ();

}

}

To Retrieve A Single Value with a stored Procedure Output Parameter

1. Establish a Sqlcommand Object To Call The Stored Procedure.

2. SET UP Any INPUT Parameters and The Single Output Parameter by Adding Sqlparameters to the Sqlcommand's Parameters Collection.

3. Open the Connection.

4. Call The ExecutenonQuery Method of The SqlCommand Object.

5. Close The Connection.

6. Retrieve The Output Value by Using The Value Property of The Output SqlParameter.

The Following Code Uses The Following Stored Procedure.

Create Procedure LookuppRoductNamespoutput

@ProductID INT,

@ProductName Nvarchar (40) Output

AS

SELECT @ProductName = ProductName

From product

Where productid = @ProductID

Go

The following code illustrates the use of a return value to indicate whether a particular row exists. From a coding perspective, this is similar to using stored procedure output parameters, except that you must explicitly set the SqlParameter direction to ParameterDirection.ReturnValue.bool CheckProduct ( int productID)

{

Using (SqlConnection Conn = New SqlConnection)

"Server = (local); integrated security = sspi; database = northwind"))

{

Sqlcommand cmd = new sqlcommand ("CheckProductSP", CONN);

cmd.commandtype = commandtype.storedProcedure;

Cmd.Parameters.Add ("@ ProductID", ProductId;

Sqlparameter paramret =

Cmd.Parameters.Add ("@ productuctexists", sqldbtype.int;

Paramret.direction = parameterDirection.ReturnValue;

Cn.open ();

cmd.executenonquery ();

}

Return (int) paramret.value == 1;

}

To Check WHether a Particular Row EXSTS BY Using A Stored Procedure Return Value

1. Establish a Sqlcommand Object To Call The Stored Procedure.

2. SET UP An Input Parameter That Contains The Primary Key Value of The Row Be Accessed.

3. SET UP The Single Return Value Parameter. Add A Sqlparameter Object To The Sqlcommand's Parameters Collection, and Set ITS Direction to ParameterDirection.ReturnValue.

4. Open the connection.

5. Call The ExecutenonQuery Method of the Sqlcommand Object.

6. Close The Connection.

7. Retrieve the return value by using the value.................

The Following Code Uses The Following Stored Procedure.

Create Procedure CheckProductSP

@ProductID Int

AS

IF EXISTS (SELECT ProductidFrom Products

Where produter = @ProductID)

Return 1

Else

Return 0

Go

How to use a sqldatareader to Retrieve A Single Item

You can use a SqlDataReader object to obtain a single output value by calling the ExecuteReader method of the command object. This requires slightly more code because the SqlDataReader Read method must be called, and then the desired value is retrieved through one of the reader's accessor methods . Use of a sqldatarader object is illustrate in the folowing code.

Bool CheckProductWithreader (int products)

{

Using (SqlConnection Conn = New SqlConnection)

"Server = (local); integrated security = sspi; database = northwind"))

{

Sqlcommand cmd = new sqlcommand ("CheckProductexistSwithcount", conn);

cmd.commandtype = commandtype.storedProcedure;

Cmd.Parameters.Add ("@ ProductID", ProductId;

CMD.Parameters ["@ productID"]. Direction = parameterdirection.input;

Cn.open ();

Using (SqlDataReader Reader = cmd.executeReader)

Commandbehavior.sing Leresult)))

{

IF (Reader.Read ())

{

Return (Reader.GetInt32 (0)> 0);

}

Return False;

}

}

The preceding code assumes the folowing stored procedure.

Create Procedure CheckProductexistSwithcount

@ProductID Int

AS

Select Count (*) from Products

Where productid = @ProductID

Go

How to code ado.net manual transactions

The following code shows how to take advantage of the transaction support offered by the SQL Server .NET Data Provider to protect a funds transfer operation with a transaction. This operation transfers money between two accounts located in the same database.

Public void TransferMoney (String toaccount, String fromaccount, Decimal Amount) {

Using (SqlConnection Conn = New SqlConnection)

"Server = (local); Integrated Security = SSPI; Database = SimpleBank"))

{

Sqlcommand cmdcredit = new SQLCOMMAND ("Credit", CONN);

cmdcredit.commandtype = commandtype.storedProcedure;

Cmdcredit.Parameters.Add (New SqlParameter ("@ Accountno", toaccount);

Cmdcredit.Parameters.Add (New Sqlparameter);

Sqlcommand cmddebit = new sqlcommand ("debit", conn);

CMDDebit.commandtype = commandtype.storedProcedure;

Cmddebit.Parameters.add (New Sqlparameter ("@ Accountno", fromaccount);

Cmddebit.Parameters.Add (New Sqlparameter);

Cn.open ();

// start a new transaction

Using (SqlTransaction Trans = Conn.BegintransAction ())

{

// Associate the two of the sand of the Same Transaction

Cmdcredit.transaction = trans;

Cmddebit.Transaction = Trans;

Try

{

cmdcredit.executenonquery ();

Cmddebit.executenonquery ();

// Both Commands (Credit and Debit) WERE SUCCESSFUL

TRANS.COMMIT ();

}

Catch (Exception EX)

{

// Transaction Failed

TRANS. ROLLBACK ();

// log exception details.

Throw EX;

}

}

}

}

How To Perform Transactions with Transact-SQL

.

Create Procedure MoneyTransfer

@Fromaccount Char (20),

@Toaccount Char (20),

@Amount Money

AS

Begin Transaction

- Perform Debit Operation

Update Accounts

Set balance = balance - @amount

Where accountnumber = @Fromaccount

IF @@ rowcount = 0

Begin

Raiserror ('Invalid from Account Number', 11, 1)

Goto Abort

End

Declare @Balance Money

SELECT @Balance = Balance from Accounts

Where accountnumber = @Fromaccount

IF @balance <0

Begin

Raiserror ('Insufficient Funds', 11, 1)

Goto Abort

End

- Perform Credit Operation

Update Accounts

Set balance = balance @amount

Where accountnumber = @toaccount

IF @@ rowcount = 0

Begin

Raiserror ('Invalid To Account Number', 11, 1)

Goto Abort

End

Commit transaction

Return 0

Abort:

Rollback Transaction

Go

THIS THE BEGIN TRANSACTION, AND ROLLBACK Transaction Statements To Manually Control The Transaction.

How To Code a Transactional .NET CLASS

The following example code shows three serviced .NET managed classes that are configured for automatic transactions. Each class is annotated with the Transaction attribute, whose value determines whether or not a new transaction stream should be started or whether the object should share the stream of its immediate caller. These components work together to perform a bank money transfer. The Transfer class is configured with the RequiresNew transaction attribute, and the Debit and Credit classes are configured with Required. As a result, at run time all three objects will share the same TRANSACTION.

Using system;

Using system.enterprises;

Transaction (TransactionOption.Requiresnew)]

Public Class Transfer: ServicedComponent

{

[AutoComplete]

Public void Transfer (String toaccount,

String fromaccount, Decimal AMOUNT)

{

Try

{

// perform the debit operation

DEBIT Debit = New Debit ();

Debit.debitaccount (fromaccount, amount); // perform the credit operation

Credit Credit = New Credit ();

Credit.creditaccount (Toaccount, Amount);

}

Catch (SQLEXCEPTION SQLEX)

{

// Handle and Log Exception Details

// Wrap and Propagate the Exception

Throw New TransferaXception ("Transfer Failure", SQLEX);

}

}

}

[Transaction (TransactionOption.Required)]

Public Class Credit: ServicedComponent

{

[AutoComplete]

Public void Creditaccount (String Account, Decimal Amount)

{

Try

{

Using (SqlConnection Conn = New SqlConnection)

"Server = (local); integrated security = SSPI"; Database = "SimpleBank"))

{

Sqlcommand cmd = new sqlcommand ("CREDIT", CONN)

cmd.commandtype = commandtype.storedProcedure;

Cmd.Parameters.Add (New Sqlparameter ("@ Accountno", Account);

cmd.Parameters.Add (New Sqlparameter);

Cn.open ();

cmd.executenonquery ();

}

}

} catch (sqlexception sqlex) {

// log exception details here

Throw; // Propagate Exception

}

}

[Transaction (TransactionOption.Required)]

Public Class Debit: ServicedComponent

{

Public void debitaccount (String Account, Decimal Amount)

{

Try

{

Using (SqlConnection Conn = New SqlConnection)

"Server = (local); integrated security = SSPI"; Database = "SimpleBank"))

{

SQLCommand cmd = new sqlcommand ("debit", conn);

cmd.commandtype = commandtype.storedProcedure;

Cmd.Parameters.Add (New Sqlparameter ("@ Accountno", Account);

cmd.Parameters.Add (New Sqlparameter);

Cn.open ();

cmd.executenonquery ();

}

}

Catch (SQLEXCEPTION SQLEX)

{

// log exception details here

Throw; // Propagate Exception Back to Caller

}

}

}

Collaborators

Many Thanks to the Following Contributors and reviewers:

Bill Vaughn, Mike Pizzo, Pablo Castro, Doug Rothaus, Kevin White, Blaine Dokter, David Schleifer, Graeme Malcolm (Content Master), Bernard Chen (Sapient), Matt Drucker (Turner Broadcasting), Steve Kirk, David Sceppa, Scott Densmore, Diego González (Lagash Systems)

To Learn More About .NET BEST PRACTICES, PLEASE VIT THE PATTERNS & PRACTICCIES Web Page.

To participate in an online collaborative development environment on this topic, join the GotDotNet workspace:. Microsoft Patterns & Practices Data Access for .NET Workspace Please share your Data Access Block questions, suggestions, and customizations with the community in this workspace.

Questions? Comments? Suggestions? For feedback on the content of this article, please e-mail us at devfdbck@microsoft.com.

转载请注明原文地址:https://www.9cbs.com/read-120899.html

New Post(0)