Enterprise Library Step By Step系列(二):配置应用程序块——进阶篇

简介:
在前一篇文章中,讲述了配置应用程序块的最简单的介绍,在本篇文章中我主要介绍一下配置应用程序块的响应配置变更通知,保护配置信息(加密配置信息),面向高级人员的扩展机制,配置数据的缓存等几个方面。在剖析篇中我会去分析配置应用程序块的底层设计及类设计。
一.响应配置变更通知:
Configuration Application Block 提供了一个事件机制,当存储的配置变更时通知应用程序   ,使用步骤:
1)创建一个EverntHandler
 1 ExpandedBlockStart.gif /// <summary>
 2InBlock.gif        /// 创建EventHanler
 3InBlock.gif        /// </summary>
 4InBlock.gif        /// <param name="sender"></param>
 5ExpandedBlockEnd.gif        /// <param name="args"></param>

 6 None.gif          private   void  OnConfigurationChanged( object  sender, ConfigurationChangedEventArgs args)
 7 ExpandedBlockStart.gif         {
 8InBlock.gif            Cursor = System.Windows.Forms.Cursors.WaitCursor;
 9InBlock.gif
10InBlock.gif            EditorFontData configData = ConfigurationManager.GetConfiguration("EditorSettings"as EditorFontData;
11InBlock.gif
12InBlock.gif            StringBuilder results = new StringBuilder();            
13InBlock.gif            results.Append("Configuration changes in storage were detected. Updating configuration.");
14InBlock.gif            results.Append(Environment.NewLine);
15InBlock.gif            results.Append("New configuration settings:");
16InBlock.gif            results.Append(Environment.NewLine);
17InBlock.gif            results.Append('\t');
18InBlock.gif            results.Append(configData.ToString());
19InBlock.gif            results.Append(Environment.NewLine);
20InBlock.gif
21InBlock.gif            Cursor = System.Windows.Forms.Cursors.Arrow;      
22ExpandedBlockEnd.gif        }
2)注册事件
1 ExpandedBlockStart.gif ///注册事件
2 None.gif         ConfigurationManager.ConfigurationChanged  +=   new  ConfigurationChangedEventHandler(OnConfigurationChanged); 
二.配置数据的缓存:
Configuration Application Block 在设计时提供了对配置数据的缓存,在读取 XML 数据后,再次读取它首先会判断缓存是否为空,如果不为空,它会直接从缓存中读取数据(在剖析篇中会有详细的介绍)。
显式的清除掉缓存用下面这句代码即可:
1 ExpandedBlockStart.gif ///清除缓存数据
2 None.gif          ConfigurationManager.ClearSingletonSectionCache();
三.面向高级人员的扩展机制:
1   除了用 XML 文件可以存储数据外,还可以创建自己的存储方式,像 SQL Server Database ,注册表存储等,这时就需要我们自己创建 StorageProvider 。创建自定义的 Storage Provider ,需要注意以下几点:
1 )要读取和写入数据,需要继承于 StorageProvider 类和分别实现 IStorageProviderReader IstorageProviderWriter 接口:
1 None.gif public   class  XmlFileStorageProvider : StorageProvider, IStorageProviderWriter
2 ExpandedBlockStart.gif         {
3InBlock.gif            //……
4ExpandedBlockEnd.gif        }
2 )如果实现了 IConfigurationProvider 接口,则方法 Initialize() 就不能为空,也必须实现:
1 None.gif public   override   void  Initialize(ConfigurationView configurationView)
2 ExpandedBlockStart.gif         {
3InBlock.gif            //……
4ExpandedBlockEnd.gif        }
3 )实现 Read() Write() 方法,记住一定要返回类型为 object ,否则 Transformer 将无法使用:
1 None.gif public   override   object  Read()
2 ExpandedBlockStart.gif         {
3InBlock.gif            //……
4ExpandedBlockEnd.gif        }

5 None.gif
6 None.gif         public   void  Write( object  value)
7 ExpandedBlockStart.gif         {
8InBlock.gif            //……
9ExpandedBlockEnd.gif        }
2 .创建自定义的 Transformer
如果我们创建的自定义的 Storage Provider 不能后支持 XMLNode ,这时候我们需要创建自己的 Transformer ,需要注意以下几点:
1 )自定义的 Transformer 如果实现了 Itransformer 接口;则必须实现方法 Serialize() Deserialize();
2 )自定义的 Transformer 如果实现了 IConfigurationProvider 接口,则方法 Initialize() 就不能为空,也必须实现;
下面给出一个 SoapSerializerTransformer 的例子程序(先声名一下,这个例子程序不是我写的,而是Dario Fruk先生^_^):
 1 None.gif namespace  idroot.Framework.Configuration
 2 ExpandedBlockStart.gif {
 3InBlock.gif    using System;
 4InBlock.gif    using System.Configuration;
 5InBlock.gif    using System.IO;
 6InBlock.gif    using System.Runtime.Serialization.Formatters.Soap;
 7InBlock.gif    using System.Text;
 8InBlock.gif    using System.Xml;
 9InBlock.gif
10InBlock.gif    using Microsoft.Practices.EnterpriseLibrary.Common;
11InBlock.gif    using Microsoft.Practices.EnterpriseLibrary.Configuration;
12InBlock.gif
13ExpandedSubBlockStart.gif    /// <summary>
14InBlock.gif    /// SoapSerializerTransformer is a custom Serialization Transformer for Microsft Enterprise Library 1.0.
15ExpandedSubBlockEnd.gif    /// </summary>

16InBlock.gif    public class SoapSerializerTransformer : TransformerProvider
17ExpandedSubBlockStart.gif    
18InBlock.gif        public override void Initialize(ConfigurationView configurationView)
19ExpandedSubBlockStart.gif        {
20InBlock.gif            // Do nothing. This implementation does not require any additional configuration data because SoapFormatter reflects types 
21InBlock.gif            // during serialization.
22ExpandedSubBlockEnd.gif        }

23InBlock.gif
24InBlock.gif        public override object Serialize(object value)
25ExpandedSubBlockStart.gif        {
26InBlock.gif            SoapFormatter soapFormatter = new SoapFormatter();
27InBlock.gif            StringBuilder stringBuilder = new StringBuilder();
28InBlock.gif            XmlDocument doc = new XmlDocument();
29InBlock.gif
30InBlock.gif            stringBuilder.Append("<soapSerializerSection>");
31InBlock.gif
32InBlock.gif            string serializedObject = "";
33InBlock.gif            using (MemoryStream stream = new MemoryStream())
34ExpandedSubBlockStart.gif            {
35InBlock.gif                soapFormatter.Serialize(stream, value);
36InBlock.gif                byte[] buffer = stream.GetBuffer();
37InBlock.gif                // quick fix for 0-byte padding
38InBlock.gif                serializedObject = ASCIIEncoding.ASCII.GetString(buffer).Replace('\0'' ').Trim();
39ExpandedSubBlockEnd.gif            }

40InBlock.gif            stringBuilder.Append(serializedObject);
41InBlock.gif
42InBlock.gif            stringBuilder.Append("</soapSerializerSection>");
43InBlock.gif            doc.LoadXml(stringBuilder.ToString());
44InBlock.gif
45InBlock.gif            return doc.DocumentElement;
46ExpandedSubBlockEnd.gif        }

47InBlock.gif
48InBlock.gif        public override object Deserialize(object section)
49ExpandedSubBlockStart.gif        {
50InBlock.gif            ArgumentValidation.CheckForNullReference(section, "section");
51InBlock.gif            ArgumentValidation.CheckExpectedType(section, typeof(XmlNode));
52InBlock.gif
53InBlock.gif            XmlNode sectionNode = (XmlNode)section;
54InBlock.gif
55InBlock.gif            XmlNode serializedObjectNode = sectionNode.SelectSingleNode("//soapSerializerSection");
56InBlock.gif            if (serializedObjectNode == null)
57ExpandedSubBlockStart.gif            {
58InBlock.gif                throw new ConfigurationException("The required element '<soapSerializationSection>' missing in the specified Xml configuration file.");
59ExpandedSubBlockEnd.gif            }

60InBlock.gif
61InBlock.gif            SoapFormatter soapFormatter = new SoapFormatter();
62InBlock.gif            try
63ExpandedSubBlockStart.gif            {
64InBlock.gif                object obj = null;
65InBlock.gif                using (MemoryStream stream = new MemoryStream())
66ExpandedSubBlockStart.gif                {
67InBlock.gif                    using (StreamWriter sw = new StreamWriter(stream, Encoding.ASCII))
68ExpandedSubBlockStart.gif                    {
69InBlock.gif                        sw.Write(serializedObjectNode.InnerXml);
70InBlock.gif                        sw.Flush();
71InBlock.gif                        // rewind stream to the begining or deserialization will throw Exception.
72InBlock.gif                        sw.BaseStream.Seek(0, SeekOrigin.Begin); 
73InBlock.gif                        obj = soapFormatter.Deserialize(stream);
74ExpandedSubBlockEnd.gif                    }

75ExpandedSubBlockEnd.gif                }

76InBlock.gif                return obj;
77ExpandedSubBlockEnd.gif            }

78InBlock.gif            catch (InvalidOperationException e)
79ExpandedSubBlockStart.gif            {
80InBlock.gif                string message = e.Message;
81InBlock.gif                if (null != e.InnerException)
82ExpandedSubBlockStart.gif                {
83InBlock.gif                    message = String.Concat(message, " ", e.InnerException.Message);
84ExpandedSubBlockEnd.gif                }

85InBlock.gif                throw new ConfigurationException(message, e);
86ExpandedSubBlockEnd.gif            }

87ExpandedSubBlockEnd.gif        }

88ExpandedSubBlockEnd.gif    }

89ExpandedBlockEnd.gif}
 
3 .使用其它的 Providers
       SQL Server Provider :使用数据库 SQL Server Provider
       Registry Provider :使用注册表 Provider
四.保护配置信息:
配置信息直接放在了 XML 文件里面是不安全,我们可以用加密应用程序块对其进行加密,其实对于所有的应用程序块的配置信息都可以进行加密,我们到加密应用程序块时再详细讨论:)
进阶篇就写到这里了,后面继续剖析篇,在剖析篇里我会从配置应用程序块的底层设计,到类设计等作一些介绍(个人理解 ^_^





















本文转自lihuijun51CTO博客,原文链接:  http://blog.51cto.com/terrylee/67600 ,如需转载请自行联系原作者


相关文章
|
6月前
|
安全 Go 数据库
Navicat-Cracker NavicatCrackerDlg.cpp:332 -3All patch solutions are 解决Navicat 162版本注册问题的方法与分析【详细步骤】
Navicat-Cracker NavicatCrackerDlg.cpp:332 -3All patch solutions are 解决Navicat 162版本注册问题的方法与分析【详细步骤】
375 0