43
Enterprise Library Enterprise Library Building an Building an Application Block Application Block Ed Jezierski Ed Jezierski Solution Architect Solution Architect Scott Scott Densmore Densmore Software Engineer Software Engineer Ron Jacobs Ron Jacobs Product Manager Product Manager

Enterprise Library Building an Application Block Ed Jezierski Solution Architect Scott Densmore Software Engineer Ron Jacobs Product Manager

Embed Size (px)

Citation preview

Enterprise LibraryEnterprise LibraryBuilding an Application Building an Application BlockBlock

Ed JezierskiEd Jezierski Solution ArchitectSolution Architect

Scott Scott DensmoreDensmoreSoftware EngineerSoftware Engineer

Ron JacobsRon JacobsProduct ManagerProduct Manager

AgendaAgenda

Architectural Guidance from Architectural Guidance from patterns & practicespatterns & practices

Application BlocksApplication Blocks

Enterprise Library VisionEnterprise Library Vision

Enterprise Library Application Enterprise Library Application BlocksBlocks

ConfigurationConfiguration

CryptographyCryptography

Data AccessData Access

SecuritySecurity

DemonstrationDemonstration

QuestionsQuestions

Logging & Logging & InstrumentationInstrumentation

Exception Exception HandlingHandling

CachingCaching

patterns & practicespatterns & practicesArchitecture Guidance for the EnterpriseArchitecture Guidance for the Enterprise

Reference Reference ArchitecturesArchitectures

Reference Reference ArchitecturesArchitectures

Application Blocks Application Blocks Application Blocks Application Blocks

Guides Guides Guidance for broad horizontal topics such as security, Guidance for broad horizontal topics such as security,

performance, deployment and operationsperformance, deployment and operations

Guides Guides Guidance for broad horizontal topics such as security, Guidance for broad horizontal topics such as security,

performance, deployment and operationsperformance, deployment and operations

PatternsPatternsPatternsPatterns

D A D I

A

D

I

D A D I

A

D

I

Atomic solutions to recurring Atomic solutions to recurring problemsproblems

Sub-system-level guidance for Sub-system-level guidance for common servicescommon services

System-level guidance for System-level guidance for common customer scenarioscommon customer scenarios

D A D I

A

D

I

Available onlineAvailable online: : http://www.microsoft.com/practiceshttp://www.microsoft.com/practices

Books available: Books available: http://www.amazon.com/practiceshttp://www.amazon.com/practices

Proven Based on field experience

Authoritative Offer the best advice available Accurate Technically validated and tested Actionable Provide the steps to success

Relevant Address real-world problems based on customer scenarios

Sound familiar?Sound familiar?

Having similar code pasted throughout Having similar code pasted throughout your applicationsyour applications

Writing components to enable and Writing components to enable and encourage reuse…then rewriting them encourage reuse…then rewriting them to meet specific application needsto meet specific application needs

Having components that Having components that shouldshould work work well together, but…well together, but…

Each component mandating Each component mandating inconsistent requirements on the inconsistent requirements on the consuming applicationconsuming application

Longing for a way to future-proof your Longing for a way to future-proof your software librarysoftware library

Enterprise Library Enterprise Library PhilosophyPhilosophy

ConsistencyConsistencyApply consistent design patterns and Apply consistent design patterns and implementation approachesimplementation approaches

ExtensibilityExtensibilityInclude extensibility points allowing developers Include extensibility points allowing developers to customize the behavior of the blocks by to customize the behavior of the blocks by plugging in their own code or customize by plugging in their own code or customize by directly modifying source codedirectly modifying source code

Ease of UseEase of UseLeverage a graphical configuration toolLeverage a graphical configuration toolProvide a simpler installation procedureProvide a simpler installation procedureInclude clear and complete documentation and Include clear and complete documentation and samplessamples

IntegrationIntegrationApplication blocks should be designed to work Application blocks should be designed to work well together and tested to make sure that they well together and tested to make sure that they do. But it should also be possible to use the do. But it should also be possible to use the application blocks individuallyapplication blocks individually

SecuritySecurity

CryptoCrypto

ConfigurationConfiguration

Data Data AccessAccess LoggingLogging

CachingCaching ExceptionsExceptions

Enterprise Library v1Enterprise Library v1

Legend

Dependency

Plug-in

ConfigConfigToolTool

p&p Enterprise Library

Enterprise Library VisionEnterprise Library Vision

Partner blocks

Customer blocks

Community blocks

p&p blocks

Partner X library

Customer Y library

Customer Z library

Block Specification

Elements of an Elements of an Application BlockApplication Block

Core functionality Core functionality

Pluggable providers Pluggable providers

FactoriesFactories

Configuration Configuration

Unit tests Unit tests

Quick StartsQuick Starts

Guidance and reference documentationGuidance and reference documentation

Core FunctionalityCore Functionality

Central to its operationCentral to its operation

May be influenced via configuration May be influenced via configuration settings, but basic behavior cannot be settings, but basic behavior cannot be changed without source code changed without source code modificationsmodifications

Often internal, but when exposed to an Often internal, but when exposed to an application, it is typically provided via a application, it is typically provided via a single class, interface, or facade single class, interface, or facade

It’s OK to have core functionality – not It’s OK to have core functionality – not everything must be replaceable or even everything must be replaceable or even configurable!configurable!

Core Functionality Core Functionality ExamplesExamplesCachingCaching

Cache implementation (hashtable) – not Cache implementation (hashtable) – not exposedexposedScavenging algorithm –not exposedScavenging algorithm –not exposedCache manager – exposed as a classCache manager – exposed as a class

Exception HandlingException HandlingException policy – exposed as a class with Exception policy – exposed as a class with single public static method single public static method (HandleException) (HandleException)

Logging and InstrumentationLogging and InstrumentationLog filters – not exposedLog filters – not exposed

Pluggable ProvidersPluggable Providers

Associated with an application block Associated with an application block capability, defined by a “provider type.”capability, defined by a “provider type.”

Caching: BackingstoreCaching: Backingstore

Data Access: DatabaseData Access: Database

Exception Handling: Exception HandlerException Handling: Exception Handler

A provider is a specific implementation A provider is a specific implementation of a provider type. Each application of a provider type. Each application block includes at least one provider block includes at least one provider implementation of each provider typeimplementation of each provider type

Caching: Database and isolated storage Caching: Database and isolated storage backingstoresbackingstores

Data Access: SQL, DB2 and Oracle Data Access: SQL, DB2 and Oracle databasesdatabases

Pluggable ProvidersPluggable Providers

Decouples the application block's core Decouples the application block's core functionality from specific functionality from specific implementation, achieving the following implementation, achieving the following goals goals

VariabilityVariability

ExtensibilityExtensibility

EncapsulationEncapsulation

Portability across environmentsPortability across environments

Minimized coupling between application Minimized coupling between application blocksblocks

Specified in configuration data with type Specified in configuration data with type information and a nameinformation and a name

Provider Provider Implementations and Implementations and ConfigurationConfigurationProviders typically allow for Providers typically allow for

configuration of each specific configuration of each specific implementationimplementation

Example: the replace exception handler Example: the replace exception handler has a configuration setting for the new has a configuration setting for the new exception typeexception type

The abstract base class The abstract base class ConfigurationProviderConfigurationProvider defines the defines the contract for initializing a provider with contract for initializing a provider with configuration informationconfiguration information

Decision point: create a new provider Decision point: create a new provider implementation, or configuration implementation, or configuration property of an existing implementationproperty of an existing implementation

Provider FactoriesProvider Factories

Uses Uses PluginPlugin [Fowler] pattern to create [Fowler] pattern to create providersproviders

Neither applications nor application Neither applications nor application blocks require information about blocks require information about specific implementation of providerspecific implementation of provider

Specific implementation to be Specific implementation to be constructed determined by constructed determined by configuration settingsconfiguration settings

Abstract base class (ProviderFactory) in Abstract base class (ProviderFactory) in Configuration Application Block contains Configuration Application Block contains code to instantiate configurable code to instantiate configurable providersproviders

Provider FactoriesProvider Factories

Static method to create provider objectsStatic method to create provider objects

Allow for creation of default provider (as Allow for creation of default provider (as specified by configuration settings)specified by configuration settings)

Allow for creation of named providerAllow for creation of named provider

' Create the default database instanceDim db As Database = DatabaseFactory.CreateDatabase()

' Use a named instance to map to configurationDim salesDb As Database = DatabaseFactory.CreateDatabase("Sales")

Allows you to reconfigure and execute Allows you to reconfigure and execute the application without recompilingthe application without recompiling

ConfigurationConfiguration

Allows you to easily adapt the Allows you to easily adapt the application block to meet the needs of application block to meet the needs of different enterprise scenariosdifferent enterprise scenarios

Creation and editing of configuration Creation and editing of configuration settings is done with the Configuration settings is done with the Configuration Console Console

Configuration settings may be defined Configuration settings may be defined for an application block’s core for an application block’s core functionality and for each provider type functionality and for each provider type

ConfigurationConfiguration

Using configuration settings to adapt an Using configuration settings to adapt an application block to a particular application block to a particular situation has two advantages:situation has two advantages:

Characteristics of an application block can Characteristics of an application block can be configured by different people at be configured by different people at different times in the application life cycledifferent times in the application life cycle

The application block can be incrementally The application block can be incrementally adapted for increasingly complex situationsadapted for increasingly complex situations

ConfigurationConfiguration

Runtime configurationRuntime configurationObject graphs that represent configuration Object graphs that represent configuration settingssettings

Configuration Application Block reads Configuration Application Block reads settings from storage and returns objects to settings from storage and returns objects to application blockapplication block

XML File Storage Provider and Transformer XML File Storage Provider and Transformer require that objects be serializablerequire that objects be serializable

Design-time configurationDesign-time configurationAllow settings to be displayed, changed and Allow settings to be displayed, changed and validated using the Configuration Consolevalidated using the Configuration Console

Design-time and Design-time and Runtime RelationshipRuntime Relationship

Design-Time Design-Time ConfigurationConfigurationBased upon System.ComponentModelBased upon System.ComponentModel

Configuration node is of type ComponentConfiguration node is of type Component

The Configuration Console provides the The Configuration Console provides the SiteSite

Services are available through Config Services are available through Config BlockBlock

Configuration node classes for each Configuration node classes for each node in the configuration treenode in the configuration tree

Each node determines the properties Each node determines the properties to be displayed when node is to be displayed when node is selectedselected

Validation rules can be included for Validation rules can be included for any propertyany property

Configuration NodesConfiguration NodesDetermine how the Configuration Determine how the Configuration Console displays the hierarchy of Console displays the hierarchy of configuration nodesconfiguration nodesDetermine which/how properties are Determine which/how properties are exposed in the graphical interfaceexposed in the graphical interfaceEnable the Configuration Console to Enable the Configuration Console to validate that the values a user assigns validate that the values a user assigns to an application block's properties are to an application block's properties are appropriateappropriateCan contain references that point from Can contain references that point from one application block to another (such one application block to another (such as an authorization database that as an authorization database that points to a database instance)points to a database instance)Contain references to the runtime data Contain references to the runtime data classesclasses

Configuration Design Configuration Design ManagerManager

Implements Implements IConfigurationDesignManagerIConfigurationDesignManager interfaceinterfaceAllows an application block to be added Allows an application block to be added to an application’s configuration to an application’s configuration hierarchy hierarchy Creates menu items and commands Creates menu items and commands that are invoked as user interacts with that are invoked as user interacts with the Configuration Console to configure the Configuration Console to configure the application blockthe application blockResponsible for loading and saving Responsible for loading and saving configuration dataconfiguration dataAssembly must be located in same Assembly must be located in same directory as Configuration Console directory as Configuration Console executableexecutable

Configuration Configuration Application Block Application Block SupportSupport

Configuration Console

Configuration Application Block

Design Time Support

Runtime Support

Application Block

Configuration Design Time

Objects

Configuration RuntimeObjects

Read and write block config file

Read and update config settings

Display, validate and update configuration settings

Design-time Services

Loads design-time support for each application block

The Configuration Application Block The Configuration Application Block provides much of the plumbing for provides much of the plumbing for runtime and design-time configurationruntime and design-time configuration

Configuration ConsoleConfiguration Console

Validation Error

PropertiesConfiguration Nodes

Unit TestsUnit Tests

Verify functionality of application blockVerify functionality of application block

Verify that modifications to application Verify that modifications to application block have not cause regressionblock have not cause regression

Enterprise Library developed using Test Enterprise Library developed using Test Driven Development (TDD)Driven Development (TDD)

Quick StartsQuick Starts

Demonstrate common scenarios of Demonstrate common scenarios of application block usageapplication block usage

Display output indicating what Display output indicating what happened “under the covers”happened “under the covers”

Detect common errors (e.g. user didn’t Detect common errors (e.g. user didn’t perform required setup) and display perform required setup) and display useful informationuseful information

Goal: Open solution, hit F5, and see it Goal: Open solution, hit F5, and see it runrun

DocumentationDocumentation

Integrated into Visual StudioIntegrated into Visual Studio

GuidanceGuidanceIntroduction and goalsIntroduction and goals

Developing applications using the Developing applications using the application blockapplication block

Design of the application blockDesign of the application block

Extending the application blockExtending the application block

Deploying the application blockDeploying the application block

Quick start walkthroughsQuick start walkthroughs

Reference APIReference APIPublic and protectedPublic and protected

Summaries, parameters and return valuesSummaries, parameters and return values

A Simple Example: Hello A Simple Example: Hello World Application BlockWorld Application Block

Client application can use the application Client application can use the application block to return a greeting for a specified userblock to return a greeting for a specified userThe implementation of how the greetings are The implementation of how the greetings are returned is encapsulated in a returned is encapsulated in a greeting greeting providerproviderAn application can use multiple greeting An application can use multiple greeting providers, each identified by a unique nameproviders, each identified by a unique nameThe Configuration Console is used to select The Configuration Console is used to select the default greeting provider, used when the the default greeting provider, used when the client does not specify a name for the client does not specify a name for the providerproviderEach greeting provider has a default Each greeting provider has a default message, set by the Configuration Consolemessage, set by the Configuration Console

Hello World Application Hello World Application Block Core FunctionalityBlock Core Functionality

Minimal to keep things simpleMinimal to keep things simple

Includes the interface definition Includes the interface definition IGreetingProviderIGreetingProvider, which all greeting , which all greeting providers must implementproviders must implement

Includes the class Includes the class HelloWorldConfigurationViewHelloWorldConfigurationView

Derives from Derives from ConfigurationViewConfigurationView

Exposes the runtime configuration settings Exposes the runtime configuration settings required by the application block’s required by the application block’s providers providers

Passed to the Initialize method of each Passed to the Initialize method of each provider when it is createdprovider when it is created

Hello World Application Hello World Application Block Configuration ViewBlock Configuration View

Initialized with ConfigurationContextInitialized with ConfigurationContextpublic virtual GreetingProviderData GetGreetingProviderData(string name){ // HelloWorldSettings is our runtime configuration object HelloWorldSettings settings = GetHelloWorldSettings(); return settings.GreetingProviders[name];}

Returns configuration data required by Returns configuration data required by application blockapplication blockpublic virtual string GetDefaultGreetingProviderDataName(){ HelloWorldSettings settings = GetHelloWorldSettings(); return settings.DefaultGreeter;}

Hello World Application Hello World Application Block ProvidersBlock Providers

Text greeting providerText greeting providerReturns plain text greeting for specified Returns plain text greeting for specified useruser

Greeting for a user is determined by Greeting for a user is determined by configuration settingsconfiguration settings

Includes configuration design-time support Includes configuration design-time support to allow greetings to be entered and to allow greetings to be entered and validatedvalidated

Custom greeting providerCustom greeting providerAllows user to select the FQTN of a class Allows user to select the FQTN of a class that implements IGreetingProviderthat implements IGreetingProvider

Configuration is provided via a property Configuration is provided via a property bag of name-value pairs (no design-time bag of name-value pairs (no design-time support)support)

Hello World Application Hello World Application Block Runtime Block Runtime ConfigurationConfigurationRequirementsRequirements

Block allows multiple greeting providersBlock allows multiple greeting providers

Each greeting provider has a nameEach greeting provider has a name

Text greeting provider can have multiple Text greeting provider can have multiple greetingsgreetings

A greeting is name and a messageA greeting is name and a message

Configuration Information is represented as Configuration Information is represented as serializable classesserializable classes

XML FileXML File

Application Block Configuration Application Block

XML FileXmlSerializerTransformer

XmlFileStorageProvider

Application object

Application object

Application block object

helloWorldConfiguration.config

Runtime Configuration Runtime Configuration DataData<?xml version="1.0" encoding="utf-8"?><?xml version="1.0" encoding="utf-8"?>

<helloWorldConfiguration><helloWorldConfiguration> <xmlSerializerSection <xmlSerializerSection

type="Microsoft.Practices.Samples.HelloWorld.Configuration.HelloWorldStype="Microsoft.Practices.Samples.HelloWorld.Configuration.HelloWorldSettings, ettings,

Microsoft.Practices.Samples.HelloWorld, Version=1.0.0.0, Culture=neutral, Microsoft.Practices.Samples.HelloWorld, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null">PublicKeyToken=null"> <<helloWorldSettingshelloWorldSettings xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

defaultGreeter="Casual Greetings" defaultGreeter="Casual Greetings"

xmlns="http://www.microsoft.com/practices/samples/08-31-2004/hellowoxmlns="http://www.microsoft.com/practices/samples/08-31-2004/helloworld">rld">

<<greetingProvidersgreetingProviders>> <<greetingProvidergreetingProvider xsi:type="TextGreetingProviderData" xsi:type="TextGreetingProviderData"

name="Casual Greetings" defaultGreeting="Hello World!">name="Casual Greetings" defaultGreeting="Hello World!"> <<greetingsgreetings>> <<greetinggreeting name="John" message="Hi John." /> name="John" message="Hi John." /> <<greetinggreeting name="Maria" message="Ciao Maria!" /> name="Maria" message="Ciao Maria!" /> </greetings></greetings> </greetingProvider></greetingProvider> </greetingProviders></greetingProviders> </helloWorldSettings></helloWorldSettings> </xmlSerializerSection></xmlSerializerSection></helloWorldConfiguration></helloWorldConfiguration>

Runtime Configuration Runtime Configuration ClassesClasses

HelloWorldSettingsHelloWorldSettingsIncludes configuration section name, Includes configuration section name, collection of providers, and default greeting collection of providers, and default greeting providerprovider

GreetingProviderData (base class), GreetingProviderData (base class), TextGreetingProviderData, TextGreetingProviderData, CustomGreetingProviderDataCustomGreetingProviderData

Common settings and settings specific to Common settings and settings specific to providersproviders

TextGreetingDataCollectionTextGreetingDataCollectionCollection of text greetingsCollection of text greetings

TextGreetingDataTextGreetingDataName and messageName and message

Configuration Configuration Application Block Application Block Runtime SupportRuntime SupportCommon

Hello World Application BlockRuntime Configuration

GreetingProviderData

Collection

HelloWorldSettings

GreetingProvider

Data

Configuration Application Block

ProviderData

Collection

TextGreeting

ProviderData

CustomGreeting

ProviderData

NameValueItem

Collection

ProviderData

TextGreetingData

Collection

TextGreetingData

DataColection

Runtime Configuration Runtime Configuration Class Serialization Class Serialization

[XmlRoot("helloWorldSettings", Namespace=HelloWorldSettings.ConfigurationNamespace)]public class HelloWorldSettings{…}

[XmlArray("greetings", Namespace=HelloWorldSettings.ConfigurationNamespace)][XmlArrayItem(Type=typeof(TextGreetingData), Namespace=HelloWorldSettings.ConfigurationNamespace)] public TextGreetingDataCollection Greetings{ get { return this.greetings; }}

Root object serializationRoot object serialization

Collection serializationCollection serialization

Runtime Configuration Runtime Configuration Class Serialization Class Serialization

[XmlType("greetingProvider", Namespace=HelloWorldSettings.ConfigurationNamespace)][XmlInclude(typeof(CustomGreetingProviderData))][XmlInclude(typeof(TextGreetingProviderData))]public abstract class GreetingProviderData : ProviderData{ …}

XML include types for base classesXML include types for base classes

Hello World Design-Time Hello World Design-Time ConfigurationConfiguration

Required to allow the application block Required to allow the application block to be configured with the Configuration to be configured with the Configuration ConsoleConsole

Hello World ClientHello World Client

Create providerCreate provider// Create default greeting provider (determined by configuration)IGreetingProvider defaultProvider = GreetingFactory.GetGreetingProvider();

// Create named instanceIGreetingProvider formalProvider = GreetingFactory.GetGreetingProvider("Formal Greetings");

Call provider methodsCall provider methods

string greeting = defaultProvider.SayGreeting(“John”);

Additional ResourcesAdditional ResourcesImproving Web Application SecurityImproving Web Application Securityhttp://msdn.microsoft.com/library/default.asp?url=/library/en-us/

dnnetsec/html/ThreatCounter.asp

Improving .NET Application Performance and Improving .NET Application Performance and ScalabilityScalabilityhttp://http://msdn.microsoft.com/library/default.asp?urlmsdn.microsoft.com/library/default.asp?url=/library/en-us/=/library/en-us/

dnpag/html/scalenet.aspdnpag/html/scalenet.asp

Application Architecture for .NETApplication Architecture for .NEThttp://http://msdn.microsoft.com/library/default.asp?urlmsdn.microsoft.com/library/default.asp?url=/library/en-us/=/library/en-us/

dnbda/html/distapp.aspdnbda/html/distapp.asp

PatternShare.orgPatternShare.orgEnterprise Library CommunityEnterprise Library Communityhttp://http://go.microsoft.com/fwlink/?linkidgo.microsoft.com/fwlink/?linkid=39209&clcid=0x09=39209&clcid=0x09

www.ronjacobs.comwww.ronjacobs.comSlidesSlidesTech TipsTech TipsPodcastsPodcasts

Announcing: Enterprise Library Announcing: Enterprise Library 1.01.0

http://www.microsoft.com/practicehttp://www.microsoft.com/practicess

Download it

Today!

Patterns and Practices Patterns and Practices Live!Live!

Slides, Hands On Labs, On Demand Slides, Hands On Labs, On Demand WebcastsWebcasts

Upcoming Live WebcastsUpcoming Live Webcasts3/28 Building your own block3/28 Building your own block

3/31 Enterprise Library Applied3/31 Enterprise Library Applied

4/12 Global Bank Baseline Architecture4/12 Global Bank Baseline Architecture

4/14 Updater Application Block v24/14 Updater Application Block v2

http://www.pnplive.com

http://www.microsoft.com/practihttp://www.microsoft.com/practicesces