Reset settings to SpecialFolder - c#

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.

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.

Application changes not taking effect

I have made a change to a method used in a Functiod in a mapping file but it seems the new code is not taking effect, ever.
I have deployed properly, started the application, restarted related host instance (actually all host instances I could find) and still, the old code seems to execute.
Here's the, simple, method:
public string RemoveNonNumericChars(string stIn, int maxLength)
{
string strOut;
try
{
strOut = Regex.Replace(stIn, "[^0-9]", "");
System.Diagnostics.EventLog.WriteEntry("BizTalk Server 2009", strOut);
return strOut.Substring(0, maxLength);
}
catch
{
return string.Empty;
}
}
I added the writing to EventLog line to see that this code is indeed being executed, but I don't get anything in "Application" event logs.
I do NOT get an empty string being returned, so it really does seem like the old code that's being executed prior to me fixing the method.
What am I missing exactly ?
Thank you.
For some reason, the script is not able to correctly retrieve the Build Config selected in Visual Studio, it's taken from Debug when I'm actually trying to build it for a Test environment. I should have known, thanks anyways.

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.

Store & Return Settings for a Webpage

So I am using C# ASP.NET 3.5 and I would like to add a feature to my site to turn on and off a sort of debug mode for testing purposes.
Is there a best way to have a file or class that stores or returns simply if myDebug is on or off. It has to be accessed fast since it will be used a lot on multiple pages and it should be easy to set using the website itself.
My first thought is just a class with get/set which is stored on every page... perhaps the master page?
Thanks for any input
-Scott
Sounds like something you'd want to put in AppSettings in your web.config.
(I'm assuming that setting compilation debug to true in web.config is insufficient for what you're trying to do.)
Use AppSettings.
You can get your app settings like so:
string appSettingValue = ConfigurationManager.AppSettings["key"];
You can change your app settings like so.
Code below has been copied from blog link above to show as sample:
private void ChangeAppSettings(string key, string NewValue)
{
Configuration cfg;
cfg = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~");
KeyValueConfigurationElement setting = (KeyValueConfigurationElement)cfg.AppSettings.Settings(key);
if ((setting != null)) {
setting.Value = NewValue;
cfg.Save();
}
}
You might have to call ConfigurationManager.RefreshSection("appSettings"); after the save to have the app see the changes.... Im not sure if the cfg.Save() will reload/refresh the settings.

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