You are on page 1of 14

Using Enterprise Library 5.

0 in Windows
Azure
This document explains the capabilities and limitations of using Enterprise Library 5.0 within .NET
applications designed to run with the Windows Azure™ technology platform. It covers the following
topics:

 Compatibility Overview

◦ The Caching Application Block


◦ The Cryptography Application Block
◦ The Data Access Application Block
◦ The Exception Handling Application Block

◦ The Logging Application Block


◦ The Policy Injection Application Block
◦ The Security Application Block
◦ The Validation Application Block

◦ Unity Dependency Injection and Interception Mechanism


◦ Configuration
◦ Instrumentation
 Sample Windows Azure QuickStart Using Enterprise Library
◦ Using the Logging Application Block
◦ Using Instrumentation
◦ Using the Policy Injection Application Block

 Summary
 More Information

1
Copyright
This document is provided "as-is." Information and views expressed in this document, including URL and
other Internet website references, may change without notice. You bear the risk of using it. Some
examples depicted herein are provided for illustration only and are fictitious. No real association or
connection is intended or should be inferred.
© 2012 Microsoft. All rights reserved.
Microsoft, Windows, Windows Server, Windows Vista, Windows Azure, Windows PowerShell, Silverlight,
Expression, Expression Blend, MSDN, IntelliSense, IntelliTrace, Internet Explorer, SQL Azure, SQL Server,
Visual C#, Visual C++, Visual Basic, and Visual Studio are trademarks of the Microsoft group of
companies.
All other trademarks are the property of their respective owners.

Compatibility Overview
The following sections provide a brief overview of the opportunities for using each of the Enterprise
Library application blocks and core tools within .NET applications designed to run with Windows Azure.

The Caching Application Block


The Caching Application Block does not provide the features required for distributed caching. Instead,
you should consider using one of the following technologies:

 Windows Azure Caching. This enables you to provision a distributed cache in the cloud. For
more information, see Windows Azure Caching Service.
 Maintaining state and value in Windows Azure table storage. Examples of how to implement
this, and other useful resources, are included in the Windows Azure Training Kit.
 The caching mechanism of the System.Runtime.Caching namespace of .NET Framework 4.0. For
more information, see System.Runtime.Caching Namespace.
The SQL Scripts which are compatible with the SQL Azure™ technology platform and are required for the
Caching Database provider are available as a separate download. To get the scripts, download the
EnterpriseLibraryIntegrationPack-WindowsAzure-sqlscripts.exe from the Microsoft® Enterprise Library
5.0 Integration Pack for Windows Azure.

The Cryptography Application Block


You can use the Cryptography Application Block to create and compare hash values using any of the
algorithms installed with the .NET Framework, or with custom hash algorithm providers you create.
However, the symmetric cryptography provider keys used by some symmetric algorithm providers
(when using symmetric algorithms such as AES Managed and Rijndael) are stored in a file that is
referenced using a full physical file path and name in the application configuration file and protected by

2
DPAPI encryption. Because DPAPI is not available in Windows Azure, you cannot use the Enterprise
Library symmetric cryptography providers. However, you may consider creating custom symmetric
algorithm providers for use with the block. These providers could use the .NET Cryptographic Service
Providers (CSPs) to implement encryption and as a best practice store the keys in encrypted format,
performing the encryption offline, and storing them in Windows Azure Blob storage. For more
information on this approach, see Using Certificate-Based Encryption in Windows Azure Applications
and Securing Your Connection String in Windows Azure: Part 1.
For general information on creating a custom provider for Enterprise Library, see Enterprise Library
Extension Points.

The Data Access Application Block


The Data Access Application Block uses individual providers for each type of database. There is no
provider for Windows Azure Blob, Queue, or Table storage mechanisms in the current release. However,
you can use the SQLDatabase provider included with the Data Access Application Block in conjunction
with SQL Azure storage.

The Exception Handling Application Block


The Exception Handling Application Block can be used to implement a consistent exception handling
strategy across components, services, and applications hosted within Windows Azure. You can use the
Wrap Handler and Replace Handler in exactly the same way as in an application not using Windows
Azure. You can also use the Fault Contract Exception Handler in your WCF services. However, there are
limitations in the use of the Logging Handler. For more details, see the following section.

The Logging Application Block


The Logging Application Block provides a powerful mechanism for creating, categorizing, and filtering log
messages, and for routing these messages to a wide range of destinations such as a Windows Event Log,
WMI, disk files, a database, a message queue, or as an email message. The mechanisms for generating,
categorizing, and filtering log messages work in exactly the same way as in an application not using
Windows Azure. In addition, you can use the Windows Azure Diagnostic Monitor Trace Listener
implementation by configuring it as a System Diagnostics TraceListener for the Logging Application
Block. Note that in order for log messages and event log entries to appear in the Windows Azure
diagnostics tables you will need to configure and initialize Windows Azure diagnostics. The Logging
Application Block will not do this automatically for you. For more information on configuring and
initializing Windows Azure Diagnostics, see Overview of Initializing the Windows Azure Diagnostic
Monitor and Configuring Data Sources.
The following limitations apply to the types of Trace Listener included with the Logging Application
Block:
 The Database Trace Listener uses the Data Access Application Block to write log messages. For
details of limitations, see the earlier section that describes the Data Access Application Block. In

3
addition, this listener requires the SQL scripts which are compatible with SQL Azure. Download
the EnterpriseLibraryIntegrationPack-WindowsAzure-sqlscripts.exe from the Microsoft
Enterprise Library 5.0 Integration Pack for Windows Azure. Note that the scripts included in the
Enterprise Library 5.0.msi and Enterprise Library 5.0 NuGet packages are not compatible with
SQL Azure.
 The Email Trace Listener requires access to a mail server that will create and route the email
message. You must ensure that you have access to a suitable server if you wish to use this trace
listener. For information on sending emails from Windows Azure applications see
EmailTheInternet.com: Sending and Receiving Email in Windows Azure.

 The Flat File Trace Listener, Rolling Flat File Trace Listener, and XML Trace Listener are
designed to write to a physical disk file. Even though access to the file system is available on
Windows Azure (such as the local VM file system and the XDrive facility) there are limitations.
For example, XDrive volumes can be written to by only one instance at a time. Therefore, use of
these trace listeners in Windows Azure hosted applications is not recommended.
If file-based trace listeners are used, it is generally helpful to rely on environment variables
when specifying the trace listeners' paths, such as the %TEMP% variable or a custom variable
pointing to a role's local resource. In the latter case, using a rolling trace listener is
recommended because the local resource has a limited size. You can use a startup task for
setting up the environment variable safely, following the technique described in Using a Local
Storage Resource From a Startup Task for getting the root path for a local resource from a
Windows PowerShell® script. Keep in mind that accessing these logging files will require
accessing each role instance.

 The Event Log Trace Listener writes log entries to the Windows Event Log. A prerequisite for
using the Event Log Trace Listener with the default settings is to ensure that the default event
source ("Enterprise Library Logging") is installed. In order to install this event source (or any
other custom source) and use this listener, a startup task that executes Windows PowerShell
scripts can be used. These scripts install the custom source. The QuickStart, referenced below,
uses this approach. See Sample Windows Azure QuickStart Using Enterprise Library for more
details.
For more information on startup tasks, see Starting Tasks Before Role Instances Start in Windows Azure.
For information on creating event logs and sources from Windows PowerShell, see New-Event Log.
You will also want to configure Windows Azure Diagnostics to transfer event logs to Windows Azure
Storage to access the events logged by the Event Log trace listener.

 You cannot access the Windows Message Queuing service, and so you cannot use the Message
Queuing Trace Listener.
 Access to Windows Management Instrumentation events requires administrative permission, so
you cannot successfully use the WMI Trace Listener to log and retrieve information. However, it
may be possible to use this in future releases of Windows Azure.
4
 Your application must run in full trust mode if you need to use a Tracer instance or extract
unmanaged context information using the Unmanaged Security Context Information Provider.

The Policy Injection Application Block


The following limitations apply when you are using policy injection with Unity and Enterprise Library call
handlers:
 The Authorization Handler can be used in a Windows Azure hosted application to cache a user's
identity and security context for use throughout the application, and to authorize users against
a range of authorization providers. For details of limitations, see The Security Application Block.
 The Caching Handler is no longer included in Enterprise Library. While you can download this
handler from the Enterprise Library Community website on CodePlex, it should only be used for
backwards compatibility in existing applications. It is not recommended for use in Windows
Azure hosted applications.
 The Exception Handling Handler can be used in a Windows Azure hosted application to
implement consistent exception handling policies. It uses the Exception Handling Application
Block. For details of limitations, see The Exception Handling Application Block.
 The Logging Handler can be used in a Windows Azure hosted application to implement logging
of method calls and property access for components and services. It uses the Logging
Application Block. For details of limitations, see The Logging Application Block.
 The Performance Counter Handler can be used in Windows Azure applications. The
performance counters can be configured following the instructions from The Performance
Counter Handler and installed using a startup task, which invokes installutil.exe. You will also
need to configure Windows Azure Diagnostics to store the performance counter samples in
Windows Azure Storage, using the appropriate category and instance names when defining the
performance counter sources. The QuickStart accompanying this white paper uses this
approach. For more details see "Sample Windows Azure QuickStart Using Enterprise Library."
 The Validation Handler can be used in a Windows Azure hosted application to implement
validation of properties, or the values specified for the parameters of methods, against specific
rules. This handler uses the Validation Application Block, taking advantage of the wide range of
capabilities that it offers. For details of limitations, see The Validation Application Block.

The Security Application Block


The Security Application Block can be used in a Windows Azure hosted application to cache a user's
identity and security context in memory for use throughout the application. These identities and
security contexts can include any implementation of IPrincipal, IIdentity (such as WindowsIdentity,
GenericIdentity, PassportIdentity, or FormsIdentity), and the ASP.NET Profile instance. The block can
also be used to authorize users against a range of authorization providers. If you decide to use the
Security Application Block, consider the following limitations:

5
 The credentials cache is implemented by the Caching Application Block, and therefore the
Security Application Block may be deprecated or change considerably in future releases of
Enterprise Library.

 Active Directory access is not available in Windows Azure, and so you cannot authorize against
Windows Authorization Manager (AzMan). You can authorize users only by using rules defined
in the Enterprise Library configuration with the Authorization Rules Provider.
 As an alternative, consider using claims identity to authorize users instead of the Security
Application Block. For more information, see A Guide to Claims-Based Identity and Access
Control (2nd Edition).

The Validation Application Block


You can use the Validation Application Block in a Windows Azure hosted application to validate a type,
the values of public readable properties, the values of public fields, and the return value of public
methods that take no parameters. In conjunction with the Unity interception mechanism and the
ValidationCallHandler, you can also validate the values of parameters passed to methods or the values
used to set properties. You can use Validation Application Block attributes, Data Annotation attributes,
self validation, and rule sets defined in the application configuration. Note that for DateTime based
validators, the UTC DateTime values are applied for validations.

Unity Dependency Injection and Interception Mechanism


You can use the Unity dependency injection and interception mechanism in a Windows Azure hosted
application. Unity uses dynamically generated methods to perform injection and in very few special-case
scenarios, full trust is required. For more information, see Using Unity in Partial Trust Environments.

Configuration
The System Configuration Source reads the Enterprise Library configuration sections in the App.config
or Web.config files. This configuration source will work in Windows Azure. However, you should be wary
of trying to use Enterprise Library application blocks which are configured in the Web.config from a web
role OnStart event because the process that runs the web role does not read the Web.config file. There
are a number of approaches that you can use to work around this issue:
 Package and deploy the Web.config file as a part of the web role deployment. You can copy it
manually or set the project to copy it automatically through the "Copy if newer" setting (just
like any other file). Then use the following code in the web role to initialize the Enterprise
Library container.
C#
EnterpriseLibraryContainer.Current =
EntepriseLibraryContainer.ConfigureDefaultContainer(new
FileConfigurationSource("web.config", false));

6
 Keep each shared section in a separate configuration file and use the configSource attribute to
point to them.
 The File-based Configuration Source reads the Enterprise Library configuration sections from an
external file. The File-based Configuration Source can be used with relative paths.
 The Manageable Configuration Source is not supported on Windows Azure.

 The SQL Configuration Source is available as a separate download and reads the Enterprise
Library configuration sections from a Microsoft SQL Server® database. To get this configuration
source and the SQL Scripts to enable you to create the database on SQL Azure, download both
the SqlConfigurationSource.zip and the SQLConfigurationSourceforSQLAzure.zip from the
Enterprise Library 5.0 - SQL Configuration Source download page on CodePlex.
Note that the Enterprise Library Configuration tool does not disable features which do not work in
Windows Azure when it is used to configure the different application blocks.

Instrumentation
There are three instrumentation mechanisms in the Enterprise Library: WMI events, performance
counters, and Windows Event Log events.
WMI instrumentation for the Enterprise Library application blocks is not supported for Windows Azure
applications.
Using performance counters and Windows Event Log instrumentation requires installing the
instrumentation by running installutil.exe for each of the Enterprise Library assemblies used by the
application, and configuring the Diagnostics Monitor to publish the instrumentation.
All the application blocks use event log sources in the Application log, so configuring the Diagnostics
Monitor to publish all events in the Application log would include the instrumentation. Alternatively,
more fine-grained configuration for the specific sources used to instrument the application block can be
set for the Diagnostics Monitor as described in Capturing Filtered Windows Events with Windows Azure
Diagnostics.
To publish performance counters instrumentation, you must specify an application name in the
instrumentation configuration section. This application name will be used to build the performance
counter instance name, and if left unspecified, the application domain name would be used instead. This
complicates the configuration for publishing the performance counter samples. The Diagnostics Monitor
must then be configured with sources resulting from the combination of the category and counter
names from each application block with the instance name for the application.

Sample Windows Azure QuickStart Using Enterprise Library


This section describes the way a sample Windows Azure QuickStart uses Enterprise Library features. This
QuickStart can be downloaded here.

7
Note that the QuickStart showcases features which require additional steps, when compared with using
Enterprise Library on-premises, in order to get these features to work in Windows Azure.

Using the Logging Application Block


The main function of the QuickStart is to log messages through the Logging Application Block, letting the
user choose the categories to which a message should be logged. The available categories are "General,"
which logs to the Diagnostics Monitor Trace Listener, "Troubleshooting," which logs to the Windows
Event Log, and "UI Events" which logs to a file.
The trace listener for the "General" category is defined as a System Diagnostics trace listener in the
configuration for the Logging Application Block:

Because this trace listener is used, the web role needs to configure and start the diagnostics monitor.
C#
DiagnosticMonitorConfiguration config =
DiagnosticMonitor.GetDefaultInitialConfiguration();

var cloudStorageAccount =

CloudStorageAccount.Parse(RoleEnvironment.GetConfigurationSettingValue("Microsoft.Win
dowsAzure.Plugins.Diagnostics.ConnectionString"));

// Azure Trace Logs


config.Logs.ScheduledTransferPeriod = TimeSpan.FromMinutes(2);
config.Logs.ScheduledTransferLogLevelFilter = LogLevel.Verbose;

// Configure Event Logs, performance counters etc


8
...

DiagnosticMonitor.Start(cloudStorageAccount, config);

The trace listener for the "Troubleshooting" category is a standard Event Log trace listener configured
with a custom source.

To publish the event log messages the web role needs, again, to configure the diagnostics monitor. In
this case, it adds a Windows Event Log data source for the specific custom source used by the trace
listener. Of course, the diagnostics monitor could be configured to publish all events in the application
log instead of just those from the trace listener.
C#
config.WindowsEventLog.DataSources.Add("Application!*[System[Provider[@Name='Logging
Demo']]]");

Finally, the custom event log must be created. The QuickStart creates the event log from a Windows
PowerShell script invoked by a startup task that runs with elevated privileges (file Setup\install.ps1).
Windows PowerShell script
if (-not [System.Diagnostics.EventLog]::SourceExists("Logging Demo"))
{
Write-Host
Write-Host "Creating event source"
[System.Diagnostics.EventLog]::CreateEventSource("Logging Demo", "Application")
}

9
The startup task is defined in the ServiceDefinition.csdef file, using the technique for avoiding executing
the task when running in emulated mode described in Skipping Windows Azure Startup Tasks When
Running in the Emulator.

XML
<Startup>
<Task taskType="simple" executionContext="elevated"
commandLine="setup\install.cmd">
<Environment>
<Variable name="EMULATED">
<RoleInstanceValue xpath="/RoleEnvironment/Deployment/@emulated" />
</Variable>
</Environment>
</Task>
</Startup>

The trace listener for the "UI Events" category is a normal formatted file trace listener with a path
defined by the %TEMP% environment variable.

Using Instrumentation
The QuickStart is configured to publish performance counter instrumentation. In order to be able to
publish the events, the web role defines an application name that will be used for the performance
counter instances.

10
As it was the case with the Windows Azure and Windows Event Logs, the web role must configure the
diagnostics monitor for publishing the performance counters. In this case only two of the performance
counters updated by the Logging Application Block are published.
C#
config.PerformanceCounters.DataSources.Add(
new PerformanceCounterConfiguration
{
CounterSpecifier = @"\Enterprise Library Logging Counters(–*)\Total Logging
Events Raised",
SampleRate = TimeSpan.FromMinutes(1)
});
config.PerformanceCounters.DataSources.Add(
new PerformanceCounterConfiguration
{
CounterSpecifier = @"\Enterprise Library Logging Counters(–*)\Total Trace
Operations Started",
SampleRate = TimeSpan.FromMinutes(1)
});

To install the instrumentation for the Logging Application Block, the QuickStart invokes the installutil.exe
tool in the startup task.
Windows PowerShell script
& "$env:windir\Microsoft.NET\Framework64\v4.0.30319\InstallUtil.exe"
..\Microsoft.Practices.EnterpriseLibrary.Common.dll

11
& "$env:windir\Microsoft.NET\Framework64\v4.0.30319\InstallUtil.exe"
..\Microsoft.Practices.EnterpriseLibrary.Logging.dll

Using the Policy Injection Application Block


The QuickStart uses the performance counter call handler to count all calls to the Home page by having
the corresponding attribute on the Index method of the Home controller class. This call handler defines
a custom category ("Logging Demo Counters") and a custom instance name ("index").
C#
[PerformanceCounterCallHandler("Logging Demo Counters", "index")]
public virtual ActionResult Index()
{
return View();
}

In order for this attribute to be consumed, the controller itself must be resolved through a properly set
up container. The start event on the application takes care of replacing the default MVC dependency
resolver with a Unity-based custom implementation.
C#
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();

RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);

CloudStorageAccount.SetConfigurationSettingPublisher(
(s, p) =>
p(RoleEnvironment.GetConfigurationSettingValue(
"Microsoft.WindowsAzure.Plugins.Diagnostics.ConnectionString")));

var container = new UnityContainer();


EnterpriseLibraryContainer.ConfigureContainer(
new UnityContainerConfigurator(container),
ConfigurationSourceFactory.Create());

container.RegisterType<HomeController>(
new Interceptor<VirtualMethodInterceptor>(),
new InterceptionBehavior<PolicyInjectionBehavior>());

var locator = new UnityServiceLocator(container);


EnterpriseLibraryContainer.Current = locator;
DependencyResolver.SetResolver(new ServiceLocatorDependencyResolver(locator));
}

12
Just as with the instrumentation performance counters, the performance counters for the call handler
needs to be installed and configured for publication. In this case, these actions need to match the
configuration for the call handler attribute.
C#
config.PerformanceCounters.DataSources.Add(
new PerformanceCounterConfiguration
{
CounterSpecifier = @"\Logging Demo Counters(*)\# of calls",
SampleRate = TimeSpan.FromMinutes(1)
});

Windows PowerShell script


& "$env:windir\Microsoft.NET\Framework64\v4.0.30319\InstallUtil.exe"
/category="Logging Demo Counters"
..\Microsoft.Practices.EnterpriseLibrary.PolicyInjection.dll

Summary
This guidance explains how Enterprise Library 5.0 can be used when building applications that will be
hosted in Windows Azure. It describes, for each of the Enterprise Library application blocks, the features
that are and are not suitable for use in Windows Azure hosted applications. It also suggests alternatives
you may consider to implement the required functionality, including extending Enterprise Library by
creating custom providers designed to work within the Windows Azure execution environment.

More Information
You can download the QuickStart described in this guidance here.
The SQL Scripts which are compatible with SQL Azure and are required for the Caching Database
provider are available as a separate download. To get the scripts, download the
EnterpriseLibraryIntegrationPack-WindowsAzure-sqlscripts.exe from the Microsoft Enterprise Library 5.0
Integration Pack for Windows Azure.
The SQL Configuration Source is available as a separate download and reads the Enterprise Library
configuration sections from a SQL Server database. To get this configuration source and the SQL Scripts
to enable you to create the database on SQL Azure, download both the SqlConfigurationSource.zip and
the SQLConfigurationSourceforSQLAzure.zip from the Enterprise Library 5.0 - SQL Configuration Source
download page on CodePlex.
For more information about Enterprise Library 5.0, see the Enterprise Library Community website on
Codeplex. For more information about Unity 2.0, see the Unity Community website on CodePlex. These
sites include links to download the latest releases, training materials, custom extensions, and support
forums for Enterprise Library and Unity.

13
For information about getting started with Windows Azure, see Windows Azure Platform. For
developers, other useful starting points are Windows Azure Developer and SQL Azure Developer.
The patterns & practices Enterprise Library 5.0 Integration Pack for Windows Azure can be found on
MSDN. The Enterprise Library 5.0 Integration Pack for Windows Azure community site on CodePlex and
the patterns & practices Windows Azure Guidance community site on CodePlex provides more
resources for building Windows Azure applications.

14

You might also like