Anda di halaman 1dari 10

Introduction to Enterprise Library

(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.

Adding Enterprise Library to Applications


Enterprise Library includes source code for the application blocks. You can include the source code in your
application or compile the application blocks and use the compiled assemblies. However, before you can use the

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.

Referencing Enterprise Library Assemblies


Before you can build applications that incorporate the Enterprise Library application blocks, you must add
references to the application block assemblies and to the Common and ObjectBuilder2. This prepares your
application to use the Enterprise Library. Take care to select the assemblies that reflect your decision to use the
Microsoft strong-named assemblies, non-strong-named assemblies, or a customized set of Enterprise Library
assemblies.
To prepare your application
1.

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.

Enterprise Library Namespaces


All application blocks adhere to the same convention for namespaces. All code for the Enterprise Library is
contained under the root namespace, Microsoft.Practices.EnterpriseLibrary.
Each application block is contained in its own namespace under this root. For example, the Security Application
Block uses the Microsoft.Practices.EnterpriseLibrary.Security namespace.

The Data Access Application Block


The Enterprise Library Data Access Application Block simplifies development tasks that implement common data
access functionality. Applications can use this application block in a variety of situations, such as reading data for
display, passing data through application layers, and submitting changed data back to the database system. The
application block includes support for both stored procedures and in-line SQL. Common housekeeping tasks, such
as managing connections and creating and caching parameters, are encapsulated in the application block's
methods. In other words, the Data Access Application Block provides access to the most often used features of
ADO.NET in simple-to-use classes; this boosts developer productivity.
ADO.NET 2.0 provides classes such as the DbCommand class and the DbConnection class; these classes help to
abstract the data provider from any particular database implementation. The Data Access Application Block takes
advantage of these classes and provides a model that further supports encapsulation of database typespecific
features, such as parameter discovery and type conversions. Because of this, applications can be ported from one
database type to another without modifying the client code. The Data Access Application Block includes an abstract
base class that defines a common interface and that provides much of the implementation needed by the data
access methods available in ADO.NET 2.0.
The application block also includes classes that are specific to Microsoft SQL Server, Microsoft SQL Server CE, and
Oracle. These classes perform operations that are particular to the database type. The code for applications written
for one type of database, such as SQL Server, looks much the same as the code for applications written for another
type of database, such as Oracle.
Another feature of the Data Access Application Block is that application code can refer to particular databases by an
ADO.NET connection string name, such as "Customer" or "Inventory." The application code can specify a named
instance of a database and pass this parameter to the DatabaseFactory.CreateDatabase method. Each named
database has its connection information stored in a configuration file. By changing the settings in the configuration
file, developers can use their applications with different database configurations without recompiling their code.

The Data Access Application Block provides the following benefits:

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 reduces the need to write boilerplate code to perform standard tasks.

It helps maintain consistent data access practices, both within an application and across the enterprise.

It reduces difficulties in changing the database type.

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.

Entering Configuration Information


The following procedure describe how to configure the Data Access Application Block. Properties associated with
the nodes appear in the right pane of the Configuration Console or the Properties window of the Visual Studio
Configuration Editor.
To add the Data Access Application Block
1.

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.

In the right pane, expand the DefaultDatabase property.

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.

Click the ConnectionString node.

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

Adding Application Code


The Data Access Application Block is designed to support the most common scenarios for accessing a database.
When you add your application code, refer to the scenarios in the Key Scenarios section and select the ones that
best match your situation. Use the code that accompanies the scenario as-is or adapt it as necessary.
First, you must prepare your application to use the Data Access Application Block. After you do that, you can create
the Database object and call the appropriate method overloads.
To prepare your application
1.

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

Dim db As Database = DatabaseFactory.CreateDatabase()


Alternatively, the application code can specify a named instance of a database. For example, if you used the
configuration console to create an instance named "Sales" the code to create a Database object for that specific
instance would look like the following.
C#

Database db = DatabaseFactory.CreateDatabase("Sales");
Visual Basic

Dim db As Database = DatabaseFactory.CreateDatabase("Sales")


If you know the connection string for the database you want to create, you can bypass the application's
configuration information and use a constructor to directly create the Database object. Because the Database
class is an abstract base class, you must construct one of its derived types. The derived Database type determines
the ADO.NET data provider. For example, the SqlDatabase class uses the SqlClientFactory provider, the
SqlCeDatabase class uses the SqlCeProviderFactory provider, and the OracleDatabase class uses the
OracleClientFactory provider. It is your responsibility to construct the appropriate type of Database class for the
connection string.
The following code creates a SqlDatabase object with the supplied connection string.

C#

// Assume the method GetConnectionString exists in your application and


// returns a valid connection string.
string myConnectionString = GetConnectionString();
SqlDatabase sqlDatabase = new SqlDatabase(myConnectionString);
Visual Basic

' Assume the method GetConnectionString exists in your application and


' returns a valid connection string.
Dim myConnectionString As String = GetConnectionString()
Dim db As SqlDatabase = New SqlDatabase(myConnectionString)

Creating a DbCommand Object


The Data Access Application Block provides a consistent way to retrieve ADO.NET DbCommand objects. The data
access methods of the application block include overloads that accept a DbCommand object. If you use the
overloads with DbCommand objects, you have more control when you call stored procedures. For example, if you
use a DbCommand object, you can have a stored procedure that returns several results in the output parameters.
In addition, a DbCommand object allows you to specify the stored procedure's timeout value.
The methods that create DbCommand objects are separated into two types:

Methods that represent stored procedure calls (for example, GetCustomers)

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:

GetStoredProcCommand. This method is for stored procedures commands.

GetSqlStringCommand. This method is for SQL text commands.

Both methods return a DbCommand object.


DbCommand Objects for SQL Statements
To create a DbCommand object for an inline SQL statement, use the GetSqlStringCommand method. The
specific SQL command to be executed is passed as an argument on the method call.
The following code shows how to use GetSqlStringCommand.
C#

Database db = DatabaseFactory.CreateDatabase();
string sql = "Select CustomerID, LastName, FirstName From Customers";
DbCommand cmd = db.GetSqlStringCommand(sql);
Visual Basic

Dim db As Database = DatabaseFactory.CreateDatabase()


Dim sql As String = "Select CustomerID, LastName, FirstName From Customers"
Dim cmd As DbCommand = db.GetSqlStringCommand(sql)
DbCommand Objects for Stored Procedures
To execute a stored procedure, you must use the GetStoredProcCommand method to create the DbCommand
object. The name of the stored procedure to be executed is passed as an argument to the method.
The following code shows how to use GetStoredProcCommand.
C#

Database db = DatabaseFactory.CreateDatabase();
DbCommand cmd = db.GetStoredProcCommand("GetProductsByCategory");
Visual Basic

Dim db As Database = DatabaseFactory.CreateDatabase()


Dim cmd As DbCommand = db.GetStoredProcCommand("GetProductsByCategory")

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

Dim db As Database = DatabaseFactory.CreateDatabase()


Dim sql As String = "Select ProductID, ProductName From Products"

Dim cmd As DbCommand = db.GetSqlStringCommand(sql)


' No need to open the connection; just make the call.
Dim customerDataSet As DataSet = db.ExecuteDataSet(cmd)
However, there are other cases where it is unclear when to close the connection. An example is the
ExecuteReader method. This method returns an object that implements the IDataReader interface. The
Database base class has a default implementation that returns a DbDataReader object. DbDataReader objects
are designed to read specific portions of the data as needed, which requires an open connection. In other words, it
is unknown when the application no longer needs the DbDataReader. If the Data Access Application Block
methods close the connection before returning the DbDataReader, the DbDataReader becomes useless to the
client code. Instead, the DbDataReader methods indicate to the underlying ADO.NET call to automatically close
the connection when the DbDataReader is disposed. In this situation, it is considered a best practice for the
application to ensure that the DbDataReader is closed in a timely fashion, either by explicitly closing the reader
with the DbDataReader.close method or by forcing the disposal of the DbDataReader, which results in the
Close method being called.
The following code demonstrates a call to the ExecuteReader method. The using statement (Using in Visual
Basic) ensures that the DbDataReader object is disposed, which closes the DbDataReader object.
C#

Database db = DatabaseFactory.CreateDatabase();
DbCommand cmd = db.GetSqlStringCommand("Select Name, Address From Customers");
using (IDataReader reader = db.ExecuteReader(cmd))
{
// Process results
}
Visual Basic

Dim db As Database = DatabaseFactory.CreateDatabase()


Dim cmd As DbCommand = db.GetSqlStringCommand("Select Name, Address From
Customers")
Using reader As IDataReader = db.ExecuteReader(cmd)
' Process results
End Using

Creating Portable Database Applications


There are issues that you must consider if your application must work with multiple database types.
Suggestions for Creating Portable Database Applications
Here are some suggestions for creating portable database applications:

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");

db.AddInParameter(cmd, "CategoryID", DbType.Int32, 100);


Visual Basic

Dim db As Database = DatabaseFactory.CreateDatabase()


Dim cmd As DbCommand = db.GetStoredProcCommand("GetProductsByCategory")
db.AddInParameter(cmd, "CategoryID", DbType.Int32, 100)

Always retrieve parameter values through the Database object.

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 RDBMS-specific data types, such as OracleBlob.

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:

AddParameter. This method passes a parameter (input or output) to a stored procedure.

AddInParameter. This method passes an input parameter to a stored procedure.

AddOutParameter. This method adds an output parameter to a stored procedure.

GetParameterValue. This method finds the value of the specified parameter.

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

Dim db As Database = DatabaseFactory.CreateDatabase()


Dim sql As String = "GetProductDetails"
Dim cmd As DbCommand = db.GetStoredProcCommand(sql)
db.AddInParameter(cmd, "ProductID", DbType.Int32, 5)
db.AddOutParameter(cmd, "ProductName", DbType.String, 50)
db.AddOutParameter(cmd, "UnitPrice", DbType.Currency, 8)

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

Dim db As Database = DatabaseFactory.CreateDatabase()


Dim sql As String = "GetProductDetails"
Dim cmd As DbCommand = 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)

Anda mungkin juga menyukai