之企业库推广
阿新
1. 概述
可重用的程序块库,用于解决共性的企业级开发过程中所面临的挑战
l 较低风险(经过实践验证的、精准的)
l 降低成本(可充用)
l 快速实施的问题(易用)
l 扩展性
l 一致性
l 是patterns & practices的一个重要组成部分
l 强调了一致性、扩展性、易用性和集成性问题
l 共有7个Application block组成分别Configuration,Data Access,Cryptography,Security,Logging & Instrumentation,Exception Handling,Caching
2. 目前项目开发中都需要什么
图形化的配置工具;方便,可靠的工具配置如数据库连接,日志管理,加密算法等内容
数据库访问;满足不同数据库访问(sql server,oracle,mysql,access)方便高性能的使用sql语句,procedure与数据库交互
对敏感信息的加密;数据库连接配置信息,登录用户的密码,传输过程中的报文进行安全的加密
统一的日志/跟踪/异常输出,通知;
缓存管理;提高系统性能,响应速度
用户授权管理;个性化制定管理
3. Enterprise Library 提供了什么
3.1图形化的配置工具 Enterprise Library Configuration
可以方便的配置生成应用程序配置文件,同时支持自定义类型的配置;可以方便将c#定义的类型序列化到配置文件中;
3.2数据库访问组件Data Access Application Block 提供功能如下
n 对数据库访问提供了简单、高效的访问方式
n 减少编写重复累赘代码去执行标准的数据访问任务
n 易于使用,使用单条语句即可完成Stored Procedure的调用
n 屏蔽了对常用ADO.NET使用的复杂度,提供了基于最佳实践, 正确快速使用接口
n 对不同类型的数据库(SQLServer/Oracle/DB2)提供了编程上的透明性
n 为不同数据库类型提供了统一的编程。
n 当移植应用程序到不同数据库类型时,减少重写代码的数量
n 搭起了逻辑数据库与物理数据库间的桥梁,降低改变物理数据目标的难度
n 增强了数据库联接串的安全性
n 容易对数据库访问的配置信息进行调整和验证
3.3安全加密模块Crypto Application Block提供功能如下
l 使用对称加密算法对敏感信息进行加密保存、或对其进行解密
l 对单台机器上使用的信息进行加密 (without using keys)
l 创建密码信息的散列值进行保存,使用时需要对用户提供的密码散列值与保存值进行对比
3.4日志管理 Logging Application Block 提供功能如下
n 需要对业务及操作数据做日志,希望能通过外部的配置能将日志输出到不同的存储区
n 需要提供Tracing机制支持Debugging
n 需要对日益增加的安全性提供审计
n 能灵活指定哪类信息以何种格式输出、输出到何处
n 能将日志定向到多个日志存储区
3.5异常处理 Exception Handling Application Block 提供功能如下
n 简单的功能强大的例外处理机制,在应用系统的不同层面采用一致的例外处理策略
n Exceptions 由配置工具进行定义和维护 – 不需要通过编码控制例外处理的行为
n 定义 “Exception Policies”,可指定该策略发生时的行为
n Exceptions of type ApplicationException should be logged
n Exceptions of type SqlClientException should be caught and wrapped with an exception of type DataLayerException and re-thrown
n Exceptions of type SecurityException should caught and replaced with an AccessDeniedException which will be thrown
n Exception Handlers提供了附加的处理行为
n 将例外写入日志
n 用另外一个例外进行封装
n 采用不同的例外替代以便隐藏敏感的例外信息
n 创建自己的Handler
3.6Caching管理 Caching Application Block提供功能如下
l 提供了灵活可扩展的缓存机制可以用于以下各种类型的应用架构中:
n Windows Forms
n Console application
n NT Service / COM+ Server
n ASP.NET Web application or Web service if you need features not included in the ASP.NET cache
l 支持两类Caching机制:
n In-memory cache –非永久缓存,但性能很好
n Backing store – 永久性缓存, 但较慢
n Database
n Isolated Storage
l 易于使用 -- 提供了Cache处理需的所有功能 (retrieve, add、remove cached data)
l 可配置的expiration和scavenging策略
3.7安全授权管理 Security Application Block 提供更能如下
l 通过一个或多个安全系统或机制,帮助开发人员在应用程序中实现通用的安全相关任务
l 一致性、可展性、配置驱动的安全机制(不需修改代码)
l 提供以下功能
l 认证
n Authenticating a User using Credentials
n Authenticating a User Using a Token
n Obtaining a Temporary Token for an Authenticated User
n Terminating a User Session (Expire a Token)
l 授权
n Determining Whether a User Is Authorized to Perform a Task
l 角色管理
n Determining the Roles a User Is In
l Profile管理
n
l 缓存登陆时的相关安全凭证(认证、授权信息)
4. 为什么要使用企业库
企业库构建了一个便于开发的通用的架构,把通用系统功能实现和具体业务想分离,通过简单方便的图形化配置,灵活的运用到每个系统中,使得系统功能分层更明确,更好体现多层架构的开发模式,方便对系统的维护
企业库作为微软提供的一个在实践中验证的具有其权威性和实用性,准确性
企业库提供了所有源代码,没有版权限制
企业库的设计模式,可以让开发人员在他的基础上方便的扩展其功能;同时也可以运行他的设计模式及思想用于我们的系统开发中;
企业库使整个系统各模块之间提供了一致性的保障,使得各系统模块间更好的协同工作,提高系统的开发速度
5. 如何方便的调用企业库API
5.1 Data Access Application Block Sample Code:
Public Function GetProductsInCategory(ByRef Category As Integer) As DataSet
' Create the Database object, using the default database service. The
' default database service is determined through configuration.
Dim db As Database = DatabaseFactory.CreateDatabase()
' Invoke the stored procedure with one line of code!
return db.ExecuteDataSet("GetProductsByCategory", Category)
' Note: connection was closed by ExecuteDataSet method call
End Function
5.2 Configuration Sample Code:
Public EditorFontData()
{
Private string fontName;
Private Double fontSize;
Private Integer fontStyle;
}
EditorFontData configData = New EditorFontData();
configData.Name = fontDialog.Font.Name;
configData.Size = fontDialog.Font.Size;
configData.Style = Convert.ToInt32(fontDialog.Font.Style);
//write an object info to config file
ConfigurationManager.WriteConfiguration("EditorSettings", configData);
// Read an object with multiple properties
EditorFontData configData = ConfigurationManager.GetConfiguration("EditorSettings")
5.3 Cryptography Application Block
//Encrypt a Secret
this.encryptedContents = Cryptographer.EncryptSymmetric(symmProvider,Encoding.Unicode.GetBytes(this.stringToEncrypt));
// Decrypting a Secret
byte[] decryptedContents = Cryptographer.DecryptSymmetric(symmProvider, this.encryptedContents);
5.4 Security Application Block
5.4.1 Authenticate a User Using Credentials
Declare member variables to hold an identity for the authenticated user by adding the following code.
[C#]
private IIdentity identity; // Identity for authenticated users
[Visual Basic]
Private identity As IIdentity ' Identity for authenticated users
Obtain the text username and password from the user by adding the following code.
[C#]
DialogResult result = this.credentialsForm.ShowDialog();
if (result == DialogResult.OK)
{
string username = this.credentialsForm.Username;
string password = this.credentialsForm.Password;
// Authentication code...
}
Convert the text password to a byte array and construct a NamePasswordCredential object by adding the following code.
[C#]
byte[] passwordByteArray = Convert.FromBase64String(password);
NamePasswordCredential credentials = new NamePasswordCredential(username, passwordByteArray);
[C#]
AuthenticationProviderFactory factory;
factory = new AuthenticationProviderFactory(ConfigurationManager.GetCurrentContext());
[C#]
// The authentication provider "Authentication Provider" is defined in configuration
IAuthenticationProvider authProvider = factory.GetAuthenticationProvider("Authentication Provider");
[C#]
bool authenticated = authProvider.Authenticate(credentials, out this.identity);
5.4.2 Determine Whether a user Is Authorized to Perform a Task
Retrieve the identity, role, and rule information to be used for the authorization check by adding the following code.
[C#]
string identity = this.roleAuthForm.Identity; // e.g. "tim"
string role = this.roleAuthForm.Role; // e.g. "Manager"
string rule = this.roleAuthForm.Rule; // e.g. "Submit Order"
[C#]
IPrincipal principal = new GenericPrincipal(new GenericIdentity(identity), new string[]{role});
[C#]
bool authorized = this.ruleProvider.Authorize(principal, rule);
5.4.3 Determine What Roles a User Is In
Declare a member variable for the role provider by adding the following code.
[C#]
private IRolesProvider rolesProvider;
Create the role provider by adding the following code.
[C#]
RolesProviderFactory rolesProviderFactory = new RolesProviderFactory(ConfigurationManager.GetCurrentContext());
this.rolesProvider = rolesProviderFactory.GetRolesProvider();
Create a GenericIdentity object representing the user by adding the following code.
[C#]
this.identity = new GenericIdentity("QuickStartUser");
Determine the roles for the user by adding the following code.
[C#]
IPrincipal principal = this.rolesProvider.GetRoles(this.identity);
if (principal != null)
{
bool isInRole = principal.IsInRole("Manager");
}
5.5 Logging Application Block
Create the information that will be submitted to the Logging Application Block.
[C#]
LogEntry log = new LogEntry();
log.EventId = this.eventForm.EventId;
log.Message = this.eventForm.Message;
log.Category = this.eventForm.Category;
log.Priority = this.eventForm.Priority;
Call the static Write method on the Logger class, passing the LogEntry object.
[C#]
Logger.Write(log);
5.6 Exception Application Block
try
{
// run code
}
catch(DataAccessException ex)
{
bool rethrow = ExceptionPolicy.HandleException(ex, "Data Access Policy");
if (rethrow)
{
throw;
}
}
catch(Exception ex)
{
bool rethrow = ExceptionPolicy.HandleException(ex, "General Policy");
if (rethrow)
{
throw;
}
}
5.7 Caching Application Block
Configure the cache. For the necessary steps, see Entering Configuration Information.
Declare a member variable for CacheManager in the QuickStartForm class.
[C#]
private CacheManager primitivesCache;
In the QuickStart_Load method, create the CacheManager by adding the following code. The call to GetCacheManager does not include the name of a CacheManager so the factory creates the default CacheManager object, as indicated in the configuration file.
[C#]
this.primitivesCache = CacheFactory.GetCacheManager();
Create the item that will be added to the cache. The following code creates an item of type Product.
[C#]
string id="ProductOneId";
string name = "ProductOneName";
int price = 50;
Product product = new Product(id, name, price);
Add the item to the cache. The following code uses the overload of the Add method that includes the scavenging priority (in this case, 2), instructions to not refresh the item if it expires, and an expiration time of 5 minutes from the time the item was last accessed.
[C#]
primitivesCache.Add(product.ProductID, product, 2, null,
new SlidingTime(TimeSpan.FromMinutes(5)));
6. 如何将企业库运用到实际的开发过程
6.1正对每个模块在研发中心作一次详细地说明,时间2个小时,内容企业库的架构,每个模块的功能介绍;
6.2介绍每个模块如何根据开发项目的具体应用做好配置文件的创建, 2个小时
6.3介绍每个模块的API函数的具体方法,Demo演示, 8个小时
6.4介绍如何在原有的基础上作一些功能的扩展 4个小时
7. 参考资源
Microsoft.com 网站
http://www.microsoft.com/practices/
GotDotNet 网站
http://workspaces.gotdotnet.com/
(搜索模式与实践)
MSDN 文档