This article provides guidelines for implementing ADO.NET-based data access layers in multi-layer .NET applications ... Overview: This article provides ADO.NET-based data access in multi-layer .NET applications. The guiding principle of the layer. Its focus is a set of universal data access tasks and scenarios, and guides you to choose the most appropriate way and technology (68 print pages). Introduction If you design a data access layer for .NET application, you should use Microsoft ADO.NET as a data access model. ADO.NET extension is rich and supports combined with loose data access requirements, multi-layer web applications, and web services. Typically, it takes advantage of many extended object models, ADO.NET provides a variety of ways to address a specific issue. This article will guide you to choose the most appropriate data access method, which is to list a wide range of universal data access programs, providing techniques, and suggesting optimal practices. This article also answered other frequently asked questions: Where is it best to store database link strings? How should I achieve a link storage pool? How to deal with transactions? How to implement paging to allow users to scroll in many records? Note The focus of this article is ADO.NET: one of the two suppliers provided with SQL Server .NetData Provider - to access Microsoft SQL Server 2000 with ADO.NET - Access Microsoft SQL Server 2000. In the right place, you need to pay attention to all the differences you need to use when you use the OLE DB .NET data supplier to access other OLE DB sensitive data sources. For the Data Access Application Block data access application blocks for the specific implementation of the data access components developed by the guidelines discussed herein and the optimal practice. Note that the source code of this implementation is available and can be used directly in your .NET application. Who should read this article? This article provides guidelines for application designers and corporate developers who wish to build .NET applications. If you are responsible for designing and developing a multi-layer .NET application, please read this article. What do you need to know? To build a .NET application using this guide, you must have the actual experience of using the ActiveX Data Object (ADO) and / or OLE DB to develop data access code, and SQL Server experience. You must also understand how to develop management code for the .NET platform, and must also know the basic changes introduced by the ADO.NET data access model. ADO.NET Introduction ADO.NET is the data access model of the .NET application. It can be used to access relational database systems, such as SQL Server 2000, and many other data sources that have OLE DB supplies. To a certain extent, ADO.NET represents the latest version of ADO technology. However, ADO.NET introduces some major changes and innovations, which are specifically used to loose, essentially non-linking web applications. For the comparison of ADO and ADO.NET, see "ADO.NET" used for ADO programmers in MSDN. An important change introduced by ADO.NET is that the ADO Recordset object is replaced with a combination of DataTable, DataSet, DataAdapter, and DataReader objects. DataTable represents a collection of rows from a table, which is similar to Recordset. DataSet represents the collection of DataTable objects and the relationships and restrictions that are bound to other tables. In fact, DataSet is an associated structure in memory supported by built-in extended marker language (XML). One of the main features of DataSet is that it does not know anything about the underlying data source, and these data sources may be used to fill them. This is an isolated independent entity for indicating data sets, and it can be passed from one component to another by different layers of a multi-layer application.
It can also be serialized as an XML data stream, so it is ideal for data transmission between different types of platforms. ADO.NET uses the DataAdapter object to create channels to send to data from DataSet and underlying data sources. The DataAdapter object also supports enhanced batch update features, before this is the Recorder's related functions. Figure 1 shows a complete DataSet object model. Figure 1 DataSet object model .NET data supplier ADO.NET relies on the service of the .NET data supply. They provide access to the underlying data source, including four main objects (Connection, Command, DataReader, and DataAdapter), currently, ADO.NET only releases two suppliers: SQL Server .NET data supplier. This is a supplier for Microsoft SQL Server 7.0 and its later version of the database, which optimizes access to SQL Server, and communicates with SQL Server with SQL Server's built-in data conversion protocol. This supplier is always used when linking to SQL Server 7.0 or SQL Server 2000. OLE DB .NET data supplier. This is a supplier for managing OLE DB data sources. Its efficiency is slightly lower than SQL Server .NET Data Provider, because when communicating with the database, it needs to be called via the OLE DB layer. Note that this supplier does not support OLE DB supplies for open database links (ODBC), MSDasql. For ODBC data sources, ODBC .NET data supplies should be used. A list of OLE DB supplies compatible with the ADO.NET. Other .NET data supplies in the current beta version include:
ODBC .NET data supplier. At present, Beta version 1.0 is available for download. It provides built-in access to the ODBC drive, which is the same as the accessibility of the local OLE DB supplies provided with the OLE DB .NET data vendor. More information about ODBC .NET and BETA download are shown. Used to get an XML management supplier from SQL Server 2000. The XML for SQL Server Web Upgrade 2 has also included a management vester for use from SQL Server 2000 to get XML. For more information on this upgraded version, see. Name Space Organization is located in its respective namespaces related to each .NET data vendor:
System.data.sqlclient. The SQL Server .NET data vendor type is included. System.Data.OLDB. The OLE DB .NET data supply type is included. System.data.odbc. The ODBC .NET data supply type is included. System.data. The type of versatile is included, such as DataSet and DataTable. In the respective associated namespace, each supplier provides the implementation of Connection, Command, DataRead, and DataAdapter objects. The SQLClient implementation has a prefix "SQL"; and the OLEDB implementation has a prefix "OLEDB". For example, the SqlClient implementation of the Connection object is SqlConnection. The OLEDB implementation is OLEDBCONNECTION. Similarly, the two implementations of the DataAdapter object are SqlDataAdapter and OLEDBDataAdapter. Universal Programming If you are likely to be targets with different data sources, you can consider IDBConnection, IDBCommand, iDataRead, and IDBDataAd, iDataRead, and IDBDataAd, iDataRead, and IDBDataAd, iDataRead, and IDBDataAdapter to the System.Data Namespace from a data source. The interface is programmed. All implementations of Connection, Command, DataReader, and DataAdapter objects must support these interfaces. Figure 2 shows how data access stack and ADO.NET are associated with other data access technologies, including ADO, and OLE DB. The figure also shows two management suppliers and primary objects in the ADO.NET model. Figure 2 Data Access Stack About ADO to ADO.NET Evolution, See MSDN Magazine November 2000 Article "ADO Introduction: Data Access Service for Microsoft .NET Framework". In most of the code segments of the stored procedure and direct SQL, the SQLCommand object calls stored procedures use the SQLCommand object calls to perform database operations. In some examples, you can't see the SQLCommand object, because the stored procedure name is passed directly to the SqlDataAdapter object, but this will still cause the SQLCommand object to be created. The use of stored procedures instead of SQL statements is that stored procedures usually increase performance because the database can optimize the data access plan used by the process and caching it for future reuse. In the database, the stored procedure can be protected separately. Customers can be given permissions to execute a stored procedure, but there is no right to process the underlying table. The stored procedure will result in a simple maintenance, because in a deployed component, modify the stored procedure is usually simpler than the modified hard-encoded SQL statement. The stored procedure adds a layer extracted from the underlying database structure. The details of the customer and the storage procedure of the stored procedure and the underlying structure are separated. The stored procedure can reduce network traffic because the SQL statement can be performed in a batch process instead of sending multiple requests from the client. The comparison of the attribute and constructor can set the specific attribute value for the ADO.NET object by constructing function parameters or direct setting properties. For example, the following code snippet is equivalent.
// Use constructor arguments to configure command objectSqlCommand cmd = new SqlCommand ( "SELECT * FROM PRODUCTS", conn); // The above line is functionally equivalent to the following // three lines which set properties explicitlysqlCommand cmd = new SqlCommand (); cmd.connection = conn; cmd.comMandText = "Select * from product"; From performance perspective, the difference between the two methods can be ignored, because the property of setting or obtaining the .NET object is effective than the COM object to perform similar operations. many. The choice made is just a personal hobby and coding style. However, it is easy to make the code easy to understand (especially when you are not familiar with the ADO.NET object model), it is easy to debug. Note that VB developers are recommended to avoid creating objects using the "DIM X AS New ..." structure. In a COM environment, these code will cause "short circuit" of the COM object to create a process, producing some wonderful and unsatisfactory mistakes. However, in the .NET environment, this is no longer a problem. Managing Database Link Database Links is a dangerous, expensive, limited resource, especially in multi-layer Web applications. You must manage your link correctly because your method will greatly affect the overall upgrade of the application. Also, you must carefully consider where the link string is stored. You need a configurable, secure location. When managing database links and linking strings, you should work hard: Help implement application scalability by multiplexing a pool database link across multiple customers. Adopt configurable, high-performance link pool strategies. Use Microsoft Windows operating system authentication when accessing SQL Server. Avoid pre-depositing of the intermediate layer. Safely store chain strings. Open the database links later, and close them earlier. This section discusses the link pool and helps you choose the right link pool strategy. Other alternative methods also exist. This section will also consider how to manage, store, and control database link strings. Finally, this section also provides two coding schemes that will help ensure that the link is reliable and returned to the link pool. The link pool database link pool allows the application to reuse the existing links in the pool rather than repeatedly establish links to the database. This technique will greatly increase the scalability of the application, because limited database links can provide services for many customers. This technology will also increase performance because it is possible to avoid huge time to establish a new link. Data Access Technology, such as ODBC and OLE DB, providing a variety of forms of link pools, which can be configured to different levels. These two ways are transparent to database client applications. The OLE DB link pool is often referred to as a session or resource pool. The ADO.NET data supplier provides a transparent link pool, and the exact mechanism of each link pool is different for each of the suppliers. The link pool discussed in this section is about:
SQL Server .NET Data Supplies OLE DB .NET Data Supplier Stored Procedure The Comparison of Direct SQL In most of the code segments of the remainder of this article, the SQLCommand object calls stored procedures are used to perform database operations. In some examples, you can't see the SQLCommand object, because the stored procedure name is passed directly to the SqlDataAdapter object, but this will still cause the SQLCommand object to be created. The reason for using the stored procedure rather than the SQL statement is:
The stored procedure usually increases performance because the database can optimize the data access plan used by the process and caching it for future reuse. In the database, the stored procedure can be protected separately. Customers can be given permissions to execute a stored procedure, but there is no right to process the underlying table. The stored procedure will result in a simple maintenance, because in a deployed component, modify the stored procedure is usually simpler than the modified hard-encoded SQL statement. The stored procedure adds a layer extracted from the underlying database structure. The details of the customer and the storage procedure of the stored procedure and the underlying structure are separated. The stored procedure can reduce network traffic because the SQL statement can be performed in a batch process instead of sending multiple requests from the client. The comparison of the attribute and constructor can set the specific attribute value for the ADO.NET object by constructing function parameters or direct setting properties. For example, the following code snippet is equivalent. // Use constructor arguments to configure command objectSqlCommand cmd = new SqlCommand ( "SELECT * FROM PRODUCTS", conn); // The above line is functionally equivalent to the following // three lines which set properties explicitlysqlCommand cmd = new SqlCommand (); cmd.connection = conn; cmd.comMandText = "Select * from product"; From performance perspective, the difference between the two methods can be ignored, because the property of setting or obtaining the .NET object is effective than the COM object to perform similar operations. many. The choice made is just a personal hobby and coding style. However, it is easy to make the code easy to understand (especially when you are not familiar with the ADO.NET object model), it is easy to debug. Note that VB developers are recommended to avoid creating objects using the "DIM X AS New ..." structure. In a COM environment, these code will cause "short circuit" of the COM object to create a process, producing some wonderful and unsatisfactory mistakes. However, in the .NET environment, this is no longer a problem. Managing Database Link Database Links is a dangerous, expensive, limited resource, especially in multi-layer Web applications. You must manage your link correctly because your method will greatly affect the overall upgrade of the application. Also, you must carefully consider where the link string is stored. You need a configurable, secure location. When you manage database links and link strings, you should work hard:
Help implement application scalability by multiplexing a pool database link across multiple customers. Adopt configurable, high-performance link pool strategies. Use Microsoft Windows operating system authentication when accessing SQL Server. Avoid pre-depositing of the intermediate layer. Safely store chain strings. Open the database links later, and close them earlier. This section discusses the link pool and helps you choose the right link pool strategy. Other alternative methods also exist. This section will also consider how to manage, store, and control database link strings. Finally, this section also provides two coding schemes that will help ensure that the link is reliable and returned to the link pool. The link pool database link pool allows the application to reuse the existing links in the pool rather than repeatedly establish links to the database. This technique will greatly increase the scalability of the application, because limited database links can provide services for many customers. This technology will also increase performance because it is possible to avoid huge time to establish a new link. Data Access Technology, such as ODBC and OLE DB, providing a variety of forms of link pools, which can be configured to different levels. These two ways are transparent to database client applications. The OLE DB link pool is often referred to as a session or resource pool. The ADO.NET data supplier provides a transparent link pool, and the exact mechanism of each link pool is different for each of the suppliers. The link pool discussed in this section is about: SQL Server .NET Data Supplier OLE DB .NET Data Supply Stored Procedure and Direct SQL In most of the code snippet in the remainder of this article, the SQLCommand object calls stored procedure Perform database operations. In some examples, you can't see the SQLCommand object, because the stored procedure name is passed directly to the SqlDataAdapter object, but this will still cause the SQLCommand object to be created. The reason for using the stored procedure rather than the SQL statement is:
The stored procedure usually increases performance because the database can optimize the data access plan used by the process and caching it for future reuse. In the database, the stored procedure can be protected separately. Customers can be given permissions to execute a stored procedure, but there is no right to process the underlying table. The stored procedure will result in a simple maintenance, because in a deployed component, modify the stored procedure is usually simpler than the modified hard-encoded SQL statement. The stored procedure adds a layer extracted from the underlying database structure. The details of the customer and the storage procedure of the stored procedure and the underlying structure are separated. The stored procedure can reduce network traffic because the SQL statement can be performed in a batch process instead of sending multiple requests from the client. The comparison of the attribute and constructor can set the specific attribute value for the ADO.NET object by constructing function parameters or direct setting properties. For example, the following code snippet is equivalent.
// Use constructor arguments to configure command objectSqlCommand cmd = new SqlCommand ( "SELECT * FROM PRODUCTS", conn); // The above line is functionally equivalent to the following // three lines which set properties explicitlysqlCommand cmd = new SqlCommand (); cmd.connection = conn; cmd.comMandText = "Select * from product"; From performance perspective, the difference between the two methods can be ignored, because the property of setting or obtaining the .NET object is effective than the COM object to perform similar operations. many. The choice made is just a personal hobby and coding style. However, it is easy to make the code easy to understand (especially when you are not familiar with the ADO.NET object model), it is easy to debug. Note that VB developers are recommended to avoid creating objects using the "DIM X AS New ..." structure. In a COM environment, these code will cause "short circuit" of the COM object to create a process, producing some wonderful and unsatisfactory mistakes. However, in the .NET environment, this is no longer a problem. Managing Database Link Database Links is a dangerous, expensive, limited resource, especially in multi-layer Web applications. You must manage your link correctly because your method will greatly affect the overall upgrade of the application. Also, you must carefully consider where the link string is stored. You need a configurable, secure location. When managing database links and linking strings, you should work hard: Help implement application scalability by multiplexing a pool database link across multiple customers. Adopt configurable, high-performance link pool strategies. Use Microsoft Windows operating system authentication when accessing SQL Server. Avoid pre-depositing of the intermediate layer. Safely store chain strings. Open the database links later, and close them earlier. This section discusses the link pool and helps you choose the right link pool strategy. Other alternative methods also exist. This section will also consider how to manage, store, and control database link strings. Finally, this section also provides two coding schemes that will help ensure that the link is reliable and returned to the link pool. The link pool database link pool allows the application to reuse the existing links in the pool rather than repeatedly establish links to the database. This technique will greatly increase the scalability of the application, because limited database links can provide services for many customers. This technology will also increase performance because it is possible to avoid huge time to establish a new link. Data Access Technology, such as ODBC and OLE DB, providing a variety of forms of link pools, which can be configured to different levels. These two ways are transparent to database client applications. The OLE DB link pool is often referred to as a session or resource pool. The ADO.NET data supplier provides a transparent link pool, and the exact mechanism of each link pool is different for each of the suppliers. The link pool discussed in this section is about:
SQL Server .NET Data Supplies OLE DB .NET Data Supply SQL Server .NET Data Supply If you are using the SQL Server .NET data supply, you can use the link pool of the links provided by this vendor. It is a highly efficient mechanism that is implemented by the supplier within the management code. Each process will create a pool and until the end, the pool is canceled. You can use this link pool in transparency, but you should clear how the pool is managed and you know which options can be used to adjust the link pool. How to configure SQL Server .NET Data Supply Link Pool You can configure a link pool in the form of a link string using a set of name-value pairs. For example, you can configure whether the pool is valid (default is valid), the pool's maximum, minimum capacity, the queue for opening the link, requested the blockped time. The following example string configures the maximum and minimum capacity of the pool. "Server = (local); integrated security = sspi; data = northwind; Max pool size = 75; min pool size = 5" When the link is opened, the pool is created, multiple links are added to the pool to satisfy the number of links The minimum configured. Thereafter, the link can be added to the pool until the maximum pool count is configured. When the maximum count is reached, the request to open a new link will queue a configurable time. Selecting the pool capacity can establish a maximum limit for a large system that manages thousands of users simultaneously issued a request. You need to monitor the performance of link pools and applications to determine the best pool capacity of the system. The optimal capacity is also dependent on the hardware running SQL Server. During development, you may need to reduce the default maximum pool capacity (currently 100) to help find link leaks. If the minimum pool capacity is set, it will result in some performance loss when the pool is initially filled to reach the value, although several customers who initially link will benefit from it. Note that the process of creating a new link is serialized, which means that when the pool is initially filled, the server cannot handle the simultaneous request. MORE INFORMATION When using the SQL Server .NET Data Supply Link pool, you must clearly: the link is poolized by a method that exactly matches the link string. The poolization mechanism is sensitive to spaces between name-value. For example, the following two link strings will generate a separate pool because the second string contains an additional empty 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 created (extra spaces in string)
In the .NET Framework Beta, the link pool is always invalid when running in the debugger. Inside the debugger, the debug version and the release, the link pool can work properly. The final release (RTM) of the .NET Framework cancels this restriction, the link pool can run in all cases. The link pool is divided into a plurality of transaction-specific pools and a pool for multiple links currently not listed in the transaction. For threads associated with a particular transaction context, the link will be returned from the appropriate pool (including links established with the transaction). This makes it a transparent process using established links. Use the OLE DB .NET Data Supply Puff OLE DB .NET Data Supply Use the OLE DB resource poolized underlying service to store the link to the pool. Many methods can be used to configure resource poolization: You can use a link string to configure, enable resource pool or make it fail. You can use the registry. Resource pool can be configured by programs. In order to avoid deployment issues related to registry, avoid using the registry to configure OLE DB resource poolization. For more details on OLE DB resource poolization, see Chapter 19 of the "OLE DB Programmer Reference" in MSDN: The resource pool section in the OLE DB service. To manage link poolization with poolization targets as a Windows DNA developer, it is recommended that you fail to make OLE DB resource poolization and / or ODBC link pool, and use COM object poolization as a technique that stores database links to the pool. This is mainly for two reasons:
The pool capacity and limits can be explicitly configured (in the COM directory). Performance is improved. The method of piochemical objects can be doubled. However, since the SQL Server .NET data supplier uses poolization, (when using this supplier), you no longer need to develop your own object poolization mechanism. This will avoid the complexity of manual recruitment. If you are using the OLE DB .NET data supplier, consider COM object poolization to benefit from advanced configuration and improvement. If you develop a pool-based object for this purpose, you must use OLE DB resource poolization and automatic transaction campaign (for example, by incorporating "OLE DB Services = -4" into the link string). Transaction recruitment must be handled in the implementation of the pool. Monitoring Link Pine To monitor the application of the application to link poching, you can use the Profiler tool issued with SQL Server or performance monitor with Microsoft Windows 2000. To use the SQL Server Profiler to monitor the link poolization, the operation is as follows:
Click Start, point to Programs, point to Microsoft SQL Server, and then click Profiler to run Profiler. In the File menu, point to New, and then click Track. Provide link content, then click OK. In the Tracking Properties dialog box, click the Event Tag. In the selected event category list, make sure that the review and review of the Terminal Event is displayed under the Security Audit. Click Run to start tracking. When the link is established, an audit login event will be seen; see the review of the event when the link is closed. To monitor the link poolization through the Performance Monitor, the operation is as follows:
Click Start, point to Programs, point to Administrative Tools, and then click Performance to Run Performance Monitor. Right-click in the chart background, and then click Add Counter. In the Performance Object drop-down list box, click SQL Server: General Statistics. In the list of appears, click the user link. Click Add, and then click Close. Note that the RTM version of the .NET framework will additionally include a set of ADO .NET performance counters (these counters are used in conjunction with performance monitor), which are used to monitor and accumulate link poolization status for SQL Server .NET data vessel. Management Security Although database linking poolization improves the overall application's overall scalability, this means you no longer manage security in database end. This is because the link string must be the same for linking poolization. If you need to track the database operation of each user, consider adding a parameter for each operation, passing this parameter, you can pass the user identity, manually log in the database. Using Windows Certification When linking to SQL Server, Windows certification should be used because it provides many advantages: security is easy to manage because the Windows security model is used instead of a dispersed SQL Server security model. Avoid embedding the username and password in the link string. The username and password are not transmitted in the network in a clear text. After the password expiration period, the minimum length, the account lock has improved the security of the login after multiple invalid login requests. Performance .NetBeta 2 performance test shows that using Windows certification with SQL Server certification, it takes more time to open the Pihua database link. However, although the cost of Windows certification is high, it is not important to relatively (caused by the performance loss) compared to the time spent on the execution of a command or store. As a result, the advantages of Windows certification listed above are usually slightly over performance loss. Similarly, when opening a pool-level link, in the RTM version of the .NET Framework, Windows Certification is not more obvious. Avoid pretending to pretending Windows certification in the middle layer to access the Database's Windows account. Although it is more logical, it is more logical, it must be avoided because it is seriously affected by damaging the linking poolization and the application's scalability. In order to solve this problem, consider the implementation of the limited Windows account (rather than authenticated person), each account represents a specific role. For example, you can consider the following method:
Create two Windows accounts, one for read operations, one for write operations (you can also map with separate account maps for specific applications. For example, you can use an account for Internet users, and internal operators and / or Administrators use additional accounts). Map each account to a SQL Server database role and then set the required database permissions for each role. When using the application logic in the data access layer to determine which Windows account needs to be pretended when performing the database operation. Note that each account must be the domain account existing in the Internet Information Service (IIS) and SQL Server in the same domain or trust domain; or a matching account that creates (with the same username and password) on each computer. Use TCP / IP SQL Server 7.0 for the network library to support Windows certification for all network libraries. Use TCP / IP to get configuration, performance, and scalable advantages. For more information on using TCP / IP, you can see a link section through the firewall. The storage chain string has a variety of ways to store a chain string, each with different degrees of flexibility and security. Although the string is hardcoded in the source code, the file system cache ensures that performance loss associated with external storage strings outside the diploma system can be ignored. In fact, additional flexibility provided by external link strings (allowing administrators) is popular in any case. When you choose to store a chain string, the two important factors to consider are the security and simplicity of configuration, followed by performance. You can choose to store the database link string in the following locations: Application configuration files such as web.config files for ASP.NET web applications. Universal Data Link File (UDL) (only supported by the OLE DB .NET Data Supply) Windows Registry Custom file COM directory, you can use Windows authentication to use Windows authentication with Windows certification by using constructor (only for service components), you can Avoid storage user names and passwords on the link string. If the safety requirements require more stringent, consider the memory of the links in an encrypted format. For ASP.NET web applications, the link string is stored in a web.config file in encryption format is a secure and configurable solution. Note that in the link string, set the Persist Security Info Names value to false, you can prevent the Connectionstring property of the SQLCONNECTION or OLEDBCONNECTION object to return to security sensitive content, such as passwords. The following sections discusses how to store chain strings with these methods and illustrate relative advantages and disadvantages. This allows you to make a corresponding choice based on a particular application environment. Profile using an XML application configuration You can store the database link string in the custom setting portion of the application configuration file using element Appsettings. This element supports any keyword-value pair, as shown in the following code segment:
Value = "server = (local); integrated security = sspi; database = northwind" />
Note: Appsettings elements are now under the Configuration element and cannot appear directly below System.Web. Advantage
Easy to deploy. The link string is deployed with the configuration file through regular .NET XCOPY deployment. It is easy to access by the program. The appSettings property of the ConfigurationSettings class makes it easier to read the database link string at runtime. Support dynamic updates (ASP.NETs are limited only). If the administrator updates the link string in the web.config file, the next time the change in the string is accessed, this is a stateless component, as the customer re-uses the components. Data Access. Request. Disadvantages security. Although the ASP.NET Internet Server Application Programming Interface (ISAPI) DLL blocks the customer from directly accessing the file with the .config extension, and NTFS file system permissions are also used to further restrict access, but you may still want to avoid these ways. The content is stored on the web server on the front end. To increase security, you need to store the link string in an encrypted format in the configuration file. MORE INFORMATION Utilize the AppSettings static properties of the System.Configuration.ConfigurationSettings class, you can get the custom settings for your application. As shown in the following code snippet, it is assumed here to set the set keyword for DBConnStr. Using system.configuration; private string getdbasettings.appsettings ["dbconnstr"];} Using the UDL file OLE DB .NET Data Supply Support Using the Unified Data Link (UDL) file name in its linked string. The link string can be transmitted to the OLEDBConnection object in the form of building parameters, or set up a link string using the Connectionstring property of the object. Note SQL Server .NET Data Supply does not support using UDL files in its link string. Therefore, this method is only valid using the OLE DB .NET data supplier. For OLE DB supplies, use the link string to reference the UDL file, use "file name = name.ud,". Advantage standard method. You may have been managed by the UDL file. Disadvantages. Each time you open the link, the link string containing UDLS is read and parsed. safety. The UDL file is stored in a plain text. With NFTS file permissions, you can ensure the security of these files, but this will lead to the same problem as the .config file. The UDL file is not supported by the SQLClient object. This method is not supported by the SQL Server .NET data vendor, and you want to use this supplier to access SQL Server 7.0 and its later versions. More information
Must ensure that the administrator has the read / write access to the file for management, and make sure that the identity of the application has read permissions. For ASP.NET web applications, the application worker process is run by default, but using the machine-wide profile (Machine.Config)
The element can cover it. Use the web.config file
Elements, and an optional specified account, you can pretend.
For web applications, make sure that the UDL file is not placed in the false directory, because the file can be downloaded from the web. Using the Windows Registry You can store the link string in a Windows registry, but not for use due to deployment issues. Advantage
safety. With Access Control List (ACLs), access to the selected registry keyword can be managed. For higher levels of security, consider encrypting data. It is easy to access by the program. The .NET class supports reading a string from the registry. Disadvantages deployment. The relevant registry settings must be deployed with applications to some extent the advantages of XCOPY deployment. You can use a custom file to store a chain string using a custom file, but this technology is not an advantage, so it is not recommended. Advantage
No shortcomings
Extra coding. This approach requires additional coding and forcing you to clearly handle the simultaneous problems. deploy. This file must be copied with other ASP.NET application files. Avoiding this file in a directory or subdirectory of the ASP.NET application, you can prevent it from downloading through the network. Use build parameters and COM directories to store the link string in the COM directory and use the object's constructor to automatically pass it to the object. COM When the object is initialized, the construct method of the object will be called immediately after the configuration construct string. Note that this method is only for service components. This method is considered only if the management component uses other services, such as distributed transaction support or object poolization. Advantage
Management. With component service MMC plugins, administrators can easily configure link strings. Disadvantage
safety. The COM directory is considered an insecure store (although you can limit the access to it by using the COM role), and thus cannot be used to maintain the link string in a clear text. deploy. The entry in the COM directory must be deployed with the .NET application. If other business services such as distributed transactions or objects are used, store the database link string in the directory will not increase the additional overhead of deployment, because other services must be supported, the COM directory must be deployed. You must provide services for components. Constructed strings can be used only for the components of the service. To enable constructing strings, you cannot derive the required component classes from the ServicesDComponent class (this will serve the component). Link usage mode No matter what .NET data supplier, you must always:
Open the database link as much as possible. Use this link with as short as possible. Turn off the link as quickly as possible. Link until it is closed through the Close or Dispose method, it returns to the pool. Even if it is found to be in a crash state, it should also be closed. This ensures that it can return to the pool and is marked as invalid. The object pool periodically scans the pool to find objects that have been marked as invalid. To ensure that the method returns the front link has been closed, consider the method of demonstrating in the following two codes. The first example uses the finally block, and the second example uses a C # using declaration, which ensures that the object's Dispose method is called. The following code ensures that the Finally block is closed. Note that this method is only used in Visual Basic .NET and C # because Visual Basic .NET supports structured exception processing.
public void DoSomeWork () {SqlConnection conn = new SqlConnection (connectionString); SqlCommand cmd = new SqlCommand ( "CommandProc", conn); cmd.CommandType = CommandType.StoredProcedure; try {conn.Open (); cmd.ExecuteNonQuery (); } Catch (Exception E) {// Handle and log error} Finally {Conn.close ();}} The current code shows another method, this method uses a C # using declaration. Note that Visual Basic .NET does not support the USING declaration, or any functionality of any functionality.
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; conn.open (); cmd.executeQuery ();}} This method also applies to other objects, such as SqlDataReader or OLEDBDataReader, these objects must be shut down. After the error handles the ADO.NET error generation, the underlying structured exception processing supported by the .NET framework will be processed. As a result, the error handling mode in the data access code is identical to the error handling method in other parts of the application. The abnormality is processed and processed by standard .NET exception processing syntax and technology. This section describes how to develop strong data access codes and explain how to handle data access errors. This section also provides an exception handling guide related to SQL Server .NET data vendor. .NET exception The .NET data supplies convert these exceptions in the data access code in the data access code to the data accessed code. The error details of a particular database can be obtained by the attributes of the relevant exception objects. All .NET exception type is finally derived from the exception base class from the System namespace. The .NET data supplier releases a specific type of supplier. For example, once SQL Server returns an error state, the SQL Server .NET data supply releases the SQLException object. Similarly, the OLE DB .NET data supplier releases an exception of the OLEDBEXCEPTION type, this object contains details exposed by the underlying OLE DB supply. Figure 3 shows an abnormal hierarchy of the .NET data supplier. Note that the OLEDBEXCEPTION class is the base class of the ExternalException class from the ExternalException class. The object's ERRORCODE property stores the COM HRESULT generated by OLE DB. Figure 3 NET Data Supply Hierarchy Caches and processes .NET exceptions To process data access exceptions, place the data access code in the TRY block, and use the appropriate filter to capture any exceptions of the generated in the CATCH block. For example, when using the SQL Server .NET Data Supply, the exception of the SQLException type should be captured, as shown in the following code: try {// data access code} catch (sqlexception sqlex) // more specific {} Catch (Exception EX) // Less Specific {} provides different filtration criteria if more than one Catch declaration, remember, arrange them in the most special type to the least special type. In this way, the most special type in the CATCH block will be performed for any given type. The property exposed by the SQLException class contains details of the exception status. These include:
The Message property contains text for describing errors. Number properties, which contains erroneous numbers that uniquely identify incorrect types. State properties. It contains additional information about the error enable state. It is often used to indicate a particular event in a particular error state. For example, if a single storage process generates the same error from more than a row, the present attribute will be used to identify a particular event. Errors collection. It contains detailed information generated by SQL Server. This collecting portion is an object that contains at least one SQLError type. The following code snippet demonstrates how to use the SQL Server .NET data supplier to process SQL Server error status:
using System.Data; using System.Data.SqlClient; using System.Diagnostics; // Method exposed by a Data Access Layer (DAL) Componentpublic string GetProductName (int ProductID) {SqlConnection conn = new SqlConnection ( "server = (local); Integrated Security = SSPI; database = northwind "); // Enclose all data access code within a try block try {conn.Open (); SqlCommand cmd = new SqlCommand (" LookupProductName ", 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 Ne W DALEXCEPTION ("Unknown Productid:" ProductId.toString (), SQLEX);} catch (exception ex) {// handle generic exception condition....................................................................................... is closed}} // Helper routine that logs SqlException details to the // Application event logprivate void LogException (SqlException sqlex) {EventLog el = new EventLog (); el.Source = "CustomAppLog"; string strMessage; strMessage = "Exception Number : " SQLEX.NUMBER " (" SQLEX.Message ") HAS Occurred "; El.writeEntry; 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.writeEntry (StrMessage);}} In the SQLEXCEPTION CATCH block, the code initially uses the LOGEXCEPTION Help function to record the error status, this function uses Foreach The declaration enumerates the details of the supplier in the ERRORS collection and records the error details to the error log. The code in the CATCH block then encapsulates the exception-specific exceptions in the DALEXCEPTION type, which is done to the caller The getProductName method is more meaningful. Exception handler uses the keyword throw to transfer exception to the call. Generate an error T-SQL from the stored procedure to provide a Raiserror (note spelling) function. You can use this function to generate a setup error, and will Error returns to customers. For ADO.NET customers, the SQL Server .NET data supplies interprets these data errors and converts them to SQLError objects. Using the RaisError function is a simple way to make message text as the first parameter included Then specify a serious and state parameters, as shown below: Raiserror ('unknown product ID:% s, 16, 1, @ProductID) In this example, the replacement parameter is used to use the current product ID as an error message Part of the text returns, parameter 2 is the severity of the message, parameter 3 is a message state. MORE INFORMATION To avoid hard coding of the message text, you can use the sp_addMessage system stored procedure or SQL Server Enterprise Manager to increase your own message Go to the SysMessages table. Then you can use the ID reference message that passed to the RAISError function. The message IDs you define must be greater than 5000, as shown in the following code segment: raiserror (50001, 16, 1, @ProductID) About raiserror functions of For complete details, please query RaisError in the online book of SQL Server. Correctly use the severity level to select the wrong severity level, and clear the impact caused by each level. The range of errors is 0-25, and it is used to indicate the type of problem encountered by SQL Server 2000. In the client code, you can get the severity of the error by checking the Class property of the SQLError object in the ERRORS collection of the SQLEXCeption class. Table 1 shows the meaning of different severity levels and the impact caused. Table 1. Error severity level - impact and significance
Severe level link has been closed to generate SQLException objects
significance
10 and the following NONO notification type messages do not indicate the wrong state. 11-16noyes can be modified by the user, for example, using the modified input data retry operation. 17-19noyes resources or system errors. 20-25yesyes fatal system error (including hardware errors). The customer link is terminated. Controlling Automated Transaction SQL Server .NET Data Supply For any severity greater than 10 errors that it encounter, throws the SQLException object. When the SQLException object is detected as a component of the Automation (COM ) transaction, the component must ensure that it can cancel the transaction. This may be, perhaps not an automation process, and depends on whether the method has made a markup of the AutoComplete property. For more information on processing objects in automated transaction context, see section of the determination transaction in this article. The notification type message 10 and the following severity level are obtained for indicating the notification type message and does not cause the thrush of the SQLException object. To get a notification type message: Create an event handler and submit an InfMessage event exposed to the SQLConnection object. The following code snippet shows the event agent.
Public Delegate Void SqlinFomessageEventHandler (Object Sender, SqlinfubMessageEventArgs E); you can get message data by passing the SQLINFOMessageEventArgs object in your event handler. This object exposes the ERRORS attribute that contains a set of SQLError objects - each notification message A SQLError object. The following code snippet demonstrates how to register an event handler for recording notification messages.
public string GetProductName (int ProductID) {SqlConnection conn = new SqlConnection ( "server = (local); Integrated Security = SSPI; database = northwind"); try {// Register a message event handlerconn.InfoMessage = new SqlInfoMessageEventHandler (MessageEventHandler) Conn.open (); // setup command Object and execute it...} catch (sqlexception sqlex) {// log and handle exception....}}} // Message Event Handlervoid MessageEventHandler (Object Sender, SqlinFomessageEventAgegs E) {Foreach (SQLERROR SQLE IN E.ErrorS) {// Log SQLError Properties..}} Performance This section introduces some common data access schemes, for each solution Data Access Codes describes the optimal performance and scalability solutions. In the right place, it also compares performance, function and development. This section takes into account the following functional solution.
Get multiple rows. Get a result set and repeat it in the obtained row. Get a line. Get a row with the specified keyword. Get one. Get one from the specified row. Determine the existence of a certain data. Check if a row with a specific keyword exists. This is a variant of single-finding scenarios, which is enough to return a simple Boolean value. Get Multi-Bank In this scenario, you have to get a set of formalized data and repeat an action in the obtained row. For example, you get a set of data and processed in a non-linked manner, and then (possibly passing it as an XML document to the client application. Optionally, you can also display these data in the form of an HTML table. To help determine the most appropriate data access method, consider whether you need (non-link) DataSet object's additional flexibility, or only the original performance provided by the SQLDataReader object, which is very suitable for data representation of the B2C web application. Figure 4 shows these two basic scenes. Note SqlDataAdapter used to fill DataSet utilize SqlDataReader method data. Figure 4 Multi-line data access scheme comparison When you get multiple rows from the data source: Use the SqlDataAdapter object to generate a DataSet or DataTabl object. Provide read-only forward data streams with the SqlDataReader object. Provide read-only XML data streams using the XMLReader object. SQLDATAREADER and DataSet / DataTable are essentially the selection between performance and functionality. SQLDataReader provides optimal performance, while DataSet provides additional functionality and flexibility. Data Binding All three objects can be used as data sources of data binding controls. DataSet and DataTable can be used as data sources for wider range controls. This is because DataSet and DataTable implementation (generating ILIST interface) IListSource interface, and SqlDataReader implements the Ienumerable interface. Many WinForm controls that can perform data binding needs to implement the data source of the ILIST interface. This difference is because the type of scene designed for each object type is different. DataSet is a rich, non-linked structure that is suitable for web and desktop applications. On the other hand, the data reader has been optimized for web applications. This application needs to be optimized and can only access forward. Check the data source requirements for the specific control type to be bound. Data Dataset is delivered between the application intercommination provides a relationship diagram that can be arbitrarily manipulated as an XML, and the non-link cache copy of the data is passed between the application layer and the component. However, SQLDataReader provides more optimized performance because it avoids performance and memory overhead associated with creating DataSet. Remember, DataSet objects will result in multiple sub-objects - including DataTable, DataRow, and Datacolumn - and as a collection object of these sub-object containers. Use DataSet to use SqlDataAdapter to populate DataSet objects when:
You need a non-linking cache data for cache data so that you can pass it to other layers in other components or applications. You need a data relationship diagram in memory to perform XML or non-XML operations. The data you are using is from multiple data sources, such as multiple databases, tables, or files. You want to update some or all rows, and hope to use the batch of SqlDataAdapter. You have to bind data to the control, and this control requires support for the ILIST interface. MORE INFORMATION If you use SqlDataAdapter to generate DataSet or DataTable, you should pay attention to:
You don't have to clearly open or close the database link. The SQLDataAdapter Fill method opens the database link and turn it off before this method returns. If the link has been turned on, this method still makes the links open. If you need link for other purposes, consider opening the link before calling the Fill method. This way you can avoid unnecessary open / closing operations, improve performance. Although the same SQLCommand object can be repeatedly executed, do not repeat the use of this object to perform different commands. Using SqlDataReader's inferior condition, you can use the SQLDataReader object obtained by calling the EXECUTEREADER method of the SQLCommand object:
When processing a lot of data - too much, it cannot be maintained in a single buffer. I hope to reduce the imprint of the application in memory. I hope to avoid creating related overhead with the DataSet object. I want to perform data binding operations for a control, and this control supports the data source of the IEnumerable interface. I hope the streamlined data access and optimize it. A row that contains the binary large object (blob) is read. You can use the SqlDataReader object to pull the BLOB data from the database from the database in a manageable large block, rather than one-time extraction. For more details on processing BLOB data, see section of the blobs in this article. MORE INFORMATION If you use the SqlDataReader object, please note:
During the data reader activity, the underlying database link is kept open and cannot be used for any other purpose. Call the CLOSE method as possible in the place of the SQLDataReader object. Each link can only have a data reader. By passing the COMMANDBEHAVIOR.CloseConnection enumeration value to the ExecuteReader method, you can clear the link after using the data reader; or bind the link lifecycle to the SqlDataReader object. This indicates that the link will also turn off when the SqlDataReader object is turned off. When using the reader access data, if you know the underlying data type of the column, you should use the type of accessor method (such as getInt32 and getString) because these methods reduce reading when reading column data. The amount of type conversion required for column data. To avoid sending unnecessary data from the server to the client, if you want to close the reader and discard all the results of all reserved results, call the CANCEL method to call the command object before calling the Close method to the reader. The CANCEL method ensures that the result of the server is abandoned without being sent to the client. Instead, the CLOSE method to call the data reader will make the reader unnecessarily extract the result of the reserved result to empty the data stream. If you want to get the output value or return value returned from the stored procedure, and you can call the Close method to the reader before you get the output or return value, you must call the reader before getting the output or return value. Using XMLReader under the following cases, use the XMLReader object obtained by calling a SQLCOMMAND object:
It is desirable to process the data as an XML, but do not want to trigger additional performance overhead due to the creation of a DataSet object, and the non-link cache of the data is not required. It is desirable to use the SQL Server for XML syntax, which allows for a flexible way to get an XML fragment from the database (ie, an XML document without root elements). For example, this approach allows you to accurately specify the element name, is the use element or a graphic of the attribute as the core, the illustration is returned with XML data, and so on. MORE INFORMATION If you use XMLReader, please pay attention: