Rick Strahl's Weblog  

Wind, waves, code and everything in between...
.NET • C# • Markdown • WPF • All Things Web
Contact   •   Articles   •   Products   •   Support   •   Advertise
Sponsored by:
West Wind WebSurge - Rest Client and Http Load Testing for Windows

Creating and writing ASP.NET 2.0 custom Configuration Sections


:P
On this page:

 

ASP.NET 2.0 has made it pretty nice to create custom configuration sections and be able to access these configuration sections via code. You can basically implement a new ConfigurationSection class. For example, I’ve built a configuration section for my Database Resource Provider like this:

 

    public class wwDbResourceProviderSection : ConfigurationSection

    {

        [ConfigurationProperty("connectionString",DefaultValue=""),

        Description("The connection string used to connect to the db Resource provider")]      

        public string ConnectionString

        {

            get { return this["connectionString"] as string; }

            set { this["connectionString"]  = value; }

        }

       

 

        [ConfigurationProperty("resourceTableName",DefaultValue="Localizations"),

        Description("The name of the table used in the Connection String database for localizations.")]

        public string ResourceTableName

        {

            get { return this["resourceTableName"] as string; }

            set { this["resourceTableName"] = value; }

        }

       

        [ConfigurationProperty("designTimeVirtualPath",DefaultValue=""),

        Description("The virtual path to the application. This value is used at design time and should be in the format of: /MyVirtual")]

        public string DesignTimeVirtualPath

        {

            get { return this["designTimeVirtualPath"] as string; }

            set { this["designTimeVirtualPath"] = value; }

        }

 

       

 

        public wwDbResourceProviderSection(string ConnectionString, string ResourceTableName, string DesignTimeVirtualPath)

        {

            this.ConnectionString = ConnectionString;

            this.DesignTimeVirtualPath = DesignTimeVirtualPath;

            this.ResourceTableName = ResourceTableName;

        }

 

        public wwDbResourceProviderSection()

        {

          

        }

 

    }

 

 

And create your ‘properties’ for the section by simply creating public properties and marking them up with a few attributes. The whole thing can then be stuck into web.config like this:

 

<configSections> 

  <section name="wwDbResourceProvider"

           type="Westwind.Globalization.wwDbResourceProviderSection"

  />

</configSections>  

<wwDbResourceProvider  

    connectionString="server=(local);database=Internationalization;integrated security=true;"

    resourceTableName="Localizations"

    designTimeVirtualPath="/internationalization"

    localizationFormWebPath="~/localizationadmin/localizeform.aspx"

    addMissingResources="false"

    useVsNetResourceNaming="false"

    showLocalizationControlOptions="false"

    showControlIcons="true"

/>

 

Nice.

 

However, I’ve not been able to figure out how to write data back to the config file through the ConfigurationSection interface. This class representation supports the ability to save the content, but when I try to assign a value like so:

 

protected void Page_Load(object sender, EventArgs e)

{

 

    object T = WebConfigurationManager.GetWebApplicationSection("wwDbResourceProvider") ;

    if (T != null)

    {

        wwDbResourceProviderSection Section = T as wwDbResourceProviderSection;

        Response.Write(Section.ConnectionString);

 

        Section.ShowControlIcons = false;           

    }

}

 

I get an exception that the configuration is read only.

 

Exception Details: System.Configuration.ConfigurationErrorsException: The configuration is read only.

 

 

As it turns out the code to write this needs to look a little differently:

 

protected void Page_Load(object sender, EventArgs e)

{

 

    Configuration config = WebConfigurationManager.OpenWebConfiguration("~");

    wwDbResourceProviderSection Section = config.GetSection("wwDbResourceProvider") as wwDbResourceProviderSection;

    Section.ShowControlIcons = true;

    config.Save();

 

    return;

}

 

And this works…

 

As long as you’re running at least with High Trust permissions. This understandably fails with Medium trust.

Posted in ASP.NET  

The Voices of Reason


 

dominick
October 29, 2006

# re: Creating and writing ASP.NET 2.0 custom Configuration Sections

Hi Rick,

you can access the config section in medium trust when you add a requirePermission="false" to the <section> registration.

http://www.leastprivilege.com/ConfigurationPermissionAndRequirePermission.aspx

dominick

Rick Strahl
October 29, 2006

# re: Creating and writing ASP.NET 2.0 custom Configuration Sections

Dominick - looks like in Medium trust you're still going to run into problems with actually savnig the configuration settings. I get a file IO error now (even though the Web server account has rights to write to web.config).

But your suggestion does at least allow setting the property value, although without the ability to write it out that's not terribly useful <s>...

Sonu Kapoor
October 29, 2006

# re: Creating and writing ASP.NET 2.0 custom Configuration Sections

You might want to check out the article that was posted last week on DotNetSlackers about custom provider configuration sections:

http://dotnetslackers.com/articles/customconfiguration/Custom_Provider_Configuration_Sections.aspx

# DotNetSlackers: Creating and writing ASP.NET 2.0 custom Configuration Sections


dominick
October 29, 2006

# re: Creating and writing ASP.NET 2.0 custom Configuration Sections

Rick -

to write to a config file you need more than just write access to web.config - they first create a temp file, and then copy it over to web.config. So you also need the "add files to directory" ACL.

But yeah - i think they are doing some CAS extra checks when saving...can't remember the details.

dominick

Configuration and Deployment
January 10, 2007

# ASP.NET Forums - (Writing to Web.config file dynamically

# A Continuous Learner's Weblog: October 2006


Sergey
February 16, 2007

# re: Creating and writing ASP.NET 2.0 custom Configuration Sections

Hi Rick,

Many thanks for this post. It was exactly what I have been searching for and was just happy to find it on your site.

You are making very useful things!

Thank you,
Sergey

Getting Started
May 04, 2007

# ASP.NET Forums - Need to write and update sections in the Web.Config


ASP.NET Forums
May 17, 2007

# (Writing to Web.config file dynamically - ASP.NET Forums


ASP.NET Forums
May 24, 2007

# Need to write and update sections in the Web.Config - ASP.NET Forums


G.Dorazio
May 29, 2007

# re: Creating and writing ASP.NET 2.0 custom Configuration Sections

Rick,

Thanks for the solution...(versus the WebConfigurationManager.GetWebApplicationSection(...) one that doesn't)

Just a comment for something I noticed:

While implementing your solution I was getting this error:

An error occurred loading a configuration file: Access to the path 'D:\Clients\ISSSecurity\Webs\GovTest.com\2roq_3jp.tmp' is denied.

I had only set permissions on the web.config file and not for the root directory. When I changed the permissions on the root folder (for Network Service) everything works fine.

The cryptic file name, I am surmising, is part of the MS synchronization for updating the web.config file when it finishes pending requests...What's interesting is that this must be using the same account when file I/O occurs for updates to dynamically dependent files like web.config. This would mean that all dynamic updates to web.config files in ANY directory must give the calling account authorization for updates to the entire folder....maybe we shouldn't be updating web.config from a web app...too much of a security hole.

What do you think?

Thanks,
Gery

Jeff Garrison
May 31, 2007

# re: Creating and writing ASP.NET 2.0 custom Configuration Sections

My question is if you write to the web.config using the WebConfigurationManager does it recycle the appdomain?

Rick Strahl
May 31, 2007

# re: Creating and writing ASP.NET 2.0 custom Configuration Sections

Depends what section you write. I seem to remember some sections can be updated without requiring a restart (which incidentally is also true in manual web.config editing). You'll have to test your scenario specifically to see what does and doesn't. Application settings definitely cause the AppDomain to restart though!

RONUA
June 11, 2007

# RONUA - Probleme cu web.config

ROmanian .NET User Association

Ted
June 22, 2007

# re: Creating and writing ASP.NET 2.0 custom Configuration Sections

Nice article. This gets me moving ahead again. i was stuck on this for hours today trying to update a sharepoit web.config file from a Feature Recever event hander.

Thanks

Chital
August 08, 2007

# re: Creating and writing ASP.NET 2.0 custom Configuration Sections

Rick,

This is really nice article about to edit section of web.config file. My question is that, can we edit <siteMap> section using the above code? Yes, I know we can edit, but I am getting error that "the configuration is read only". Can you please help me out for this? I want to set DefaultProvider property of <siteMap> section of web.config file at runtime. The sitemapprovider is different for different language of my application. I can set defaultProvider="XMLSiteProviderDefault" for the first time, but whenever selected language is different then I should be able to change the defaultProvider.

I am stuck up in this problem, I am not sure what to do with this error "The configuration is read only".

Please help me out.

Chital

ngocdiem
August 16, 2007

# re: Creating and writing ASP.NET 2.0 custom Configuration Sections

Thanks. It is a small demo, but it help me know clearly about custom Configuration Sections.

Pravesh
March 30, 2008

# re: Creating and writing ASP.NET 2.0 custom Configuration Sections

Hi there,
I cannot get this to work.

I get an error message "An error occurred creating the configuration section handler for wwDbResourceProvider: Could not load type 'XXX.wwDbResourceProviderSection'. (C:\\Development\\WebSites\\AMLVerification\\web.config line 23)" and it's driving me crazy. Any idea why??

XXX -> My namespace
Line 23 -> <section name="wwDbResourceProvider" type="XXX.wwDbResourceProviderSection" />

Cheers,
Pravesh

West Wind  © Rick Strahl, West Wind Technologies, 2005 - 2024