(http://msdn.microsoft.com/en-us/library/dd203099.aspx)
Enterprise Library consists of a collection of application blocks. All of these are reusable software components
designed to assist developers with common enterprise development challenges.
Different Versions
3.1, 4.0 and 4.1
We will be talking about 4.1 version.
Benefits of Enterprise Library
Application blocks help address the common problems that developers face from one project to the next. Their
design encapsulates the Microsoft recommended best practices for .NET applications; developers can add them
to .NET applications quickly and easily. For example, the Data Access Application Block provides access to the most
frequently used features of ADO.NET, exposing them through easily used classes. In some cases, application blocks
also add related functionality not directly supported by the underlying class libraries.
This release of Enterprise Library (4.1) contains the following application blocks:
Caching Application Block. Developers can use this application block to incorporate a local cache in their
applications.
Cryptography Application Block. Developers can use this application block to incorporate hashing and
symmetric encryption in their applications.
Data Access Application Block. Developers can use this application block to incorporate standard database
functionality in their applications.
Exception Handling Application Block. Developers and policy makers can use this application block to
create a consistent strategy for processing exceptions that occur throughout the architectural layers of
enterprise applications.
Logging Application Block. Developers can use this application block to include standard logging
functionality in their applications.
The Policy Injection Application Block. Developers can use this application block to implement interception
policies that streamline the implementation of common features, such as logging, caching, exception
handling, and validation, across an application.
Security Application Block. Developers can use this application block to incorporate authorization and
security caching functionality in their applications.
Unity Application Block. Developers can use this application block to implement a lightweight, extensible
dependency injection container with support for constructor, property, and method call injection.
The Validation Application Block. Developers can use this application block to create validation rules for
business objects that can be used across different layers of their applications.
Enterprise Library assemblies in your application, you must add references to the relevant application block
assemblies and to the Common assembly. Then, to write application code, you also must be aware of the
Enterprise Library namespace conventions and object creation patterns.
Add a reference to the application block assembly. In Visual Studio, right-click your project node in
Solution Explorer, and then click Add References. Click the Browse tab, and then find the location of the
application block assembly (the script CopyAssemblies.bat copies all application block assemblies to the
bin subdirectory). Select the assembly, and then click OK to add the reference. For example, to reference
the Caching Application Block assembly, browse to the bin subdirectory, select the assembly
Microsoft.Practices.EnterpriseLibrary.Caching.dll, and then click OK.
2.
Use the same procedure to set a reference to the Enterprise Library Common assembly,
Microsoft.Practices.EnterpriseLibrary.Common.dll and to the ObjectBuilder assembly,
Microsoft.Practices.ObjectBuilder2.dll.
It uses the functionality provided by ADO.NET 2.0 and with it, you can use ADO.NET functionality along
with the application block's functionality.
It helps maintain consistent data access practices, both within an application and across the enterprise.
It relieves developers from learning different programming models for different types of databases.
It reduces the amount of code that developers must write when they port applications to different types of
databases.
Open the configuration file. For more information, see Configuring Enterprise Library.
2.
Right-click Application Configuration, point to New, and then click Data Access Application Block.
The next procedure explains how to configure an instance of the default database. This instance is used if the
application calls the DatabaseFactory.CreateDatabase method with no instance name.
To configure the default database
1.
2.
Enter the connection string name for the DefaultDatabase property or select it from the drop-down box.
The default connection string name is ConnectionString.
3.
(Optional) Set the Name property by typing a new name. The default name is ConnectionString.
4.
In the ProviderName property section, change the provider name as required. Enter the name of the
provider or select it from the drop-down list. The default provider name is System.Data.SqlClient. The
ProviderName property must be a provider name specified in a DBProviderFactory class.
The next procedure explains how to create the connection string for a named database instance. When the
configuration tools save the connection string, they generate a colon-delimited string that stores the connectin
information as a series of name=value pairs. For example, if you used the configuration tools to create a
connection string with all the default values, they would generate the following connection string.
Database=Database;Server=(local)\SQLEXPRESS;Integrated Security=SSPI;
To configure a connection string
1.
2.
(Optional) Set the Name property by typing a new name. This is the name of the ConnectionString
node. The default name is ConnectionString.
3.
(Optional) In the ProviderName property section, change the provider name. Enter the name of the
provider or select it from the drop-down list. The default provider name is System.Data.SqlClient. The
ProviderName property must be a provider name specified in a DbProviderFactory class.
4.
Update the ConnectionString property as required. For example, this connection string specifies the local
SQL Server Express named database instance using itegrated Windows security:
Database=Database;Server=(local)\SQLEXPRESS;Integrated Security=SSPI
Add a reference to the Data Access Application Block assembly. In Visual Studio, right-click your project
node in Solution Explorer, and then click Add References. Click the Browse tab, and then navigate to
the location of the Microsoft.Practices.EnterpriseLibrary.Data.dll assembly. Select the assembly, and
then click OK to add the reference.
2.
Following the same procedure, add references to the Enterprise Library Core assemblies,
Microsoft.Practices.EnterpriseLibrary.Common.dll and Microsoft.Practices.ObjectBuilder2.dll.
3.
(Optional) To use elements from Data Access Application Block without fully qualifying the element
reference, you can add the following using statement (C#) or Imports statement (Visual Basic) to the
top of your source code file.
using Microsoft.Practices.EnterpriseLibrary.Data;
using System.Data;
Visual Basic
Imports Microsoft.Practices.EnterpriseLibrary.Data
Imports System.Data
Creating the Database Object
All data access methods are executed against a Database object. You can use the DatabaseFactory class to
create a Database object. The specific type of Database object created by the factory is determined by the
application configuration information. Alternatively, you can use the Unity Integration approach to create instances
of the objects in the Data Access Application Block. For more details of the integration of Enterprise Library and the
Unity Application Block, see Creating Objects Using the Unity Application Block.
You can use the configuration tools to specify a default database instance. The DatabaseFactory creates the
database specified by the default instance when you call the CreateDatabase method without passing a database
instance name. The following application code shows how to create a Database object for the default instance
when you are not using the Unity Integration approach.
C#
Database db = DatabaseFactory.CreateDatabase();
Visual Basic
Database db = DatabaseFactory.CreateDatabase("Sales");
Visual Basic
C#
Methods that represent SQL text commands (for example, Select CustomerID, Fullname From
Customers)
The method you call to retrieve a DbCommand object is determined by whether you want to execute inline SQL or
call a stored procedure. The method that creates a DbCommand object for a stored procedure also provides
parameter caching. For more information about parameter caching, see Handling Parameters.
All DbCommand objects are created using methods on the Database class. These methods are the following:
Database db = DatabaseFactory.CreateDatabase();
string sql = "Select CustomerID, LastName, FirstName From Customers";
DbCommand cmd = db.GetSqlStringCommand(sql);
Visual Basic
Database db = DatabaseFactory.CreateDatabase();
DbCommand cmd = db.GetStoredProcCommand("GetProductsByCategory");
Visual Basic
Managing Connections
Database connections are a limited resource, and proper management of them is essential for scalable applications.
It is good practice to keep connections open only as long as they are needed and to close them as soon as
practical. By design, most of the Database class methods handle the opening and closing of connections to the
database on each call. Therefore, the application code does not need to include code for managing connections. (By
default, and for performance reasons, ADO.NET returns connections to the connection pool without closing them.
Therefore, you do not need to cache your Database objects.)
For example, the ExecuteDataSet method returns a DataSet object that contains all the data. This gives you
your own local copy. The call to ExecuteDataSet opens a connection, populates a DataSet, and closes the
connection before returning the result.
The following code demonstrates the use of the ExecuteDataSet method.
C#
Database db = DatabaseFactory.CreateDatabase();
string sql = "Select ProductID, ProductName From Products";
DbCommand cmd = db.GetSqlStringCommand(sql);
// No need to open the connection; just make the call.
DataSet customerDataSet = db.ExecuteDataSet(cmd);
Visual Basic
Database db = DatabaseFactory.CreateDatabase();
DbCommand cmd = db.GetSqlStringCommand("Select Name, Address From Customers");
using (IDataReader reader = db.ExecuteReader(cmd))
{
// Process results
}
Visual Basic
Avoid using database-specific tokens with stored procedure parameter names. The Database-derived
classes for specific providers include code to adjust parameter names as required. For example, do not
include the "@" character when supplying stored procedure parameter names to a SQL Server database.
The following code shows how to call the AddInParameter method to create a parameter with the name
CategoryID. When this code is executed using the SqlDatabase object, the provider prefaces the
parameter name with "@".
C#
Database db = DatabaseFactory.CreateDatabase();
DbCommand cmd = db.GetStoredProcCommand("GetProductsByCategory");
Consider the case sensitivity of the back-end relational database management system (RDBMS). For
example, string comparison in SQL Server 2000 is not case sensitive, but it is case sensitive in both Oracle
8i and DB2. To develop a portable application, you should write your string comparison logic either to be
case insensitive or to force the application to store only one case for columns used in a comparison
operation.
Avoid using return values when executing your stored procedure. Instead, use output parameters.
When adding parameters to the parameter collection, make sure that the order in your application code
matches the order in the database. The OLE DB provider executes the stored procedure with parameters
in the order they appear, instead of allocating them by name, so it is important that you add the
parameters to the collection in the correct order.
If you must use in-line SQL in your application code, make sure your SQL syntax is valid across all the
database types that your application will run against. Also, beware of SQL injection risks.
Avoid passing null values to the stored procedure's parameter of value type. Doing so may not work if you
need a portable interface that uses DB2 with SQLJ stored procedures.
Handling Parameters
Most stored procedures accept parameters whose values are either used as input to the stored procedure or are set
during output. As with ADO.NET, the Data Access Application Block allows developers to explicitly specify all of the
attributes of a parameter. These attributes can include direction, data type, and length. This approach is named
explicit parameter handling. However, as a convenience, you can specify only the values when using input
parameters. In this case, the application block will look up and supply the parameter attributes. This approach is
named parameter discovery.
Explicit Parameter Handling
The Database class includes a variety of methods for passing parameters to stored procedures. This class also
includes methods for setting and examining the values of those parameters. These methods are the following:
SetParameterValue. This method sets the value of the specified parameter when you want to execute
multiple inserts using the same connection and command but with different parameter values.
The following code demonstrates how to use AddInParameter and AddOutParameter to specify parameters.
C#
Database db = DatabaseFactory.CreateDatabase();
string sql = "GetProductDetails";
DbCommand cmd = db.GetStoredProcCommand(sql);
db.AddInParameter(cmd, "ProductID", DbType.Int32, 5);
db.AddOutParameter(cmd, "ProductName", DbType.String, 50);
db.AddOutParameter(cmd, "UnitPrice", DbType.Currency, 8);
Visual Basic
Note:
The preceding code example does not include a parameter name token specific to a database type. Because of
this, the code can remain generic across different database providers. When this code executes against the
SqlClient data provider (and therefore uses the SqlDatabase class), the following code would result in
identical behavior as the preceding code. However, this code would not be portable to other data providers.
C#
Database db = DatabaseFactory.CreateDatabase();
string sql = "GetProductDetails";
DbCommand cmd = db.GetStoredProcCommand(sql);
// NOTE: specifying parameter prefixes makes the code database-specific
db.AddInParameter(cmd, "@ProductID", DbType.Int32, 5);
db.AddOutParameter(cmd, "@ProductName", DbType.String, 50);
db.AddOutParameter(cmd, "@UnitPrice", DbType.Currency, 8);
Visual Basic