100% found this document useful (3 votes)
55 views

Developer s Guide to Microsoft Enterprise Library C Edition Alex Homer 2024 Scribd Download

C

Uploaded by

corkedilsy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (3 votes)
55 views

Developer s Guide to Microsoft Enterprise Library C Edition Alex Homer 2024 Scribd Download

C

Uploaded by

corkedilsy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 71

Download the full version of the ebook at

https://ebookultra.com

Developer s Guide to Microsoft Enterprise


Library C Edition Alex Homer

https://ebookultra.com/download/developer-s-guide-
to-microsoft-enterprise-library-c-edition-alex-
homer/

Explore and download more ebook at https://ebookultra.com


Recommended digital products (PDF, EPUB, MOBI) that
you can download immediately if you are interested.

C net Web Developer s Guide 1st Edition Saurabh Nandu

https://ebookultra.com/download/c-net-web-developer-s-guide-1st-
edition-saurabh-nandu/

ebookultra.com

The Little Book on CoffeeScript The JavaScript Developer s


Guide to Building Better Web Apps 1st Edition Alex Maccaw

https://ebookultra.com/download/the-little-book-on-coffeescript-the-
javascript-developer-s-guide-to-building-better-web-apps-1st-edition-
alex-maccaw/
ebookultra.com

Applications Code Markup A Guide to the Microsoft Windows


Presentation Foundation Pro Developer 1st Edition Charles
Petzold
https://ebookultra.com/download/applications-code-markup-a-guide-to-
the-microsoft-windows-presentation-foundation-pro-developer-1st-
edition-charles-petzold/
ebookultra.com

Developer s Guide to Web Application Security 1st Edition


Michael Cross

https://ebookultra.com/download/developer-s-guide-to-web-application-
security-1st-edition-michael-cross/

ebookultra.com
The NET Developer s Guide to Windows Security 1st Edition
Keith Brown

https://ebookultra.com/download/the-net-developer-s-guide-to-windows-
security-1st-edition-keith-brown/

ebookultra.com

The Ruby Developer s Guide 1st Edition Syngress

https://ebookultra.com/download/the-ruby-developer-s-guide-1st-
edition-syngress/

ebookultra.com

Professional Microsoft Robotics Developer Studio Wrox


Programmer to Programmer 1st Edition Kyle Johns

https://ebookultra.com/download/professional-microsoft-robotics-
developer-studio-wrox-programmer-to-programmer-1st-edition-kyle-johns/

ebookultra.com

Sun Certification Training Guide 310 080 Java 2 Enterprise


Edition J2EE Web Component Developer Alain Trottier

https://ebookultra.com/download/sun-certification-training-
guide-310-080-java-2-enterprise-edition-j2ee-web-component-developer-
alain-trottier/
ebookultra.com

Microsoft SharePoint 2010 Developer Reference 1st Edition


Paolo Pialorsi

https://ebookultra.com/download/microsoft-sharepoint-2010-developer-
reference-1st-edition-paolo-pialorsi/

ebookultra.com
Developer s Guide to Microsoft Enterprise Library C
Edition Alex Homer Digital Instant Download
Author(s): Alex Homer, Nicolas Botto
ISBN(s): 9780735645233, 073564523X
Edition: Kindle
File Details: PDF, 3.35 MB
Year: 2010
Language: english
DEVE LO P E R S’S GU I D E TO

MICROSOFT ®

ENTERPRISE
LI B RARY
Solutions for
Enterprise Development

Alex Homer
with
Nicolas Botto
Bob Brumfield
Grigori Melnik
Erik Renaud
Fernando Simonazzi
Chris Tavares

C# Edition
developer’s guide to microsoft® enterprise library
developer’s guide to
Microsoft Enterprise®

Library
Solutions for Enterprise Development

Alex Homer
with
Nicolas Botto
Bob Brumfield
Grigori Melnik
Erik Renaud
Fernando Simonazzi
Chris Tavares
Copyright and Terms of Use
ISBN: 9780735645233
This document is provided “as-is.” Information and views expressed in
this document, including URL and other Internet Web site 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.
This document does not provide you with any legal rights to any
intellectual property in any Microsoft product. You may copy and
use this document for your internal, reference purposes.
© 2010 Microsoft. All rights reserved.
Microsoft, Windows, Windows Server, Windows Vista, Visual C#,
SQL Server, Active Directory, IntelliSense, Silverlight, MSDN, Internet
Explorer, and Visual Studio are trademarks of the Microsoft group of
companies. All other trademarks are property of their respective owners.
Contents

foreword
Scott Guthrie ix

preface xv
About This Guide xv
What Does This Guide Cover? xv
What This Guide Does Not Cover xvi
How Will This Guide Help You? xvii
What Do You Need to Get Started? xvii

the team who brought you this guide xix


The Enterprise Library 5.0 Development Team xix
1 Welcome to the Library 1
Meet the Librarian 1
What You Get with Enterprise Library 1
Things You Can Do with Enterprise Library 3
Why You Should Use Enterprise Library 4
Some Fundamentals of Enterprise Library 6
Choosing Which Blocks To Install 6
Installing Enterprise Library 7
Assemblies And References 7
GAC or Bin, Signed or Unsigned? 8
Importing Namespaces 9
Configuring Enterprise Library 10
The Configuration Tools 10
Using The Configuration Tools 11
Encrypting Configuration Sections 14
Instantiating and Using Enterprise Library Objects 14
Enterprise Library Objects, Facades, and Factories 15
Creating Instances of Enterprise Library Types 15
The Simple Approach
— Using The Enterprise Library Service Locator 16
The Sophisticated Approach
— Accessing The Container Directly 16
Pros and Cons of Object Instantiation 18
More Reasons to be Sophisticated 19
Getting Objects From Previous Versions
Of Enterprise Library 21
The Example Applications 22
Summary 23
2 Much ADO about Data Access 25
Introduction 25
What Does the Data Access Application Block Do? 26
Data Operations Supported by the Data Access Block 26
How Do I Use the Data Access Block? 28
Configuring the Block and Referencing the Required Assemblies 28
Creating Database Instances 29
The Example Application 30
Reading Multiple Data Rows 31
Reading Rows Using a Query with No Parameters 31
Reading Rows Using an Array of Parameter Values 32
Reading Rows Using Queries with Named Parameters 33
Retrieving Data as Objects 35
About Accessors 35
Creating and Executing an Accessor 37
Creating and Using Mappers 38
Retrieving Xml Data 39
Retrieving Single Scalar Values 40
Retrieving Data Asynchronously 41
Preparing for Asynchronous Data Access 42
Retrieving Row Set Data Asynchronously 43
Retrieving Data as Objects Asynchronously 45
Updating Data 45
Executing an Update Query 46
Working with DataSets 47
Updating the Database from a DataSet 48
Managing Connections 52
Working with Connection-Based Transactions 53
Working with Distributed Transactions 55
Extending the Block to Use Other Databases 58
Summary 58
3 Error Management Made Exceptionally Easy 61
Introduction 61
When Should I Use the Exception Handling Block? 62
How Do I Use the Exception Handling Block? 62
What Exception Policies Do I Need? 63
Allowing Exceptions to Propagate 63
About Exception Handling Policies 63
Choosing an Exception Handling Strategy 65
Process or Handle Exception? 66
Using the Process Method 67
Diving in with a Simple Example 68
Applying Exception Shielding 69
Wrapping an Exception 70
Configuring the Wrap Handler Policy 70
Initializing the Exception Handling Block 71
Editing the Application Code to Use the New Policy 71
Replacing an Exception 74
Logging an Exception 75
Shielding Exceptions at WCF Service Boundaries 78
Creating a Fault Contract 78
Configuring the Exception Handling Policy 78
Editing the Service Code to Use the New Policy 79
The Fault Contract Exception Handler 80
Handling Specific Exception Types 81
Executing Code around Exception Handling 82
Assisting Administrators 84
Extending Your Exception Handling 87
Summary 87
4 As Easy as Falling Off a Log 89
Introduction 89
What Does the Logging Block Do? 90
Logging Categories 92
Logging Overhead and Additional Context Information 93
How Do I Use the Logging Block? 93
Configuring the Logging Block 93
Initializing the Logging Block 94
Diving In with an Example 95
Creating and Writing Log Entries with a Logwriter 95
About Logging Categories 98
Filtering by Category 100
Writing Log Entries to Multiple Categories 100
Controlling Output Formatting 101
Non-Formatted Trace Listeners 102
Filtering by Severity in a Trace Listener 103
Filtering All Log Entries by Priority 103
Creating and Using Logentry Objects 104
Capturing Unprocessed Events and Logging Errors 105
About Special Sources 105
An Example of Using Special Sources 106
Logging to a Database 108
Using the Database Trace Listener 109
Testing Logging Filter Status 110
Obtaining Information about Trace Sources
and Trace Listeners 111
Checking if Filters Will Block a Log Entry 112
Adding Additional Context Information 114
Tracing and Correlating Activities 115
An Example of Tracing Activities 116
Creating Custom Trace Listeners, Filters, and Formatters 119
Summary 119
5 A Cache Advance for Your Applications 121
Introduction 121
What Does the Caching Block Do? 123
Flushed or Expired? 123
Which Expiration Policy? 124
How Do I Configure the Caching Block? 124
Persistent Caching 125
Encrypting Cached Items 126
Initializing the Caching Block 126
How Do I Use the Caching Block? 127
About the Example Application 127
Adding Items to and Retrieving Items from the Cache 127
What’s In My Cache? 130
Using the Isolated Storage Backing Store 131
Encrypting the Cached Data 133
Using the Database Backing Store 134
Removing Items From and Flushing the Cache 135
Using a File Dependency and Extended Time Expiration 136
Adding the Items to the Cache 137
Refreshing the Cache 139
Loading the Cache 141
Proactive Cache Loading 141
Reactive Cache Loading 142
Extending Your Cache Advance 143
Summary 144
6 Banishing Validation Complication 145
Introduction 145
Techniques for Validation 146
Where Should I Validate? 146
What Should I Validate? 146
How Should I Validate? 147
What Does the Validation Block Do? 147
The Range of Validators 149
Validating with Attributes 151
DataAnnotations Attributes 151
Self-Validation 152
Validation Rule Sets 154
Assigning Validation Rules to Rule Sets 154
Configuring Validation Block Rule Sets 154
Specifying Rule Sets When Validating 155
How Do I Use The Validation Block? 156
Preparing Your Application 156
Choosing a Validation Approach 157
Options for Creating Validators Programmatically 158
Performing Validation and Displaying Validation Errors 159
Understanding Message Template Tokens 160
Diving in With Some Simple Examples 161
Validating Objects and Collections of Objects 162
Creating a Type Validator using the ValidatorFactory 162
Delving Deeper into ValidationResults 163
Using the Object Validator 164
Differences Between the Object Validator
and the Factory-Created Type Validators 165
Validating Collections of Objects 165
Using Validation Attributes 166
Using the Validation Block Attributes 166
Using Data Annotation Attributes 169
Defining Attributes in Metadata Classes 171
Specifying the Location of Validation Rules 172
Creating and Using Individual Validators 173
Validating Strings for Contained Characters 173
Validating Integers within a Domain 173
Validating with a Composite Validator 174
Validating Single Members of an Object 175
WCF Service Validation Integration 176
Defining Validation in the Service Contract 176
Editing the Service Configuration 177
Using the Product Service and Detecting Validation Errors 178
User Interface Validation Integration 180
ASP.NET User Interface Validation 180
Windows Forms User Interface Validation 181
WPF User Interface Validation 181
Creating Custom Validators 182
Summary 182
7 Relieving Cryptography Complexity 183
Introduction 183
What Does the Cryptography Block Do? 183
A Secret Shared 184
Making a Hash of It 184
How Does the Cryptography Block Manage
Encryption Keys? 184
How Does the Cryptography Block Integrate
With Other Blocks? 185
How Do I Use the Cryptography Block? 185
Configuring Cryptographic Providers 186
Adding the Required References 187
Diving in with an Example 187
Encrypting and Decrypting Data Using
A Symmetric Provider 188
Encrypting and Decrypting a Text String 188
Encrypting and Decrypting an Object Instance 189
Obtaining and Comparing Hash Values 191
Creating and Comparing Hash Values for Text Strings 191
Creating and Comparing Hash Values for Object Instances 193
Creating Custom Cryptography Providers 195
Summary 196
8 An Authentic Approach to Token Identity 197
Introduction 197
What Does the Security Block Do? 198
What are Authorization Rule Providers? 198
About Authorization Manager (AzMan) 198
Why Do I Need a Security Cache? 199
How Do I Configure the Security Block? 200
Configuring Authorization Rules 202
How Do I Use the Security Block? 202
Diving in With an Example 203
Caching a User Identity and Obtaining
A Temporary Token 204
Displaying User Identity Details 205
Displaying Generic Principal Details 205
Authenticating a User Using a Token 206
Terminating a User Session and Expiring the Token 207
Checking If a User is Authorized to Perform a Task 208
Using Security Block Configured Rules 208
Using AzMan Provider Rules 210
Creating Custom Authorization Providers 212
Summary 212
appendices
a dependency injection with unity 213
What is Dependency Injection? 213
The Unity Dependency Injection and Interception Mechanism 214
Summary of Unity Features 215
Defining Dependencies with Unity 216
Constructor Injection 217
Automatic Constructor Injection 217
Design-Time Configuration 218
Run-Time Configuration 219
Configuration with Attributes 219
Property (Setter) Injection 220
Design-Time Configuration 220
Run-Time Configuration 221
Configuration with Attributes 221
Method Call Injection 222
Design-Time Configuration 222
Run-Time Configuration 223
Configuration with Attributes 223
More Dependency Injection Opportunities 224
Resolving Populated Instances of Your Classes 224
b dependency injection in enterprise library 225
Loading Configuration Information into a Unity Container 225
Viewing Registrations in the Container 226
Populating Entire Object Graphs at Application Startup 227
Maintaining a Container Reference in Request-Based
Applications 228
Using an Alternative Service Locator or Container 229
c policy injection in enterprise library 231

d enterprise library configuration scenarios 233


About Enterprise Library Configuration 233
External Configuration 234
Programmatic Support 234
Using the Fluent Interfaces 234
Scenarios for Advanced Configuration 235
scenario 1: Using The Default Application
Configuration File 235
scenario 2: Using A Non-Default Configuration Store 235
scenario 3: Sharing The Same Configuration
Between Multiple Applications 236
scenario 4: Managing And Enforcing Configuration
For Multiple Applications 236
scenario 5: Sharing Configuration Sections
Across Multiple Applications 237
scenario 6: Applying a Common Configuration
Structure for Applications 238
Deployment Environments 239
e encrypting configuration files 241

index 243
Foreword

You are holding in your hands a book that will make your life as an enterprise developer a
whole lot easier.
It’s a guide on Microsoft Enterprise Library and it’s meant to guide you through how
to apply .NET for enterprise development. Enterprise Library, developed by the patterns
& practices group, is a collection of reusable components, each addressing a specific cross
cutting concern—be it system logging, or data validation, or exception management.
Many of these can be taken advantage of easily. These components are architecture
agnostic and can be applied in a multitude of different contexts.
The book walks you through functional blocks of the Enterprise Library, which
include data access, caching, cryptography, exception handling, logging, security, and
validation. It contains a large collection of exercises, tricks and tips.
Developing robust, reusable, and maintainable application requires knowledge of
design patterns, software architectures and solid coding skills. We can help you develop
those skills with Enterprise Library since it encapsulates proven and recommended prac-
tices of developing enterprise applications on the .NET platform. Though this guide does
not go into the depth of discussions of architecture and patterns, it provides a solid basis
for you to discover and implement these patterns from a reusable set of components.
That’s why I also encourage you to check out the Enterprise Library source code and
read it.
This guide is not meant to be a complete reference on Enterprise Library. For that,
you should go to MSDN. Instead, the guide covers most commonly used scenarios and
illustrates how Enterprise Library can be applied in implementing those. The powerful
message manifesting from the guide is the importance of code reuse. In today’s world of
complex large software systems, high-quality pluggable components are a must. After all,
who can afford to write and then maintain dozens of different frameworks in a system—
all to accomplish the same thing? Enterprise Library allows you to take advantage of the
proven code complements to manage a wide range of task and leaves you free to concen-
trate on the core business logic and other “working parts” of your application.
Another important emphasis that the guide makes is on software designs, which are
easy to configure, testable and maintainable. Enterprise Library has a flexible configura-
tion subsystem driven from either external config files, or programmatically, or both.
Leading by example, Enterprise Library itself is designed in a loosely-coupled manner. It

xiii
promotes key design principles of the separation of concerns, single responsibility prin-
ciple, principle of least knowledge and the DRY principle (Don’t Repeat Yourself). Having
said this, don’t expect this particular guide to be a comprehensive reference on design
patterns. It is not. It provides just enough to demonstrate how key patterns are used with
Enterprise Library. Once you see and understand them, try to extrapolate them to other
problems, contexts, scenarios.
The authors succeeded in writing a book that is targeted at both those who are sea-
soned Enterprise Library developers and who would like to learn about the improvements
in version 5.0, and those, who are brand new to Enterprise Library. Hopefully, for the
first group, it will help orientate you and also get a quick refresher of some of the key
concepts. For the second group, the book may lower your learning curve and get you
going with Enterprise Library quickly.
Lastly, don’t just read this book. It is meant to be a practical tutorial. And learning
comes only through practice. Experience Enterprise Library. Build something with it.
Apply the concepts learnt in practice. And don’t forget to share your experience.
In conclusion, I am excited about both the release of Enterprise Library 5.0 and this
book. Especially, since they ship and support some of our great new releases—Visual
Studio 2010, .NET Framework 4.0 and Silverlight 4, which together will make you, the
developer, ever more productive.

Scott Guthrie
Corporate Vice-President
Microsoft .NET Developer Platform
Redmond, Washington
Preface

About This Guide


When you casually pick up a book in your local bookstore or select one from the endless
collection available on your favorite Web site, you’re probably wondering what the book
actually covers, what you’ll learn from it, whether the content is likely to be interesting
and useful, and—of course—whether it is actually any good. We’ll have a go at answering
the first three of these questions here. The final question is one only you can answer. Of
course, we would be pleased to hear your opinion through our community Web site at
http://entlib.codeplex.com/.

what does this guide cover?


As you can probably tell from the title, this guide concentrates on how you can get
started with Enterprise Library. It will help you learn how to use Enterprise Library in your
applications to manage your crosscutting concerns, simplify and accelerate your develop-
ment cycle, and take advantage of proven practices. Enterprise Library is a collection of
prewritten code components that have been developed and fine-tuned over many years.
You can use them out of the box, modify them as required, and distribute them with your
applications. You can even use Enterprise Library as a learning resource. It includes the
source code that demonstrates Microsoft® .NET programming techniques and the use of
common design patterns that can improve the design and maintainability of your applica-
tions. By the way, if you are not familiar with the term crosscutting concerns, don’t worry;
we’ll explain it as we go along.
Enterprise Library is an extensive collection, with a great many moving parts. To the
beginner knowing how to best take advantage of it is not completely intuitive. Therefore,
in this guide we’ll help you to quickly understand what Enterprise Library is, what it
contains, how you can select and use just the specific features you require, and how easy
it is to get started using them. You will see how you can quickly and simply add Enterprise
Library to your applications, configure it to do exactly what you need, and then benefit
from the simple-to-use, yet extremely compelling opportunities it provides for writing
less code that achieves more.
The first chapter of this guide discusses Enterprise Library in general, and provides
details of the individual parts so that you become familiar with the framework as a whole.

xv
xvi

The aim is for you to understand the basic principles of each of the application blocks in
Enterprise Library, and how you can choose exactly which blocks and features you re-
quire. Chapter 1 also discusses the fundamentals of using the blocks, such as how to
configure them, how to instantiate the components, and how to use these components
in your code.
The remaining seven chapters discuss in detail the application blocks that provide the
basic crosscutting functionality such as data access, caching, logging, and exception han-
dling. These chapters explain the concepts that drove development of the blocks, the
kinds of tasks they can accomplish, and how they help you implement many well-known
design patterns. And, of course, they explain—by way of code extracts and sample pro-
grams—how you actually use the blocks in your applications. After you’ve read each
chapter, you should be familiar with the block and be able to use it to perform a range of
functions quickly and easily, in both new and existing applications.
Finally, the appendices present more detailed information on specific topics that you
don’t need to know about in detail to use Enterprise Library, but are useful as additional
resources and will help you understand how features such as dependency injection, inter-
ception, and encryption fit into the Enterprise Library world.
You can also download and work through the Hands-On Labs for Enterprise Library,
which are available at http://go.microsoft.com/fwlink/?LinkId=188936.

what this guide does not cover


The aim of this guide is to help you learn how to benefit from the capabilities of Enter-
prise Library. It does not describe the common design patterns in depth, or attempt to
teach you about application architecture in general. Instead, it concentrates on getting
you up to speed quickly and with minimum fuss so you can use Enterprise Library to
manage your crosscutting concerns.
One of the core tenets of modern application design is that you should reduce the
coupling or dependencies between components and objects, and Enterprise Library ver-
sion 5.0 helps you achieve this goal through use of the Dependency Injection (DI) design
pattern. However, you do not have to be a DI expert to use Enterprise Library; all of the
complexity is managed internally by the core mechanisms within the framework. While
we do explain the basic use of DI in terms of Enterprise Library, that is not a fundamental
feature of this guide.
Enterprise Library is designed to be extensible. You can extend it simply by writing
custom plug-in providers, by modifying the core code of the library, or even by creating
entirely new blocks. In this guide, we provide pointers to how you can do this and explain
the kinds of providers that you may be tempted to create, but it is not a topic that we
cover in depth. These topics are discussed more fully in the documentation installed with
Enterprise Library and available online at http://go.microsoft.com/fwlink/?LinkId=188874,
and in the many other resources available from our community Web site at http://www.
codeplex.com/entlib.
For more information about the Dependency Injection (DI) design pattern and the
associated patterns, see “Inversion of Control Containers and the Dependency Injection
pattern” at http://martinfowler.com/articles/injection.html.
xvii

how will this guide help you?


If you build applications that run on the Microsoft .NET Framework, whether they are
enterprise-level business applications or even relatively modest Windows® Forms, Win-
dows Presentation Foundation (WPF), Windows Communication Foundation (WCF), or
ASP.NET applications, you can benefit from Enterprise Library. This guide helps you to
quickly grasp what Enterprise Library can do for you, presents examples that show it in
action, and make it easier for you to start experimenting with Enterprise Library.
The sample applications are easy to assimilate, fully commented, and contain code
that demonstrates all of the main features. You can copy this code directly into your ap-
plications if you wish, or just use it as a guide when you need to implement the common
functionality it provides. The samples are console-based applications that contain sepa-
rate procedures for each function they demonstrate. You can download these samples
from http://go.microsoft.com/fwlink/?LinkId=189009.
Finally, what is perhaps the most important feature of this guide is that it will hope-
fully allay any fears you may have about using other people’s code in your applications. By
understanding how to select exactly the features you need, and installing the minimum
requirements to implement these features, you will see that what might seem like a huge
and complicated framework is actually a really useful set of individual components and
features from which you can pick and choose—a candy store for the architect and devel-
oper.

What Do You Need to Get Started?


The prerequisites for using this guide are relatively simple. You’ll need to be relatively
experienced in C#, and understand general object-oriented programming techniques. The
system requirements and prerequisites for using Enterprise Library are:
• Supported architectures: x86 and x64.
• Operating system: Microsoft Windows® 7 Professional, Enterprise, or Ultimate;
Windows Server® 2003 R2; Windows Server 2008 with Service Pack 2; Win-
dows Server 2008 R2; Windows Vista® with Service Pack 2; or Windows XP
with Service Pack 3.
• Microsoft .NET Framework 3.5 with Service Pack 1 or Microsoft .NET Frame-
work 4.0.
• For a rich development environment, the following are recommended:
• Microsoft Visual Studio® 2008 Development System with Service Pack
1 (any edition) or Microsoft Visual Studio 2010 Development System
(any edition).
• To run the unit tests, the following are also required:
• Microsoft Visual Studio 2008 Professional, Visual Studio 2008 Team
Edition, Visual Studio 2010 Premium, Visual Studio 2010 Professional,
or Visual Studio 2010 Ultimate Edition.
• Moq v3.1 assemblies.
xviii

• For the Data Access Application Block, the following is also required:
• A database server running a database that is supported by a .NET
Framework 3.5 with Service Pack 1 or .NET Framework 4.0 data
provider. This includes Microsoft SQL Server® 2000 or later, SQL
Server 2005 Compact Edition, and Oracle 9i or later. The database
server can also run a database that is supported by the .NET Frame-
work 3.5 with Service Pack 1 or the .NET Framework 4.0 data provid-
ers for OLE DB or ODBC.
• For the Logging Application Block, the following are also required:
• Stores to maintain log messages. If you are using the MSMQ trace
listener to store log messages, you need the Microsoft Message
Queuing (MSMQ) component installed. If you are using the Database
trace listener to store log messages, you need access to a database
server. If you are using the Email trace listener to store log messages,
you need access to an SMTP server.
Other than that, all you require is some spare time to sit and read, and to play with the
example programs. Hopefully you will find the contents interesting (and perhaps even
entertaining), as well as a useful source for learning about Enterprise Library.
the team who brought you this guide

Idea/Vision Grigori Melnik


Main Author Alex Homer
Contributing Authors Nicolas Botto, Bob Brumfield, Grigori Melnik, Erik Renaud,
Fernando Simonazzi, and Chris Tavares.
Reviewers Scott Densmore, Tom Hollander, Hernan de Lahitte, Ajoy
Krishnamoorthy, Ade Miller, and Don Smith.
Graphic Artists Patrick Lanfear and Tom Draper.
Editors RoAnn Corbisier and Nancy Michell.

the enterprise library 5.0 development team


Product/Program
Management Grigori Melnik (Microsoft Corporation).
Architecture/
Development Bob Brumfield and Chris Tavares (Microsoft Corporation);
Fernando Simonazzi (Clarius Consulting); Nicolas Botto
(Digit Factory); and Olaf Conijn (Olaf Conijn BV).
Testing Carlos Farre, Masashi Narumoto, and Rohit Sharma
(Microsoft Corporation); Nicolas Botto (Digit Factory);
Lavanya Selvaraj, Magdelene Sona, Mani Krishnaswami,
Meenakshi Krishnamoorthi, Santhosh Panneerselvam,
and Ravindra Varman (Infosys Technologies Ltd); Erik
Renaud and François Tanguay (nVentive Inc); and Rick
Carr (DCB Software Testing, Inc).
User Experience Damon van Vessem, Heidi Adkisson, Jen Amsterlaw, and
Kelly Franznick (Blink Interactive); and Brad Cunningham
(Interknowlodgy).
Documentation Alex Homer (Microsoft Corporation) and Dennis DeWitt
(Linda Werner &Associates Inc).

xix
xx

Editing/Production RoAnn Corbisier and Steve Elston (Microsoft Corporation);


Nancy Michell (Content Master Ltd.); John Hubbard (Eson)
Ted Brian Neveln (Ballard Indexing Services) and Patrick
Lanfear and Tom Draper (Twist Creative LLC).
Release Management Richard Burte (ChannelCatalyst.com, Inc.) and Jennifer
Burch (DCB Software Testing, Inc).
Administrative Support Tracy Emory (Microsoft Corporation).
Advisory Council Brian Button (Asynchrony Solutions); Kyle Huntley
(Avanade); David Starr (Pluralsight); Wallin Ludwik (Volvo);
Bill Wilder (Fidelity); Andrej Golcov (Hermes SoftLab);
John Askew, Nicholas Blumhardt, Martin Bennedik, and
Serge Baranovsky (Independent); Evgeny Sorokin and
Ksenia Mukhortova (Intel); Scott Nichols (Idaho Central);
Eng Chong Lim and Isabel Niu (McDonald’s Corporation);
Aaron Hanks, Glenn Block, Hugo Batista, Jason Hogg,
Jason Olson, John Czernuszka, Joshy Joseph, Lenny Fenster,
Massimo Mascaro, Matthew Podwysocki, Tom Hollander,
Piyush Gupta, and Scott Densmore (Microsoft Corpora-
tion); Matthew Buonomano and Nikola Malovic (Monster.
com); Daniel Piessens and Phill Van Hoven (Red Prairie);
and Walter Wu (Royal Bank of Canada).
Community Attendees at patterns & practices summits, PDC,
TechReady, and TechEd conferences who provided informal
feedback; and Enterprise Library users who commented on
this guide on CodePlex, through our blogs, surveys and via
e-mail.

Thank you!
1 Welcome to the Library

Meet the Librarian


Before we begin our exploration of Microsoft® Enterprise Library and the wondrous
range of capabilities and opportunities it encompasses, you need to meet the Librarian.
Sometimes we call him Tom, sometimes we call him Chris, and sometimes we call him
Grigori. But, despite this somewhat unnerving name variability, he—in collaboration with
an advisory board of experts from the industry and other internal Microsoft product
groups, and a considerable number of other community contributors—is the guardian and
protector of the Microsoft Enterprise Library.
Since its inception as a disparate collection of individual application blocks, the Li-
brarian has guided, prodded, inspired, and encouraged his team to transform it into a
comprehensive, powerful, easy-to-use, and proven library of code that can help to mini-
mize design and maintenance pain, maximize development productivity, and reduce costs.
And now in version 5.0, it contains even more built-in goodness that should make your
job easier. It’s even possible that, with the time and effort you will save, Enterprise Library
can reduce your golf handicap, help you master the ski slopes, let you spend more time
with your kids, or just make you a better person. However, note that the author, the
publisher, and their employees cannot be held responsible if you just end up watching
more TV or discovering you actually have a life.

What You Get with Enterprise Library


Enterprise Library is made up of a series of application blocks, each aimed at managing
specific crosscutting concerns. In case this concept is unfamiliar, crosscutting concerns
are those annoying tasks that you need to accomplish in several places in your application.
When trying to manage crosscutting concerns there is often the risk that you will imple-
ment slightly different solutions for each task at each location in your application, or that
you will just forget them altogether. Writing entries to a system log file or Windows®
Event Log, caching data, and validating user input are typical crosscutting concerns. While
there are several approaches to managing them, the Enterprise Library application blocks
make it a whole lot easier by providing generic and configurable functionality that you
can centralize and manage.

1
2 ch a pter one

What are application blocks? The definition we use is “pluggable and reusable
software components designed to assist developers with common enterprise development
challenges.” Application blocks help address the kinds of problems developers commonly
face from one line-of-business project to the next. Their design encapsulates the
Microsoft recommended practices for Microsoft .NET Framework-based applications,
and developers can add them to .NET-based applications and configure them quickly
and easily.
As well as the application blocks, Enterprise Library contains configuration tools, plus
a set of core functions that manage tasks applicable to all of the blocks. Some of
these functions—routines for handling configuration and serialization, for example—are
exposed and available for you to use in your own applications.
And, on the grounds that you need to learn how to use any new tool that is more
complicated than a hammer or screwdriver, Enterprise Library includes a range of sample
applications, descriptions of key scenarios for each block, hands-on labs, and comprehen-
sive reference documentation. You even get all of the source code and the unit tests that
the team created when building each block (the team follows a test-driven design
approach by writing tests before writing code). So you can understand how it works, see
how the team followed good practices to create it, and then modify it if you want it to
do something different. Figure 1 shows the big picture for Enterprise Library.

Enterprise Library Big Picture

In the Box

Run time Design time Guidance

Configuration Console Conceptual


Documentation

Functional Wiring API Reference


Blocks Blocks Configuration Schema Documentation

Visual Studio Source Code (with tests)


Integration

Ancillary

Developer’s Guide Hands on Labs Videos & Demos

Migration Guide CodePlex Support Forum FAQs

EntLibContrib
Community Extensions

figure 1
Enterprise Library—the big picture
Things You Can Do with Enterprise Library
If you look at the installed documentation, you’ll see that Enterprise Library today actu-
ally contains nine application blocks. However, there are actually only seven blocks that
“do stuff”—these are referred to as functional blocks. The other two are concerned with
“wiring up stuff” (the wiring blocks). What this really means is that there are seven blocks
that target specific crosscutting concerns such as caching, logging, data access, and valida-
tion. The other two, the Unity Dependency Injection mechanism and the Policy Injection
Application Block, are designed to help you implement more loosely coupled, testable,
and maintainable systems. There’s also some shared core pieces used in all the blocks. This
is shown in Figure 2.

Functional Application Blocks


Core
Data Access Logging

Exception
Caching Handling
Wiring Application Blocks

Cryptography Security Unity

Policy Injection/
Validation Interception

figure 2
The parts of Enterprise Library

In this book we’ll be concentrating on the seven functional blocks. If you want to know
more about how you can use Unity and the Policy Injection Application Block, check out
the appendices for this guide. They describe the capabilities of Unity as a dependency
injection mechanism and the use of policy injection in more detail.
The following list describes the crosscutting scenarios you’ll learn about in this book:
• Caching. The Caching Application Block lets you incorporate a local cache in
your applications that uses an in-memory cache and, optionally, a database or
isolated storage backing store. The block provides all the functionality needed
to retrieve, add, and remove cached data, and supports configurable expiration
and scavenging policies. You can also extend it by creating your own pluggable

3
4 ch a pter one

providers or by using third-party providers—for example, to support distrib-


uted caching and other features. Caching can provide considerable improve-
ments in performance and efficiency in many application scenarios.
• Credential Management. The Security Application Block lets you easily
implement common authorization-related functionality, such as caching the
user’s authorization and authentication data and integrating with the Microsoft
.NET Framework security features.
• Data Access. The Data Access Application Block simplifies many common data
access tasks such as reading data for display, passing data through application
layers, and submitting changed data back to the database system. It includes
support for both stored procedures and in-line SQL, can expose the data as a
sequence of objects for client-side querying, and provides access to the most
frequently used features of ADO.NET in simple-to-use classes.
• Encryption. The Cryptography Application Block makes it easy to incorporate
cryptographic functionality such as encrypting and decrypting data, creating a
hash from data, and comparing hash values to verify that data has not been
altered. Using this block can help you avoid common pitfalls when developing
custom mechanisms that might introduce security vulnerabilities.
• Exception Handling. The Exception Handling Application Block lets you
quickly and easily design and implement a consistent strategy for managing
exceptions that occur in various architectural layers of your application. It can
log exception information, hide sensitive information by replacing the original
exception with another exception, and maintain contextual information for an
exception by wrapping the original exception inside another exception.
• Logging. The Logging Application Block simplifies the implementation of
common logging functions such as writing information to the Windows Event
Log, an e-mail message, a database, Windows Message Queuing, a text file, a
Windows Management Instrumentation (WMI) event, or a custom location.
• Validation. The Validation Application Block provides a range of features for
implementing structured and easy-to-maintain validation mechanisms using
attributes and rule sets, and integrating with most types of application inter-
face technologies.

Why You Should Use Enterprise Library


As you can see from the previous section, Enterprise Library provides a comprehensive
set of features that can help you to manage your crosscutting concerns though a reusable
set of components and core functionality. Of course, like many developers, you may suf-
fer from the well-known NIH (not invented here) syndrome. But, seriously, isn’t it about
time that every developer on your team stopped writing his or her own logging frame-
work? It’s a commonly accepted fact that the use of standard and proven code libraries
and components can save development time, minimize costs, reduce the use of precious
test resources, and decrease the overall maintenance effort. In the words of the Librarian,
“These days you cannot afford not to reuse.”
welcome to the libr a ry 5

You can download the Nucleus Research 2009 Report on Microsoft patterns &
practices, which reviews the key components, benefits, and includes direct feedback
from software architects and developers who have adopted patterns & practices
deliverables in their projects and products from http://msdn.microsoft.com/en-us/
practices/ee406167.aspx.
And it’s not as though Enterprise Library is some new kid on the block that might
morph into something completely different next month. Enterprise Library as a concept
has been around for many years, and has passed through five full releases of the library as
well as intermediate incremental releases.
Enterprise Library continues to evolve along with the capabilities of the .NET Frame-
work. As the .NET Framework has changed over time, some features that were part of
Enterprise Library were subsumed into the core, while Enterprise Library changed to take
advantage of the new features available in both the .NET Framework and the underlying
system. Examples include new programming language capabilities and improved perfor-
mance and capabilities in the .NET configuration and I/O mechanisms. Yet, even in version
5.0, the vast majority of the code is entirely backwards compatible with applications
written to use Enterprise Library 2.0.
You can also use Enterprise Library as learning material—not only to implement de-
sign patterns in your application, but also to learn how the development team applies
patterns when writing code. Enterprise Library embodies many design patterns, and dem-
onstrates good architectural and coding techniques. The source code for the entire library
is provided, so you can explore the implementations and reuse the techniques in your own
applications.
And, finally, it is free! Or rather, it is distributed under the Microsoft Public License
(MSPL) that grants you a royalty-free license to build derivative works, and distribute
them free—or even sell them. You must retain the attribution headers in the source files,
but you can modify the code and include your own custom extensions. Do you really need
any other reasons to try Enterprise Library?
You’ ll notice that, even though we didn’t print “Don’t Panic!” in large friendly letters
on the cover, this book does take a little time to settle down into a more typical style
of documentation, and start providing practical examples. However, you can be sure
that—from here on in—you’ ll find a whole range of guidance and examples that will
help you master Enterprise Library quickly and easily. There are other resources to help
if you’re getting started with Enterprise Library (such as hands-on-labs), and there’s
help for existing users as well (such as the breaking changes and migration information
for previous versions) available at http://www.codeplex.com/entlib/. You can also visit
the source code section of the site to see what the Enterprise Library team is working
on as you read this guide.
6 ch a pter one

Some Fundamentals of Enterprise Library


Before we dive into our tour of the application blocks and features of Enterprise Library,
you need to grasp some fundamentals. In this chapter, the Librarian will help you explore
topics such as how to install and deploy the library, and how to perform initial configura-
tion. After that, you’ll be free to skip to any of the other chapters and learn more about
the ways that each block helps you to simplify your code and manage your crosscutting
concerns. For more information about the topics covered in this chapter, see the product
documentation installed with Enterprise Library, or the online documentation available at
http://go.microsoft.com/fwlink/?LinkId=188874.

choosing which blocks to install


Enterprise Library is a “pick and mix” candy store, where you choose just the features you
want to use and simply disregard the rest. Of course, before you can choose your favorite
candies from the tempting displays in the candy store, you need to find a paper bag to
hold them. You can think of this as a prerequisite for picking and mixing, and a basic
feature that you will use every time—irrespective of whether you choose gummy bears,
chocolate-covered hazelnuts, or mint imperials.
Likewise, with Enterprise Library, there are prerequisites and basic features. The main
prerequisite before you start development is to install the binaries and support files onto
your machine. The basic features that you need every time you use Enterprise Library are
the core assemblies that implement access to configuration, object creation, and ancillary
features used by all of the blocks.
However, when you install Enterprise Library, you can choose which of the applica-
tion blocks you want to install; though it is generally a good idea to install them all unless
you are sure you will not use specific blocks. Some blocks have dependencies on other
blocks, and installing all of them while developing your applications will simplify configu-
ration and ensure that you do not have to re-run the installer to add other blocks later on.
When you come to deploy your application, you only need to deploy the blocks you are
using and their dependent blocks.
For example, the Exception Handling block depends on the Logging block for logging
exception information. Table 1 shows the full list of these dependencies.
table 1 Application block optional dependencies
Application Block Optional dependencies
Caching Block May use the Data Access block to cache data in a database.
May use the Cryptography block to encrypt cached data.
Exception Handling Block May use the Logging block to log exception information.
May use the Data Access block to log exception information to
a database.
Logging Block May use the Data Access block to log to a database.
Security Block May use the Caching block to cache credentials.
May use the Data Access block to cache credentials in a database.
May use the Cryptography block to encrypt cached credentials.
welcome to the libr a ry 7

The configuration tools will automatically add the required block to your application
configuration file with the default configuration when required. For example, when you
add a Logging handler to an Exception Handling block policy, the configuration tool will
add the Logging block to the configuration with the default settings.
The seven application blocks we cover in this guide are the functional blocks that are
specifically designed to help you manage a range of crosscutting concerns. All of these
blocks depend on the core features of Enterprise Library, which in turn depend on the
Unity dependency injection and interception mechanism (the Unity Application Block) to
perform object creation and additional basic functions.

installing enterprise library


To begin using Enterprise Library you must first install it. You can download the current
version from http://msdn.microsoft.com/entlib/. Simply run the Microsoft Installer (MSI)
package to begin the installation, and select the blocks and features you want to install.
This installs the precompiled binaries ready for you to use, along with the accompanying
tools and resources such as the configuration editor and scripts to install the samples and
instrumentation.
If you want to examine the source code, and perhaps even modify it to suit your own
requirements, be sure to select the option to install the source code when you run the
installer. The source code is included within the main installer as a separate package,
which allows you to make as many working copies of the source as you want and go back
to the original version easily if required. If you choose to install the source, then it’s also
a good idea to select the option to have the installer compile the library for you so that
you are ready to start using it straight away. However, if you are happy to use the precom-
piled assemblies, you do not need to install or compile the source code.
After the installation is complete, you will see a Start menu entry containing links to
the Enterprise Library tools, source code installer, and documentation. The tools include
batch files that install instrumentation, database files, and other features. There are also
batch files that you can use to compile the entire library source code, and to copy all the
assemblies to the bin folder within the source code folders, if you want to rebuild the li-
brary from the source code.

assemblies and references


It’s not uncommon, when people first look at Enterprise Library, to see a look of mild
alarm spread across their faces. Yes, there are quite a few assemblies, but remember:
• You only need to use those directly connected with your own scenario.
• Several are required for only very special situations.
• The runtime assemblies you will use in your applications are mostly less than
100 KB in size; and the largest of all is only around 500 KB.
• In most applications, the total size of all the assemblies you will use will be
between 1 and 2 MB.
8 ch a pter one

The assemblies you should add to any application that uses Enterprise Library are the
common (core) assembly, the Unity dependency injection mechanism (if you are using the
default Unity container), and the container service location assembly:
• Microsoft.Practices.EnterpriseLibrary.Common.dll
• Microsoft.Practices.Unity.dll
• Microsoft.Practices.Unity.Interception.dll
• Microsoft.Practices.ServiceLocation.dll

You will also need the assembly Microsoft.Practices.Unity.Configuration.dll


if you wish to reference specific Unity configuration classes in your code. However,
in the majority of cases, you will not require this assembly.
In addition to the required assemblies, you must reference the assemblies that implement
the Enterprise Library features you will use in your application. There are several assem-
blies for each application block. Generally, these comprise a main assembly that has the
same name as the block (such as Microsoft.Practices.EnterpriseLibrary.Logging.dll),
plus additional assemblies that implement specific handlers or capabilities for the block.
You only need these additional assemblies if you want to use the features they add. For
example, in the case of the Logging block, there is a separate assembly for logging to a
database (Microsoft.Practices.EnterpriseLibrary.Logging.Database.dll). If you do not
log to a database, you do not need to reference this additional assembly.

GAC or Bin, Signed or Unsigned?


All of the assemblies are provided as precompiled signed versions that you can install into
the global assembly cache (GAC) if you wish. However, if you need to run different ver-
sions of Enterprise Library assemblies side by side, this may be problematic and you may
prefer to locate them in folders close to your application.
You can then reference the compiled assemblies in your projects, which automati-
cally copies them to the bin folder. In a Web application, you can simply copy them di-
rectly to your application’s bin folder. This approach gives you simple portability and easy
installation.
Alternatively, you can install the source code for Enterprise Library and use the scripts
provided to compile unsigned versions of the assemblies. This is useful if you decide to
modify the source code to suit your own specific requirements. You can strong name and
sign the assemblies using your own credentials afterwards if required.
For more information about side-by-side operation and other deployment issues,
see the documentation installed with Enterprise Library and available online at http://
go.microsoft.com/fwlink/?LinkId=188874.
welcome to the libr a ry 9

Importing Namespaces
After you reference the appropriate assemblies in your projects, you will probably want
to add using statements to your project files to simplify your code and avoid specifying
objects using the full namespace names. Start by importing the two core namespaces that
you will require in every project that uses Enterprise Library:
• Microsoft.Practices.EnterpriseLibrary.Common
• Microsoft.Practices.EnterpriseLibrary.Common.Configuration

Depending on how you decide to work with Enterprise Library in terms of instantiating
the objects it contains, you may need to import two more namespaces. We’ ll come to
this when we look at object instantiation in Enterprise Library a little later in this
chapter.
You will also need to import the namespaces for the specific application blocks you are
using. Most of the Enterprise Library assemblies contain several namespaces to organize
the contents. For example, as you can see in Figure 2, the main assembly for the Logging
block (one of the more complex blocks) contains a dozen subsidiary namespaces. If you
use classes from these namespaces, such as specific filters, listeners, or formatters, you
may need to import several of these namespaces.

figure 3
Namespaces in the Logging block
10 ch a pter one

Configuring Enterprise Library


Before the original individual application blocks were combined into Enterprise Library,
one of the biggest challenges for users was configuration. You had to edit the sections of
the application configuration file manually, which proved to be error-prone and just plain
annoying. In Enterprise Library, you have a choice of tools for performing configuration
and a wealth of opportunities for defining and managing your configuration informa-
tion.
This flexibility comes about because Enterprise Library uses configuration sources to
expose configuration information to the application blocks and the core features of the
library. The configuration sources can read configuration from standard .NET configura-
tion files (such as App.config and Web.config), from other files, from a database (using the
example SQL Configuration Source available from http://entlib.codeplex.com), and can
also take into account Group Policy rules for a machine or a domain.
In addition, you can use the fluent interface or the .NET configuration API to create
and populate configuration sources programmatically, merge parts of your configuration
with a central shared configuration, generate merged configuration files, and generate
different configurations for individual run-time environments. For more information
about these more advanced configuration scenarios, see Appendix D, “Enterprise Library
Configuration Scenarios.”

the configuration tools


Enterprise Library includes a stand-alone configuration console, and a configuration edi-
tor that integrates with Microsoft Visual Studio®. The stand-alone console is provided
as versions specifically aimed at the 32-bit (x86) platform and versions compiled for any
platform. For each of these platforms, there is a separate version of the console for the
3.5 and 4.0 versions of the .NET Framework. You can even copy it (and the assemblies it
uses) to a machine that does not have Enterprise Library installed if you just want to
perform post-deployment configuration and system administration. Figure 3 shows the
configuration console with some of the application blocks covered in this book installed
into the configuration.
welcome to the libr a ry 11

figure 4
The Enterprise Library configuration console

The Visual Studio configuration editor displays an interface very similar to that shown in
Figure 3, but allows you to edit your configuration files with a simple right-click in Solu-
tion Explorer.

using the configuration tools


The most common scenario for basic configuration of an application is to store the con-
figuration information in a local configuration file (such as Web.config or App.config). You
can create a new Enterprise Library configuration in the configuration console and then
save it to disk, or you can open an existing configuration file and edit it to add Enterprise
Library to your application.
Even if you use the more advanced approaches described in Appendix D, “Enterprise
Library Configuration Scenarios,” the techniques for defining your Enterprise Library
configuration are basically the same. The general procedure for configuring an application
is as follows:
12 ch a pter one

1. Open the stand-alone configuration tool from your Start menu, or right-
click on a configuration file in Visual Studio Solution Explorer and click Edit
Enterprise Library V5 Configuration.
2. Click the Blocks menu and select the block you want to add to the configura-
tion. This adds the block with the default settings.
• If you want to use the configuration console to edit values in
the <appSettings> section of your configuration file, select Add
Application Settings.
• If you want to enable instrumentation for Enterprise Library,
select Add Instrumentation Settings.
• If you want to use an alternative source for your configuration, such
as a custom XML file, select Add Configuration Settings.
3. To view the configuration settings for each section, block, or provider, click
the right-facing arrow next to the name of that section, block, or provider.
Click it again, or press the Spacebar key, to collapse this section.
4. To view the properties pane for each main configuration section, click the
downward-facing double arrow. Click it again to close the properties pane.
5. To add a provider to a block, depending on the block or the type of provider,
you either right-click the section in the left column and select the appropriate
Add item on the shortcut menu, or click the plus-sign icon in the appropriate
column of the configuration tool. For example, to add a new exception type to
a policy in the Exception Handling block, right-click the Policy item and click
Add Exception Type.
When you rename items, the heading of that item changes to match the name. For
example, if you renamed the default Policy item in the Exception Handling block,
the item will show the new name instead of “Policy.”

1. Edit the properties of the section, block, or provider using the controls in that
section for that block. You will see information about the settings required,
and what they do, in the subsequent chapters of this guide. For full details of
all of the settings that you can specify, see the documentation installed with
Enterprise Library for that block.
2. To delete a section or provider, right-click the section or provider and click
Delete on the shortcut menu. To change the order of providers when more
than one is configured for a block, right-click the section or provider and click
the Move Up or Move Down command on the shortcut menu.
welcome to the libr a ry 13

3. To set the default provider for a block, such as the default Database for the
Data Access block, click the down-pointing double arrow icon next to the
block name and select the default provider name from the drop-down list.
In this section you can also specify the type of provider used to encrypt this
section, and whether the block should demand full permissions.
For more details about encrypting configuration, see the next section of this chapter.
For information about running the block in partial trust environments, which requires
you to turn off the Require Permission setting, see the documentation installed with
Enterprise Library.

4. To use a wizard to simplify configuration for a common task, such as configur-


ing logging to a database, open the Wizards menu and select the one you
require. The wizard will display a series of dialogs that guide you through
setting the required configuration.
5. If you want to configure different settings for an application based on different
deployment scenarios or environments, open the Environments menu and click
New Environment. This adds a drop-down list, Overrides on Environment, to
each section. If you select Override Properties in this list, you can specify the
settings for each new environment that you add to the configuration. This
feature is useful if you have multiple environments that share the same basic
configuration but require different property settings. It allows you to create a
base configuration file (.config) and an environment delta file that contains
the differences (.dconfig). See Appendix D, “Enterprise Library Configuration
Scenarios” for information on configuring and using multiple environments.
6. As you edit the configuration, the lower section of the tool displays any
warnings or errors in your configuration. You must resolve all errors before you
can save the configuration.
7. When you have finished configuring your application, use the commands on the
File menu to save it as a file in your application folder with the appropriate
name; for example, use Web.config for a Web application and App.config for
a Windows Forms application.
You can, of course, edit the configuration files using a text or XML editor, but this is
likely to be a more tedious process compared to using the configuration console. How-
ever, it may be a useful approach for minor changes to the configuration when the
application is running on a server where the configuration console is not installed.
Enterprise Library also contains an XML configuration schema that you can use to enable
IntelliSense® and simplify hand editing of the configuration files.
To enable the Enterprise Library XML schema in Visual Studio, open the configuration
file, open the XML menu, and click Schemas. In the XML Schemas dialog, locate
the Enterprise Library schema and change the value in the Use column to Use this
schema. Then click OK.
14 ch a pter one

encrypting configuration sections


Probably the most common approach for storing configuration information for your
applications that use Enterprise Library is to use an App.config or Web.config file stored
in the root folder of your application. That’s fine, but you may be concerned that anyone
who happens to stroll past the server (either physically, or virtually over the Internet) will
be able to open the file and see sensitive details. These might include connection strings
for the Data Access block, validation rules for the Validation block, or connection infor-
mation used by the Logging block to communicate with Windows Message Queuing.
While in theory, you will protect your configuration files by physically securing the
server and not leaving it running under a logged-on administrator account, you can (and
probably should) add an extra layer of protection by encrypting sections of your configu-
ration files. The configuration tools can do this for you automatically; all you need to do
is set the ProtectionProvider property of the specific block or configuration section that
you want to encrypt. For more information, see Appendix E, “Encrypting Configuration
Files.”

Instantiating and Using Enterprise Library Objects


After you have referenced the assemblies you need, imported the required namespaces,
and configured your application, you can start to think about creating instances of the
Enterprise Library objects you want to use in your applications. As you will see in each of
the following chapters, the Enterprise Library application blocks are optimized for use as
loosely coupled components in almost any type of application. In addition, the change in
this release to using a dependency injection container to generate instances of Enterprise
Library objects means that you can realize the benefits of contemporary design patterns
and solution architectures more easily.
By default, Enterprise Library uses the Unity dependency injection mechanism, which is
provided as part of Enterprise Library. However, it’s possible to configure Enterprise
Library to use any dependency injection container—or other underlying mechanism—
that exposes the required configuration information though an implementation of the
IServiceLocator interface. See Appendix B, “Dependency Injection in Enterprise
Library,” and http://commonservicelocator.codeplex.com for more information.
In Appendix A, “Dependency Injection with Unity,” we take a more in-depth look at what
a dependency injection container actually is, and how it can assist you in applying design
patterns that follow the dependency inversion principle (DIP); in particular, how the
Dependency Injection (DI) pattern can help you to create more decoupled applications
that are easier to build, test, and maintain. However, you don’t need to understand this or
learn about DI to be able to use Enterprise Library. You can create instances of Enterprise
Library objects easily and quickly with a single line of code.
welcome to the libr a ry 15

enterprise library objects, facades, and factories


Each of the application blocks in Enterprise Library contains one or more core objects
that you typically use to access the functionality of that block. An example is the
Exception Handling Application Block, which provides a facade named Exception
Manager that exposes the methods you use to pass exceptions to the block for handling.
The following table lists the commonly used objects for each block.

Application Block Non-static Instance or Factory


Caching ICacheManager
Cryptography CryptographyManager
Data Access Database
Exception Handling ExceptionManager
Logging LogWriter
TraceManager
Security ISecurityCacheProvider
IAuthorizationProvider
Validation ValidatorFactory
ConfigurationValidatorFactory
AttributeValidatorFactory
ValidationAttributeValidatorFactory

There are also task-specific objects in some blocks that you can create directly in your
code in the traditional way using the new operator. For example, you can create
individual validators from the Validation Application Block, or log entries from the
Logging Application Block. We show how to do this in the examples for each applica-
tion block chapter.
To use the features of an application block, all you need to do is create an instance of the
appropriate object, facade, or factory listed in the table above and then call its methods.
The behavior of the block is controlled by the configuration you specified, and often you
can carry out tasks such as exception handling, logging, caching, and encrypting values
with just a single line of code. Even tasks such as accessing data or validating instances of
your custom types require only a few lines of simple code. So, let’s look at how you create
instances of the Enterprise Library objects you want to use.

creating instances of enterprise library types


In this release of Enterprise Library, there are two recommended approaches to creating
instances of the Enterprise Library objects. The decision as to which you use is based
solely on the way you decide to architect your application. You can use the simple ap-
proach of obtaining instances using the Enterprise Library service locator, which provides
access to the Unity container that holds the Enterprise Library configuration information.
Alternatively, if you are already a DI convert, you can take charge of the entire process by
creating and populating a container and using it to create and manage both Enterprise
Library objects and your own custom types. We’ll look at both approaches next.
16 ch a pter one

The Simple Approach — Using the Enterprise Library Service Locator


When you initially create an instance of an Enterprise Library type in your application
code, the underlying mechanism reads your configuration information into a container
and exposes it to your code through a service locator that is initialized as part of the En-
terprise Library configuration mechanism. This service locator provides methods that you
can call at any point in your application code to obtain configured instances of any Enter-
prise Library type.
For example, if you are using the Logging Application Block, you can obtain a refer-
ence to a LogWriter using a single line of code, and then call its Write method to write
your log entry to the configured targets, as shown here.
var writer = EnterpriseLibraryContainer.Current.GetInstance<LogWriter>();
writer.Write("I'm a log entry created by the Logging block!");

Notice that this code uses type inference through the var keyword. The variable will
assume the type returned by the assignment; this technique can make your code more
maintainable.
If you configured more than one instance of a type for a block, such as more than one
Database for the Data Access Application Block, you can specify the name when you call
the GetInstance method. For example, you may configure an Enterprise Library Database
instance named Customers that specifies a Microsoft SQL Server® database, and a sepa-
rate Database instance named Products that specifies another type of database. In this
case, you specify the name of the object you want to resolve when you call the Get
Instance method, as shown here.
var customerDb
= EnterpriseLibraryContainer.Current.GetInstance<Database>("Customers");

You don’t have to initialize the block, read configuration information, or do anything
other than call the methods of the service locator. For many application scenarios, this
simple approach is ideal for obtaining instances of the Enterprise Library types you want
to use.

The Sophisticated Approach — Accessing the Container Directly


If you want to take advantage of design patterns such as Dependency Injection and Inver-
sion of Control in your application, you will probably already be considering the use of a
dependency injection mechanism to decouple your components and layers, and to resolve
types. If this is the case, the more sophisticated approach to incorporating Enterprise
Library into your applications will fit well with your solution architecture.
Instead of allowing Enterprise Library to create, populate, and expose a default con-
tainer that holds just Enterprise Library configuration information, you can create the
container and populate it yourself—and hold onto a reference to the container for use in
your application code. This not only allows you to obtain instances of Enterprise Library
objects, it also lets you use the container to implement dependency injection for your
own custom types. Effectively, the container itself becomes your service locator.
welcome to the libr a ry 17

For example, you can create registrations and mappings in the container that specify
features such as the dependencies between the components of your application, map-
pings between types, the values of parameters and properties, interception for methods,
and deferred object creation.
You may be thinking that all of these wondrous capabilities will require a great deal
of code and effort to achieve; however, they don’t. To initialize and populate the default
Unity container with the Enterprise Library configuration information and make it avail-
able to your application, only a single line of code is required. It is shown here:
var theContainer = new UnityContainer()
.AddNewExtension<EnterpriseLibraryCoreExtension>();

Now that you have a reference to the container, you can obtain an instance of any Enter-
prise Library type by calling the container methods directly. For example, if you are using
the Logging Application Block, you can obtain a reference to a LogWriter using a single
line of code, and then call its Write method to write your log entry to the configured
targets.
var writer = theContainer.Resolve<LogWriter>();
writer.Write("I'm a log entry created by the Logging block!");

And if you configured more than one instance of a type for a block, such as more than
one database for the Data Access Application Block, you can specify the name when you
call the Resolve method, as shown here:
var customerDb = theContainer.Resolve<Database>("Customers");

You may have noticed the similarity in syntax between the Resolve method and the
GetInstance method we used earlier. Effectively, when you are using the default Unity
container, the GetInstance method of the service locator simply calls the Resolve
method of the Unity container. It therefore makes sense that the syntax and parameters
are similar. Both the container and the service locator expose other methods that allow
you to get collections of objects, and there are both generic and non-generic overloads
that allow you to use the methods in languages that do not support generics.
One point to note if you choose this more sophisticated approach to using Enterprise
Library in your applications is that you should import two additional namespaces into
your code. These namespaces include the container and core extension definitions:
• Microsoft.Practices.EnterpriseLibrary.Common.Configuration.Unity
• Microsoft.Practices.Unity
18 ch a pter one

Pros and Cons of Object Instantiation


If you haven’t already decided which approach to follow for creating Enterprise Library
objects, the following table will help you to understand the advantages and disadvan-
tages of each one.

Object instantiation Advantages Considerations


technique
Using the Requires no initialization code. The You can only resolve Enterprise
Enterprise Library service locator is made available Library types (as interfaces, abstract
service locator automatically. types, or concrete types that are
You can resolve types anywhere in registered automatically).
your application code. You don’t need You cannot manipulate, or add
to hold onto a reference to the registrations or mappings to the
container. container.
Using the container You can directly access all the Requires initialization, though this
as the service functionality of the Unity container. is simply one line of code executed
locator You can iterate over the contents and at application startup, or simple
read or manipulate the registrations configuration settings, when you
and mappings (though you should not use the default Unity container.
attempt to change the Enterprise Request-based applications such
Library configuration information). as ASP.NET and Web services
You can add and remove your own require additional code to store the
registrations and mappings, allowing container reference and resolve
you to take full advantage of DI the dependencies of the request
techniques. class (such as the Page).

One of the prime advantages of the more sophisticated approach of accessing the con-
tainer directly is that you can use it to resolve dependencies of your own custom types.
For example, assume you have a class named TaxCalculator that needs to perform logging
and implement a consistent policy for handling exceptions that you apply across your
entire application. Your class will contain a constructor that accepts an instance of an
ExceptionManager and a LogWriter as dependencies.
public class TaxCalculator
{
private ExceptionManager _exceptionManager;
private LogWriter _logWriter;

public TaxCalculator(ExceptionManager em, LogWriter lw)


{
this._exceptionManager = em;
this._logWriter = lw;
}
...
}
welcome to the libr a ry 19

If you use the Enterprise Library service locator approach, you could simply obtain these
instances within the class constructor or methods when required, rather than passing
them in as parameters. However, a more commonly used approach is to generate and reuse
the instances in your main application code, and pass them to the TaxCalculator when
you create an instance.
var exManager
= EnterpriseLibraryContainer.Current.GetInstance<ExceptionManager>();
var writer
= EnterpriseLibraryContainer.Current.GetInstance<LogWriter>();
TaxCalculator calc = new TaxCalculator(exManager, writer);

Alternatively, if you have created and held a reference to the container, you just need to
resolve the TaxCalculator type through the container. Unity will instantiate the type,
examine the constructor parameters, and automatically inject instances of the Exception-
Manager and a LogWriter into them. It returns your new TaxCalculator instance with
all of the dependencies populated.
TaxCalculator calc = theContainer.Resolve<TaxCalculator>();

More Reasons to be Sophisticated


It is clear from the preceding examples that managing the container yourself offers con-
siderable advantages in all but the simplest applications or scenarios. And the example
you’ve seen for using dependency injection only scratches the surface of what you can do
using the more sophisticated approach. For example, if you have a reference to the con-
tainer, you can:
• Manage the lifetime of your custom types. They can be resolved by the con-
tainer as singletons, with a lifetime based on the lifetime of the object that
created them, or as a new instance per execution thread.
• Implement patterns such as plug-in and service locator by mapping interfaces
and abstract types to concrete implementations of your custom types.
• Defer creation of the resolved custom type until it is actually required.
• Specify dependencies and values for parameters and properties of the resolved
instances of your custom types.
• Apply interception to your custom types to modify their behavior, implement
management of crosscutting concerns, or add additional functionality.
• Set up hierarchies of dependencies that are automatically populated to achieve
maximum decoupling between components, assist in debugging, simplify
testing, and reduce maintenance cost and effort.
When you use the default Unity container, you have a powerful general-purpose depen-
dency injection mechanism in your arsenal. You can define and modify registrations and
mappings in the container programmatically at run time, or you can define them using
configuration files. Appendix A, “Dependency Injection with Unity,” contains more infor-
mation about using Unity.
20 ch a pter one

To give you a sense of how easy it is to use, the following code registers a mapping
between an interface named IMyService and a concrete type named CustomerService,
specifying that it should be a singleton.
theContainer.RegisterType<IMyService, CustomerService>(
new ContainerControlledLifetimeManager());

Then you can resolve the single instance of the concrete type using the following code.
IMyService myServiceInstance = theContainer.Resolve<IMyService>();

This returns an instance of the CustomerService type, though you can change the actual
type returned at run time by changing the mapping in the container. Alternatively, you can
create multiple registrations or mappings for an interface or base class with different
names and specify the name when you resolve the type.
Unity can also read its configuration from your application’s App.config or Web.
config file (or any other configuration file). This means that you can use the sophisticated
approach to creating Enterprise Library objects and your own custom types, while being
able to change the behavior of your application just by editing the configuration file.
If you want to load type registrations and mappings into a Unity container from a
configuration file, you must add the assembly Microsoft.Practices.Unity.Configuration.
dll to your project, and optionally import the namespace Microsoft.Practices.Unity.
Configuration into your code. This assembly and namespace contains the extension to
the Unity container for loading configuration information.
For example, the following extract from a configuration file initializes the container and
adds the same custom mapping to it as the RegisterType example shown above.
<unity>
<alias alias="CoreExtension"
type="Microsoft.Practices.EnterpriseLibrary.Common.Configuration
.Unity.EnterpriseLibraryCoreExtension,
Microsoft.Practices.EnterpriseLibrary.Common" />
<namespace name="Your.Custom.Types.Namespace" />
<assembly name="Your.Custom.Types.Assembly.Name" />
<container>
<extension type="CoreExtension" />
<register type="IMyService" mapTo="CustomerService">
<lifetime type="singleton" />
</register>
</container>
</unity>
welcome to the libr a ry 21

Then, all you need to do is load this configuration into a new Unity container. This requires
just one line of code, as shown here.
var theContainer = new UnityContainer().LoadConfiguration();

Other techniques we demonstrate in Appendix A, “Dependency Injection with Unity,”


include using attributes to register type mappings and dependencies, defining named
registrations, and specifying dependencies and values for parameters and properties.
The one point to be aware of when you use the more sophisticated technique for creating
objects is that your application is responsible for managing the container, holding a refer-
ence to it, and making that reference available to code that must access the container. In
forms-based applications that automatically maintain global state (for example, applica-
tions built using technologies such as Windows Forms, Windows Presentation Foundation
(WPF), and Silverlight®), you can use an application-wide variable for this.
However, in request-based applications built using technologies such as ASP.NET,
ASMX, and Windows Communication Foundation (WCF), you generally require addi-
tional code to maintain the container and make it available for each request. We discuss
some of the ways that you can achieve this in Appendix B, “Dependency Injection in En-
terprise Library,” and you will find full details in the documentation installed with Enter-
prise Library and available online at http://go.microsoft.com/fwlink/?LinkId=188874.

getting objects from previous versions


of enterprise library
If you have used versions of Enterprise Library prior to version 5.0, you may be more
familiar with the previous approach to creating objects within your application code.
Earlier versions generally supported or recommended the use of a series of static facades.
While these facades are still supported in version 5.0 for backward compatibility with
existing applications, they are no longer the recommended approach and may be depre-
cated in future releases.
Figure 5 summarizes all the approaches you can use to get access to the features of
Enterprise Library. 1 and 2 are the recommended approaches for Enterprise Library 5.0; 3
and 4 are still supported to make it easier to upgrade your existing applications that use
a previous version of Enterprise Library.
22 ch a pter one

Configuration

Container

1 4

var myLogger = Container.Resolve<LogWriter>( );


myLogger.Write(…); Instance Factory
var factory = new LogWriterFactory( );
var myLogger = factory.Create( );
2 3 myLogger.Write(…);

Service Locator Static Facade

var myLogger = Logger.Write(…);


EnterpriseLibraryContainer.Current.GetInstance<LogWriter>( );
myLogger.Write(…);

figure 5
Four ways, one library

The Example Applications


To help you understand how you can use Enterprise Library and each of the seven applica-
tion blocks covered in this guide, we provide a series of simple example applications that
you can run and examine. Each is a console-based application and, in most cases, all of
the relevant code that uses Enterprise Library is found within a series of routines in the
Program.cs file. This makes it easy to see how the different blocks work, and what you
can achieve with each one.
The examples use the simplest approach (the service locator and GetInstance meth-
od described earlier in the chapter) for creating the Enterprise Library objects they require,
and have the configuration information for the blocks they use stored in the App.config
file. Each of the options in the examples exercises specific features of the relevant block
and displays the results. You can open the solutions for these examples in Visual Studio,
or just run the executable file in the bin\debug folder and view the source files in a text
editor if you prefer.
To obtain the example applications, go to
http://go.microsoft.com/fwlink/?LinkId=189009.
welcome to the libr a ry 23

Summary
This brief introduction to Enterprise Library will help you to get started if you are not
familiar with its capabilities and the basics of using it in applications. This chapter de-
scribed what Enterprise Library is, where you can get it, and how it can make it much
easier to manage your crosscutting concerns. This book concentrates on the application
blocks in Enterprise Library that “do stuff” (as opposed to those that “wire up stuff”). The
blocks we concentrate on in this book include the Caching, Cryptography, Data Access,
Exception Handling, Logging, Security, and Validation Application Blocks.
The aim of this chapter was also to help you get started with Enterprise Library by
explaining how you deploy and reference the assemblies it contains, how you configure
your applications to use Enterprise Library, how you instantiate Enterprise Library objects,
and the example applications we provide. Some of the more advanced features and con-
figuration options were omitted so that you may concentrate on the fundamental require-
ments. However, each appendix in this guide provides more detailed information, while
Enterprise Library contains substantial reference documentation, samples, and other re-
sources that will guide you as you explore these more advanced features.
Exploring the Variety of Random
Documents with Different Content
tying to go to the trains. Then the machine is rolled along the line of
pigeonholes and fed, by hand, by its retainer. Packs of letters, four inches
thick, are placed into position, the machine is set in motion, and then—
click, click, clop! That’s the way it sounds. The first two clicks indicate the
tying of the packet of letters, sidewise and then lengthwise, and the “clop”
the dropping of the bundle into a waiting basket.
Where the best men used to tie five or six packets in a minute, the
machine now ties thirty—and it has not tried for a record yet!

Flesh From Body Saves Eye.


The sight of Doctor E. Lerendinger, a professor of Hood College,
Frederick, Md., has been restored as the result of an unusual surgical
operation. Flesh was removed from the professor’s abdomen and placed in a
cavity above one of his eyes, which had been caused by an accident. The
operation was performed several weeks ago, but was not made public until
success was assured.

Tallest Couple are Wedded.


The tallest couple in Pennsylvania were united in marriage a few days
ago in Lewistown. The bridegroom, George Schaffer, who stands six feet
seven inches in his stockings, achieved quite a reputation when he was a
member of the Allentown police as the tallest cop. The bride is Mrs. Angie
Kern, six feet two inches tall. Both parties are about forty years of age.
Mrs. Schaffer is a prospective heiress if she can break the will of the late
Charles Losch, who left about $150,000 to be divided among relatives. She
produced a letter purporting to have been signed by Losch, saying that if
she would take care of him in his declining years he would leave her his
homestead in Allentown, valued at $12,000. Schaffer says he often heard
Losch say he would leave Mrs. Kern the homestead.
The newlyweds have purchased a farm, and whatever the outcome of the
will contest, it will not affect their happiness. The bride says she fell in love
with her new husband because she detested walking around with a man
shorter than herself.
This Modest Inventor Would Stop World War.
“I can make the United States the strongest nation in the world. I can end
the European struggle in a short time. I can make the smallest nation most
powerful.”
This is the assertion of John Vogelzangs, of Menominee, Mich., an
inventor, who claims to have a method of extracting electricity from the air
so that air craft might be manned with powerful guns and not be forced to
land until they want to.
“I can sweep the seas clear of vessels. I can kill armies and level cities,”
claimed the inventor, who in the same breath asserted he favored universal
peace, but that the world was not ready for it.
He says Secretary Daniels’ plan for an advisory board is good.
He refused to give out much information about his new device. He said
he lacked money to carry on the work, and displayed a letter from Mr.
Daniels, written before the war broke out, saying this nation was not ready
to take up his ideas.
Vogelzangs has a reputation for being an inventor of ability. He made a
street cleaner, which he refused to sell for $10,000. He also claims he will
revolutionize the berry business with a new picker.

Walks on 113th Birthday.


Mrs. Edna G. Goldman, of Glamorgan, Va., celebrated her 113th
birthday by walking ten miles to the home of her son, Henry Goldman, at
Pound, Va.
Mrs. Goldman was born in Appomattox County, Va., in 1802. Despite
her age, she cultivates a small patch of land in corn and beans each year.
This year she is “farming” about two acres.

Flivver is Not Amphibious.


Edward Kirby, of Newton, N. J., erred in believing a flivver amphibious.
It is alleged that he stole the automobile at the Grand Hotel, Golden
Springs, and, when closely pursued by other automobiles, he ran the flivver
into the Delaware River, seeking to reach Pike County shore.
The flivver floated several minutes and made quite a little progress in the
current, but when the body filled, she went down at the bow and soon
plunged to the bottom.
Kirby swam out and made his way across the river. He disappeared into
the woods there, and a posse under Sheriff Applegate is seeking him.

Song Tells of Old Man Who Had a Wooden Leg.


John Strain, of Greenwich, Conn., who lost his leg three years ago and
his temper recently, has announced that he intends to obtain a rubber
artificial limb. His statement was made to-day through a window of the
county jail, from which he will watch the dying sun precede each of the
next thirty twilights.
The reason Mr. Strain intends to obtain the new artificial limb described
it that his wife, a muscular woman, who has been getting plenty of exercise
since John ceased to work eight years ago, has been and is in the habit of
bounding his artificial limb off his forehead when a domestic storm brews.
The present limb is of wood, and, for various reasons, is unsatisfactory to
Mr. Strain and his brow.
Over the condition of the weather a quarrel started in the Strain home.
Mr. Strain declared he felt that a gale was coming from the northeast,
inasmuch as his left leg—not the wooden one—pained slightly. Mrs. Strain,
with that rare spirit of raillery which characterizes a woman who supports
four children, told John the weather could scarcely affect a man who sat in
the house smoking all the time. It was then that John, according to the
testimony of his wife in police court, threw eight volumes of Dumas,
apparently bound in zinc. His aim was true.
Mrs. Strain then took John’s artificial limb and hung it just west of
where he parts his hair. Her judgment of distance was perfect—it generally
is. She then cried for help.
When help arrived, John had hopped on one foot over the State border,
into New York. A sheriff with a rich baritone voice explained to him that
hopping about New York State with no hat and only an undershirt over his
shoulders would mean but little in his life. John thought deeply, hopped
over into Connecticut again, and was sentenced to thirty days in jail by
Judge James R. Meade.
Machine That Remembers.
A machine which will remember the date and hour of an appointment
made several weeks previous is one of the latest efficiency devices to be
placed on the market. A roll of paper strip passes over a flat surface where
the appointment is indicated, and a punch mark made in the margin. When
that time occurs, a gong is sounded and a reference to the strip will give the
information as to what appointment is to be kept.

Fifty Dollars Gone, Flivver May Survive.


Probably the maddest man in and about Montgomery County, New York
State, just at present is Reuben Hyney, who keeps a shoe store on the main
street of Fonda, and who, as a side line, rents his automobile to any one
who can fit in it. Mr. Hyney has no more temper than any other normal man
who lives in Montgomery County, but the shoe business has run over at the
heel a bit recently, and the other afternoon something happened which
increased Mr. Hyney’s height four inches.
Hyney was adjusting a spring-heeled shoe to a broad foot at about a
moment after two o’clock, when the telephone rang sharply. He dropped his
client’s foot onto his own and limped to the booth. A man with an educated
voice, as Mr. Hyney describes it, was asking if he might hire an automobile
for the afternoon. He said he was a school inspector and was as busy as a
one-eyed mouse in a cheese factory. He would come running if the buzz
wagon was not busy. It was not.
Hardly had the satisfied customer walked from the store when a bearded
stranger, wearing a slouch hat, stopped at the door, looked up and down the
street craftily, and entered.
“Wait there,” said the shoe merchant, pointing to the central design on a
piece of linoleum. “I will oil the machine and call my daughter.”
The stranger, laughing up his sleeve, through his vest and along his
hatband, reached into the cash register and took fifty dollars. Then he sat
down and waited until Miss Hyney came to watch the store. By this time it
was hardly worth it.
An hour later the mysterious stranger told the owner of the machine to
stop in front of a building in Fort Plain. He went upstairs.
Three hours later Hyney decided the stranger had given him the
metropolitan fare-thee-well. He entered the building and found nothing but
the janitor and a flock of rent signs.
Two hours later he was back in Fonda, telling his daughter about the
“cuss” who tore the soul out of a dandy four-hundred-dollar touring car and
didn’t pay for it. Then his daughter asked him if he had taken fifty dollars
from the cash register.
Mr. Hyney is in bed. But what’s the use?—he can’t sleep.

Capture Odd Pair of Mice.


A most remarkable freak of nature is a white mouse and a black one
captured in a bureau drawer by John Elias, who lives in Atchison, Kan. The
white mouse hasn’t a black spot on it and has black eyes. The black mouse
has fur as black as the ace of spades, and its eyes are brown.
Local zoölogists are unable to account for the strange markings of the
mice. They are very vicious and never miss a chance to attempt to bite
members of the Elias family while being fed.

Billy Goat is Boss of Town.


A billy goat tied up traffic in Kokomo, Ind., as effectively as the street-
car strike did in Chicago. The goat broke away from a colored man who
was leading it at the transfer corner.
The conductors of two cars standing there were on the sidewalk at the
time. They started for their cars and the goat started for them. The men
“beat it” for a candy store and won.
The goat then turned his attention to several pedestrians and soon made a
scatterment. About this time Patrolmen Elkins and Webb came along.
Webb lived on a farm and knew the habits of the goat. He kept in the
rear. Elkins bravely went forward to capture the goat. He managed to seize
the animal by the head and tried to go with him to the station. Every time he
pulled, the goat started to butt him. He held on for several minutes, afraid to
let go, until the owner of the goat relieved him.

Aged Couple Joined at Last.


George W. Hayden, a retired farmer of Big Laurel, Va., and Larestia
Fulton, of Lipps, were married at the home of the bride’s son, Henry Fulton,
a few days ago. The bridegroom was some few days past ninety years of
age when the knot was tied and the bride was lacking a few days of being
eighty-seven.
About seventy years ago Hayden and Miss Helt—the bride’s maiden
name—were engaged, but quarreled, and both married other parties and
reared large families. Hayden’s wife died eighteen years ago and Mrs.
Fulton was left a widow three years ago.

“Well Broken to Hard Work.”


Although many bones in his body have been broken as a result of
various accidents during his life, W. M. Morgan, who lives near Lancaster,
Kan., finds little cause for complaint for the treatment he has had at the
hands of “cruel fate.”
At various times he has had both shoulders fractured, a number of ribs
cracked, a thumb broken, both legs broken, and his right foot has almost
every bone in it broken. Despite all these handicaps, he works every day at
hard labor and has little use for the fellow who thinks hard luck has given
him a jolt.

Snake Swallows China Egg.


Blacksnakes down Gales Ferry way cannot tell china nest eggs for hen’s
eggs, according to a story related by Mr. and Mrs. R. B. de Bussy, of Mount
Vernon, N. Y. The De Bussys were recent guests of Miss Caroline Freeman
at the Bouwerie, Gales Ferry. Miss Freeman’s guests at that time included
Professor Heuser, instructor in German at Columbia University, and his
family.
Professor Heuser’s daughter, six years old, returning from the poultry
house at Bouwerie, reported no eggs, but said a big snake was in a hen’s
nest. A manservant, using an ax, killed the five-foot snake.
Miss Freeman then discovered that the china nest egg was missing from
the nest. The search led to the interior of the snake, where the missing china
nest egg was recovered.
Lightning’s Queer Freak.
Lightning apparently photographed a perfect likeness of a tree, branches,
twigs, and leaves, in minutest detail, on the breast of Edwin Liesman, who
was instantly killed in the Magnolia clubhouse on Mount Penn, near
Reading, Pa., in a violent electrical storm.
Liesman’s mother, Mrs. Bernard Liesman, and a friend, Harry
Opperman, were badly shocked, but will recover.
Liesman was sitting at a window next to a telephone. The bolt followed
the telephone wire. The tree outside the window was almost exactly
reproduced on Liesman’s body. The tragedy occurred during four brilliant
flashes in swift succession, putting out all the lights in the cottage. Medical
men and photographers were puzzled by the strange features wrought on the
dead man.

Sounds Like a Fish Story.


A flock of geese were swimming in White River, near Augusta, Ark.,
and a splash attracted the attention of several men and boys who were near
by. A large blue channel catfish came up and grabbed a goose, taking the
fowl under with him.
People watched for some time, but the goose never came up. This may
sound like a fish story, but nevertheless it is true.

Ghostly Figure That is an Awful Shrieker.


A ghost, or some other creature with a voice like an armload of siren
whistles, has frightened the residents of Somerville, N. J., to the point
where it is no longer a joke, and they want to get to sleep. The disorder,
frightful beyond words, ghastly, ghostly, and hair elevating, has been going
on for a week, and the whole town is determined that something is to be
done about it.
Thomas Hagen, night roundhouse watchman, was the first one to hear
the shrieks. He was going round and round the roundhouse when the most
frightful bellow imaginable rent the air. Mr. Hagen, who comes of a warm-
blooded race, was so startled that his blood ran cold. It could barely run,
even.
Right across the railroad tracks from the roundhouse is the cemetery, and
Mr. Hagen, after recalling this, took a little jaunt up the road that restored
his circulation to normal. He notified the police force, who were sitting up
late, reading, and he became indignant when the department took a cigar
out of its mouth and laughed at him.
Every night since then the terrible noise has been repeated, and persons
who have passed the roundhouse have seen a strange figure flitting about
among the bushes and trees which border the railroad tracks at that point.
Some of them even describe the flitter, which is going some, considering
the speed with which they invariably leave the neighborhood.
For the last two nights every one in the village has been shuddering in
unison, and the vibration can be felt as far as Philadelphia. Every now and
then the shriek ceases and is replaced by a wail—and the wail is a whale of
a wail. It is a relief when the shriek starts again.
Mr. Hagen, who originally heard the alleged ghost and who has become
more bored with the noise than any of the comparative beginners, yesterday
resigned his position as watchman in the roundhouse. He declared that if
everything was on the square he would work forever and willingly walk
around and around and around all night, but that under present conditions
no self-respecting roundhouse watchman could stand around watching.
Chief of Police Bellis will watch with seven railroad detectives. They
will stay right at the roundhouse until the ghost appears. Beyond that they
have made no arrangements.

Hoodoo Pursues Two Miners.


Two mining partners, Gus Erickson and Bert Pinney, of Hailey, Idaho,
are certainly pursued by some hoodoo. While working on a stage ten feet
below the surface, the stage broke away from its fastenings, dropping
Pinney down the shaft twenty feet, where, after he had turned head down,
his buckskin shoe laces caught on a nail and held him until help arrived.
Three hundred feet of water would have received him had his laces broke.
The next afternoon Erickson came to town on his motor cycle to get the
mail. Returning, the motor cycle skidded in a rut, throwing its rider over the
handlebars into the road, the machine piling on top of him. With his skull
fractured in three places, he lay in the road an hour before he was found.
Both men will recover.

Former Water Boy’s Story.


A prominent business man of Castleton, Ill., told the following story the
other night to three or four citizens assembled in A. A. Webber’s real-estate
office:
“When I was a boy,” he said, “I used to carry water for the men to drink
when they were working in the field some distance from the house. One
real warm day I carried water to my father, who was running a mower and
cutting timothy for hay. As I was about to return home, I noticed a prairie
chicken fly up from the freshly mown swath. Thinking there might be a nest
of eggs—which, by the way, are fine eating—I investigated, and what do
you think I found? A prairie chicken with its head cut off, the mowing bar
being just the right height to perform the operation. I also found the feet and
legs that belonged to the one that flew away. It probably stood up ready to
fly as the mowing bar came along, while the other remained sitting and lost
its head. Needless to say, we had prairie chicken for dinner.”

The Nick Carter Stories


ISSUED EVERY SATURDAY BEAUTIFUL COLORED COVERS
When it comes to detective stories worth while, the Nick Carter Stories
contain the only ones that should be considered. They are not overdrawn
tales of bloodshed. They rather show the working of one of the finest minds
ever conceived by a writer. The name of Nick Carter is familiar all over the
world, for the stories of his adventures may be read in twenty languages. No
other stories have withstood the severe test of time so well as those
contained in the Nick Carter Stories. It proves conclusively that they are
the best. We give herewith a list of some of the back numbers in print. You
can have your news dealer order them, or they will be sent direct by the
publishers to any address upon receipt of the price in money or postage
stamps.
730—The Torn Card.
731—Under Desperation’s Spur.
732—The Connecting Link.
733—The Abduction Syndicate.
738—A Plot Within a Plot.
739—The Dead Accomplice.
746—The Secret Entrance.
747—The Cavern Mystery.
748—The Disappearing Fortune.
749—A Voice from the Past.
752—The Spider’s Web.
753—The Man With a Crutch.
754—The Rajah’s Regalia.
755—Saved from Death.
756—The Man Inside.
757—Out for Vengeance.
758—The Poisons of Exili.
759—The Antique Vial.
760—The House of Slumber.
761—A Double Identity.
762—“The Mocker’s” Stratagem.
763—The Man that Came Back.
764—The Tracks in the Snow.
765—The Babbington Case.
766—The Masters of Millions.
767—The Blue Stain.
768—The Lost Clew.
770—The Turn of a Card.
771—A Message in the Dust.
772—A Royal Flush.
774—The Great Buddha Beryl.
775—The Vanishing Heiress.
776—The Unfinished Letter.
777—A Difficult Trail.
782—A Woman’s Stratagem.
783—The Cliff Castle Affair.
784—A Prisoner of the Tomb.
785—A Resourceful Foe.
789—The Great Hotel Tragedies.
795—Zanoni, the Transfigured.
796—The Lure of Gold.
797—The Man With a Chest.
798—A Shadowed Life.
799—The Secret Agent.
800—A Plot for a Crown.
801—The Red Button.
802—Up Against It.
803—The Gold Certificate.
804—Jack Wise’s Hurry Call.
805—Nick Carter’s Ocean Chase.
807—Nick Carter’s Advertisement.
808—The Kregoff Necklace.
811—Nick Carter and the Nihilists.
812—Nick Carter and the Convict Gang.
813—Nick Carter and the Guilty Governor.
814—The Triangled Coin.
815—Ninety-nine—and One.
816—Coin Number 77.
NEW SERIES
NICK CARTER STORIES
1—The Man from Nowhere.
2—The Face at the Window.
3—A Fight for a Million.
4—Nick Carter’s Land Office.
5—Nick Carter and the Professor.
6—Nick Carter as a Mill Hand.
7—A Single Clew.
8—The Emerald Snake.
9—The Currie Outfit.
10—Nick Carter and the Kidnapped Heiress.
11—Nick Carter Strikes Oil.
12—Nick Carter’s Hunt for a Treasure.
13—A Mystery of the Highway.
14—The Silent Passenger.
15—Jack Dreen’s Secret.
16—Nick Carter’s Pipe Line Case.
17—Nick Carter and the Gold Thieves.
18—Nick Carter’s Auto Chase.
19—The Corrigan Inheritance.
20—The Keen Eye of Denton.
21—The Spider’s Parlor.
22—Nick Carter’s Quick Guess.
23—Nick Carter and the Murderess.
24—Nick Carter and the Pay Car.
25—The Stolen Antique.
26—The Crook League.
27—An English Cracksman.
28—Nick Carter’s Still Hunt.
29—Nick Carter’s Electric Shock.
30—Nick Carter and the Stolen Duchess.
31—The Purple Spot.
32—The Stolen Groom.
33—The Inverted Cross.
34—Nick Carter and Keno McCall.
35—Nick Carter’s Death Trap.
36—Nick Carter’s Siamese Puzzle.
37—The Man Outside.
38—The Death Chamber.
39—The Wind and the Wire.
40—Nick Carter’s Three Cornered Chase.
41—Dazaar, the Arch-Fiend.
42—The Queen of the Seven.
43—Crossed Wires.
44—A Crimson Clew.
45—The Third Man.
46—The Sign of the Dagger.
47—The Devil Worshipers.
48—The Cross of Daggers.
49—At Risk of Life.
50—The Deeper Game.
51—The Code Message.
52—The Last of the Seven.
53—Ten-Ichi, the Wonderful.
54—The Secret Order of Associated Crooks.
55—The Golden Hair Clew.
56—Back From the Dead.
57—Through Dark Ways.
58—When Aces Were Trumps.
59—The Gambler’s Last Hand.
60—The Murder at Linden Fells.
61—A Game for Millions.
62—Under Cover.
63—The Last Call.
64—Mercedes Danton’s Double.
65—The Millionaire’s Nemesis.
66—A Princess of the Underworld.
67—The Crook’s Blind.
68—The Fatal Hour.
69—Blood Money.
70—A Queen of Her Kind.
71—Isabel Benton’s Trump Card.
72—A Princess of Hades.
73—A Prince of Plotters.
74—The Crook’s Double.
75—For Life and Honor.
76—A Compact With Dazaar.
77—In the Shadow of Dazaar.
78—The Crime of a Money King.
79—Birds of Prey.
80—The Unknown Dead.
81—The Severed Hand.
82—The Terrible Game of Millions.
83—A Dead Man’s Power.
84—The Secrets of an Old House.
85—The Wolf Within.
86—The Yellow Coupon.
87—In the Toils.
88—The Stolen Radium.
89—A Crime in Paradise.
90—Behind Prison Bars.
91—The Blind Man’s Daughter.
92—On the Brink of Ruin.
93—Letter of Fire.
94—The $100,000 Kiss.
95—Outlaws of the Militia.
96—The Opium-Runners.
97—In Record Time.
98—The Wag-Nuk Clew.
99—The Middle Link.
100—The Crystal Maze.
101—A New Serpent in Eden.
102—The Auburn Sensation.
103—A Dying Chance.
104—The Gargoni Girdle.
105—Twice in Jeopardy.
196—The Ghost Launch.
107—Up in the Air.
108—The Girl Prisoner.
109—The Red Plague.
110—The Arson Trust.
111—The King of the Firebugs.
112—“Lifter’s” of the Lofts.
113—French Jimmie and His Forty
Thieves.
114—The Death Plot.
115—The Evil Formula.
116—The Blue Button.
117—The Deadly Parallel.
118—The Vivisectionists.
119—The Stolen Brain.
120—An Uncanny Revenge.
121—The Call of Death.
122—The Suicide.
123—Half a Million Ransom.
124—The Girl Kidnapper.
125—The Pirate Yacht.
126—The Crime of the White Hand.
127—Found in the Jungle.
128—Six Men in a Loop.
129—The Jewels of Wat Chang.
130—The Crime in the Tower.
131—The Fatal Message.
132—Broken Bars.
133—Won by Magic.
134—The Secret of Shangore.
135—Straight to the Goal.
136—The Man They Held Back.
137—The Seal of Gijon.
138—The Traitors of the Tropics.
139—The Pressing Peril.
140—The Melting-Pot.
141—The Duplicate Night.
142—The Edge of a Crime.
143—The Sultan’s Pearls.
144—The Clew of the White Collar.
145—An Unsolved Mystery.
146—Paying the Price.
147—On Death’s Trail.
148—The Mark of Cain.
Dated July 17th, 1915.
149—A Network of Crime.
Dated July 24th, 1915.
150—The House of Fear.
Dated July 31st, 1915.
151—The Mystery of the Crossed Needles.
Dated August 7th, 1915.
152—The Forced Crime.
Dated August 14th, 1915.
153—The Doom of Sang Tu.
Dated August 21st, 1915.
154—The Mask of Death.
Dated August 28th, 1915.
155—The Gordon Elopement.
Dated Sept. 4th, 1915.
156—Blood Will Tell.

PRICE, FIVE CENTS PER COPY. If you want any back numbers of our
weeklies and cannot procure them from your news dealer, they can be
obtained direct from this office. Postage stamps taken the same as money.

STREET & SMITH, Publishers, 79-89 Seventh Ave., NEW YORK CITY
*** END OF THE PROJECT GUTENBERG EBOOK NICK CARTER
STORIES NO. 157, SEPTEMBER 11, 1915: A HUMAN
COUNTERFEIT; OR, NICK CARTER AND THE CROOK'S DOUBLE
***

Updated editions will replace the previous one—the old editions will
be renamed.

Creating the works from print editions not protected by U.S.


copyright law means that no one owns a United States copyright in
these works, so the Foundation (and you!) can copy and distribute it
in the United States without permission and without paying copyright
royalties. Special rules, set forth in the General Terms of Use part of
this license, apply to copying and distributing Project Gutenberg™
electronic works to protect the PROJECT GUTENBERG™ concept
and trademark. Project Gutenberg is a registered trademark, and
may not be used if you charge for an eBook, except by following the
terms of the trademark license, including paying royalties for use of
the Project Gutenberg trademark. If you do not charge anything for
copies of this eBook, complying with the trademark license is very
easy. You may use this eBook for nearly any purpose such as
creation of derivative works, reports, performances and research.
Project Gutenberg eBooks may be modified and printed and given
away—you may do practically ANYTHING in the United States with
eBooks not protected by U.S. copyright law. Redistribution is subject
to the trademark license, especially commercial redistribution.

START: FULL LICENSE


THE FULL PROJECT GUTENBERG LICENSE
PLEASE READ THIS BEFORE YOU DISTRIBUTE OR USE THIS WORK

To protect the Project Gutenberg™ mission of promoting the free


distribution of electronic works, by using or distributing this work (or
any other work associated in any way with the phrase “Project
Gutenberg”), you agree to comply with all the terms of the Full
Project Gutenberg™ License available with this file or online at
www.gutenberg.org/license.

Section 1. General Terms of Use and


Redistributing Project Gutenberg™
electronic works
1.A. By reading or using any part of this Project Gutenberg™
electronic work, you indicate that you have read, understand, agree
to and accept all the terms of this license and intellectual property
(trademark/copyright) agreement. If you do not agree to abide by all
the terms of this agreement, you must cease using and return or
destroy all copies of Project Gutenberg™ electronic works in your
possession. If you paid a fee for obtaining a copy of or access to a
Project Gutenberg™ electronic work and you do not agree to be
bound by the terms of this agreement, you may obtain a refund from
the person or entity to whom you paid the fee as set forth in
paragraph 1.E.8.

1.B. “Project Gutenberg” is a registered trademark. It may only be


used on or associated in any way with an electronic work by people
who agree to be bound by the terms of this agreement. There are a
few things that you can do with most Project Gutenberg™ electronic
works even without complying with the full terms of this agreement.
See paragraph 1.C below. There are a lot of things you can do with
Project Gutenberg™ electronic works if you follow the terms of this
agreement and help preserve free future access to Project
Gutenberg™ electronic works. See paragraph 1.E below.
1.C. The Project Gutenberg Literary Archive Foundation (“the
Foundation” or PGLAF), owns a compilation copyright in the
collection of Project Gutenberg™ electronic works. Nearly all the
individual works in the collection are in the public domain in the
United States. If an individual work is unprotected by copyright law in
the United States and you are located in the United States, we do
not claim a right to prevent you from copying, distributing,
performing, displaying or creating derivative works based on the
work as long as all references to Project Gutenberg are removed. Of
course, we hope that you will support the Project Gutenberg™
mission of promoting free access to electronic works by freely
sharing Project Gutenberg™ works in compliance with the terms of
this agreement for keeping the Project Gutenberg™ name
associated with the work. You can easily comply with the terms of
this agreement by keeping this work in the same format with its
attached full Project Gutenberg™ License when you share it without
charge with others.

1.D. The copyright laws of the place where you are located also
govern what you can do with this work. Copyright laws in most
countries are in a constant state of change. If you are outside the
United States, check the laws of your country in addition to the terms
of this agreement before downloading, copying, displaying,
performing, distributing or creating derivative works based on this
work or any other Project Gutenberg™ work. The Foundation makes
no representations concerning the copyright status of any work in
any country other than the United States.

1.E. Unless you have removed all references to Project Gutenberg:

1.E.1. The following sentence, with active links to, or other


immediate access to, the full Project Gutenberg™ License must
appear prominently whenever any copy of a Project Gutenberg™
work (any work on which the phrase “Project Gutenberg” appears, or
with which the phrase “Project Gutenberg” is associated) is
accessed, displayed, performed, viewed, copied or distributed:

You might also like