85
Getting Started with Getting Started with Enterprise Library 4.x Enterprise Library 4.x in ASP.NET in ASP.NET Pawas Goyal [email protected] +91 9967502429

Getting Started with Enterprise Library 4.x in ASP.NET

Embed Size (px)

DESCRIPTION

Getting Started with Enterprise Library 4.x in ASP.NET. Pawas Goyal [email protected] +91 9967502429. Agenda. What is Enterprise Library? Enterprise Library Components /Architecture Common Scenarios Pre Requisite Enterprise Library Component Details Brief Prerequisite - PowerPoint PPT Presentation

Citation preview

Page 1: Getting Started with Enterprise Library 4.x in ASP.NET

Getting Started withGetting Started withEnterprise Library 4.x in Enterprise Library 4.x in ASP.NETASP.NET

Pawas [email protected]+91 9967502429

Page 2: Getting Started with Enterprise Library 4.x in ASP.NET

AgendaAgenda What is Enterprise Library? Enterprise Library Components /Architecture Common Scenarios Pre Requisite Enterprise Library Component Details

◦ Brief ◦ Prerequisite ◦ Sample Code◦ Scenarios◦ Issues

References

Page 3: Getting Started with Enterprise Library 4.x in ASP.NET

What is Enterprise Library?What is Enterprise Library?Enterprise Library is:

◦ A library of application blocks that solve common challenges

◦ A set of helper classes that work in any architectural style

◦ Architectural guidance embodied in code, which ships with full source allowing you to modify and extend it

◦ Available as a free download

Page 4: Getting Started with Enterprise Library 4.x in ASP.NET

What is Enterprise Library?What is Enterprise Library?

Enterprise Library is NOT:◦ Part of the .NET Framework

◦ An application framework that imposes an architectural style

◦ A Microsoft product with support, compatibility and localization

◦ Available to purchase

Page 5: Getting Started with Enterprise Library 4.x in ASP.NET

Enterprise Library and Enterprise Library and ASP.NETASP.NET

Can be used in any ASP.NET applicationConfigure just the blocks you requireThe most useful blocks in ASP.NET are:

◦Data Access◦Caching◦Logging◦Cryptography◦Policy Injection◦Validation

Page 6: Getting Started with Enterprise Library 4.x in ASP.NET

AgendaAgenda What is Enterprise Library? Enterprise Library Components /Architecture Common Scenarios Pre Requisite Enterprise Library Component Details

◦ Brief ◦ Prerequisite ◦ Sample Code◦ Scenarios◦ Issues

References

Page 7: Getting Started with Enterprise Library 4.x in ASP.NET

Enterprise Library Enterprise Library ArchitectureArchitecture

Page 8: Getting Started with Enterprise Library 4.x in ASP.NET

Security

Crypto

Configuration

Data Access

LoggingCaching

ExceptionHandling

ConfigTools

Core/Design

Enterprise Library Enterprise Library ComponentsComponents

PolicyInjection

ValidationDependency Plug-in

Page 9: Getting Started with Enterprise Library 4.x in ASP.NET

Enterprise Library Application Enterprise Library Application BlocksBlocks

CoreCore

Page 10: Getting Started with Enterprise Library 4.x in ASP.NET

The Application Blocks (1)The Application Blocks (1)Caching Application Block

◦ incorporate a cache in applications. Pluggable cache providers are supported.

Cryptography Application Block◦ incorporate hashing and symmetric encryption in

their applications. Data Access Application Block

◦ incorporate standard database functionality in their applications.

Exception Handling Application Block◦ consistent strategy for processing exceptions that

occur throughout the architectural layers of enterprise applications.

Validation Application Block◦ create validation rules for business objects that can

be used across different layers of their applications.

Page 11: Getting Started with Enterprise Library 4.x in ASP.NET

The Application Blocks (2)The Application Blocks (2)

Logging Application Block◦ include standard logging functionality in their

applications. Policy Injection Application Block

◦ The Enterprise Library Policy Injection Application Block provides a mechanism for automatically applying policies to object instances;.

Security Application Block◦ Developers can use this application block to

incorporate authorization and security caching functionality in their applications

Unity Application Block◦ Lightweight and extensible dependency injection

container with support for constructor, property, and method call injection, as well as instance and type interception (via an extension).

Page 12: Getting Started with Enterprise Library 4.x in ASP.NET

AgendaAgenda What is Enterprise Library? Enterprise Library Components /Architecture Common Scenarios Pre Requisite Enterprise Library Component Details

◦ Brief ◦ Prerequisite ◦ Sample Code◦ Scenarios◦ Issues

References

Page 13: Getting Started with Enterprise Library 4.x in ASP.NET

Common Scenarios (1)Common Scenarios (1) Enterprise Library can be useful in a variety of situations: Enterprise Library provides enough functionality to

support many common scenarios that enterprise-level applications must address.

Enterprise Library can serve as the basis for a custom library. You can take advantage of the extensibility points incorporated in each application block and extend the application block by supplying new providers.

You can also modify the source code for the existing application blocks to incorporate new functionality. You can also add new application blocks to Enterprise Library. You can either develop extensions for existing application blocks and new application blocks yourself or you can use extensions and application blocks developed by others.

Enterprise Library is designed so that its application blocks can function independently of each other. You have to add only the application blocks that your application will use; you do not have to add the entire library.

Page 14: Getting Started with Enterprise Library 4.x in ASP.NET

Common Scenarios (2)Common Scenarios (2)

Enterprise Library includes the source code and the unit tests for all application blocks. This means you can modify the application blocks to merge into your existing library or you can use parts of the Enterprise Library source code in other application blocks or applications that you build.

Enterprise Library includes documentation, quick start samples, and source code. Hands-on-labs and webcasts are posted as separate downloads on the Enterprise Library Home page. This means that you can use the library as a tool for learning architectural, design, and coding best practices

Page 15: Getting Started with Enterprise Library 4.x in ASP.NET

AgendaAgenda What is Enterprise Library? Enterprise Library Components /Architecture Common Scenarios Pre Requisite Enterprise Library Component Details

◦ Brief ◦ Prerequisite ◦ Sample Code◦ Scenarios◦ Issues

References

Page 16: Getting Started with Enterprise Library 4.x in ASP.NET

PrerequisitePrerequisiteFor all application blocks except for the Unity

Application Block, the Enterprise Library core features, and the configuration tools, the minimum requirements are: ◦ Microsoft Windows XP Professional, Windows Server

2003, Windows Server 2008, or Windows Vista operating system

◦ Microsoft .NET Framework 3.5 or later ◦ Microsoft Visual Studio 2008 development system

(any of the following editions): ◦ Standard Edition ◦ Professional Edition ◦ Team Edition for Software Developers ◦ Team Edition for Software Testers ◦ Team Edition for Software Architects ◦ Team Suite

Page 17: Getting Started with Enterprise Library 4.x in ASP.NET

AgendaAgenda What is Enterprise Library? Enterprise Library Components /Architecture Common Scenarios Pre Requisite Enterprise Library Component Details

◦ Brief ◦ Prerequisite ◦ Sample Code◦ Scenarios◦ Issues

References

Page 18: Getting Started with Enterprise Library 4.x in ASP.NET

Security

CryptoData

Access

Logging

Caching

ExceptionHandling

Enterprise Library Components Enterprise Library Components DetailsDetails

PolicyInjection

ValidationUnity

Page 19: Getting Started with Enterprise Library 4.x in ASP.NET

◦Brief

◦Prerequisite

◦Sample Code

◦Scenarios

◦ Issues

Caching Application BlockCaching Application Block

Page 20: Getting Started with Enterprise Library 4.x in ASP.NET

Caching Application BlockCaching Application Block◦Brief

The Caching application block has been designed to simplify development tasks that implement caching functionality. It provides a thread and exception safe model that give support for local caches that can help improve performance, scalability and availability.The caching block is not designed to replace the ASP.NET cache but to work with it. The caching block provides a number of features that are not available to the ASP.NET cache such as: The ability to use a persistent backing store Multiple methods of setting expiration times Can be used for project types other than web applications The core settings are described in configuration and can be

changed without recompilation of the project. In addition to the caching block can be extended to create your own expiration policies and storage mechanisms

Page 21: Getting Started with Enterprise Library 4.x in ASP.NET

◦ PrerequisiteNo Specific Requirements

◦ Sample Code◦ First prepare application

Add a reference to the Caching Application Block assembly. In Visual Studio, right-click your project node in Solution Explorer, and then click Add References. Click the Browse tab and find the location of the Microsoft.Practices.EnterpriseLibrary.Caching.dll Microsoft.Practices.EnterpriseLibrary.Common.dll Microsoft.Practices.ObjectBuilder2.dll

Select the assemblies and then click OK to add the reference.• To use elements from the Caching Application Block without fully

qualifying the element reference, add the following • using Microsoft.Practices.EnterpriseLibrary.Caching; • using

Microsoft.Practices.EnterpriseLibrary.Caching.Expirations;

Caching Application BlockCaching Application Block

Page 22: Getting Started with Enterprise Library 4.x in ASP.NET

Example Code

The following code shows how to Add item in Cache

ICacheManager productsCache = CacheFactory.GetCacheManager();

string id = "ProductOneId";

string name = "ProductXYName";

int price = 50;

Product product = new Product(id, name, price); productsCache.Add(product.ProductID, product, CacheItemPriority.Normal, null, new SlidingTime(TimeSpan.FromMinutes(5)));

Caching Application BlockCaching Application Block

Page 23: Getting Started with Enterprise Library 4.x in ASP.NET

Caching Application BlockCaching Application Block

◦ Scenarios◦ A consistent form of caching is required across

different application environments. ◦ If there is a requirement for a persistent backing store. ◦ Caching configuration may need to change after

deployment. ◦ When one of the following expiration policies of

cached data need to be used. absolute time, extended time, sliding time, file dependency or never expired.

Page 24: Getting Started with Enterprise Library 4.x in ASP.NET

◦ Issues/Disadvantages◦ You cannot synchronize caching across a Web farm.

◦ The Caching Application Block does not support encryption of data that is cached in memory. If a malicious user finds a way of compromising the system and accessing the memory of your application's process, he or she would be able to access information stored in the cache. If this is a significant threat to your application, do not store sensitive information, such as credit card numbers or passwords, in the cache.

Caching Application BlockCaching Application Block

Page 25: Getting Started with Enterprise Library 4.x in ASP.NET

◦Brief

◦Prerequisite

◦Sample Code

◦Scenarios

◦ Issues

Cryptography Application BlockCryptography Application Block

Page 26: Getting Started with Enterprise Library 4.x in ASP.NET

Cryptography Application BlockCryptography Application Block◦Brief The Cryptography application block has been designed to

simplify development tasks that implement cryptographic functionality. It encapsulates the available windows security API's simplifying and standardising the way cryptographic functionality is performed within an application.

The key design goals of this application block that improve coding and productivity for developers are.◦ Provide a simple and intuitive interface to the commonly required

functionality. ◦ Present a standard consistent model for common cryptography tasks.  ◦ Make sure minimal or negligible performance impact compared to

manually written cryptography code that accomplishes the same functionality.

◦ Provide a key protection model that can be customized to satisfy your organization's security requirements.

Page 27: Getting Started with Enterprise Library 4.x in ASP.NET

◦ PrerequisiteNo Specific Requirements

◦ Sample Code◦ First prepare application

Add a reference to the Caching Application Block assembly. In Visual Studio, right-click your project node in Solution Explorer, and then

click Add References.Click Browse to locate the

Microsoft.Practices.EnterpriseLibrary.Security.Cryptography.dll Microsoft.Practices.EnterpriseLibrary.Common.dll Microsoft.Practices.ObjectBuilder2.dll.

Select the assemblies and then click OK to add the reference.

To use elements from the Caching Application Block without fully qualifying the element reference, add the following

using Microsoft.Practices.EnterpriseLibrary.Security.Cryptography ;

Cryptography Application BlockCryptography Application Block

Page 28: Getting Started with Enterprise Library 4.x in ASP.NET

Example Code

The following code shows how to encrypt and decrypt data. This code shows how to use the overloads that accept a string. string encryptedContentsBase64

=Cryptographer.EncryptSymmetric("symmProvider", "SensitiveData");

// Decrypt the base64 encoded string

string readableString;

readableString = Cryptographer.DecryptSymmetric("symmProvider", encryptedContentsBase64);

Cryptography Application BlockCryptography Application Block

Page 29: Getting Started with Enterprise Library 4.x in ASP.NET

Cryptography Application Cryptography Application BlockBlock◦ Scenarios

◦ There is a requirement for secure encryption of data. ◦ There is a requirement for Hash values to be create.

E.g. Password Hashes ◦ The encrypted data does not need to be sent across a

network and decrypted at the other end. This is better done using Asymmetric encryption

◦ If there is a requirement to standardize how encryption is handled both within an application and across the enterprise.

Page 30: Getting Started with Enterprise Library 4.x in ASP.NET

◦ Issues/Disadvantages◦ There is a requirement to use Asymmetric

encryption. This is not supported by the application block

◦ An encryption algorithm provides no security if the encryption algorithm is cracked or is vulnerable to brute force cracking.

Cryptography Application BlockCryptography Application Block

Page 31: Getting Started with Enterprise Library 4.x in ASP.NET

◦Brief

◦Prerequisite

◦Sample Code

◦Scenarios

◦ Issues

Data Access Application BlockData Access Application Block

Page 32: Getting Started with Enterprise Library 4.x in ASP.NET

Data Access Application BlockData Access Application Block◦ Brief

◦ The Data Access application block has been designed to simplify development tasks that implement data access functionality, regardless of the source of that data.

The Data Access Application Block provides the following benefits: It uses the functionality provided by ADO.NET 2.0 and with it, you can

use ADO.NET functionality along with the application block's functionality.

It reduces the need to write boilerplate code to perform standard tasks.

It helps maintain consistent data access practices, both within an application and across the enterprise.

It reduces difficulties in changing the database type. It relieves developers from learning different programming models for

different types of databases. It reduces the amount of code that developers must write when they

port applications to different types of databases.

Page 33: Getting Started with Enterprise Library 4.x in ASP.NET

◦ PrerequisiteNo Specific Requirements

◦ Sample Code◦ First prepare application

Add a reference to the Data Access Application Block assembly. In Visual Studio, right-click your project node in Solution Explorer, and

then click Add References.Click Browse to locate the

Microsoft.Practices.EnterpriseLibrary.Data.dll Microsoft.Practices.EnterpriseLibrary.Common.dll Microsoft.Practices.ObjectBuilder2.dll.

Select the assemblies and then click OK to add the reference.

To use elements from the Data Access Application Block

without fully qualifying the element reference, add the following

using Microsoft.Practices.EnterpriseLibrary.Data;

Data Access Application BlockData Access Application Block

Page 34: Getting Started with Enterprise Library 4.x in ASP.NET

Data Access Application Data Access Application BlockBlockTo configure a connection string

◦ Click the Connection String node.

◦ (Optional) Set the Name property by typing a new name. This is the name of the Connection String node. The default name is Connection String.

◦ (Optional) In the ProviderName property section, change the provider name. Enter the name of the provider or select it from the drop-down list. The default provider name is System.Data.SqlClient. The ProviderName property must be a provider name specified in a DbProviderFactory class.

◦ Update the ConnectionString property as required. For example, this connection string specifies the local SQL Server Express named database instance using itegrated Windows security:

◦ Database=Database;Server=(local)\SQLEXPRESS;Integrated Security=SSPI

Page 35: Getting Started with Enterprise Library 4.x in ASP.NET

Example Application Code The following code shows how to call a stored procedure that returns a DataSet.

Database db = DatabaseFactory.CreateDatabase();

DbCommand dbCommand = db.GetStoredProcCommand("GetProductsByCategory");

db.AddInParameter(dbCommand, "CategoryID", DbType.Int32, 7);

DataSet productDataSet = db.ExecuteDataSet(dbCommand);

Data Access Application BlockData Access Application Block

Page 36: Getting Started with Enterprise Library 4.x in ASP.NET

Data Access Application Data Access Application BlockBlock◦ Scenarios• The Data Access Block should be used if the

application will be using standard data access techniques and there is a need to use a simple standardized method of data access that conforms to Microsoft's Patterns and Practices recommendations.

• If however the application needs to get data in a specialized way or customizations are required then using ADO. NET directly may be a better option

Page 37: Getting Started with Enterprise Library 4.x in ASP.NET

◦ Issues/Disadvantages◦ DAAB places quite a bit of logic into configuration

files.

◦ Does not support Connected Architecture.

◦ Connection string is not stored in encrypted format in the configuration file.

◦ you are using another layer over ADO.NET, which can make debugging a little harder, but the speed loss and complexity are miniscule.

Data Access Application BlockData Access Application Block

Page 38: Getting Started with Enterprise Library 4.x in ASP.NET

◦Brief

◦Prerequisite

◦Sample Code

◦Scenarios

◦ Issues

Exception Handling Application Exception Handling Application Block Block

Page 39: Getting Started with Enterprise Library 4.x in ASP.NET

Exception Handling Application Exception Handling Application BlockBlock

◦Brief The Enterprise Library Exception Handling Application Block helps developers and policy makers to create a consistent strategy for processing exceptions that occur in all architectural layers of an enterprise application. It does this in the following ways: ◦ It supports exception handling in all architectural layers of an

application and is not limited to service interface boundaries. ◦ It allows exception handling policies to be defined and

maintained at the administrative level so that policy makers, who might be system administrators as well as developers, can define how to handle exceptions. They can maintain and modify the rules that govern exception handling without changing the application block code.

◦ It invokes exception handlers in a consistent manner. This means that the handlers can be used in multiple places within and across applications.

Page 40: Getting Started with Enterprise Library 4.x in ASP.NET

Exception Handling Exception Handling Application BlockApplication Block

Brief(continue)◦ It provides commonly used exception handling

functions, such as the ability to log exception information, the ability to hide sensitive information by replacing the original exception with another exception and the ability to maintain contextual information for an exception by wrapping the original exception inside another exception. These functions are encapsulated in .NET classes named exception handlers.

◦ It can combine exception handlers to produce the desired response to an exception, such as logging exception information followed by replacing the original exception with another.

◦ It lets developers create their own exception handlers.

Page 41: Getting Started with Enterprise Library 4.x in ASP.NET

◦ PrerequisiteNo Specific Requirements

◦ Sample Code◦ First prepare application

Add a reference to the Exception Handling Application Block assembly. In Visual Studio, right-click your project node in Solution

Explorer, and then click Add References . Click Browse to locate the

Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.dll

Microsoft.Practices.EnterpriseLibrary.Common.dll Microsoft.Practices.ObjectBuilder2.dll.

Select the assemblies and then click OK to add the reference.

To use elements from the Exception Handling Application Block

without fully qualifying the element reference, add the following

using Microsoft.Practices.EnterpriseLibrary.ExceptionHandling;

Exception Handling Application Exception Handling Application BlockBlock

Page 42: Getting Started with Enterprise Library 4.x in ASP.NET

Example Code The following code shows how to execute the policy named "Data Access Policy" when an exception occurs.

try

{ // Run code. }

catch(Exception ex)

{

bool rethrow = ExceptionPolicy.HandleException(ex, " Data Access Policy");

if (rethrow)

throw;

}

Exception Exception HandlingHandling Application Application BlockBlock

Page 43: Getting Started with Enterprise Library 4.x in ASP.NET

Exception Handling Exception Handling Application BlockApplication Block

◦ ScenariosA method should catch exceptions only when it has to perform one or more of the following actions:◦ Gather information for logging. ◦ Add any relevant information to the exception. ◦ Try to recover◦ When you need to change policies because of changing

security or other operational issues. ◦ When you need to log exception information or display

exception information to the user.

Page 44: Getting Started with Enterprise Library 4.x in ASP.NET

◦ Issues/DisadvantagesIt depends on that you have configured all

policies that you use in code. This could be a problem if you develop generic components or smaller frameworks because you are suddenly in the situation where you have to trust the user (=the developer) of your components to define all policies that you use in your code or else your code will break. This requires that you document it very well and probably also make some recommended configuration for the components that you deliver as part of the component. Generally the documentation of the entire EntLib has a lot more to wish and I hope that they start publishing better examples and documentation (hopefully before their next release, that will target .NET Framework 2.0).

Exception Handling Application Exception Handling Application BlockBlock

Page 45: Getting Started with Enterprise Library 4.x in ASP.NET

◦Brief

◦Prerequisite

◦Sample Code

◦Scenarios

◦ Issues

Logging Application Block Logging Application Block

Page 46: Getting Started with Enterprise Library 4.x in ASP.NET

Logging Application BlockLogging Application Block◦ Brief The logging application block simplifies the

implementation of common logging functions. It allows the developer to write information to a variety of locations based on the configuration used. These include◦ The event log ◦ An e-mail message ◦ A database ◦ A message queue ◦ A text file ◦ A WMI event

Custom locations using application block extension points

Page 47: Getting Started with Enterprise Library 4.x in ASP.NET

◦ PrerequisiteNo Specific Requirements

◦ Sample Code◦ First prepare application

Add a reference to the Logging Application Block assembly. In Visual Studio, right-click your project node in Solution Explorer, and then click Add References. Click the Browse tab and find the location of the Microsoft.Practices.EnterpriseLibrary.Logging.dllMicrosoft.Practices.EnterpriseLibrary.Common.dllMicrosoft.Practices.ObjectBuilder2.dll

Select the assemblies and then click OK to add the reference.• To use elements from the Logging Application Block without fully

qualifying the element reference, add the following • using Microsoft.Practices.EnterpriseLibrary.Logging; • using

Microsoft.Practices.EnterpriseLibrary.Logging.ExtraInformation; • using Microsoft.Practices.EnterpriseLibrary.Logging.Filters;

Logging Application BlockLogging Application Block

Page 48: Getting Started with Enterprise Library 4.x in ASP.NET

Example Application Code The following code shows how to populate and raise an event in your application. The LogEntry object has a priority of 2 and belongs to both the Trace and UI Events categories.

LogEntry logEntry = new LogEntry();

logEntry.EventId = 100;

logEntry.Priority = 2;

logEntry.Message = "Informational message"; logEntry.Categories.Add("Trace"); logEntry.Categories.Add("UI Events"); Logger.Write(logEntry);

Logging Application BlockLogging Application Block

Page 49: Getting Started with Enterprise Library 4.x in ASP.NET

Logging Application BlockLogging Application Block

◦ ScenariosThe Logging Application Block should be used

when:◦ There is a requirement to log information to the event

log, e-mail, a database, a message queue, windows management instrumentation (WMI), or a file.

◦ There is a need to filter logging messages based on category or priority.

◦ The messages need to be formatted. ◦ There is a requirement to change the destination of the

message without changing the application code. ◦ A simple, consistent interface for logging within the

application and across the enterprise is required

Page 50: Getting Started with Enterprise Library 4.x in ASP.NET

◦ Issues/Disadvantages◦ The Logging Application Block formatters do not

encrypt logging information

◦ LAB places quite a bit of logic into configuration files.

Logging Application BlockLogging Application Block

Page 51: Getting Started with Enterprise Library 4.x in ASP.NET

◦Brief

◦Prerequisite

◦Sample Code

◦Scenarios

◦ Issues

Policy Injection Application Policy Injection Application BlockBlock

Page 52: Getting Started with Enterprise Library 4.x in ASP.NET

Policy Injection Application Policy Injection Application BlockBlock◦ Brief

◦ The Enterprise Library Policy Injection Application Block provides a mechanism for automatically applying policies to object instances. This helps developers to better manage crosscutting concerns, maximize separation of concerns, and encapsulate behavior. Developers define the set of policies for the target classes and their members through configuration of the Policy Injection Application Block or by applying attributes to individual members of the target class.

◦ The Policy Injection Application Block ships with pre-built handlers for these application blocks that speed up development when using Enterprise Library to help manage crosscutting concerns. Developers can also create custom handlers and policies that carry out almost any required interception processing for methods and properties of their objects.

Page 53: Getting Started with Enterprise Library 4.x in ASP.NET

◦ PrerequisiteNo Specific Requirements

◦ Sample Code◦ First prepare application

Add a reference to the Policy Injection Application Block assembly. In Visual Studio, right-click your project node in Solution

Explorer, and then click Add References. Click the Browse tab and find the location of the Microsoft.Practices.EnterpriseLibrary.PolicyInjection.dllMicrosoft.Practices.EnterpriseLibrary.Common.dllMicrosoft.Practices.ObjectBuilder2.dll

Select the assemblies and then click OK to add the reference.• To use elements from the Policy Injection Application Block

without fully qualifying the element reference, add the following using Microsoft.Practices.EnterpriseLibrary.PolicyInjection; using

Microsoft.Practices.EnterpriseLibrary.PolicyInjection.CallHandlers;

Policy Injection Application BlockPolicy Injection Application Block

Page 54: Getting Started with Enterprise Library 4.x in ASP.NET

Example code Let's say we have a policy for our store that whenever an

order is returned it must be logged along with the reason it was returned. For simplification, here are my classes:

public class Order : IOrder

{

public void Return(string reason)

{ // Do something... }

}

public interface IOrder

{

void Return(string reason);

}  

Policy Injection Application Policy Injection Application BlockBlock

Page 55: Getting Started with Enterprise Library 4.x in ASP.NET

Policy Injection Application Policy Injection Application BlockBlock

One option is to use the Enterprise Library Logging Application Block directly and somewhere during the Return Process just make a call that logs the information:

LogEntry logEntry = new LogEntry(); logEntry.Message = "...“ logEntry.Categories.Add("..."); // ... Logger.Write(logEntry);  

With the Policy Injection Application Block, however, we can avoid this extra code by defining a policy that whenever a call is made to the Return Method on IOrder we should log a message.

Page 56: Getting Started with Enterprise Library 4.x in ASP.NET

Policy Injection Application Policy Injection Application BlockBlock There are numerous ways to match policies to methods, but

in this case I am going to use the TagMatchingRule which means I just have to add a tag attribute to the Return Method on the Interface. Hence rather than writing all the LogEntry code above and explicitly calling the logging application block, I will just add the following to the IOrder Interface:

public interface IOrder

{

[Tag("Log")]

void Return(string reason);

}  

Page 57: Getting Started with Enterprise Library 4.x in ASP.NET

Policy Injection Application Policy Injection Application Block Block

◦ Scenarios◦ The Policy Injection Application Block provides a ready-built solution that

is easy to implement in new and existing applications, particularly in applications that already take advantage of the features of the Enterprise Library.

◦ The Policy Injection Application Block provides a solution that allows developers, operators, and administrators to create, modify, remove, and fine-tune interception policies though configuration, generally without requiring any changes to the code or recompilation of the application. This limits the chances of introducing errors into the code, simplifies versioning, and reduces downtime.

Page 58: Getting Started with Enterprise Library 4.x in ASP.NET

◦ Issues/DisadvantagesSome functional limitations arise when using the

Policy Injection Application Block to call routines that implement crosscutting concerns (such as validation, logging, and authorization) from handlers instead of directly from custom application code:

Threaded applications where multiple calls passing through the same handler could corrupt the internal state.

The application block caches policies as it initializes; the matching rules are not re-evaluated on each call. Therefore, matching rules cannot contain dynamic logic that changes over time.

Policy Injection Application Policy Injection Application BlockBlock

Page 59: Getting Started with Enterprise Library 4.x in ASP.NET

◦Brief

◦Prerequisite

◦Sample Code

◦Scenarios

◦ Issues

Security Application Block Security Application Block

Page 60: Getting Started with Enterprise Library 4.x in ASP.NET

Security Application BlockSecurity Application BlockBrief

Developers frequently write applications that must authorize users using one or more security providers such as Microsoft Active Directory directory service, Authorization Manager, Active Directory Application Mode (ADAM), and custom authorization providers. These applications may also need to cache authentication or authorization data for the duration of a logon session.

The Security Application Block simplifies these tasks by handling them in a consistent manner, abstracting the application code from the specific security providers. You can even change underlying providers through configuration without changing the underlying application code.

The Security Application Block provides code that will help you with the following scenarios: ◦ Authorization ◦ Caching security-related credentials

Page 61: Getting Started with Enterprise Library 4.x in ASP.NET

Security Application BlockSecurity Application Block◦ The Security Application Block has the following

features:◦ It reduces the requirement to write boilerplate code to perform

standard tasks.

◦ It helps maintain consistent security practices, both within an application and across the enterprise.

◦ It eases the learning curve for developers by using a consistent architectural model across the various areas of functionality provided.

◦ It provides implementations that you can use to solve common application security problems.

◦ It is extensible; it supports custom implementations of security providers.

Page 62: Getting Started with Enterprise Library 4.x in ASP.NET

Security Application BlockSecurity Application BlockThe security application block has been designed to

address the following areas.◦ Authorisation ◦ Role management ◦ Profile management ◦ Caching principals ( Caching profile information and

security-related credentials )

The security application block focuses on a role-based security model. The Security Application Block simplifies these tasks by handling them in a consistent manner and abstracting the application code from the specific security providers. Authentication, Authorisation, Roles and Profile Providers can work completely independently of one another but they are closely related

Page 63: Getting Started with Enterprise Library 4.x in ASP.NET

◦ PrerequisiteNo Specific Requirements

◦ Sample Code◦ First prepare application

Add a reference to the Security Application Block assembly. In Visual Studio, right-click your project node in Solution Explorer, and then click Add References. Click the Browse tab and find the location of the Microsoft.Practices.EnterpriseLibrary.Security.dll Microsoft.Practices.EnterpriseLibrary.Common.dll

Microsoft.Practices.ObjectBuilder2.dll

Select the assemblies and then click OK to add the reference.• To use elements from the Security Application Block without

fully qualifying the element reference, add the following

using Microsoft.Practices.EnterpriseLibrary.Security;

Security Application BlockSecurity Application Block

Page 64: Getting Started with Enterprise Library 4.x in ASP.NET

Example Application Code

The following code shows how to determine if a user is authorized to perform a task.

IPrincipal principal = new GenericPrincipal(new GenericIdentity("Username"), new string[]{"Manager"});

IAuthorizationProvider ruleProvider = AuthorizationFactory.GetAuthorizationProvider("RuleProvider");

// Determine whether user is authorized for the rule defined as "Print Document".

bool authorized = ruleProvider.Authorize(principal, "Print Document");

Security Application BlockSecurity Application Block

Page 65: Getting Started with Enterprise Library 4.x in ASP.NET

Security Application Block Security Application Block

◦ ScenariosThe Security Application Block includes implementations of the following functions: ◦ Authorization ◦ Security-related caching and session management

If your applications require the provided implementations, you can use the application block to provide this functionality. However, the application block is also designed to be extensible and includes generic providers for each function. You can adapt the providers to meet your own security requirements.

Page 66: Getting Started with Enterprise Library 4.x in ASP.NET

◦ Issues/Disadvantages◦ SAB places quite a bit of logic into configuration

files.

Security Application BlockSecurity Application Block

Page 67: Getting Started with Enterprise Library 4.x in ASP.NET

◦Brief

◦Prerequisite

◦Sample Code

◦Scenarios

◦ Issues

Unity Application BlockUnity Application Block

Page 68: Getting Started with Enterprise Library 4.x in ASP.NET

Unity Application BlockUnity Application Block◦ Brief

The Unity Application Block (Unity) is a lightweight, extensible dependency Injection container with support for constructor, property and method call injection. It provides developers with the following advantages: It provides simplified object creation, especially for hierarchical

object structures and dependencies, which simplifies application code.

It supports abstraction of requirements , this allows developers to specify dependencies at run time or in configuration and simplify management of crosscutting concerns.

It increases flexibility by deferring component configuration to the container.

It has a service location capability , this allows clients to store or cache the container. This is especially useful in ASP.NET Web applications where the developers can persist the container in the ASP.NET session or application.

Page 69: Getting Started with Enterprise Library 4.x in ASP.NET

Security

Crypto

Configuration

Data Access

LoggingCaching

ExceptionHandling

ConfigTools

Core/Design

Enterprise Library Enterprise Library ComponentsComponents

PolicyInjection

ValidationDependency Plug-in

Page 70: Getting Started with Enterprise Library 4.x in ASP.NET

Enterprise Library Enterprise Library ComponentsComponents

Page 71: Getting Started with Enterprise Library 4.x in ASP.NET

◦ PrerequisiteFor all application blocks except for the Unity

Application Block, the Enterprise Library core features, and the configuration tools, the minimum requirements are: ◦ Microsoft Windows XP Professional, Windows Server

2003, Windows Server 2008, or Windows Vista operating system

◦ Microsoft .NET Framework 2.0, 3.0, or 3.5 Microsoft Visual Studio 2005 or Visual Studio 2008

development system (any of the following editions): Standard Edition Professional Edition Team Edition for Software Developers Team Edition for Software Testers Team Edition for Software Architects Team Suite

Unity Application BlockUnity Application Block

Page 72: Getting Started with Enterprise Library 4.x in ASP.NET

Unity Application BlockUnity Application Block◦ Sample Code

◦ First prepare application Add a reference to the Unity Application Block assembly. In Visual

Studio, right-click your project node in Solution Explorer, and then click Add References. Click the Browse tab and find the location of the Microsoft.Practices.Unity.dll Microsoft.Practices.ObjectBuilder2.dll

Select the assemblies and then click OK to add the reference.

To use elements from the Unity Application Block without fully qualifying the element reference, add the following

• using Microsoft.Practices.Unity; • using Microsoft.Practices.Unity.Configuration; • using Microsoft.Practices.Unity.StaticFactory;

Page 73: Getting Started with Enterprise Library 4.x in ASP.NET

Example Code

Unity Application BlockUnity Application Block

Page 74: Getting Started with Enterprise Library 4.x in ASP.NET

Unity Application Block Unity Application Block ◦ Scenarios

Dependency injection provides opportunities to simplify code, abstract dependencies between objects, and generate dependent object instances automatically. However, the process may have a minor impact on performance, and it can increase complexity where only simple dependencies exist.

In general, you should use the Unity Application Block in the following situations:◦ Your objects and classes may have dependencies on other

objects or classes. ◦ Your dependencies are complex or require abstraction. ◦ You want to take advantage of constructor, method, or

property call injection features. ◦ You want to manage the lifetime of object instances. ◦ You want to be able to configure and change dependencies at

run time. ◦ You want to be able to cache or persist the dependencies

across postbacks in a Web application.

Page 75: Getting Started with Enterprise Library 4.x in ASP.NET

◦ Issues/Disadvantages◦ Complex to understand

◦ Places a little bit coding logic in configuration files.

◦ Before use this you should be have great knowledge about your object there dependencies and relations . In general scenario it’s not possible .

Unity Application BlockUnity Application Block

Page 76: Getting Started with Enterprise Library 4.x in ASP.NET

◦Brief

◦Prerequisite

◦Sample Code

◦Scenarios

◦ Issues

Validation Application BlockValidation Application Block

Page 77: Getting Started with Enterprise Library 4.x in ASP.NET

Validation Application BlockValidation Application Block◦Brief

The Enterprise Library Validation Application Block provides useful features that allow developers to implement structured and easy-to-maintain validation scenarios in their applications. Any application that accepts input either from users or from other systems must ensure that the information is valid in terms of some set of rules that you specify. For example phone number

You can also group validators together in a rule set. A rule set allows you to validate a complex object or graph by composing different validators of different types and applying them to elements in the object graph. Examples of these elements include fields, properties, and nested objects.

Page 78: Getting Started with Enterprise Library 4.x in ASP.NET

Validation Application Validation Application BlockBlock

Brief (Continue)By using the Validation Application Block, you can

perform validation and create rule sets in the following three ways: Using configuration Using attributes Using code

In addition, the Validation Application Block includes adapters that allow you to use the application block with the following technologies: ASP.NET Windows Forms Windows Communications Framework (WCF)

Page 79: Getting Started with Enterprise Library 4.x in ASP.NET

◦ PrerequisiteNo Specific Requirements

◦ Sample Code◦ First prepare application

Add a reference to the Validation Application Block assembly. In Visual Studio, right-click your project node in Solution Explorer, and then click Add References. Click the Browse tab and find the location of the Microsoft.Practices.EnterpriseLibrary.Validation.dll Microsoft.Practices.EnterpriseLibrary.Common.dll Microsoft.Practices.ObjectBuilder2.dll

Select the assemblies and then click OK to add the reference.To use elements from the Unity Application Block without fully

qualifying the element reference, add the following

using Microsoft.Practices.EnterpriseLibrary.Validation;

using Microsoft.Practices.EnterpriseLibrary.Validation.Validators;

Validation Application BlockValidation Application Block

Page 80: Getting Started with Enterprise Library 4.x in ASP.NET

Example Application Code

This example shows how to associate a validator with an object and then validate that object.

public class Customer

{ [StringLengthValidator(0, 20)]

public string CustomerName;

public Customer(string customerName)

{this.CustomerName = customerName; }

}

public class MyExample

{ public static void Main() {

Customer myCustomer = new Customer("A name that is toolong");

ValidationResults r = Validation.Validate<Customer>(myCustomer);

If (!r.IsValid)

{throw new InvalidOperationException("Validation error found."); }}}

Validation Application BlockValidation Application Block

Page 81: Getting Started with Enterprise Library 4.x in ASP.NET

Validation Application BlockValidation Application Block

◦ Scenarioso The Validation Application Block allows you to encapsulate

validation best practices into easily maintainable code that you can reuse. Encapsulation also allows you to separate the application code from the validation logic.

o In some situations, you may be able to update the validation logic without redeploying the application.

o where the application block works well is when your validation code must work across multiple layers of the application's architecture.

o In very simple cases, when you only need to validate a few objects, you may not want to incur the overhead of adding the application block.

Page 82: Getting Started with Enterprise Library 4.x in ASP.NET

◦ Issues/Disadvantages

◦ when you need only to validate a few objects then

you have to include all VAB references .

Validation Application BlockValidation Application Block

Page 83: Getting Started with Enterprise Library 4.x in ASP.NET

AgendaAgenda What is Enterprise Library? Enterprise Library Components /Architecture Common Scenarios Pre Requisite Enterprise Library Component Details

◦ Brief ◦ Prerequisite ◦ Sample Code◦ Issues◦ Key Scenarios

References

Page 84: Getting Started with Enterprise Library 4.x in ASP.NET

References

Book covering Enterprise Library:◦ "Effective Use of Microsoft Enterprise

Library: Building Blocks for Creating Enterprise Applications and Services" (Addison-Wesley ISBN 0-321-33421-3).

All about Enterprise Library:◦ http://msdn.microsoft.com/hi-in/library/

cc467894(en-us).aspx

Set up for Enterprise Library:◦ 192.168.2.7\Software\Utility\Enterprise

Library

Contact: Pawas Goyal

Page 85: Getting Started with Enterprise Library 4.x in ASP.NET