Thursday, February 4, 2010

C# - Change compilation debug value of the configuration file at runtime

Below is a C# code snippet to demonstrate on how to change the compilation-debug value at runtime.
Configuration config = WebConfigurationManager.OpenWebConfiguration("/WebPersonalExercises");
            
CompilationSection compSection = ((CompilationSection)(config.GetSection("system.web/compilation")));
            
compSection.Debug = true;

config.Save();

Please note that there might be times that this section is locked, so it is always helpful to check them first. Below is a revision C# code snippet to show that.
Configuration config = WebConfigurationManager.OpenWebConfiguration("/WebPersonalExercises");
CompilationSection compSection = ((CompilationSection)(config.GetSection("system.web/compilation")));
            
compSection.Debug = true;
            
if (!(compileSection.SectionInformation.IsLocked))
{
     config.Save();
}

Tuesday, February 2, 2010

C# - Manipulating the appSettings section of the configuration file at runtime

There might be a time wherein you have to manipulate the configuration at runtime, either adding or removing key-value pair. Below are some code snippets in C# to do this.

Adding a new appSetting value:
Configuration config = WebConfigurationManager.OpenWebConfiguration("/WebPersonalExercises");

AppSettingsSection appSection = ((AppSettingsSection)(config.GetSection("appSettings")));

KeyValueConfigurationCollection keyVal = appSection.Settings;

keyVal.Add("myNewValue", "value" + ++intCounter);

config.Save();

Removing the value:
Configuration config = WebConfigurationManager.OpenWebConfiguration("/WebPersonalExercises");

AppSettingsSection appSection = ((AppSettingsSection)(config.GetSection("appSettings")));

KeyValueConfigurationCollection keyVal = appSection.Settings;

keyVal.Remove("myNewValue");

config.Save();

Note that if you add the same appSetting key multiple times, it would be presented in the file like this (concatenated with a comma separator):
<appSettings>
  <add key="myNewValue" value="value1,value2,value3"/>
</appSettings>

But when you call the remove method, all of the appSetting key-value would be removed, regardless of how many times you add the same appSetting key of different values.