Best-practice enterprise coding

This article was originally published in VSJ, which is now part of Developer Fusion.
Before considering an overview of the Enterprise Library, it’s essential to understand the nature of the application blocks that the library configures and manages. So what are application blocks?

The Microsoft Patterns and Practices group gives guidance on patterns and best practice when developing enterprise applications. These patterns are applicable both to normal desktop applications and enterprise applications, but they are really applicable when developing for the enterprise. A common vision of the enterprise is shown in Figure 1.

Figure 1
Figure 1

There are clear layers, and the layers communicate with each other via service interfaces. Allied to these layers are common services which provide security, transactions and persistence management to the enterprise. Application blocks essentially take the guidance that Microsoft supplies and provide code blocks that you can use in your application to utilise this good practice. You can review the 12 available blocks.

The enterprise library has several aims – to make these application blocks more consistent, to make them easier to configure by providing a tool to configure them, as shown in Figure 2, and by making them extensible.

Figure 2
Figure 2

This allows you to create your own blocks, and to catalogue, manage and configure them via a centralised configuration tool. Equally importantly, you can validate your configuration, and any errors are highlighted at compilation time, rather than run time, as is the case now. We will discuss the configuration later in the article, but essentially to allow for common configuration clearly each block must have a fairly common feature set. Once again patterns come to our rescue, as shown in Figure 3.

Figure 3
Figure 3

Each block must provide at least one Abstract Factory which is derived from the base class ProviderFactory. This class is located in the

Microsoft.Practices.EnterpriseLibrary.
	Configuration
namespace. The factory will return a Provider instance. This provider is an instance of a specific interface, or alternatively a subclass of an abstract class, that will provide the functionality of the block. Some blocks will have more than one ProviderFactory, for instance the security block has providers for authentication, role-based authorisation, and profile management.

Where do you get it?

Simply download the enterprise library.

You will have to register (unless you are an existing ‘Passport’ customer). Once you have the exe file, run it to install. This will install the source code (yes, you heard right, the source code, along with an open source EULA, so that you are allowed to modify and redistribute the code) for the blocks, and optionally build all the blocks and store the DLLs in the bin folder. When the install is complete your start menu will have a new program group, as shown in Figure 4. (If you didn’t perform the build during the installation, then perform it now).

Figure 4
Figure 4

One issue with the enterprise library that is slightly problematic is that it uses the event log to report to, and the sources are not created in the event log. This means that the blocks must run under administrative control to function properly. To fix this problem, simply run the Install Services task as an administrator. This will create the event log sources you need (and install extra performance counters), so you can now use the blocks with lower privileges.

Using the Enterprise Library

To demonstrate the use of the library you will create a simple form and populate it with data from the Northwind database. Begin by creating a new Windows Application and adding references to the
Microsoft.Practices.EnterpriseLibrary.
	Configuration
and
Microsoft.Practices.EnterpriseLibrary
DLLs. You will be using the Data Application Block to retrieve data from the Northwind database so the first step is to configure the DataProvider to use this database. Open the Enterprise Library Configuration tool and create a new Application, giving it a suitable name (SmartDataClient for instance). Now right click this application and select new Data Access Application Block. This will automatically create a configuration block as well. You can now configure the Sql Connection String – give the database the value Northwind, leave integrated security set to True and then fill in the server field. If your SQL server is local, simply provide the value (local); alternatively provide your SQL Server name. You will find a Database Instance; rename this to something appropriate like Northwind. Now save your application to the file App.config located in your Visual Studio project location.

If you look in the project location, you will find an App.config file, but you should also notice a dataConfiguration.config file. This pattern is used throughout the enterprise library, the main application file contains the configuration file location, and each block has its own configuration file. This configuration needs to be available at runtime, so the *.config files need to be copied to the executable folder, so you need to create a custom build task as shown in Figure 5.

Figure 5
Figure 5

You will use the ConfigurationManager to retrieve the configuration at runtime. This configuration is then passed to the Factory to create a Provider. In the Data Access Application Block, the provider we are interested in is the Database, as shown in the following code:

DatabaseProviderFactory factory =
	new DatabaseProviderFactory(
	ConfigurationManager.GetCurrentContext());
Database db =
	factory.CreateDatabase(“Northwind”);
This Database object encapsulates the underlying database and has methods to execute commands and return ether DataReaders or DataSets. Commands are encapsulated by DBCommandWrapper objects, as shown in the code below.
DBCommandWrapper cw =
	db.GetStoredProcCommandWrapper(
	“CustOrderHist”,new object[]{“ALFKI”});
DataSet ds = db.ExecuteDataSet(cw);
From that point on you use the DataSet as you would normally.

It’s more than just a data block

Another of the very useful application blocks contained within the Enterprise Library is the caching block, which allows you to store items in a cache and to specify a wide range of dependencies to invalidate the cache, much as the ASP.NET cache is available for web applications. A very useful feature of the caching block is the ability to specify an offline backing store, so that the cache can be persisted between invocations of your program. The cache can be persisted to Isolated Storage or to a Database, and of course you could create your own CacheStorageProvider. To begin using this block, you will configure it using the Enterprise Library Configuration Tool as shown in Figure 6.

Figure 6
Figure 6
Now using the same factory pattern you will retrieve a provider and add and retrieve items from the cache, as shown in the code below.

CacheManager cache =
	CacheFactory.GetCacheManager();
symbols = (IList)cache.GetData(“Symbols”);
if (symbols == null)
{
	Logger.Write(
		“Items not in cache”,”General”);
	symbols = . . .;
	cache.Add(“Symbols”,
		symbols, CacheItemPriority.Normal, null,
		new SlidingTime(TimeSpan.
		FromSeconds(15)));
}
else
{
	Logger.Write(
		“Retrieved from cache”,”General”);
}

So what are you waiting for?

The Enterprise Library is a well thought out framework, which will make it easier for you to develop code using best practices. The security block, in particular, makes some tricky functionality much easier to implement. The code blocks have a consistent approach, so effort spent learning one block is easily transferred to another application block, and finally if you don’t like the standard implementation you can change it to suit your business needs by creating your own application block and adding it to the library.


James Winters is a principal technologist at QA, where he specialises in training development, course delivery, and product consulting on Java and .NET technology.

You might also like...

Comments

Contribute

Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“Perl - The only language that looks the same before and after RSA encryption.” - Keith Bostic