Set a setting at runtime - c#

I'm having trouble setting application properties at runtime. My application connects to a database and so I have stored the location of the database, which is used to generate the connection string.
The database is stored on a usb stick and so when plugged into different computers it checks to see if the database exists in the saved location, then if it isn't there, it prompts the user to select it in an OpenFileDialog.
I then try to store it as a setting, which gets saved while the application is open, but as soon as the application is closed the setting reverts to it's default value.
Here's how I try to set the dbLocation setting.
DBce_TEST2.Properties.Settings.Default.dbLocation = fileName;
This is how the getter and setter looks. The get part was generated by visual studio, and I added the set part which is where the problem lies (I think).
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("E:\\C# Projects\\DBce_TEST2\\TestDB2.sdf")]
public string dbLocation {
get {
return ((string)(this["dbLocation"]));
}
set
{
this["dbLocation"] = value; //most likely error here
}
}

Setting the property isn't enough. You need to save it, too:
DBce_TEST2.Properties.Settings.Default.dbLocation = fileName;
DBce_TEST2.Properties.Settings.Default.Save();

Related

Where does WebConfigurationManager.AppSettings write its data? Not to web.config

I am trying to use WebConfigurationManager.AppSettings[string] to read/write values to be stored in a configuration file on the server. I thought that it read/wrote it to the Web.config file, or maybe app.config. However, I ran the following test code - which the first time through (as desired) it throws an exception and but writes 'NOTSet' to that configuration entry - this allows me go easily go edit the file and change it to the correct value.
After running it a 2nd time, I can see the value returned is "NOTSet" - exactly as I would like. The code is working exactly as planned.
Except - Where is it written? I did a 'baregrep NOTSet .' - which recursively searched the ENTIRE project source directory and ONLY found the line in code that set the var - which means it was not written to anything in the entire project tree - not web.config, app.config or any other file.
I sighed, and said it must be in the registry - I searched the whole registry for anything with that value, then tried the key value - nothing.
Yet, running the program IS pulling the value that was set on the last run! Where did my data go? I want to be able to edit the value- and more importantly, have a FILE that I can copy to the production web server with all the GUIDs set correctly.
public enum Guids
{
IncidentSourceEnumPortal,
WorkItemClass,
WorkItemManagementPack
}
public class GuidConsts
{
static readonly Dictionary<Guids, Guid> GuidList = new Dictionary<Guids, Guid>();
public static Guid Guids(Guids guidId)
{
if (!GuidList.ContainsKey(guidId))
{
string id = WebConfigurationManager.AppSettings[guidId.ToString()];
Guid newGuid;
if ( (id == null) || Guid.TryParse(id, out newGuid))
{
WebConfigurationManager.AppSettings[guidId.ToString()] = "NOTSet";
throw new Exception(String.Format("Invalid guid - not found in Config: {0}", guidId));
}
GuidList.Add(guidId, newGuid);
return newGuid;
}
return GuidList[guidId];
}
}
To save the web.config file you need to call Configuration.Save() to persist changes. They are not automatically saved when you change a value:
https://msdn.microsoft.com/en-us/library/ms134088%28v=vs.110%29.aspx
Writing to web.config on the fly is not really advisable anyway, for one thing it will cause the app pool to be restarted potentially resulting in loss of session state across your application and probably other application-wide things you don't want to happen.

use settings.default.upgrade to keep setting when update to new version clickonce

I used following code that mention on this post
Do not overwrite settings.settings file with clickonce
but it is not working for my connection string that stored in setting with application scope, I am in doubt that this method work for user scope only or both application and user scope ?
if (Settings.Default.upgradeRequired)
{
Settings.Default.Upgrade();
Settings.Default.upgradeRequired = false;
Settings.Default.Save();
}
I come up with that by adding one more setting named "userconnection" Scope:User then
every time that user must set its connection string then this "userconnection" updated, Then in main point of my application check if userconnection(User Scope)!=ConnectionString(Applicaiton Scope) then try to change application ConnectionString to user customized one which was stored in userconnection properties.

Properties.Settings has no setter

I decided to use Properties.Settings to store some application settings for my ASP.net project. However, when trying to modify the data, I get an error The property 'Properties.Settings.Test' has no setter, since this is generated I have no idea what I should do to change this as all my previous C# Projects have not had this issues.
My guess is that you defined the property with the Application scope, rather than the User scope. Application-level properties are read-only, and can only be edited in the web.config file.
I would not use the Settings class in an ASP.NET project at all. When you write to the web.config file, ASP.NET/IIS recycles the AppDomain. If you write settings regularly, you should use some other settings store (e.g. your own XML file).
As Eli Arbel already said you can’t modify values written in web.config from your application code. You can only do this manually but then the application will restart and this is something you don’t want.
Here is a simple class you can use to store values and make them easy to read and modify. Just update the code to suite your needs if you’re reading from XML or database and depending on whether you want to permanently store modified values.
public class Config
{
public int SomeSetting
{
get
{
if (HttpContext.Current.Application["SomeSetting"] == null)
{
//this is where you set the default value
HttpContext.Current.Application["SomeSetting"] = 4;
}
return Convert.ToInt32(HttpContext.Current.Application["SomeSetting"]);
}
set
{
//If needed add code that stores this value permanently in XML file or database or some other place
HttpContext.Current.Application["SomeSetting"] = value;
}
}
public DateTime SomeOtherSetting
{
get
{
if (HttpContext.Current.Application["SomeOtherSetting"] == null)
{
//this is where you set the default value
HttpContext.Current.Application["SomeOtherSetting"] = DateTime.Now;
}
return Convert.ToDateTime(HttpContext.Current.Application["SomeOtherSetting"]);
}
set
{
//If needed add code that stores this value permanently in XML file or database or some other place
HttpContext.Current.Application["SomeOtherSetting"] = value;
}
}
}
Here:
http://msdn.microsoft.com/en-us/library/bb397755.aspx
is the solution for your problem.

Reset settings to SpecialFolder

I store the directory path of a folder in Properties.Settings.Default.Temporary and I allow the user to change this value and other settings using a PropertyGrid.
When the user decides to reset the Settings, I would like to change Properties.Settings.Default.Temporary to the value of System.IO.Path.GetTempPath() by using Properties.Settings.Default.Reset()
I know about System.Configuration.DefaultSettingValueAttribute. Something like this:
[global::System.Configuration.DefaultSettingValueAttribute(System.IO.Path.GetTempPath())]
does not work.
I also read Storing default value in Application settings (C#), which described a related problem, but I wonder if there is a way to solve my problem in the way described above.
The DefaultSettingValueAttribute.Value property is a string, therefore you cannot pass a function call to be called when the value is used. In fact there is no ability to pass code to an attribute: only literals are possible.
Instead in your applications code where you reset the settings, follow this by setting and settings that you want to have values that are not literals at compile time (eg. dependent on the execution environment).
I just had an idea for a workaround myself:
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute(null)]
public string TemporaryDirectory
{
get
{
if (this["TemporaryDirectory"] == null)
{
return System.IO.Path.GetTempPath();
}
return ((string)this["TemporaryDirectory"]);
}
set
{
if (System.IO.Directory.Exists(value) == false)
{
throw new System.IO.DirectoryNotFoundException("Directory does not exist.");
}
this["TemporaryDirectory"] = value;
}
}
I don't know, if this has any side effects, but so far it seems to work. I am sorry that I had this idea shortly after posting. I should've thought about the problem a bit longer.

Reading default application settings in C#

I have a number of application settings (in user scope) for my custom grid control. Most of them are color settings. I have a form where the user can customize these colors and I want to add a button for reverting to default color settings. How can I read the default settings?
For example:
I have a user setting named CellBackgroundColor in Properties.Settings.
At design time I set the value of CellBackgroundColor to Color.White using the IDE.
User sets CellBackgroundColor to Color.Black in my program.
I save the settings with Properties.Settings.Default.Save().
User clicks on the Restore Default Colors button.
Now, Properties.Settings.Default.CellBackgroundColor returns Color.Black. How do I go back to Color.White?
#ozgur,
Settings.Default.Properties["property"].DefaultValue // initial value from config file
Example:
string foo = Settings.Default.Foo; // Foo = "Foo" by default
Settings.Default.Foo = "Boo";
Settings.Default.Save();
string modifiedValue = Settings.Default.Foo; // modifiedValue = "Boo"
string originalValue = Settings.Default.Properties["Foo"].DefaultValue as string; // originalValue = "Foo"
Reading "Windows 2.0 Forms Programming", I stumbled upon these 2 useful methods that may be of help in this context:
ApplicationSettingsBase.Reload
ApplicationSettingsBase.Reset
From MSDN:
Reload contrasts with Reset in that
the former will load the last set of
saved application settings values,
whereas the latter will load the saved
default values.
So the usage would be:
Properties.Settings.Default.Reset()
Properties.Settings.Default.Reload()
Im not really sure this is necessary, there must be a neater way, otherwise hope someone finds this useful;
public static class SettingsPropertyCollectionExtensions
{
public static T GetDefault<T>(this SettingsPropertyCollection me, string property)
{
string val_string = (string)Settings.Default.Properties[property].DefaultValue;
return (T)Convert.ChangeType(val_string, typeof(T));
}
}
usage;
var setting = Settings.Default.Properties.GetDefault<double>("MySetting");
Properties.Settings.Default.Reset() will reset all settings to their original value.
I've got round this problem by having 2 sets of settings. I use the one that Visual Studio adds by default for the current settings, i.e. Properties.Settings.Default. But I also add another settings file to my project "Project -> Add New Item -> General -> Settings File" and store the actual default values in there, i.e. Properties.DefaultSettings.Default.
I then make sure that I never write to the Properties.DefaultSettings.Default settings, just read from it. Changing everything back to the default values is then just a case of setting the current values back to the default values.
How do I go back to Color.White?
Two ways you can do:
Save a copy of the settings before the user changes it.
Cache the user modified settings and save it to Properties.Settings before the application closes.
I found that calling ApplicationSettingsBase.Reset would have the effect of resetting the settings to their default values, but also saving them at the same time.
The behaviour I wanted was to reset them to default values but not to save them (so that if the user did not like the defaults, until they were saved they could revert them back).
I wrote an extension method that was suitable for my purposes:
using System;
using System.Configuration;
namespace YourApplication.Extensions
{
public static class ExtensionsApplicationSettingsBase
{
public static void LoadDefaults(this ApplicationSettingsBase that)
{
foreach (SettingsProperty settingsProperty in that.Properties)
{
that[settingsProperty.Name] =
Convert.ChangeType(settingsProperty.DefaultValue,
settingsProperty.PropertyType);
}
}
}
}

Categories

Resources