Read and write settings programmatically in C# - c#

I've got the following example content generated by the Settings-Designer in Visual Studio 2015:
<configuration>
<applicationSettings>
<Test.Properties.Settings>
<setting name="LogFileFolder" serializeAs="String">
<value>logs</value>
</setting>
<setting name="sPluginsFolder" serializeAs="String">
<value>plugins</value>
</setting>
<setting name="sLangBaseName" serializeAs="String">
<value>Test.Resources.Language.Test</value>
</setting>
<setting name="ConfirmationExit" serializeAs="String">
<value>True</value>
</setting>
</Test.Properties.Settings>
</applicationSettings>
</configuration>
Now I want to access, for example, the variable "ConfirmationExit" within my code. In first I tried with Properties.Settings.Default which is working nicely, but I want to retrieve the configuration keys more generic and provide a ConfigurationService which can be used by any other .NET program.
I tried playing around with the ConfigurationManager, but I didn't get the values of the different settings/properties. I always got null if I tried something like this:
string test = ConfigurationManager.AppSettings["ConfirmationExit"];
How can I PROGRAMMATICALLY read AND write properties/settings defined within the app.config file with the use of the Settings-Designer. Thx for any help ;)
UPDATE:
Maybe I have to mention, that there is a namspace used as XML element (I think this is generated by the designer or soemthing else?!):
<Test.Properties.Settings>
inside of
<applicationSettings>
Also please remind:
This is a project structure like this:
1. Project_Common
2. Project_Main
|-- Project_Common
3. Project_Plugin1
|-- Project_Common
4. Project_Plugin2
|-- Project_Common
...
In Project_Common there should be a ConfigurationService which can retrieve all properties of all applications. Maybe the constructor has to have a parameter to inject settings or something.

string test = Properties.Settings.Default.ConfirmationExit;
From MSDN: https://msdn.microsoft.com/en-us/library/a65txexh.aspx

read:
Settings.Default.{propertyName}
so in your case for example
Settings.Default.ConfirmationExit
reads ConfirmationExit-Value
Set it:
Settings.Default.ConfirmationExit = false
Write:
Settings.Default.Save();

Related

Dynamically encrypting user configuration settings file

I have an application that connects to a database. Is there a way to encrypt the file that contains the connection string along with other settings? The file is quite exposed as the database connection password is stored inside the user.config file. The only semi-solution I found was for web applications by adding a web.config file, but I'm not sure if this applies the same way. Is there any documentation regarding configuration encryption?
Here's my attempt so far:
user.config:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<userSettings>
<TimeClock.Properties.Settings>
<setting name="webserver" serializeAs="String">
<value>test.js.com/</value>
</setting>
<setting name="timeclockConnectionString" serializeAs="String">
<value>port=3306;server=localhost;user id=root;password=123456;database=timeclock;convertzerodatetime=True</value>
</setting>
<setting name="screenmode" serializeAs="String">
<value>0</value>
</setting>
</TimeClock.Properties.Settings>
</userSettings>
</configuration>
Method:
System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(
ConfigurationUserLevel.PerUserRoamingAndLocal);
string provider = "RsaProtectedConfigurationProvider";
ConfigurationSection connStrings = config.GetSection("timeclockConnectionString");
connStrings.SectionInformation.ProtectSection(provider);
connStrings.SectionInformation.ForceSave = true;
config.Save(ConfigurationSaveMode.Full);
As you can see, I'm trying to encrypt only the timeclockConnectionString and nothing else. Obviously, I get an error:
Object reference not set to an instance of an object.
which probably stems from the config.GetSection.
Any help would be greatly appreciated.

C# Changing Web Reference url

I'm trying to change a web reference path depending on whether the site is live or not.
The application settings are in the web.config
<applicationSettings>
<WebReferenceName.Properties.Settings>
<setting name="WebReferenceName_Service_TBService"
serializeAs="String">
<value>http://localhost:50711/Service.svc</value>
</setting>
</WebReferenceName.Properties.Settings>
I've tried the following:
Properties.Settings.Default.WebReferenceName_Service_TBService.Equals("http://www.newurl.com/service.svc");
which although doesn't error, checking it later, shows it hasn't changed.
and
var config = WebConfigurationManager.OpenWebConfiguration("~/web.config");
config.AppSettings["WebReferenceName_Service_TBService"] = "http://www.newurl2.com/service.svc";
config.Save();
but this errors saying I don't have permissions
Is there another way of doing this?
I'd rather not have to use if statements all over the place, as my types are namespaced differently.
e.g.
using (var service = new WebServiceLocal.TheWebServiceService())
{
WebServiceLocal.blah();
}
Thanks
The preferred way to do this is to use config transformations. So your default web.config would contain:
<applicationSettings>
<WebReferenceName.Properties.Settings>
<setting name="WebReferenceName_Service_TBService" serializeAs="String">
<value>http://localhost:50711/Service.svc</value>
</setting>
</WebReferenceName.Properties.Settings>
</applicationSettings>
And in your transform, you would have something like this (note the xdt:Transform="Replace"):
<applicationSettings>
<WebReferenceName.Properties.Settings>
<setting name="WebReferenceName_Service_TBService" serializeAs="String">
<value xdt:Transform="Replace">http://www.newurl2.com/service.svc</value>
</setting>
</WebReferenceName.Properties.Settings>
</applicationSettings>
A point to note, if you are doing something similar for an app.config (as opposed to web.config) you will need to install an addon like SlowCheetah.

C# WPF app won't compile when I try to use newly added app settings

A WPF app I've written will no longer compile when I try to use a recently added app setting in my code behind. I can see the setting in the settings designer and in the app config, and will compile if I comment out a reference to the setting.
The new setting is intended to store a date that informs it when to show a balloon tip if minimized. It appears any newly added setting breaks the build, regardless of what type it is.
Is there a step to adding new settings I'm not aware of?
Here's what it looks like:
//designer, pretty much the same as all the other declarations:
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public global::System.DateTime BaloonLastSeen {
get {
return ((global::System.DateTime)(this["BaloonLastSeen"]));
}
set {
this["BaloonLastSeen"] = value;
}
}
<!-- app.config: -->
<userSettings>
<MyNS.MyApp>
<setting name="WindowState" serializeAs="String">
<value>-1</value>
</setting>
<setting name="BaloonLastSeen" serializeAs="String">
<value />
</setting>
</MyNS.MyApp>
</userSettings>
//and finally, my attempt to use it in code-behind:
System.DateTime baloon = Properties.Settings.Default.BaloonLastSeen;
Calls to other properties through Properties.Settings.Default work just fine, it's only recently added ones it seems to be tripping over. I've tried cleaning and rebuilding, and even restarting Visual Studio, but it doesn't seem to help.
One other piece of information is that an attempt to call this property breaks intellisense. After the failed attempt to build, VS will no longer detect types or member names as I'm typing until I restart.
Here's what the compiler says is wrong:
Error 31 'MyNS.MyApp.Properties.Settings' does not contain a definition for 'BaloonLastSeen' and no extension method 'BaloonLastSeen' accepting a first argument of type 'MyNS.MyApp.Properties.Settings' could be found (are you missing a using directive or an assembly reference?)
What have I wrought!?
Whilst I'm grasping at straws, the only aspect which looks slightly out-of-kilter to me are the MyNS.MyApp tags in the app.config which I believe should be MyNS.MyApp.Properties.Settings e.g.
<!-- app.config: -->
<userSettings>
<MyNS.MyApp.Properties.Settings>
<setting name="WindowState" serializeAs="String">
<value>-1</value>
</setting>
<setting name="BaloonLastSeen" serializeAs="String">
<value />
</setting>
</MyNS.MyApp.Properties.Settings>
</userSettings>

Unable to load settings file. It might be corrupted or contain invalid XML or contain duplicate identifiers

I'm trying to open my project Settings XMl
in order to add some configurable pair to it
but I get this error:
Unable to load settings file. It might be corrupted or contain invalid XML or contain duplicate identifiers.
However, my XML is very thin:
<?xml version='1.0' encoding='utf-8'?>
<SettingsFile xmlns="http://schemas.microsoft.com/VisualStudio/2004/01/settings" CurrentProfile="(Default)" GeneratedClassNamespace="Conduit.Mam.MaMDBEntityFramework.Properties" GeneratedClassAppName="Settings">
<Profiles />
<Settings>
<Setting AppName="SavedSuccessfullyInDB" Type="System.String" Scope="Application">
<Value Profile="(Default)">The Test saved in DB successfully</Value>
</Setting>
</Settings>
</SettingsFile>
I also had this error ("Unable to load settings file. It might be corrupted or contain invalid XML or contain duplicate identifiers.") which was also the result of resharper refactoring. After a little research, this was my solution:
Close Visual Studio
Navigate to the projects Properties directory
Delete Settings.settings and Settings.Designer.cs
Start Visual Studio and open your project
Add a new Settings (Properties -> Settings)
The beauty about this approach is that Visual Studio will read your app/web.config and notice that you already have entries and will automatically add those key/values for you.
The attribute for "SettingsFile" node should be "GeneratedClassName" not "GeneratedClassAppName". Likewise the attribute "AppName" on "Setting" node should be "Name".
In my case I think the cause was Resharper being too aggressive refactoring.
Your XML declaration is using single quotes. I thought it needed to be double quotes. Might be worth a try.
This simple case sensitivity issue in my app.config caused the issue for me
<setting Name="BlankPrescriberNoWhenWelshFormInGroup" serializeAs="String">
<value>2</value>
</setting>
this needed to be 'name' instead of 'Name'
<setting name="BlankPrescriberNoWhenWelshFormInGroup" serializeAs="String">
<value>2</value>
</setting>
However note I've also had this before when I typed a capital 'S' for
<Setting name="value" serializeAs="String">
in my app.config rather than a lower case 's' as in
<setting name="value" serializeAs="String">
so case sensitivity can get you here watch out! And another to watch out for and uppercase 'V' for
<Value>2</Value>
when it really only likes 'v' for
<value>2</value>

How to read name-value attributes from an app.config file?

I am able to read the key-value attributes from the app.config file by using the following syntax.
System.Configuration.ConfigurationManager.AppSettings["ConfigurationFile"]
I want to read the name-value attributes from the app.config file which are defined under the following schema.
<applicationsettings>
<Host.Properties.Settings>
<setting name="Path" serializeAs="String">
<value>F:\PATH\</value>
</setting>
<Host.Properties.Settings>
</applicationSettings>
</configuration>
What is the correct solution?
System.Configuration.ConfigurationManager.AppSettings["Path"]
or this:
Host.Properties.Settings.Default.Path
should work.

Categories

Resources