kacalapy
kacalapy

Reputation: 10134

asp.net change value of a web.config item?

im trying to get role provider working in multiple environments and hitting a wall (link text)

i should be able to dynamically set the connectionString property of the web.congig item on app_onstart to the correct DB conection String to get it to work...

can anyone show me how to dynamically alter items in the web.config? im guessing reflection...

<roleManager enabled="true" defaultProvider="SqlRoleManager">
    <providers>
        <clear/>
        <add name="SqlRoleManager" type="System.Web.Security.SqlRoleProvider" connectionStringName="ISConnectionString_prod" applicationName="IS"/>
    </providers>
</roleManager>

i want to adjust the connectionStringName value in the above snipet

thanks

Upvotes: 0

Views: 2164

Answers (2)

Basic
Basic

Reputation: 26756

If you're using VS2010, you can get it to automatically apply transforms to your config files depending on which environment you're publishing to.

We use this to set connection strings, payment provider config settings (sandbox mode, username, etc.) and a couple of other things like how exceptions are handled.

If you're not publishing, you can actually hook these transforms straight into the build engine by editing the project file.

This makes it incredibly simple to maintain (You have a web.config and a web.Live.config which contains the transforms). It also makes the whole process far less error-prone

eg:

web.config

  <connectionStrings>
    <clear />
    <add name="OurConnectionString" connectionString="Data Source=DevDbHostname;Initial Catalog=DevDb;user id=Username;password=Password;MultipleActiveResultSets=True" />
  </connectionStrings>

web.Release.config

<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
  <connectionStrings>
    <add name="OurConnectionString"
      connectionString="Data Source=LiveDbHostname;Initial Catalog=LiveDb;user id=Username;password=Password;MultipleActiveResultSets=True"
      xdt:Transform="SetAttributes" xdt:Locator="Match(name)"/>
  </connectionStrings>
</configuration>

Upvotes: 1

naspinski
naspinski

Reputation: 34687

As long as the permissions allow it (you will have to change them), you can treat the web.config just as any other XML file. Knowing that, you can simply use an XDocument and pop in a new XElement where you want it. But be very careful and be sure to save some backups!

Upvotes: 0

Related Questions