środa, 2 września 2009

Automatically changing web.config files for production and development mode

The reason of this post was forced by a need to automatically change the web.config file of asp application depending on DEBUG or RELEASE version chosen when building application. The code in your web.config file can be different for example in section, where you set up web services. Listing 1 - part of web.config file - Release version
<endpoint address="https://yourdomain.com/services/serviceName.svc" binding="basicHttpBinding" bindingConfiguration="HttpsBinding" contract="ServiceProject.IService">
     <identity>
        <dns value="yourdomain.com" />
     </identity>
</endpoint>
Listing 2 - part of web.config file - development version
<endpoint address="http://localhost:65310/services/ServiceName.svc" binding="basicHttpBinding" contract="ServiceProject.IService">
   <identity>
      <dns value="localhost" />
   </identity>
</endpoint>
When you've got a lot of services in your application it can take a while to change maintain this changes during development and when releasing your application. The solution for this problem is to create 2 files. First will be called Web.DEBUG.config and will contain the same what standard web.config file contains, but with all settings needed when trying out your application on localhost. The second file is Web.RELEASE.config and differs from Web.DEBUG.config file only in this sections where things need to be set for production server. This two files should be placed in the same folder where standard Web.config file is placed. Having that done we can now set our application to change Web.config file depending on Soluction Configuration (debug or release). Right click on your web project and select Properties from context menu. Then go to tab "Build Events" and in "Post-build event command line:" window write this code: Listing 3 - Post-build event command line code
   1:  if $(ConfigurationName) == Debug goto :debug
   2:   
   3:  :release
   4:  xcopy  "$(ProjectDir)Web.RELEASE.config" "$(ProjectDir)Web.config" /Y /R
   5:  goto :exit
   6:   
   7:  :debug
   8:  xcopy  "$(ProjectDir)Web.DEBUG.config" "$(ProjectDir)Web.config" /Y /R
   9:   
  10:  :exit
I think thre's not a lot to explain. Thi code checks your Solution Configuration and replaces Web.config file with appropriate one using xcopy shell function. The paremeters are as fallows: /Y suppresses prompting to confirm you want to overwrite an existing destination file /R overwrites read-only files.

Brak komentarzy: