摘要:Configuration Section Designer
Configuration Section Designer 學習記錄
參考文章:
http://mtaulty.com/CommunityServer/blogs/mike_taultys_blog/archive/2008/02/20/10191.aspx
本篇僅作為學習記錄之用。
最近在學習configration,有興趣的可以看一下小朱大的這篇。
簡單的說,就是籍由設計自已的configuration區段與類別,來管理你的設定值參數。小弟才疏學淺,還在依樣畫葫蘆的階段,說不出這樣作的好處,還有望各位前輩多多指教。不過對我目前的應用,能夠籍由僅修改config檔,不需re-compile就能某種程度的修改程式,就感到威力相當強大,值得一學。
想深入了解如何設何ConfigurationSection類別的人,MSDN看一看是很有幫助的,我推薦這幾篇:
ConfigurationPropertyAttribute
ConfigurationCollectionAttribute
之前在作xml序列化的時候,有一個工具「xsd.exe」來幫助開發人員快速建立類別。Config檔的區段其實也是xml這種標籤式語法,難到沒有工具可以讓開發人員偷懶更有效率嗎?「Configuration Section Designer」似乎就是那個好工具,OK~開始吧。
1 下載並安裝「Configuration Section Designer」
2 首先加入一個Console專案,並加入一個ConfigurationSectionDesigner檔
3 我們可以看到多了一個Configuration Section Explorer
4 工具箱
5 這時候,我們先看一下我們要設計的ConfigSection的樣子
<processLauncherConfigxmlns="urn:my-config">
<processes>
<processexecutable="c:\temp\foo.exe"
restart="true">
<arguments>
<argumentvalue="one"/>
<argumentvalue="two"/>
</arguments>
</process>
<processexecutable="c:\temp\foo.exe"
restart="false"/>
</processes>
</processLauncherConfig>
接下來,我們要分析一下這個config section,以及我們該怎麼透過工具替我們產生出類別。
6 在工具箱中的Configuration Section,其實就是指整個區塊最外層的標籤。
在這裡<processLauncherConfigxmlns="urn:my-config"></processLauncherConfig>
就是一個Configuration Section。
我們可以透過工具拖進一個Configuration Section,並命名為processLauncherConfig
7 包含在Configuration Section區段裡面只會有幾種標籤,Configuration Element 與Configuration Element Collection。
在我們的範例中processes與arguments就是種Configuration Element Collection,而process與argument就是Configuration Element,我們很容易理解Configuration Element Collection就是Configuration Element的集合。
8 接下來我們先加入process與argument這兩個Configuration Element,同樣的透過工具箱拖拉並修改Name屬性。接下來我們修改process與argument的attribute與element,attribute是指這元素(或標籤)本身的屬性,element指的就是在這元素(或標籤)底下還有其它的元素,我認為這部份知識在學習xml或html的dom結構時就應該有了(關鍵字都給了google吧),就不再多提。我們可以從範例中看到
<processexecutable="c:\temp\foo.exe" restart="true"> 的attribute就是executable 與restart,<argumentvalue="one"/>則是他底下的元素。記得在加入attribute時必須加入相對應的Type。
9 再來我們加入processes與arguments這兩個Configuration Element Collection,我們很清楚知道他們分別代表什麼元素的集合,這時我們可以拖拉工具箱中的Collection Item Type 建立起關聯,而Configuration Section Explorer也會顯示得讓我們容易理解。
同樣的在加入Element時必須加入相對應的Type。
10 最後的大概會長這個樣子
11 最後我們把專案建置一下,就可以取config檔與class code了
MyConfig.csd.config檔
MyConfig.cs檔
12 不知道為什麼有時候檔案會消失,但是只要稍微異動一下.csd檔再存檔就又會出現了。