April 12, 2014

使用SlowCheetah套件新增及轉換組態設定檔內容

在開發專案的過程中,常會遇到需要因應不同的開發或佈署環境而有不同的組態設定。在Visual Studio裡,預設的兩種組態分別為Debug及Release。當我們需要除了這兩種以外的組態時,可以到BUILD-> Configuration Manager裡新增。



在Console Application專案中,預設會有一個App.config設定檔,按照前述需求,不同的開發或佈署環境會有不同的組態設定,我們可以透過SlowCheetah套件新增不同組態下相對應的App.config,如App.Debug.config或App.Release.config。除此之外,SlowCheetah還可以協助應用程式於程式碼建置時輸出正確的設定檔內容。

先建立一個名為SlowCheetahDemo的Console Application專案,並透過nuget指令安裝SlowCheetah,Install-Package SlowCheetah

右鍵選取App.config,點選Add transform,App.config下會新增App.Debug.config及App.Release.config檔案



以下為App.config內容
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <connectionStrings>
    <add name="Default"
         connectionString="Server=localhost;Database=Demo;Persist Security Info=True;integrated security=false; user id=demo; password=1234"
         providerName="System.Data.SqlClient" />
  </connectionStrings>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
  </startup>
</configuration>


現在我們希望在Release組態下,設定檔內容可以切換到不同的連線字串,App.Release.config設定如下
<?xml version="1.0" encoding="utf-8" ?>
<!-- For more information on using transformations
     see the web.config examples at http://go.microsoft.com/fwlink/?LinkId=214134. -->
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
  <connectionStrings>
    <add name="Default" xdt:Transform="SetAttributes" xdt:Locator="Match(name)"
         connectionString="Server=ReleaseServer;Database=Release;Persist Security Info=True;integrated security=false; user id=release; password=5678"
         providerName="System.Data.SqlClient" />
  </connectionStrings>
</configuration>

設定完成後,將專案組態模式切到Debug並建置程式碼,可以看到在bin\Debug\SlowCheetahDemo.exe.config內容為一開始設定在App.config的內容。接下來切換到Release組態再次建置程式碼,可以看到bin\Release\SlowCheetahDemo.exe.config裡的連線字串已設定為在App.Release.config中所設定的連線字串。

組態設定檔的轉換除了對開發上有幫助外,對於有導入持續整合及自動化佈署的專案,也增加了不少彈性。目前我所在團隊開發的一個專案中,就有Dev、QA、Staging和Production不同的組態設定,在build server建置程式碼時便會根據當下的組態設定去轉換出對應的資料庫連線字串,佈署位址及網站位址等。

完整範例檔可至https://github.com/petekcchen/blog/tree/master/SlowCheetahDemo下載

參考

4 comments:

Faizal said...

To Enhance Your Skills with JAVA...Visit Here and Explore it...
Java training in chennai | Java training in annanagar | Java training in omr | Java training in porur | Java training in tambaram | Java training in velachery

Back linker said...

DriverToolkit Crack is a program that updates all kinds of drivers. The main and main goal of this program is to manage all operating software Driver Downloader License Key

Hi Every One said...

Adobe XD CC 51.0.12 Crack is a fresh innovative tool from Stone for creating top quality representative models of user terme for cellular and web software. Adobe XD Crack

Back linker said...

But when a relationship ends it brings endless emotions of sorrow and sadness. The breakup or love failure makes people carry only memories of their loved one. Love Failure