How To: "Upsert" Into AppSettings

ASP.NET 2.0 allows developers to update or insert values into web.config programmatically.  This allows senior ASP.NET developers to create an administration or support page to modify values into web.config sections - without tampering with the web.config file directly.

If I have a value I would like to update or insert into the <appSettings> section, I would like to make an idempotent call that will either UPdate or inSERT the key value pair.  Thus some call this behavior - upsert.  Here is a utility method that demonstrates what I want:

public static void UpsertAppSettings(string key, string value)
{
    // Current is an instance of System.Configuration.Configuration 
    AppSettingsSection appSettings = Current.AppSettings;

    // Does the key argument already exist in appSettings?
    if (!Array.Exists<string>(appSettings.Settings.AllKeys,
        delegate(string s) { return (s == key); }))
        appSettings.Settings.Add(key, value);
    else
        appSettings.Settings[key].Value = value;

    Current.Save();
}// method
Published Wednesday, July 11, 2007 11:25 PM by Palermo4
Filed under: , , ,

Comments

# re: How To: "Upsert" Into AppSettings

Thursday, July 12, 2007 6:14 AM by Dested

Does this physically updated the web.config file, or is it just for the session, or what? If not, when does it revert back?

# itworks &raquo; Blog Archive &raquo; How To: &#8220;Upsert&#8221; Into AppSettings

Pingback from  itworks  &raquo; Blog Archive   &raquo; How To: &#8220;Upsert&#8221; Into AppSettings

# re: How To: "Upsert" Into AppSettings

Friday, July 13, 2007 8:17 AM by Palermo4

Dested,

Yes, this does physically change the web.config file.  Thus, it is important to know that each time this is called, it will cause an application shut down.

# re: How To: "Upsert" Into AppSettings

Tuesday, July 17, 2007 10:35 AM by Oskar Austegard

"I would like to make an idempotent call that will either UPdate or inSERT the key value pair.  Thus some call this behavior - upsert. "

And some of us radials call this behavior "Set"....

But you got me on idempotent - had to look that one up.

# re: How To: "Upsert" Into AppSettings

Tuesday, July 17, 2007 11:03 AM by Palermo4

Oskar,

Of course, I agree that this is simply "set"ting a value.  I came across the term Upsert from a DBA who made stored procedures behave the same way.

As far as idempotent - the context was purely on the end state of the call.  Regardless of how I call it (or how many times I call it) the end state is the same.

# re: How To: "Upsert" Into AppSettings

Monday, December 10, 2007 2:27 AM by Patrick

I tried doing this but I didn't make it work.

Leave a Comment

(required) 
(required) 
(optional)
(required)