DEVELOPER’S GUIDE TO MICROSOFT ENTERPRISE LIBRARY, 2 nd Edition DEVELOPER’S GUIDE 2 nd Edition Enterprise Library Dominic Betts Julián Domínguez Alex Homer Hernan de Lahitte Grigori Melnik Fernando Simonazzi Mani Subramanian Forewords by S. Somasegar and Scott Guthrie DEVELOPER’S GUIDE TO MICROSOFT ENTERPRISE LIBRARY, 2 ND EDITION For more information explore: microsoft.com/practices Software Architecture and Software Development patterns & practices proven practices for predictable results Save time and reduce risk on your software development projects by incorporating patterns & practices, Microsoft’s applied engineering guidance that includes both production quality source code and documentation. The guidance is designed to help software development teams: Make critical design and technology selection decisions by highlighting the appropriate solution architectures, technologies, and Microsoft products for common scenarios Understand the most important concepts needed for success by explaining the relevant patterns and prescribing the important practices Get started with a proven code base by providing thoroughly tested software and source that embodies Microsoft’s recommendations The patterns & practices team consists of experienced architects, developers, writers, and testers. We work openly with the developer community and industry experts, on every project, to ensure that some of the best minds in the industry have contributed to and reviewed the guidance as it is being developed. We also love our role as the bridge between the real world needs of our customers and the wide range of products and technologies that Microsoft provides. Welcome to the era of software reuse! Microsoft Enterprise Library helps accelerate development by providing reusable components and guidance on proven practices. This guide helps you to quickly grasp what Enterprise Library v6 can do for you, presents examples that show it in action, and makes it easier for you to start experimenting with Enterprise Library. Enterprise Library is made up of a series of application blocks, each aimed at managing specic crosscutting concerns. You can use them out of the box, modify them as required, and distribute them with your applications. Logging Transient Fault Handling Semantic Logging Exception Handling Policy Injection Unity Validation Data Access Common The main themes for the latest v6 release are: simplifying the library all around, embracing semantic logging, increasing resiliency to errors, and streamlining programmatic conguration of all blocks. The guide explains 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, it explains — by way of code extracts and sample programs — how you can actually use the blocks in your applications. Benet from the capabilities of Enterprise Library, spend more time focusing on your business logic and less on the plumbing. Enterprise Library will do the heavy lifting for you! Happy Coding! “This guide is an absolute must read for anybody looking to put Enterprise Library into practice. Its clear and pragmatic advice is invaluable.” S. Somasegar, Corporate Vice President, Microsoft Developer Division “You are holding in your hands a book that will make your life as an enterprise developer a whole lot easier.” Scott Guthrie, Corporate Vice President, Windows Azure Developer's Guide to Microsoft Enterprise Library, 2nd Edition Dominic Betts Julián Domínguez Alex Homer Hernan de Lahitte Grigori Melnik Fernando Simonazzi Mani Subramanian 978-1-62114-034-4 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. 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. © 2013 Microsoft. All rights reserved. Microsoft, Windows, Windows Azure, Windows Server, Visual C#, SQL Server, Active Directory, IntelliSense, MSDN, Internet Explorer, and Visual Studio are trademarks of the Microsoft group of companies. All other trademarks are property of their respective owners. Foreword xiii Foreword to the 1st Edition xv Preface 1 About This Guide 1 What Does This Guide Cover? 1 What This Guide Does Not Cover 2 How Will This Guide Help You? 2 Who’s Who 3 What Do You Need to Get Started? 4 The Team Who Brought You This Guide 5 The Enterprise Library 6 Development Team 5 1 Welcome to the Library: Introduction to the Microsoft Enterprise Library 7 Meet the Librarian 7 What You Get with Enterprise Library 7 Things You Can Do with Enterprise Library 9 Why You Should Use Enterprise Library 10 Some Fundamentals of Enterprise Library 11 Choosing Which Blocks to Install 12 Installing Enterprise Library 12 Assemblies and References 13 GAC or Bin, Signed or Unsigned? 13 Importing Namespaces 13 Configuring Enterprise Library 14 Diving in with an Example 14 Configuration Classes 14 Instantiating and Using Enterprise Library Objects 15 Enterprise Library Objects and Factories 16 Creating Instances of Enterprise Library Types 17 The Example Applications 17 Summary 18 More Information 18 Contents vi 2 Much ADO about Data Access: Using the Data Access Application Block 21 Introduction 21 What Does the Data Access Application Block Do? 22 Data Operations Supported by the Data Access Block 22 How Do I Use the Data Access Block? 24 Adding the Data Access Application Block to Your Project 24 Configuring the Block and Referencing the Required Assemblies 24 Creating Database Instances 25 The Example Application 26 Reading Multiple Data Rows 27 Reading Rows Using a Query with No Parameters 27 Reading Rows Using an Array of Parameter Values 28 Reading Rows Using Queries with Named Parameters 29 Retrieving Data as Objects 31 About Accessors 31 Creating and Executing an Accessor 32 Creating and Using Mappers 33 Retrieving XML Data 34 Retrieving Single Scalar Values 35 Retrieving Data Asynchronously 36 Preparing for Asynchronous Data Access 37 Retrieving Row Set Data Asynchronously using BeginXXX and EndXXX Methods Directly 38 Retrieving Row Set Data Asynchronously using a Task 39 Retrieving Data as Objects Asynchronously 40 Updating Data 41 Executing an Update Query 41 Working with DataSets 42 Updating the Database from a DataSet 43 Managing Connections 46 Working with Connection-Based Transactions 47 Working with Distributed Transactions 49 Extending the Block to Use Other Databases 51 Summary 52 More Information 52 3 Error Management Made Exceptionally Easy: Using the Exception Handling Application Block 55 Introduction 55 When Should I Use the Exception Handling Block? 56 How Do I Use the Exception Handling Block? 56 What Exception Policies Do I Need? 57 Allowing Exceptions to Propagate 57 About Exception Handling Policies 57 Choosing an Exception Handling Strategy 59 Process or HandleException? 60 Using the Process Method 61 Using the HandleException Method 62 vii Diving in with a Simple Example 63 Applying Exception Shielding 64 Wrapping an Exception 65 Configuring the Wrap Handler Policy 65 Initializing the Exception Handling Block 65 Editing the Application Code to Use the New Policy 66 Replacing an Exception 68 Logging an Exception 68 Shielding Exceptions at WCF Service Boundaries 71 Creating a Fault Contract 71 Configuring the Exception Handling Policy 71 Editing the Service Code to Use the New Policy 72 The Fault Contract Exception Handler 73 Handling Specific Exception Types 74 Executing Code around Exception Handling 75 Assisting Administrators 78 Extending Your Exception Handling 79 Summary 80 More Information 80 4 Perseverance, Secret of All Triumphs: Using the Transient Fault Handling Application Block 83 What Are Transient Faults? 83 What Is the Transient Fault Handling Application Block? 83 Historical Note 86 Using the Transient Fault Handling Application Block 86 Adding the Transient Fault Handling Application Block to Your Visual Studio Project 86 Instantiating the Transient Fault Handling Application Block Objects 87 Defining a Retry Strategy 87 Defining a Retry Policy 88 Executing an Operation with a Retry Policy 88 When Should You Use the Transient Fault Handling Application Block? 89 You are Using a Windows Azure Service 89 You are Using Service Bus for Window Server 90 You Are Using a Custom Service 90 More Information 90 5 As Easy As Falling Off a Log: Using the Logging Application Block 93 Introduction 93 What Does the Logging Block Do? 94 Logging Categories 96 Logging Overhead and Additional Context Information 96 How Do I Use the Logging Block? 97 Adding the Logging Block to Your Project 97 Configuring the Logging Block 97 Diving in with an Example 98 viii Creating and Writing Log Entries with a LogWriter 98 About Logging Categories 100 Filtering by Category 102 Writing Log Entries to Multiple Categories 102 Controlling Output Formatting 102 Filtering by Severity in a Trace Listener 103 Filtering All Log Entries by Priority 104 Creating and Using LogEntry Objects 104 Capturing Unprocessed Events and Logging Errors 106 About Special Sources 106 An Example of Using Special Sources 107 Logging to a Database 109 Using the Database Trace Listener 110 Logging Asynchronously 111 Reconfiguring Logging at Run Time 112 Testing Logging Filter Status 112 Obtaining Information about Trace Sources and Trace Listeners 113 Checking if Filters Will Block a Log Entry 114 Adding Additional Context Information 116 Tracing and Correlating Activities 117 An Example of Tracing Activities 118 Creating Custom Trace Listeners, Filters, and Formatters 120 Summary 121 More Information 121 6 Logging What You Mean: Using the Semantic Logging Application Block 123 Introduction 123 What Does the Semantic Logging Application Block Do? 125 In-Process or Out-of-Process? 128 Buffering Log Messages 128 How Do I Use the Semantic Logging Application Block? 129 Creating an Event Source 129 Specifying the Event and its Payload 131 Specifying the Log Level 131 Using Keywords 131 Using Opcodes and Tasks 132 Sensitive Data 132 Verifying your EventSource Class 133 Versioning your EventSource Class 133 Adding the Semantic Logging Application Block to Your Project 134 Configuring the Semantic Logging Application Block 134 Writing to the Log 136 How do I Use the Semantic Logging Application Block to Log Events Out-of-Process? 137 Running the Out-of-Process Host Application 137 Updating an Event Source Class in the Out-of-Process Scenario 138 ix Creating Trace Messages 138 Choosing Sinks 139 Collecting and Processing the Log Messages 139 Customizing the Semantic Logging Application Block 141 Creating Custom Filters Using Reactive Extensions (Rx) 141 Creating Custom Formatters 142 Creating a Custom In-Process Event Text Formatter 143 Creating a Custom Out-of-Process Event Text Formatter without IntelliSense Support 144 Creating a Custom Out-of-Process Event Text Formatter with IntelliSense Support 145 Creating Custom Sinks 147 Creating a Custom In-Process Sink 147 Creating a Custom Out-of-Process Sink without IntelliSense Support 150 Creating a Custom Out-of-Process Sink with IntelliSense Support 151 Creating Custom Event Listener Host Applications 152 Summary 153 More Information 154 7 Banishing Validation Complication: Using the Validation Application Block 155 Introduction 155 Techniques for Validation 156 Where Should I Validate? 156 What Should I Validate? 157 How Should I Validate? 157 What Does the Validation Block Do? 157 The Range of Validators 159 Validating with Attributes 160 DataAnnotations Attributes 161 Self-Validation 161 Validation Rule Sets 163 Assigning Validation Rules to Rule Sets 163 Configuring Validation Block Rule Sets 163 Specifying Rule Sets When Validating 164 How Do I Use The Validation Block? 165 Preparing Your Application 165 Choosing a Validation Approach 165 Options for Creating Validators Programmatically 167 Performing Validation and Displaying Validation Errors 167 Understanding Message Template Tokens 168 Diving in With Some Simple Examples 169 Validating Objects and Collections of Objects 169 Creating a Type Validator using the ValidationFactory 170 Delving Deeper into ValidationResults 170 Using the Object Validator 172 Differences Between the Object Validator and the Factory-Created Type Validators 172 Validating Collections of Objects 173 x Using Validation Attributes 173 Using the Validation Block Attributes 174 Using Data Annotation Attributes 177 Defining Attributes in Metadata Classes 178 Specifying the Location of Validation Rules 179 Creating and Using Individual Validators 180 Validating Strings for Contained Characters 180 Validating Integers within a Domain 180 Validating with a Composite Validator 180 Validating Single Members of an Object 181 WCF Service Validation Integration 182 Defining Validation in the Service Contract 183 Editing the Service Configuration 183 Using the Product Service and Detecting Validation Errors 184 User Interface Validation Integration 186 ASP.NET User Interface Validation 186 Windows Forms User Interface Validation 187 WPF User Interface Validation 187 Creating Custom Validators 187 Summary 188 More Information 188 8 Updating aExpense to Enterprise Library 6 189 The aExpense Application 189 The aExpense Architecture 189 Using Enterprise Library v5.0 191 Caching 191 Logging 191 Exception Handling 192 Validation 193 Security 193 Policy Injection 193 Unity 194 NuGet Packages and References – Before and After 194 Handling Blocks Removed from Enterprise Library 6 196 Replacing Caching Functionality 196 Replacing the Authorization Rule Provider 196 Handling Blocks Updated in Enterprise Library 6 196 Using the Exception Handling Application Block Version 6 196 Using the Validation Application Block Version 6 197 Using the Policy Injection Application Block Version 6 197 Using Unity Version 3 198 Using the New Blocks in Enterprise Library Version 6 199 The Semantic Logging Application Block 199 The Transient Fault Handling Application Block 200 Other Possible Changes 201 More Information 202 [...]... Most of the Enterprise Library assemblies contain several namespaces to organize the contents For example, the Semantic Logging Application Block includes the following namespaces • Microsoft. Practices.EnterpriseLibrary.SemanticLogging • Microsoft. Practices.EnterpriseLibrary.SemanticLogging.Database • Microsoft. Practices.EnterpriseLibrary.SemanticLogging.Etw • Microsoft. Practices.EnterpriseLibrary.SemanticLogging.Etw.WindowsService... available (http://msdn.com/entlib), so make sure to check them out If you want to share your story with the developer community at large, send a draft to ourstory @microsoft. com and we’ll work with you to get your story across 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... read this guide 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 configuration After that, you’ll be free to skip to any of the other chapters and learn... Microsoft Developer Division Redmond, Washington November 7, 2013 Foreword to the 1st Edition 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... 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 Welcome to the Libr a ry 17 Creating Instances of Enterprise Library Types In this release of Enterprise Library, the recommended approach to creating instances of Enterprise Library objects is to use the programmatic approach... use Enterprise Library to manage your crosscutting concerns 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... the EnterpriseLibrary.ExceptionHandling.Logging NuGet package Not surprisingly, if you begin by trying to install the EnterpriseLibrary ExceptionHandling.Logging package, NuGet will automatically install both the EnterpriseLibrary.ExceptionHandling and EnterpriseLibrary.Logging packages that it depends on The configuration tool will automatically add the required block configuration to your application... the Enterprise Library Reference Documentation and the Enterprise Library 6 Class Library You can download and work through the Hands-On Labs for Enterprise Library, which are available at http://aka.ms/el6hols You can download the Enterprise Library binaries, source code, Reference Implementation, or QuickStarts from the Microsoft Download Center at http://go .microsoft. com/fwlink/p/?LinkID=290898 To. .. block helps you to simplify your code and manage your crosscutting concerns For more information about the topics covered in this chapter, see the Enterprise Library Reference Documentation 11 The Enterprise Library source code and tests are great learning resources, not just for Enterprise Library but for NET development as well 12 ch a pter one 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 Once you have chosen which Enterprise Library blocks to use in your application, you need to add the appropriate assemblies to your project: for the Enterprise Library blocks, you can use the NuGet package manager in Visual Studio to handle this for you NuGet makes it very easy to get started Installing . This Guide 5 The Enterprise Library 6 Development Team 5 1 Welcome to the Library: Introduction to the Microsoft Enterprise Library 7 Meet the Librarian 7 What You Get with Enterprise Library. DEVELOPER’S GUIDE TO MICROSOFT ENTERPRISE LIBRARY, 2 nd Edition DEVELOPER’S GUIDE 2 nd Edition Enterprise Library Dominic Betts Julián Domínguez Alex Homer Hernan. 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