Mel May2007

You might also like

Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 50

Microsoft Enterprise Library 3.

1 , May 2007 1 of 50

©2008 Microsoft Corporation. All rights reserved.

Enterprise Library

[ http://msdn2.microsoft.com/en-

us/practices/default.aspx ]

patterns & practices Developer Center [ http://msdn2.microsoft.com/en-us/practices/default.aspx ]

Microsoft Corporation

May 2007

Summary

This page provides an overview of the Enterprise Library 3.1. The patterns & practices Enterprise
Library is a library of application blocks designed to assist developers with common enterprise
development challenges. Application blocks are a type of guidance, provided as source code that
can be used "as is," extended, or modified by developers to use on enterprise development projects.

Contents

Overview
Getting Started
Community
Future Plans
Feedback and Support
Authors and Contributors
Related Titles

Overview

The Enterprise Library application blocks help address the common problems that developers face
from one project to the next. They are designed to encapsulate the Microsoft recommended best
practices for .NET applications. In addition, they can be added to .NET applications quickly and
easily. For example, the Data Access Application Block provides access to the most frequently used
features of ADO.NET 2.0 in simple-to-use classes, thus boosting developer productivity. It also
addresses scenarios not directly supported by the underlying class libraries.

Different applications have different requirements, and you will not find that every application block
is useful in every application that you build. Before using an application block, you should have a
good understanding of your application requirements and of the scenarios that the application block
is designed to address.

Enterprise Library 3.1–May 2007 contains the following general purpose application blocks:

• Caching Application Block [ http://msdn2.microsoft.com/en-us/library/aa480456.aspx ] .

Developers can use this application block to incorporate a local cache in their applications.

Document Prepared by : Abhishek Maitrey


Source : www.msdn.microsoft.com
Microsoft Enterprise Library 3.1 , May 2007 2 of 50

• Cryptography Application Block [ http://msdn2.microsoft.com/en-

us/library/aa480457.aspx ] . Developers can use this application block to incorporate hashing


and symmetric encryption in their applications.

• Data Access Application Block [ http://msdn2.microsoft.com/en-us/library/aa480458.aspx ]

. Developers can use this application block to incorporate standard database functionality in
their applications.

• Exception Handling Application Block [ http://msdn2.microsoft.com/en-

us/library/aa480461.aspx ] . 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 [ http://msdn2.microsoft.com/en-us/library/aa480464.aspx ] .

Developers can use this application block to include standard logging functionality in their
applications.

• Policy Injection Application Block [ http://msdn2.microsoft.com/en-

us/library/bb410104.aspx ] . Developers can use this application block to implement


interception policies that can be used to streamline the implementation of common features,
such as logging, caching, exception handling, and validation, across an application.

• Security Application Block [ http://msdn2.microsoft.com/en-us/library/aa480465.aspx ] .

Developers can use this application block to incorporate authorization and security caching
functionality in their applications.

• Validation Application Block [ http://msdn2.microsoft.com/en-us/library/bb410105.aspx ] .

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 also includes a set of core functions, including configuration, instrumentation, and
object builder services. These functions are used by all other application blocks.

Common Scenarios

Enterprise Library can be useful in a variety of situations:

• Enterprise Library provides enough functionality to support many common scenarios that

enterprise-level applications must address.

• Enterprise Library can serve as the basis for a custom library. You can take advantage of the

extensibility points incorporated in each application block and extend the application block by
supplying new providers. You can also modify the source code for the existing application
blocks to incorporate new functionality. Finally, you can add new application blocks to
Enterprise Library. You can either develop extensions for existing application blocks and new
application blocks yourself, or you can use extensions and application blocks developed by
others.

• Enterprise Library is designed so that its application blocks can function independently of each

other. You have to add only the application blocks that your application will use; you do not
have to add the entire library.

Document Prepared by : Abhishek Maitrey


Source : www.msdn.microsoft.com
Microsoft Enterprise Library 3.1 , May 2007 3 of 50

• Enterprise Library includes the source code for the application blocks. This means you can

modify the application blocks to merge into your existing library or you can use parts of the
Enterprise Library source code in other application blocks or applications that you build.

• Enterprise Library includes documentation, QuickStart samples, and source code. This means

that you can use the library as a tool for learning architectural, design, and coding best
practices.

Audience Requirements

This guidance is intended for software architects and software developers. To get the most benefit
from this guidance, you should have an understanding of the following technologies:

• Microsoft Visual C# or Microsoft Visual Basic .NET

• Microsoft .NET Framework

System Requirements

To develop applications using Enterprise Library, you need the following:

• Microsoft Windows XP Professional, Windows Server 2003, or Windows Vista operating system

• Microsoft .NET Framework 2.0 or 3.0. You need .NET Framework 3.0 for:

• The Application Block Software Factory

• The Validation Application Block Windows Communication Foundation (WCF) adapter

• The Exception Handling Application Block Windows Communication Foundation (WCF)

exception shielding functionality

• Microsoft Visual Studio 2005 development system (any of the following editions):

• Microsoft Visual Studio 2005 Standard Edition

• Microsoft Visual Studio 2005 Professional Edition

• Microsoft Visual Studio 2005 Team Edition for Software Developers

• Microsoft Visual Studio 2005 Team Edition for Software Testers

• Microsoft Visual Studio 2005 Team Edition for Software Architects

• Microsoft Visual Studio 2005 Team Suite

Note Enterprise Library includes both unit test binaries and source code. You need either Visual
Studio 2005 Team Edition or NUnit 2.2 to execute the unit tests. If you modify the unit test source,
you will need to recompile it, which also requires either Visual Studio 2005 Team Edition or NUnit
2.2.

To use the Application Block Software Factory and the Strong-Naming Guidance Package, you need
the Microsoft Guidance Automation Extensions (GAX) [ http://msdn2.microsoft.com/en-
us/teamsystem/aa718948.aspx ] . To modify and compile these guidance packages, you also need
the Microsoft Guidance Automation Toolkit (GAT) [ http://msdn2.microsoft.com/en-
us/teamsystem/aa718948.aspx ] .

Document Prepared by : Abhishek Maitrey


Source : www.msdn.microsoft.com
Microsoft Enterprise Library 3.1 , May 2007 4 of 50

To use the Data Access Application Block, you need a database server running a database that is
supported by a .NET Framework 2.0 data provider. This includes SQL Server 2000 or later, SQL
Server 2005 Compact Edition [ http://www.microsoft.com/sql/editions/compact/default.mspx ] ,
and Oracle 9i or later. The database server can also run a database that is supported by the .NET
Framework 2.0 data providers for OLE DB or ODBC.

Contents of this Release

The Enterprise Library 3.1–May 2007 contains the following:

• Binaries. The Enterprise Library includes pre-compiled, strong-named assemblies for all the

source code.

• Source code. The Enterprise Library includes the source code for the application blocks, the

guidance packages, the configuration tools, the unit tests, and the QuickStarts.

• Unit tests. The Enterprise Library includes the unit tests that were created while the

application blocks were being developed.

• QuickStarts. Enterprise Library QuickStarts are brief, easy-to-understand illustrations of key

application block features. Each application block includes one or more QuickStarts.

• Documentation. Enterprise Library includes documentation that can be viewed with the

Visual Studio Help system. The documentation includes guidance about how to use the
Enterprise Library, as well as a class library reference.

What's New

This release of Enterprise Library includes a new application block named the Validation Application
Block, another new application block named the Policy Injection Application Block, two guidance
packages, and a configuration editor that is integrated with Visual Studio. There are also additions in
functionality to the Data Access Application Block and to the Logging Application Block. For
information about migrating from the January 2006 release, see About the Enterprise Library 3.1 -
May 2007 Release [ http://msdn2.microsoft.com/en-us/library/aa480454.aspx ] .

Enterprise Library Dependencies

Figure 1 illustrates the interdependencies of the application blocks that make up Enterprise Library.

Document Prepared by : Abhishek Maitrey


Source : www.msdn.microsoft.com
Microsoft Enterprise Library 3.1 , May 2007 5 of 50

Figure 1 . Interdependence of application blocks

All the application blocks are designed to have a limited number of dependencies so that they can
be used individually as well as with other application blocks. All application blocks depend on the
Enterprise Library Core, which is a logical grouping made up of the following subsystems:

• The Common assembly, including instrumentation.

• Configuration helper classes, design-time components, and the Enterprise Library

Configuration Console.

• The ObjectBuilder subsystem.

Getting Started

Enterprise Library has been developed as a result of analyzing common enterprise development
challenges and successful solutions to these challenges. However, because each application is
unique, you will not find this application block suitable for every application. You should evaluate

Document Prepared by : Abhishek Maitrey


Source : www.msdn.microsoft.com
Microsoft Enterprise Library 3.1 , May 2007 6 of 50

each application block and determine its applicability to your projects. Microsoft suggests that you
dedicate at least half of a day to explore each application block. The following is a suggested
evaluation approach:

1. Download Enterprise Library.


2. Install Enterprise Library and compile all application blocks and tools.
3. Read the "Introduction" and "Scenarios and Goals" sections of the documentation.
4. Compile and run the QuickStart samples, and read through the related "QuickStart
Walkthroughs" and "Key Scenarios" sections of the documentation.
5. If the application block looks like a good fit for your application, try implementing a simple use
case in your application or in a throw-away prototype application using the application block.

Document Prepared by : Abhishek Maitrey


Source : www.msdn.microsoft.com
Microsoft Enterprise Library 3.1 , May 2007 7 of 50

Document Prepared by : Abhishek Maitrey


Source : www.msdn.microsoft.com
Microsoft Enterprise Library 3.1 , May 2007 8 of 50

©2008 Microsoft Corporation. All rights reserved.

Caching Application Block

May 2007

Summary

This page provides an overview of the Enterprise Library Caching Application Block. An application
block is reusable and extensible source code-based guidance that simplifies development of
common caching functionality in .NET Framework applications.

Contents

Introduction to the Caching Application Block


Design of the Caching Application Block
Getting Started
Community
Feedback and Support
Related Titles

Introduction to the Caching Application Block

The Enterprise Library Caching Application Block lets developers incorporate a local cache in their
applications. It supports both an in-memory cache and, optionally, a backing store that can either
be the database store or isolated storage. The application block can be used without modification; it
provides all the needed functionality to retrieve, add, and remove cached data. Configurable
expiration and scavenging policies are also part of the application block.

When building enterprise-scale distributed applications, architects and developers are faced with
many challenges. Caching can help them to overcome some of these challenges, including the
following:

• Performance. Caching improves application performance by storing relevant data as close as

possible to the data consumer. This avoids repetitive data creation, processing, and
transportation.

• Scalability. Storing information in a cache helps save resources and increases scalability as

the demands on the application increase.

• Availability. By storing data in a local cache, the application may be able to survive system

failures such as network latency, Web service problems, and hardware failures.

Common Scenarios

The Caching Application Block is suitable if you encounter any of the following situations:

• You must repeatedly access static data or data that rarely changes.

• Data access is expensive in terms of creation, access, or transportation.

• Data must always be available, even when the source, such as a server, is not available.

Document Prepared by : Abhishek Maitrey


Source : www.msdn.microsoft.com
Microsoft Enterprise Library 3.1 , May 2007 9 of 50

You can use the Caching Application Block with any of the following application types:

• Windows Forms

• Console application

• Windows service

• COM+ server

• ASP.NET Web application or Web service if you need features not included in the ASP.NET cache

You should deploy the Caching Application Block within a single application domain. Each application
domain can have one or multiple caches, either with or without backing stores. Caches cannot be
shared among different application domains.

The Caching Application Block is optimized for performance and is both thread safe and exception
safe. You can extend it to include your own expiration policies and your own backing store.

Example Application Code

The following code shows how to add an item to a cache and retrieve an item from the cache. It
creates an object of type Product and then adds it to the cache, together with a scavenging priority
of 2, an instruction not to refresh the item if it expires, and an expiration date of 5 minutes from the
last time the item was accessed.

Note The code does not include the Product class definition.
Copy Code
[C#]
CacheManager productsCache = CacheFactory.GetCacheManager();
string id = "ProductOneId";
string name = "ProductXYName";
int price = 50;
Product product = new Product(id, name, price);
productsCache.Add(product.ProductID, product, CacheItemPriority.Normal, null,
new SlidingTime(TimeSpan.FromMinutes(5)));
// Retrieve the item
product = (Product) productsCache.GetData(id);

[Visual Basic]
Dim productsCache As CacheManager = CacheFactory.GetCacheManager()
Dim id As String = "ProductOneId"
Dim name As String = "ProductOneName"
Dim price As Integer = 50
Dim newProduct As Product = New Product(id, name, price)
productsCache.Add(newProduct.ProductID, newProduct, CacheItemPriority.Normal,
Nothing, New SlidingTime(TimeSpan.FromMinutes(5)))

Document Prepared by : Abhishek Maitrey


Source : www.msdn.microsoft.com
Microsoft Enterprise Library 3.1 , May 2007 10 of 50

' Retrieve the item product = DirectCast(productsCache.GetData(id), Product)

Design of the Caching Application Block

The Caching Application Block is designed to do the following:

• It provides a set of APIs that are manageable in size.

• It allows developers to incorporate the standard caching operations into their applications

without having to learn the internal workings of the application block.

• It uses the Enterprise Library Configuration Console for easy configuration.

• It performs efficiently.

• It is thread safe. Something is considered thread safe when it can be called from multiple

programming threads without unwanted interaction among those threads.

• It ensures that the backing store remains intact if an exception occurs while it is being

accessed.

• It ensures that the states of the in-memory cache and the backing store remain synchronized.

Design Highlights

Figure 1 shows the interrelationships between the key classes in the Caching Application Block.

Document Prepared by : Abhishek Maitrey


Source : www.msdn.microsoft.com
Microsoft Enterprise Library 3.1 , May 2007 11 of 50

Figure 1. Design of the Caching Application Block

When you initialize an instance of the CacheManager using the CacheFactory, it internally creates
a CacheManagerFactory object, which in turn creates a Cache object. After the Cache object is
created, all data in the backing store is loaded into an in-memory representation that is contained in
the Cache object. Applications can then make requests to the CacheManager object to retrieve
cached data, add data to the cache, and remove data from the cache.

Document Prepared by : Abhishek Maitrey


Source : www.msdn.microsoft.com
Microsoft Enterprise Library 3.1 , May 2007 12 of 50

When an application uses the GetData method to send a request to the CacheManager object to
retrieve an item, the CacheManager object forwards the request to the Cache object. If the item
is in the cache, it is returned from the in-memory representation in the cache to the application. If it
is not in the cache, the request returns the value NULL. If the item is expired, the item also returns
the value NULL.

When an application uses the Add method to send a request to the CacheManager object to add
an item to the cache, the CacheManager object again forwards the request to the Cache object. If
there is already an item with the same key, the Cache object first removes it before adding the new
item to the in-memory store and the backing store. If the backing store is the default backing store,
NullBackingStore, the data is written only to memory. If the number of cached items exceeds a
predetermined limit when the item is added, the BackgroundScheduler object begins scavenging.
When adding an item, the application can use an overload of the Add method to specify an array of
expiration policies, the scavenging priority, and an object that implements the
ICacheItemRefreshAction interface. This object can be used to refresh an expired item from the
cache.

When adding an item that is not already in the in-memory hash table, the Cache object first creates
a dummy cache item and adds it to the in-memory hash table. It then locks the cache item in the
in-memory hash table, adds the item to backing store, and finally replaces the existing cache item
in the in-memory hash table with the new cache item. (In the case where the item was already in
the in-memory hash table, it replaces the dummy item.) If there is an exception while writing to the
backing store, it removes the dummy item added to the in-memory hash table and does not
continue. The Caching Application Block enforces a strong exception safety guarantee. This means
that if an Add operation fails, the state of the cache rolls back to what it was before it tries to add
the item. In other words, either an operation is completed successfully or the state of the cache
remains unchanged. (This is also true for the Remove and Flush methods.)

The BackgroundScheduler object periodically monitors the lifetime of items in the cache. When an
item expires, the BackgroundScheduler object first removes it and then, optionally, notifies the
application that the item was removed. At this point, it is the responsibility of the application to
refresh the cache.

Getting Started

The Caching Application Block has been developed as a result of analyzing common enterprise
development challenges and successful solutions to these challenges. However, because each
application is unique, you will not find this application block suitable for every application. To
evaluate this application block and determine its applicability to your projects, Microsoft suggests
you dedicate at least half of a day to explore the application block. The following is a suggested
evaluation approach:

1. Download Enterprise Library.


2. Install Enterprise Library and compile all application blocks and tools.
3. Read the "Introduction" and "Scenarios and Goals" sections of the documentation.
4. Compile and run the QuickStart samples, and read through the related "QuickStart
Walkthroughs" and "Key Scenarios" sections of the documentation.
5. If the application block looks like a good fit for your application, try implementing a simple use
case in your application or in a throw-away prototype application using the application block.

Document Prepared by : Abhishek Maitrey


Source : www.msdn.microsoft.com
Microsoft Enterprise Library 3.1 , May 2007 13 of 50

©2008 Microsoft Corporation. All rights reserved.

Cryptography Application Block

Microsoft Corporation

May 2007

Summary

This page provides an overview of the Enterprise Library Cryptography Application Block. An
application block is reusable and extensible source code-based guidance that simplifies development
of common cryptographic functionality in .NET Framework applications.

Contents

Introduction to the Cryptography Application Block


Design of the Cryptography Application Block
Getting Started
Community
Feedback and Support
Related Titles

Introduction to the Cryptography Application Block

The Microsoft Enterprise Library Cryptography Application Block simplifies how developers
incorporate cryptographic functionality in their applications. Applications can use the application
block for a variety of tasks, such as encrypting information, creating a hash from data, and
comparing hash values to verify that data has not been altered.

The Cryptography Application Block has the following features:

• It reduces the requirement to write boilerplate code to perform standard tasks, providing

implementations that you can use to solve common application cryptography problems.

• It helps maintain consistent cryptography practices, both within an application and across the

enterprise.

• It eases the learning curve for developers by using a consistent architectural model across the

various areas of functionality that are provided.

• It provides implementations that you can use to solve common application cryptography

problems.

• It is extensible; it supports additional implementations of cryptography providers.

Common Scenarios

Developers frequently write applications that require encryption and hashing capabilities to meet the
security requirements of their organization. Data that is created and maintained by applications, as

Document Prepared by : Abhishek Maitrey


Source : www.msdn.microsoft.com
Microsoft Enterprise Library 3.1 , May 2007 14 of 50

well as configuration information, often needs to be encrypted. Additionally, passwords that are
used to access application functionality or data need to be hashed.

The Cryptography Application Block simplifies the work of developers by abstracting application code
from specific cryptography providers. You can change underlying providers through configuration
changes without changing the underlying application code.

The Cryptography Application Block supports only symmetric algorithms. Symmetric algorithms use
the same key for both encryption and decryption. The application block does not support
asymmetric (also known as public-key) encryption, which uses one key to encrypt a message and
another to decrypt the message.

Example Application Code

The following code shows how to encrypt and decrypt data. This code shows how to use the
overloads that accept a string.

Copy Code
[C#]
string encryptedContentsBase64 = Cryptographer.EncryptSymmetric("symmProvider",
"SensitiveData");
// Decrypt the base64 encoded string
string readableString; readableString =
Cryptographer.DecryptSymmetric("symmProvider", encryptedContentsBase64);

[Visual Basic]
Dim encryptedContentsBase64 As String encryptedContentsBase64 =
Cryptographer.EncryptSymmetric("symmProvider", "SensitiveData")
' Decrypt the base64 encoded string
Dim readableString As String readableString =
Cryptographer.DecryptSymmetric("symmProvider", encryptedContentsBase64)

Design of the Cryptography Application Block

The Cryptography Application Block was designed to achieve the following goals:

• Provide a simple and intuitive interface to the commonly required functionality.

• Encapsulate the logic that is used to perform the most common application cryptography

tasks.

• Present a standard consistent model for common cryptography tasks.

• Make sure the application block is extensible.

• Make sure minimal or negligible performance impact compared to manually written

cryptography code that accomplishes the same functionality.

• Provide a key protection model that can be customized to satisfy your organization's security

requirements.

Document Prepared by : Abhishek Maitrey


Source : www.msdn.microsoft.com
Microsoft Enterprise Library 3.1 , May 2007 15 of 50

Design Highlights

The following diagram illustrates the design of the Cryptography Application Block:

Figure 1. Design of the Cryptography Application Block

The Cryptography Application Block separates decisions about how cryptographic functions are
implemented from how an application uses them. The application block is designed so you change
the behavior of a cryptography provider without changing the application code.

The Cryptographer class is a façade that mediates between the client code and the Cryptography
Application Block's cryptographic functions. The client code calls static methods on the

Document Prepared by : Abhishek Maitrey


Source : www.msdn.microsoft.com
Microsoft Enterprise Library 3.1 , May 2007 16 of 50

Cryptographer class to create hashes, compare hashes, encrypt data, and decrypt data. Each
static method instantiates a factory class and passes the configuration source to the factory class's
constructor. The factory uses the configuration data to determine the type of the provider to create.

The DpapiCryptographer class uses DPAPI to encrypt and decrypt data. DPAPI uses logon
credentials to encrypt data. The logon credentials can either be a user's logon credentials or the
local computer's logon credentials. If you use the local computer's logon credentials, DPAPI allows
all applications that run under those credentials to decrypt that data. To counteract this, you can
use an additional secret to protect the data. This additional secret is named entropy. The
DpapiCryptographer class has overloads of the Encrypt and Decrypt methods that accept an
entropy value.

Note Developers should be careful about how they store the entropy value. If it is simply saved to
an unprotected file, attackers can access the file, retrieve the entropy value, and use it to decrypt
an application's data.

The SymmetricCryptographer class encapsulates provider implementations that derive from the
abstract base class SymmetricAlgorithm, which is located in the .NET Framework's
System.Security.Cryptography namespace. This means that you can use the
SymmetricCryptographer class with any of the .NET Framework symmetric algorithms, such as
the Rijndael symmetric encryption algorithm. The application block uses DPAPI to encrypt and
decrypt the symmetric algorithm key.

Getting Started

The Cryptography Application Block has been developed as a result of analyzing common enterprise
development challenges and successful solutions to these challenges. However, because each
application is unique, you will not find this application block suitable for every application. To
evaluate this application block and determine its applicability to your projects, Microsoft suggests
you dedicate at least half of a day to explore the application block. The following is a suggested
evaluation approach:

1. Download Enterprise Library.


2. Install Enterprise Library and compile all application blocks and tools.
3. Read the "Introduction" and "Scenarios and Goals" sections of the documentation.
4. Compile and run the QuickStart samples, and read through the related "QuickStart
Walkthroughs" and "Key Scenarios" sections of the documentation.
5. If the application block looks like a good fit for your application, try implementing a simple use
case in your application or in a throw-away prototype application using the application block.

Document Prepared by : Abhishek Maitrey


Source : www.msdn.microsoft.com
Microsoft Enterprise Library 3.1 , May 2007 17 of 50

©2008 Microsoft Corporation. All rights reserved.

Data Access Application Block

Microsoft Corporation

May 2007

Summary

This page provides an overview of the Enterprise Library Data Access Application Block. An
application block is reusable and extensible source code-based guidance that simplifies development
of common data access functionality in .NET Framework applications.

Contents

Introduction to the Data Access Application Block


Design of the Data Access Application Block
Getting Started
Community
Feedback and Support
Related Titles

Introduction to 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 type-specific 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.

Document Prepared by : Abhishek Maitrey


Source : www.msdn.microsoft.com
Microsoft Enterprise Library 3.1 , May 2007 18 of 50

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.

Common Scenarios

Developers often write applications that use databases. Because it is so common, developers may
find themselves repeatedly writing the same code for each application. In addition, these
applications may need to work with different types of databases. Although the tasks are the same,
the code must be adapted to suit the programming model of each database. The Data Access
Application Block solves these problems by providing the logic to perform the most common data
access tasks. Developers only need to do the following:

• Create the database object.

• Supply the parameters for the command, if they are needed.

• Call the appropriate method(s). These methods are optimized for performance. They are also

portable.

The Data Access Application Block works transparently with SQL Server, SQL Server CE, and Oracle
databases.

Example Application Code

The following code shows how to call a stored procedure that returns a DataSet.

Copy Code
[C#]
Database db = DatabaseFactory.CreateDatabase();
DbCommand dbCommand = db.GetStoredProcCommand("GetProductsByCategory");
// Retrieve products from category 7.
db.AddInParameter(dbCommand, "CategoryID", DbType.Int32, 7);
DataSet productDataSet = db.ExecuteDataSet(dbCommand);

[Visual Basic]

Document Prepared by : Abhishek Maitrey


Source : www.msdn.microsoft.com
Microsoft Enterprise Library 3.1 , May 2007 19 of 50

Dim db As Database = DatabaseFactory.CreateDatabase()


Dim dbCommand As DbCommand = db.GetStoredProcCommand("GetProductsByCategory")
' Retrieve products from the category 7.
db.AddInParameter(dbCommand, "CategoryID", DbType.Int32, 7)
Dim productDataSet As DataSet = db.ExecuteDataSet(dbCommand)

What's New

Changes in Enterprise Library 3.1 – May 2007

In addition to the changes in the Enterprise Library 3.0 release, connection strings for OLEDB and
ODBC connections in the May 2007 release of the Data Access Application Block can now be edited
using custom dialog boxes from the configuration tools.

Changes in Enterprise Library 3.0 – April 2007

Enterprise Library 3.0 – April 2007 supports SQL Server Compact Edition (CE). SQL Server CE
provides the essential features of a relational database and is intended for desktop and mobile
applications that need a local data store but do not require the full functionality of SQL Server.

There have been changes to some of the Database class methods in order to take advantage of the
.NET Framework 2.0 TransactionScope class. This class automatically enlists database calls into
an ambient transaction. In this release of the Data Access Application Block, the Database class
methods, such as ExecuteDataSet, recognize when a TransactionScope instance is active and
they enlist database calls in this transaction

There is a new overload of the Database.UpdateDataSet method that takes an updateBatchSize


parameter. Setting the UpdateBatchSize parameter to a positive integer value causes the
DataAdapter object to send updates to the database as batches of the specified size. This reduces
the number of database round trips.

System Requirements

To run the Data Access Application Block, you need a database server running a database that is
supported by a .NET Framework 2.0 data provider (in addition to the system requirements
described on the Enterprise Library page). This includes SQL Server 2000 or later and Oracle 9i. The
database server can also run a database that is supported by the .NET Framework 2.0 data
providers for OLE DB or ODBC.

Design of the Data Access Application Block

The application block was designed to achieve the following goals:

• Encapsulate the logic used to perform the most common data access tasks.

• Eliminate common coding errors, such as failing to close connections.

• Relieve developers of the need to write duplicate code for common data access tasks.

• Reduce the need for custom code.

• Incorporate best practices for data access, as described in the .NET Data Access Architecture

Guide [ http://msdn2.microsoft.com/en-us/library/ms978510.aspx ] .

Document Prepared by : Abhishek Maitrey


Source : www.msdn.microsoft.com
Microsoft Enterprise Library 3.1 , May 2007 20 of 50

• Ensure that, as far as possible, the application block functions work with different types of

databases.

• Ensure that applications written for one type of database are, in terms of data access, the

same as applications written for another type of database.

Design Highlights

Figure 1 illustrates the interrelationship between the key classes in the Data Access Application
Block.

Figure 1. Design of the Data Access Application Block

Assuming that the client code is using the application block configuration information, it calls the
static CreateDatabase method on the DatabaseFactory class to create instances of the
Database object. The DatabaseFactory class uses configuration information found in the
configuration file to determine the specific Database object type to construct and return to the
application. The factory uses the following criteria to determine the Database object type to
construct:

Document Prepared by : Abhishek Maitrey


Source : www.msdn.microsoft.com
Microsoft Enterprise Library 3.1 , May 2007 21 of 50

• If the client code passes a database instance name that identifies a connection string in the

configuration file, the factory uses that string to create the Database object.

Note The .NET Framework classes now maintain the connection strings in the
connectionStrings section of the configuration file. This means that connection string
definitions can be shared among all applications that access the connectionStrings section.

• If the client code does not pass a database instance name, the factory identifies the connection

string by the default instance setting in the configuration file. The defaultDatabase attribute
in the dataConfiguration configuration section controls the default instance. The following
XML fragment from a configuration file shows a default instance that corresponds to the
Production connection string.

Copy Code

<dataConfiguration defaultDatabase="Production">

The <connectionStrings> section in the configuration file maps logical identifiers (names) to
connection strings and DbProviderFactory types. The DatabaseFactory object obtains the logical
name of the ADO.NET data provider from the connection string. The DatabaseFactory object then
calls the .NET Framework DbProviderFactory class to obtain the fully qualified type name for the
ADO.NET data provider. The DatabaseFactory object uses this information to determine the type
of Database object to construct. Although the .NET Framework considers database provider names
in connection strings to be optional, the Data Access Application Block requires them.

The application block configuration code contains default mappings. These map a SqlDatabase
object to a System.Data.SqlClient data provider, an OracleDatabase object to a
System.Data.OracleClient data provider, and a GenericDatabase object to all other data
providers. You can use the configuration console to override the default mappings.

Changing the default mappings or using the configuration console to add new mappings creates a
providerMappings section in the configuration file. The providerMappings section maps the
DbProviderFactory type to the Database type. You can add your own mapping by creating your
own database class and mapping it a DbProviderFactory object.

The abstract base class Database defines the common interface and provides much of the
implementation for the data access methods. The SqlDatabase class and OracleDatabase class
derive from the Database class. They provide methods to their respective database server
systems, which include common functionality that is implemented differently from database to
database, as well as functionality unique to that database system. The application block also
includes a GenericDatabase class. This class does not provide any database-specific features but
operates with any ADO.NET data provider.

The application block supports the dynamic discovery of parameters for stored procedures. This
discovery requires a round trip to the database system. The ParameterCache class allows
parameter information to be cached, thus avoiding round trips for subsequent invocations of the
same stored procedure. (The GenericDatabase class does not support parameter discovery).

Getting Started

The Data Access Application Block has been developed as a result of analyzing common enterprise
development challenges and successful solutions to these challenges. However, because each
application is unique, you will not find this application block suitable for every application. To

Document Prepared by : Abhishek Maitrey


Source : www.msdn.microsoft.com
Microsoft Enterprise Library 3.1 , May 2007 22 of 50

evaluate this application block and determine its applicability to your projects, Microsoft suggests
you dedicate at least half of a day to explore the application block. The following is a suggested
evaluation approach:

1. Download Enterprise Library.


2. Install Enterprise Library and compile all application blocks and tools.
3. Read the "Introduction" and "Scenarios and Goals" sections of the documentation.
4. Compile and run the QuickStart samples, and read through the related "QuickStart
Walkthroughs" and "Key Scenarios" sections of the documentation.
5. If the application block looks like a good fit for your application, try implementing a simple use
case in your application or in a throw-away prototype application using the application block.

Document Prepared by : Abhishek Maitrey


Source : www.msdn.microsoft.com
Microsoft Enterprise Library 3.1 , May 2007 23 of 50

©2008 Microsoft Corporation. All rights reserved.

Exception Handling Application Block

Microsoft Corporation

May 2007

Summary

This page provides an overview of the Enterprise Library Exception Handling Application Block. An
application block is reusable and extensible source code-based guidance that simplifies development
of common exception handling functionality in .NET Framework applications.

Contents

Introduction to the Exception Handling Application Block


Design of the Exception Handling Application Block
Getting Started
Community
Feedback and Support
Related Titles

Introduction to the Exception Handling Application Block

The Enterprise Library Exception Handling Application Block lets developers and policy makers
create a consistent strategy for processing exceptions that occur in all architectural layers of an
enterprise application. It does this in the following ways:

• It supports exception handling in all architectural layers of an application and is not limited to

service interface boundaries.

• It allows exception handling policies to be defined and maintained at the administrative level

so that policy makers, who might be system administrators as well as developers, can define
how to handle exceptions. They can maintain and modify the rules that govern exception
handling without changing the application block code.

• It provides commonly used exception handling functions, such as the ability to log exception

information, the ability to hide sensitive information by replacing the original exception with
another exception, and the ability to maintain contextual information for an exception by
wrapping the original exception inside of another exception. These functions are encapsulated
in .NET classes named exception handlers.

• It can combine exception handlers to produce the desired response to an exception, such as

logging exception information followed by replacing the original exception with another.

• It lets developers create their own exception handlers.

• It invokes exception handlers in a consistent manner. This means that the handlers can be

used in multiple places within and across applications.

Document Prepared by : Abhishek Maitrey


Source : www.msdn.microsoft.com
Microsoft Enterprise Library 3.1 , May 2007 24 of 50

Common Scenarios

The Exception Handling Application Block is designed to support the typical code contained in catch
statements in application components. Instead of repeating this code (such as logging exception
information) throughout identical catch blocks in an application component, the application block
allows developers to encapsulate this logic as reusable exception handlers. Exception handlers are
.NET Framework classes that encapsulate exception handling logic and implement the Exception
Handling Application Block interface named IExceptionHandler. The Exception Handling
Application Block includes four exception handlers:

• Wrap handler. This exception handler wraps one exception around another.

• Replace handler. This exception handler replaces one exception with another.

• Logging handler. This exception handler formats exception information, such as the message

and the stack trace. Then the logging handler gives this information to the Enterprise Library
Logging Application Block so that it can be published.

• Fault Contract Exception Handler. This exception handler is designed for use at Windows

Communication Foundation (WCF) service boundaries, and generates a new Fault Contract
from the exception.

Example Application Code

The following code shows how to execute the policy named "Data Access Policy" when an exception
occurs

Copy Code
[C#]
try
{
// Run code.
}
catch(Exception ex)
{
bool rethrow = ExceptionPolicy.HandleException(ex, " Data Access Policy");
if (rethrow)
throw;
}
Try
' Run code.
Catch ex As Exception
Dim rethrow As Boolean = ExceptionPolicy.HandleException(ex, " Data Access
Policy")
If (rethrow) Then
Throw

Document Prepared by : Abhishek Maitrey


Source : www.msdn.microsoft.com
Microsoft Enterprise Library 3.1 , May 2007 25 of 50

End If
End Try

What's New

This release of the Exception Handling Application Block includes the following improvements:

• The Exception Handling Application Block can be used to implement exception shielding at the

service interface of a WCF application. The ExceptionShieldingAttribute can be defined on a


service implementation class to invoke an exception policy at the service boundary. The
FaultContractExceptionHandler can be used to map exceptions to fault contracts and to
prevent sensitive information from being returned to untrusted callers.

• The ExceptionPolicy.HandleException method includes a new overload that calls the

exception policy and returns the resulting exception in an out parameter instead of throwing
the resulting exception.

• The Wrap and Replace exception handlers include additional configuration properties that allow

you to specify exception messages in external resources instead of directly in the configuration
file. This capability can be used to support localization of exception messages.

Design of the Exception Handling Application Block

The Exception Handling Application Block is designed to achieve the following goals:

• Encapsulate the logic used to perform the most common exception handling tasks into minimal

application code.

• Relieve developers of the requirement to write duplicate code and custom code for common

exception handling tasks.

• Allow exception handling policies to be changed after they have been deployed and to ensure

that changes happen simultaneously and consistently.

• Incorporate best practices for exception handling, as described in the Exception Management

Architecture Guide [ http://msdn2.microsoft.com/en-us/library/ms954599.aspx ] .

Design Highlights

Figure 1 shows the interrelationships between the key classes in the Exception Handling Application
Block.

Document Prepared by : Abhishek Maitrey


Source : www.msdn.microsoft.com
Microsoft Enterprise Library 3.1 , May 2007 26 of 50

Figure 1. Design of the Exception Handling Application Block

The client code interacts with the Exception Handling Application Block through the static method
HandleException. This method is on the ExceptionPolicy class. The HandleException method
uses a factory to create an object of type ExceptionPolicyImpl for the named policy. The
ExceptionPolicyImpl object has a collection of ExceptionPolicyEntry objects. There is one
object for each exception type that is specified in the configuration file for the named policy. For
each exception type, the ExceptionPolicyEntry object contains a collection of objects that
implements the IExceptionHandler interface. The collection is ordered and provides the sequence
that the Exception Handling Application Block uses when executing the policy. Each object that

Document Prepared by : Abhishek Maitrey


Source : www.msdn.microsoft.com
Microsoft Enterprise Library 3.1 , May 2007 27 of 50

implements the IExceptionHandler interface has associated configuration information that is


specific to each type of handler.

Getting Started

The Exception Handling Application Block has been developed as a result of analyzing common
enterprise development challenges and successful solutions to these challenges. However, because
each application is unique, you will not find this application block suitable for every application. To
evaluate this application block and determine its applicability to your projects, Microsoft suggests
you dedicate at least half of a day to explore the application block. The following is a suggested
evaluation approach:

1. Download Enterprise Library.


2. Install Enterprise Library and compile all application blocks and tools.
3. Read the "Introduction" and "Scenarios and Goals" sections of the documentation.
4. Compile and run the QuickStart samples, and read through the related "QuickStart
Walkthroughs" and "Key Scenarios" sections of the documentation.
5. If the application block looks like a good fit for your application, try implementing a simple use
case in your application or in a throw-away prototype application using the application block.

Document Prepared by : Abhishek Maitrey


Source : www.msdn.microsoft.com
Microsoft Enterprise Library 3.1 , May 2007 28 of 50

©2008 Microsoft Corporation. All rights reserved.

Logging Application Block

Microsoft Corporation

May 2007

Summary

This page provides an overview of the Enterprise Library Logging Application Block. An application
block is reusable and extensible source code-based guidance that simplifies development of
common logging functionality in .NET Framework applications.

Contents

Introduction to the Logging Application Block


Design of the Logging Application Block
Getting Started
Community
Feedback and Support
Related Titles

Introduction to the Logging Application Block

The Enterprise Library Logging Application Block simplifies the implementation of common logging
functions. Developers can use the Logging Block to write information to a variety of locations:

• The event log

• An e-mail message

• A database

• A message queue

• A text file

• A WMI event

• Custom locations using application block extension points

The application block provides a consistent interface for logging information to any destination. Your
application code does not specify the destination for the information. Configuration settings
determine whether the application block writes the logging information and the location for that
information. This means that operators as well as developers can modify logging behavior without
changing application code. The Logging Application Block helps with application development in a
number of ways:

• It helps maintain consistent logging practices, both within an application and across the

enterprise.

• It eases the learning curve for developers by using a consistent architectural model.

Document Prepared by : Abhishek Maitrey


Source : www.msdn.microsoft.com
Microsoft Enterprise Library 3.1 , May 2007 29 of 50

• It provides implementations that you can use to solve common application logging tasks.

• It is extensible, supporting custom implementations of components that format and write

event information.

Common Scenarios

Developers frequently write applications that require logging functionality. Typically, these
applications format and log information in response to application events. For example, developers
often write code to log information in response to unexpected conditions, such as an application
exception, or failure to connect to a database. Developers also write code to trace application flow
through components during the execution of an application use case or scenario.

Applications need to write information either locally or over the network. In some cases, you may
have to collate events from multiple sources into a single location.

The Logging Application Block simplifies application development by providing a small set of easy-
to-use classes and methods that encapsulate many of the most common logging scenarios. These
scenarios include:

• Populating and logging event information.

• Including context information in the event.

• Tracing application activities.

Each task is handled in a consistent manner, abstracting the application code from the specific
logging providers.

Example Application Code

The following code shows how to populate and raise an event in your application. The LogEntry
object has a priority of 2 and belongs to both the Trace and UI Events categories.

Copy Code
[C#]
LogEntry logEntry = new LogEntry();
logEntry.EventId = 100;
logEntry.Priority = 2;
logEntry.Message = "Informational message";
logEntry.Categories.Add("Trace");
logEntry.Categories.Add("UI Events");
Logger.Write(logEntry);

[Visual Basic]
Dim logEntry As New LogEntry()
logEntry.EventId = 100
logEntry.Priority = 2

Document Prepared by : Abhishek Maitrey


Source : www.msdn.microsoft.com
Microsoft Enterprise Library 3.1 , May 2007 30 of 50

logEntry.Message = "Informational message"


logEntry.Categories.Add("Trace")
logEntry.Categories.Add("UI Events")
Logger.Write(logEntry)

What's New

This release of the Logging Application Block includes the following new features:

• The RollingFlatFileTraceListener class. This class allows you to control the size and age of a

text log file. It either overwrites the existing file or creates a new file depending on criteria that
you configure.

• Integration with WCF. You can now integrate the Logging Application Block with applications

that use WCF.

• An enhanced version of the TimeStampToken class. Earlier releases of the Logging

Application Block only allowed timestamps to be logged in UTC time. In this release, the
timestamp token now supports a local: prefix that indicates that the timestamp should be
displayed in local time.

• The ReflectedPropertyToken class. This release of the Logging Application Block supports a

new formatting token that allows you to log custom properties on custom classes that either
derive from the LogEntry class or modify it.

System Requirements

To use the Logging Application Block, you need stores to maintain log messages. If you are using
the MsmqTraceListener trace listener to store log messages, you need a message queue. If you
are using the DatabaseTraceListener trace listener to store log messages, you need a database
server. If you are using the EmailTraceListener trace listener to store log messages, you need an
SMTP server.

Design of the Logging Application Block

The Logging Application Block was designed to achieve the following goals:

• Meet the performance requirements for the application block by ensuring that the application

block's code has minimal overhead compared to custom code that uses the
System.Diagnostics namespace directly.

• Take advantage of the capabilities provided by the .NET Framework's System.Diagnostics

namespace.

• Make message routing more flexible than in earlier releases by simplifying the model for

distributing log entries.

• Encapsulate the logic that performs the most common application logging tasks, minimizing

the need for custom logging-related code.

Document Prepared by : Abhishek Maitrey


Source : www.msdn.microsoft.com
Microsoft Enterprise Library 3.1 , May 2007 31 of 50

• Make sure that the application block is easily and highly configurable.

• Make sure that the application block is extensible.

Design Highlights

Figure 1 illustrates the design of the Logging Application Block.

Figure 1. Design of the Logging Application Block

Log Information

The LogEntry class encapsulates content and associated properties for the information an
application sends to the application block for logging. Your client code creates new log entries and
sets properties such as the message, title, priority, severity, and event ID. Other properties, such as
the process name, process ID, and ThreadId, are populated by the application block. A LogEntry
object also contains the ExtendedProperties property. This property is a collection of name/value

Document Prepared by : Abhishek Maitrey


Source : www.msdn.microsoft.com
Microsoft Enterprise Library 3.1 , May 2007 32 of 50

pairs that allows you to place arbitrary string information into the LogEntry object. You can also
create a custom LogEntry object by creating a class that derives from the LogEntry class.

Note You must either create new formatters and trace listeners or modify the existing ones to
support your custom LogEntry class.

A LogEntry object has a collection of categories. The application block determines the destination
for the log entry by its categories. You can also prevent the application from writing log entries with
a designated category by using category filters.

Note Client code can also pass information to the Logging Application Block without constructing a
LogEntry object by using overloads of the Logger.Write method that do not require a LogEntry
object. The application block will construct a LogEntry object for its internal use.

Logging Façade

The Logger class is a façade that sends a log entry to one or more destinations. The client code
sends the information to the Logger instance, which then sends the LogEntry to an instance of the
LogWriter class.

The LogWriter instance checks the filters to see if the LogEntry object should be discarded or sent
to any of the trace sources. The filters are implementations of the ILogFilter interface. You specify
the filter implementations in the configuration information. If the LogEntry object passes through
the filters, the LogWriter instance sends it to each trace source identified by a name that matches
one of the LogEntry object's categories.

Note Whenever a LogEntry object fails within the LogWriter instance, the LogWriter instance
writes a LogEntry object to the ErrorSource special trace source. The EventID is always the
LogWriterFailureEventID. The EventID number is 6352.

The application block relies on the LogSource class to route LogEntry objects. The LogWriter
instance has a collection of LogSource objects that correspond to the sources defined in the
configuration file. The application block uses the collection of categories in a LogEntry object to
determine the LogSource object to use for writing the LogEntry. Categories map directly to
LogSource object names.

The LogWriter object also has three special LogSource objects. The AllEventsLogSource object
receives all LogEntry objects. The NotProcessedLogSource object receives any LogEntry object
that contains a category that does not have an associated LogSource object. The
ErrorsLogSource object receives information about errors or warnings that occur while the Logging
Application Block code is executing. It does not process errors or warnings from the application
code.

Trace Listeners

Each trace source contains a (potentially empty) collection of trace listeners. A trace listener is a
class that derives from the abstract class TraceListener in the System.Diagnostics namespace.
Examples of trace listeners are the event log, a text file, and Message Queuing. Although any
TraceListener instance will work with the Logging Application Block, only those trace listeners that
are provided with the Logging Application Block can format a LogEntry object. The trace listeners
that the .NET Framework provides can be used by the Logging Application Block but they only send
strings.

The Logging Application Block trace listeners do not require a LogEntry object or a formatter to be
instantiated. Instead, you can construct them by including the necessary information in the
configuration file. The FormattedEventLogTraceListener, the FlatFileTraceListener, and the
WmiTraceListener trace listeners use the same configuration information as the
System.Diagnostics trace listeners. This means you can configure your application to use these
three trace listeners in the <system.diagnostics> configuration section of your configuration file.

Document Prepared by : Abhishek Maitrey


Source : www.msdn.microsoft.com
Microsoft Enterprise Library 3.1 , May 2007 33 of 50

The MsmqTraceListener, FormattedDatabaseListener, and EmailTraceListener trace listeners


require more configuration information. For example, the EmailTraceListener trace listener
requires the destination e-mail address, the SMTP server name, and related e-mail information. You
can configure your application to use these trace listeners by including the appropriate information
in the configuration file. However, because these trace listeners require more information than the
System.Diagnostics trace listeners do, you cannot configure them in the <system.diagnostics>
configuration section. Instead, you should use the <listeners> section located in the Logging
Application Block configuration section. You can also construct these trace listeners in code and pass
the required configuration information as parameters to their constructors.

The application block populates the collection of trace listeners from the application configuration
data. The LogSource object sends the LogEntry object to each trace listener in the collection.

Log Filters

You can define configuration settings that control filtering of LogEntry objects. Filtering a LogEntry
object prevents the application block from sending it to any trace source. The application block
includes three types of filters. The CategoryFilter filters LogEntry objects by their category
collection. The PriorityFilter filters LogEntry objects by their priority property. The
LogEnabledFilter is a global filter that applies to all LogEntry objects in an application. With it,
you can turn on and turn off logging. You can also create your own trace sources. Use the
configuration console to list them in the application block's configuration information.

Log Formatters

Log entry information must often be formatted before it is written to the destination. Application
block trace listeners that derive from the FormattedTraceListenerBase class format the log entry
information before writing it to a destination. The application block includes two classes for
formatting LogEntry information. (You can also build your own formatters.) The TextFormatter
class converts the LogEntry into a text string. The contents of the string are determined by
replacing tokens in the template property of the TextFormatter configuration information in your
application configuration file. The BinaryLogFormatter class uses the .NET Framework
BinaryFormatter to serialize and deserialize the LogEntry in binary format. It should be used with
the Message Queuing distributor service.

Getting Started

The Logging Application Block has been developed as a result of analyzing common enterprise
development challenges and successful solutions to these challenges. However, because each
application is unique, you will not find this application block suitable for every application. To
evaluate this application block and determine its applicability to your projects, Microsoft suggests
you dedicate at least half of a day to explore the application block. The following is a suggested
evaluation approach:

1. Download Enterprise Library.


2. Install Enterprise Library and compile all application blocks and tools.
3. Read the "Introduction" and "Scenarios and Goals" sections of the documentation.
4. Compile and run the QuickStart samples, and read through the related "QuickStart
Walkthroughs" and "Key Scenarios" sections of the documentation.
5. If the application block looks like a good fit for your application, try implementing a simple use
case in your application or in a throw-away prototype application using the application block.

Document Prepared by : Abhishek Maitrey


Source : www.msdn.microsoft.com
Microsoft Enterprise Library 3.1 , May 2007 34 of 50

©2008 Microsoft Corporation. All rights reserved.

Policy Injection Application Block

Microsoft Corporation

May 2007

Summary

This page provides an overview of the Enterprise Library Policy Injection Application Block. An
application block is reusable and extensible source code-based guidance that simplifies development of
common logging functionality in .NET Framework applications.

Contents

Introduction to the Policy Injection Application Block


Design of the Policy Injection Application Block
What's New
Getting Started
Community
Feedback and Support
Related Titles

Introduction to the Policy Injection Application Block

Applications include a mix of business logic and crosscutting concerns, and the two are typically
intermingled—which can make the code harder to read and maintain. Each task or feature of an
application is referred to as a "concern." Concerns that implement the features of an object within the
application, such as the business logic, are core concerns. Crosscutting concerns are the necessary
tasks, features, or processes that are common across different objects—for example, logging,
authorization, validation, and instrumentation. The purpose of the Policy Injection Application Block is to
separate the core concerns and crosscutting concerns.

Developers can use the Policy Injection Application Block to specify crosscutting behavior of objects in
terms of a set of policies. A policy is the combination of a series of handlers that execute when client
code calls methods of the class and—with the exception of attribute-based policies—a series of matching
rules that select the classes and class members (methods and properties) to which the application block
attaches the handlers. Attribute-based policies rely on attributes directly applied to the members of the
target class to identify those to which the application block will apply policies. The result is a mechanism
for declaratively applying a chain of handlers to members of the target class instance. This chain of
handlers is a pipeline.

Figure 1 illustrates a high-level view of the way the Policy Injection Application Block implements a
handler pipeline for a specified member of a specified class.

Document Prepared by : Abhishek Maitrey


Source : www.msdn.microsoft.com
Microsoft Enterprise Library 3.1 , May 2007 35 of 50

Figure 1. High-level view of the way the Policy Injection Application Block implements a
handler pipeline

The Policy Injection Application Block provides a mechanism for automatically applying policies to object
instances; this helps developers to better manage crosscutting concerns and maximize separation of
concerns and encapsulation of behavior. Developers define the set of policies for the target classes and
their members through configuration of the Policy Injection Application Block or by applying attributes to
individual members of the target class.

The matching rules for each policy encompass a range of capabilities for selecting classes and members,
including the name of the assembly, the namespace, the type, the member name, the member
signature, attributes that are applied to the member, and more.

A factory method of the Policy Injection Application Block creates a proxy for each configured class
selected by the matching rules or the directly applied attributes; the method attaches the handler
pipelines to each proxy and connects them to the appropriate methods and properties of a new instance
of the target object. If there are no policies for the object, the application block detects this and returns
the object itself instead of a proxy to that object.

The handlers within each pipeline are reusable and independent of the object. Each handler can
implement a specific requirement, such as validating a property value or checking a user's authorization
status. In fact, many of the crosscutting tasks regularly occurring within applications that use Enterprise
Library are calls to other application blocks within the library, such as the Validation Application Block,
the Logging Application Block, the Exception Handling Application Block, the Security Application Block,
and the Instrumentation and Performance Counters features of the Enterprise Library Core.

The Policy Injection Application Block ships with pre-built handlers for these application blocks that
speed up development when using the Enterprise Library to help manage crosscutting concerns.
Developers can also create custom handlers and policies that carry out almost any required interception
processing for methods and properties of their objects.

Design of the Policy Injection Application Block

The Policy Injection Application Block provides a configurable and easy to use mechanism for applying
policies to objects in order to reduce crosscutting concerns and improve object encapsulation. In
particular, it makes it easy to take advantage of common features of the other Enterprise Library
application blocks and core features to accomplish commonly required tasks such as validation,
exception handling, logging, and more. This section describes the design and operation of the Policy
Injection Application Block, showing how the interception mechanism works.

Class Hierarchy of the Policy Injection Application Block

Figure 2 illustrates the interrelationships between the key classes in the Policy Injection Application
Block. This diagram also shows the relative structure and hierarchy of the objects in the set of policies

Document Prepared by : Abhishek Maitrey


Source : www.msdn.microsoft.com
Microsoft Enterprise Library 3.1 , May 2007 36 of 50

for the application block when code executes the Create or Wrap method of the PolicyInjection
factory class.

Figure 2. Class diagram of the Policy Injection Application Block

The Policy Injection Application Block uses .NET Framework remoting technology to perform interception
and allow policies to insert handler pipelines between the client call to a method or property and the
actual target object method or property. Remoting an object requires the .NET Framework to create two
proxies between the client and the target object.

Document Prepared by : Abhishek Maitrey


Source : www.msdn.microsoft.com
Microsoft Enterprise Library 3.1 , May 2007 37 of 50

The first of these proxies is an instance of the __TransparentProxy class (from the
System.Runtime.Remoting.Proxies namespace), which deceives all the common language runtime
(CLR) code that performs casting, field access, method dispatch, and so on, into thinking that it is
dealing with a local instance of the appropriate type. The second of the proxies is an instance of a class
that inherits from the RealProxy class (also in the System.Runtime.Remoting.Proxies namespace).
This class provides an extensibility point where you can define your own proxy to perform
communication across the chosen channel to the target object.

In the Policy Injection Application Block, InterceptingRealProxy is the concrete class that inherits
from the RealProxy class. The InterceptingRealProxy instance generates the handler pipeline and
invokes the first handler in response to calls from the client code arriving through the
TransparentProxy.

Figure 1 also shows the hierarchy of objects that implement the set of policies for the Policy Injection
Application Block. The InterceptingRealProxy instance uses these to select the appropriate classes
and members for which interception will apply, and to generate the handler pipeline for matching class
members. The RuleDrivenPolicy instance holds information about the matching rules and handlers for
a policy defined in the application configuration. The AttributeDrivenPolicy instance holds information
about the set of handlers applied to target object classes and class members through directly applied
attributes, for which there is no information in the application configuration.

Runtime Behavior of the Policy Injection Application Block

To understand how the application block passes client code calls to the target object at run time, you
must visualize the dynamic behavior. Figure 3 illustrates how the InterceptingRealProxy invokes the
first handler in the handler pipeline. Each handler invokes the next handler in the pipeline through a
delegate named GetNextHandlerDelegate until the final handler in the pipeline invokes the method or
accesses the property of the target object.

Figure 3. The process flows through the handler pipeline for a method call to the target
object

After the target method or property accessor completes, control passes back to the previous handler in
the pipeline as the Invoke method calls unwind from the run-time stack. Finally, the
InterceptingRealProxy passes the return value (if any) through the TransparentProxy to the client.

The remoting mechanism in the .NET Framework defines interfaces named IMessage and
IMethodCallMessage that can hold details of the message passed along the remoting channel.
However, the Policy Injection Application Block defines two specific interfaces for classes that implement
invocation and return messages transmitted over the handler pipeline:

Document Prepared by : Abhishek Maitrey


Source : www.msdn.microsoft.com
Microsoft Enterprise Library 3.1 , May 2007 38 of 50

• IMethodInvocation. This interface defines the structure of a message that passes the client call

to the target object. It defines properties that expose the inputs and parameters of the call, the
target object and target member (method or property), and the invocation context (a Dictionary).
It also defines two methods that generate a message or an exception to return to the client.

• IMethodReturn. This interface defines the structure of a message that passes back from the

target object to the client and contains the result of the property access or method invocation. It
defines a property that exposes the output parameters, read/write properties that expose the
return value and any exception for return to the client, and the invocation context (a Dictionary).

Each handler can examine and modify the values in the messages, although they must not attempt to
modify the method or property accessor signature because this will generally result in remoting failures
and hard to find bugs in the handler code.

Aborted Handler Exception

Figure 4 demonstrates a scenario where a handler in the handler pipeline aborts execution. In this
scenario, the handler pipeline contains—in execution order—a Logging Handler, an Authorization
Handler, and a Validation Handler. If, as shown in Figure 4, the Authorization Handler detects an
authorization failure, it simply fails to invoke the next handler in the chain. Therefore, only the series of
Invoke calls already executed will unwind from the stack. This means that only the handlers that have
already executed can perform their post-processing tasks.

Figure 4. The process flows through the handler pipeline when a handler aborts the method
call to the target object

Also notice in Figure 4 how a handler can return an exception to the client code by adding it to the
message that passes along the handler pipeline. This allows handlers earlier in the pipeline to carry out
their post-processing tasks (such as, in this example, creating and writing a log message) as the
Invoke stack unwinds. If, instead of passing it back through the message, a handler raises an
unhandled exception, the previous handlers will not be able to execute their post-processing tasks.

What's New

The interception mechanism used by the Policy Injection Application Block depends on standard .NET
Framework remoting techniques. However, in the Enterprise Library 3.1 – May 2007 release, you can
change the interception mechanism to one that better suits your custom requirements via configuration.

Document Prepared by : Abhishek Maitrey


Source : www.msdn.microsoft.com
Microsoft Enterprise Library 3.1 , May 2007 39 of 50

For example, you may want to use a different communication channel for messages sent between
handlers and the target object, or you may need to use a custom message type.

Connecting your new interception mechanism to the rest of the Policy Injection Application Block
requires that you create a class that inherits from the PolicyInjector class. For configuration support,
you can implement a configuration element by deriving from the InjectorData class. After you do that,
you can use the Enterprise Library Configuration Console to set the Policy Injection Application Block to
use your injector as the default instead of the normal remoting proxy based interception.

Additionally, this release of the Policy Injection Application Block includes the following improvements:

• Call Handler attributes are now correctly honored when they are placed on interface methods.

• An issue that could cause duplicate handlers where matching rules matched both a class and its

interface is fixed in this release.

• Classes implementing COM interfaces (including those derived from

System.Windows.Forms.Form) can now be intercepted.

• TraceLogEntry class is now serializable, allowing it to be used with the MSMQ Trace Listener.

Getting Started

The Policy Injection Application Block has been developed as a result of analyzing common enterprise
development challenges and successful solutions to these challenges. However, because each application
is unique, you will not find this application block suitable for every application. To evaluate this
application block and determine its applicability to your projects, Microsoft suggests you dedicate at
least half of a day to explore the application block. The following is a suggested evaluation approach:

1. Download the Enterprise Library.


2. Install the Enterprise Library and compile all application blocks and tools.
3. Read the "Introduction" and "Scenarios and Goals" sections of the documentation.
4. Compile and run the QuickStart samples, and read through the related "QuickStart Walkthroughs"
and "Key Scenarios" sections of the documentation.
5. If the application block looks like a good fit for your application, try implementing a simple use case
in your application or in a throw-away prototype application using the application block.

Document Prepared by : Abhishek Maitrey


Source : www.msdn.microsoft.com
Microsoft Enterprise Library 3.1 , May 2007 40 of 50

©2008 Microsoft Corporation. All rights reserved.

Security Application Block

Microsoft Corporation

May 2007

Summary

This page provides an overview of the Enterprise Library Security Application Block. An application
block is reusable and extensible source code-based guidance that simplifies development of
common security functionality in .NET Framework applications.

Contents

Introduction to the Security Application Block


Design of the Security Application Block
Getting Started
Community
Feedback and Support
Related Titles

Introduction to the Security Application Block

The Microsoft Enterprise Library Security Application Block helps developers implement common
authorization-related functionality in their applications. Applications can use the Security Application
Block to support authorization and to cache a user's authorization and authentication data. Together
with the Microsoft .NET Framework 2.0 features, developers can easily implement common security-
related functionality. The Security Application Block has the following features:

• It reduces the requirement to write boilerplate code to perform standard tasks.

• It helps maintain consistent security practices, both within an application and across the

enterprise.

• It eases the learning curve for developers by using a consistent architectural model across the

various areas of functionality provided.

• It provides implementations that you can use to solve common application security problems

• It is extensible; it supports custom implementations of security providers.

Common Scenarios

Developers frequently write applications that must authorize users using one or more security
providers such as Microsoft Active Directory directory service, Authorization Manager, Active
Directory Application Mode (ADAM), and custom authorization providers. These applications may
also need to cache authentication or authorization data for the duration of a logon session.

The Security Application Block simplifies these tasks by handling them in a consistent manner,
abstracting the application code from the specific security providers. You can even change

Document Prepared by : Abhishek Maitrey


Source : www.msdn.microsoft.com
Microsoft Enterprise Library 3.1 , May 2007 41 of 50

underlying providers through configuration changes without changing the underlying application
code.

The Security Application Block provides code that will help you with the following scenarios:

• Authorization

• Caching security-related credentials

Example Application Code

The following code shows how to determine if a user is authorized to perform a task.

Copy Code
[C#]
IPrincipal principal = new GenericPrincipal(new GenericIdentity("Username"),
new string[]{"Manager"});
IAuthorizationProvider ruleProvider =
AuthorizationFactory.GetAuthorizationProvider("RuleProvider");
// Determine whether user is authorized for the rule defined as "Print
Document".
bool authorized = ruleProvider.Authorize(principal, "Print Document");

[Visual Basic]
Dim principal As IPrincipal = New GenericPrincipal(New
GenericIdentity("Username"), New String() {"Manager"})
Dim ruleProvider As IAuthorizationProvider =
AuthorizationFactory.GetAuthorizationProvider("RuleProvider")
' Determine whether user is authorized for the rule defined as "Print
Document".
Dim authorized As Boolean = ruleProvider.Authorize(principal, "Print Document")

Design of the Security Application Block

The application block is designed to achieve the following goals:

• Provide a simple and intuitive interface to the commonly required authorization functionality.

• Encapsulate the logic used to perform authorization and security-related caching.

• Present a standard provider model for authorization and security-related caching.

• Ensure that the application block is extensible.

• Ensure that there is minimal or negligible performance impact compared to manually written

security code that accomplishes the same functionality.

Document Prepared by : Abhishek Maitrey


Source : www.msdn.microsoft.com
Microsoft Enterprise Library 3.1 , May 2007 42 of 50

• Incorporate best practices for application security, as described in Improving Web Application

Security: Threats and Countermeasures [ http://msdn2.microsoft.com/en-


us/library/ms994921.aspx ]

Design Highlights

The Security Application Block is designed to externalize the implementation of the authorization
and caching provider from a running application. This design lets you change implementations
without changing the code of the application. Figure 1 illustrates the interrelationship between the
key classes in the Security Application Block.

Figure 1. Design of the Security Application Block

Getting Started

Document Prepared by : Abhishek Maitrey


Source : www.msdn.microsoft.com
Microsoft Enterprise Library 3.1 , May 2007 43 of 50

The Security Application Block has been developed as a result of analyzing common enterprise
development challenges and successful solutions to these challenges. However, because each
application is unique, you will not find this application block suitable for every application. To
evaluate this application block and determine its applicability to your projects, Microsoft suggests
you dedicate at least half of a day to explore the application block. The following is a suggested
evaluation approach:

1. Download Enterprise Library.


2. Install Enterprise Library and compile all application blocks and tools.
3. Read the "Introduction" and "Scenarios and Goals" sections of the documentation.
4. Compile and run the QuickStart samples, and read through the related "QuickStart
Walkthroughs" and "Key Scenarios" sections of the documentation.
5. If the application block looks like a good fit for your application, try implementing a simple use
case in your application or in a throw-away prototype application using the application block.

Document Prepared by : Abhishek Maitrey


Source : www.msdn.microsoft.com
Microsoft Enterprise Library 3.1 , May 2007 44 of 50

©2008 Microsoft Corporation. All rights reserved.

Validation Application Block

Microsoft Corporation

May 2007

Summary

This page provides an overview of the Enterprise Library Validation Application Block. An application
block is reusable and extensible source code-based guidance that simplifies development of
common logging functionality in .NET Framework applications.

Contents

Introduction to the Validation Application Block


Design of the Validation Application Block
What's New
Getting Started
Community
Feedback and Support
Related Titles

Introduction to the Validation Application Block

Any application that accepts input either from users or from other systems must ensure that the
information is valid in terms of some set of rules that you specify. For example, when processing an
order, you may need to check that a customer's phone number has the correct number of digits, or
that a date falls within a particular range. In addition, if the validation fails, you may need to send
an error message that explains what is wrong.

The Enterprise Library Validation Application Block provides a library of classes, called validators,
that supplies the code for validating .NET Framework data types. For example, one validator checks
for null strings and another validator checks that a number falls within a specified range.

There are also special validators named AndCompositeValidator and OrCompositeValidator. If


you create an AndCompositeValidator, which aggregates other validators, all validators in the
composite must be true for a successful validation. If you create an OrCompositeValidator, at
least one of the validators in the composite must be true for a successful validation.

You can also group validators together in a rule set. A rule set allows you to validate a complex
object or graph by composing different validators of different types and applying them to elements
in the object graph. Examples of these elements include fields, properties, and nested objects.

There are three ways to perform validation within the application block, and to create rule sets.
They are:

• Using configuration

• Using attributes

Document Prepared by : Abhishek Maitrey


Source : www.msdn.microsoft.com
Microsoft Enterprise Library 3.1 , May 2007 45 of 50

• Using code

In addition, the Validation Application Block includes adapters that allow you to use the application
block with the following technologies:

• ASP.NET

• Windows Forms

• Windows Communications Framework (WCF)

Common Scenarios and Goals

Validation has many applications. For example, you can use it to prevent the injection of malicious
data by checking to see if a string is too long or if it contains illegal characters. You can also use
validation to enforce business rules and to provide responses to user input. It is often important to
validate data several times within the same application. For example, you may need to validate data
at the UI layer to give immediate feedback when a user enters an invalid data value, and again at
the service interface layer for security.

Example Application Code

Copy Code
C#
using Microsoft.Practices.EnterpriseLibrary.Validation;
using Microsoft.Practices.EnterpriseLibrary.Validation.Validators;
public class Customer
{
[StringLengthValidator(0, 20)]
public string CustomerName;

public Customer(string customerName)


{
this.CustomerName = customerName;
}
}

public class MyExample


{
public static void Main()
{
Customer myCustomer = new Customer("A name that is too long");
ValidationResults r = Validation.Validate<Customer>(myCustomer);
if (!r.IsValid)

Document Prepared by : Abhishek Maitrey


Source : www.msdn.microsoft.com
Microsoft Enterprise Library 3.1 , May 2007 46 of 50

{
throw new InvalidOperationException("Validation error found.");
}
}
}
Visual Basic
Imports Microsoft.Practices.EnterpriseLibrary.Validation
Imports Microsoft.Practices.EnterpriseLibrary.Validation.Validators
Public Class Customer
<StringLengthValidator(0, 20)> _
Public CustomerName As String
Public Sub Customer(ByVal customerName As String)
Me.CustomerName = customerName
End Sub
End Class
Module Module1
Public Sub Main()
Dim myCustomer As Customer = New Customer()
myCustomer.CustomerName = "A name that is too long"
Dim r As ValidationResults = Validation.Validate(myCustomer)
If Not r.IsValid Then
Throw New InvalidOperationException("Validation error found.")
End If
End Sub
End Module

Because the StringLengthValidator attribute is applied, the Validation Block checks that the
length of the customer name is between 0 and 20 characters. The application creates a new
Customer object and validates it using the Validation Block façade. In this case, the customer
name is illegal because it is too long. The application throws an exception that notifies you of the
error.

Highlights

The Validation Application Block has the following benefits:

• It helps maintain consistent validation practices.

• It includes validators for validating most standard .NET data types.

• It allows you to create validation rules with configuration, with attributes, and with code.

Document Prepared by : Abhishek Maitrey


Source : www.msdn.microsoft.com
Microsoft Enterprise Library 3.1 , May 2007 47 of 50

• It allows you to associate multiple rule sets with the same class and with members of that

class.

• It can be integrated with ASP.NET, Windows Forms, and Windows Communications Foundation

(WCF).

Design of the Validation Application Block

The Validation Application Block is designed to do the following:

• Encapsulate the logic used to perform the most common validation tasks into minimal

application code.

• Relieve developers of the requirement to write duplicate code and custom code for common

validation tasks.

• Allow validation rules to be changed after they have been deployed and to ensure that changes

happen simultaneously and consistently.

Design Highlights

Figure 1 illustrates the interrelationships between the key classes in the Validation Application Block.

Document Prepared by : Abhishek Maitrey


Source : www.msdn.microsoft.com
Microsoft Enterprise Library 3.1 , May 2007 48 of 50

Figure 1. Diagram of Validation Application Block

The client code can call the Validation façade, which allows you to create a validator and validate
an object with a single line of code. Alternatively, it can call the ValidationFactory class to create a
validator and then call the Validate method on the Validator class to perform the check.

The class diagram shows the various kinds of validators and attributes provided by the Validation
Application Block. These are described in the previous sections.

What's New

The May 2007 release of the Validation Application Block includes the following improvements:

• An issue that prevented the PropertyComparisonValidator from working with the Windows

Forms integration adapter is fixed in this release.

• The message template for the PropertyComparisonValidator can now be saved using the

configuration tools.

Document Prepared by : Abhishek Maitrey


Source : www.msdn.microsoft.com
Microsoft Enterprise Library 3.1 , May 2007 49 of 50

Getting Started

The Validation Application Block has been developed as a result of analyzing common enterprise
development challenges and successful solutions to these challenges. However, because each
application is unique, you will not find this application block suitable for every application. To
evaluate this application block and determine its applicability to your projects, Microsoft suggests
you dedicate at least half of a day to explore the application block. The following is a suggested
evaluation approach:

1. Download Enterprise Library.


2. Install Enterprise Library and compile all application blocks and tools.
3. Read the "Introduction" and "Scenarios and Goals" sections of the documentation.
4. Compile and run the QuickStart samples, and read through the related "QuickStart
Walkthroughs" and "Key Scenarios" sections of the documentation.
5. If the application block looks like a good fit for your application, try implementing a simple use
case in your application or in a throw-away prototype application using the application block.

Document Prepared by : Abhishek Maitrey


Source : www.msdn.microsoft.com
Microsoft Enterprise Library 3.1 , May 2007 50 of 50

Document Prepared by : Abhishek Maitrey


Source : www.msdn.microsoft.com

You might also like