Does Monodevelop support configuration files? - c#

I added a file app.config to a C# mono project.
Inside the project I used
foreach (string key in ConfigurationManager.AppSettings)
{
string value = ConfigurationManager.AppSettings[key];
Console.WriteLine("Key: {0}, Value: {1}", key, value);
}
The config file looks like this
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="Key1" value="Kevin" />
<add key="Key2" value="150" />
<add key="Key3" value="Rice" />
</appSettings>
</configuration>
No keys are detected. How can I read the config values?

This answer comes awfully late, but for anybody that comes across this, yes, mono does support configuration files. You can use the ConfigurationManager method discussed above or you can even create your own custom settings section in the app.config file and manipulate it through a class which derives from ApplicationSettingsBase. In my opinion, this is a much more natural way of handling the app.config file because you work with a class and strongly typed properties, rather than accessing strings out of an array with the way that ConfigurationManager does it. Creating a class for app settings is pretty easy, too. Here's the MSDN page explaining how to create the class: http://msdn.microsoft.com/en-us/library/system.configuration.applicationsettingsbase.aspx
The only caveat to be aware of with Mono is that the .NET Framework allows UserScopedSettings to be defined in the app.config file (to provide a default value) but Mono will throw exceptions if you do that. The workaround for that is to leave UserScopedSettings out of the app.config file and just define the default value for a property in code. This isn't a perfect workaround because it doesn't give a way to change the default value outside of the code, but this will be sufficient in most cases.

Related

Use App.config with a Custom Section shared between two different projects

Scenario
I have developed a windows service which is configured by its App.config file.
This file contains the information in the standard sections (connectionStrings, appSettings) and in a custom section (sourceTabSection).
In the windows service project i have 4 classes which allow me to get/set the config file content. They are based on what is written in this article: Writing a Custom ConfigurationSection to handle a Collection and i have no problems on using them inside my service.
The problems come when i try to get/set the custom section (with the standard sections i don't have any problems) of the App.config, belong to the Windows service, using another application that in my case is a Windows Form that allows users to view/set parameters for the windows service.
The Windows Form application has the same pack of 4 classes used by the service, in order to handle the App.config.
When the code that get/set custom parameters of Windows Service is excuted on the Windows Form app I get the following error message:
{"An error occurred creating the configuration section handler for sourceTabSection: Could not load type 'DataReportingService.CustomSourceTabSection.SourceTabSection' from assembly 'DataReportingService'."}
The problem is due to this following line of code in the App.config
<section name="sourceTabSection" type="DataReportingService.CustomSourceTabSection.SourceTabSection, DataReportingService"/>
The attribute type of the tag shown above has the following meaning (it's explained here: section Element for configSections):
type="Fully qualified class name, assembly file name, version, culture, public key token"
Following what is written on Writing a Custom ConfigurationSection to handle a Collection article I defined only the first two parameter (Fully qualified class name, assembly file name) of the attribute type. Microsoft documentation (no more maintained) doesn't specify that the other parameters can be not defined, but the example that I followed and others use this approach.
However the point is this phrase about the type attribute on Microsoft documentation:
The assembly file must be located in the same application directory
So, due to this bond, seems to be impossible to handle custom section of an application A from another application B (which has another assembly) using this approach.
So do you know how could I solve this problem?
Windows service - App.config
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="sourceTabSection" type="DataReportingService.CustomSourceTabSection.SourceTabSection, DataReportingService"/>
</configSections>
<!-- *** CUSTOM SECTION *** -->
<sourceTabSection>
<Tables>
<sourceTab name="TEST" db_conn_str="****"
keep_time="1" scan_frequency_process_rows="1"
scan_frequency_delete_processed_rows="1" />
<sourceTab name="TEST_2" db_conn_str="****"
keep_time="1" scan_frequency_process_rows="1"
scan_frequency_delete_processed_rows="1" />
</Tables>
</sourceTabSection>
<!-- *** STANDARD SECTIONS *** -->
<connectionStrings>
<add name="DB_Target" connectionString="Data Source=192.168.2.2;Initial Catalog=PlantDompe;Persist Security Info=True;User ID=sa;Password=Gf6swML0MXiqbOFuvRDvdg==;"
providerName="System.Data.SqlClient" />
</connectionStrings>
<appSettings>
<add key="TAB_ALARMS_TARGET" value="AlarmsProcess" />
<add key="TAB_VALUE_TARGET" value="USER_CHANGES" />
<add key="TAB_LOGINS_TARGET" value="USER_LOGONS" />
<add key="LOG_DIR" value="C:/Users/rossi/Documents/Visual Studio 2017/Projects/DRS_proj/Log/" />
</appSettings>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.2" />
</startup>
<system.web>
<trust level="Full" />
<webControls clientScriptsLocation="/aspnet_client/{0}/{1}/" />
</system.web>
</configuration>
Ugly solution
If found a work around to this problem by performing the two following steps on the Windows Form application that need to view/set the parameters (custom and no custom) inside the App.config of the Windows Service:
Using visual studio i go to Solution Properties > Application tab, and I change the following values
Assembly name = DataReportingService
Default namespace = DataReportingService
Note: DataReportingService is the name of the window service with the App.config file
Find and replace all the references to old namespace with the new one
In this way I can handle the custom section of the App.config, but honestly it's a really ugly solution and I think that there should be something better.
Thanks #Alex Paven, your comment has helped me to solve this problem!
Here below there are the detailed steps of what I've done:
I moved the 4 classes which handles the Windows service config file in a Class Library project (.NET Framework) called: DRS_CustomConfig.
I changed the namespace of the 4 classes with the following value: DRS_CustomConfig and then I compiled the project.
I linked the external library both in the Windows service project and in Windows Form application
For each class of both projects which need to use the classes contained in the external library I inserted the following piece of code:
using DRS_CustomConfig;
In the App.config of the Windows service I changed the section element as follows:
Old
<section name="sourceTabSection"
type="DataReportingService.CustomSourceTabSection.SourceTabSection,
DataReportingService"/>
New
<section name="sourceTabSection"
type="DRS_CustomConfig.SourceTabSection, DRS_CustomConfig"/>

AppSettings in App or Web Config Using a Linked File

I'm trying to reference some common config settings between a Windows Service and an ASP.NET MVC website. I am doing this by using the file attribute on appSettings in either the App.config or Web.config (respectively). The file (named common.config) that is being referenced is a linked file in a separate project in the same solution. That common.config is set to Content with Copy Always in both projects.
This stack answer to a similiar question seems to suggest at least for configSource this solution would work. I don't want configSource though as I only want a handful of the properties to be common amongst the two projects. Update: I just tried this, and the configSource also doesn't work. It can't find the config file. This leads me to believe the common.config is not treated as content with copy always.
Example App.config
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings file="common.config">
<add key="NotCommonKey" value="1"/>
</appSettings>
</configuration>
Example Web.config
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<appSettings file="common.config">
<add key="NotCommonKey2" value="2" />
</appSettings>
</configuration>
Example common.config (Content -> Copy Always)
<appSettings>
<add key="CommonKey" value="1" />
</appSettings>
I am using ConfigurationManager / WebConfigurationManager reading from the AppSettings property.
Any ideas why when the common.config is a linked file, it's AppSettings values are not used and when it is not linked it works as normal?
Thanks!
In the Web.Config you must add "bin/" (se example below).
By default the web.config is NOT copied into the bin folder but the file common.config is, therefore you must add the path from web.config. In a non-web project the default behavior is that the App.config is copied to the bin folder with name MyProgram.exe.config and is in the same directory as common.config.
<appSettings file="bin/common.config">
The idea of using "bin/..." is good but leads to an error saying that "/" is an invalid character in the resulting virtual path.
The proper solution is tu use "bin...".
Cheers
I use this to access another .exe's config file, not sure whether it will work with a MVC project, but this might get you closer:
string proj2Exe = #"C:\projects\proj2\bin\Debug\proj2.exe";
Configuration proj2Config = ConfigurationManager.OpenExeConfiguration(proj2Exe);
string mysetting = proj2Config .AppSettings.Settings["ThatSetting"].Value;

Can I store settings in a settings.config file in ASP.NET MVC?

I'm using .NET MVC
I have about 10 properties I want to store in a configuration file (.config etc.), related to environment/deployment stuff, + other things for quick changes without doing dLL deploys.
I'm using Team foundation service for CI builds etc, and my web.config is obviously under version-contrl.
What I'd like to do is have a settings.config (that's not in version control) file to store these, am I able to do this?
Or does it need to be in web.config?
To answer the title question, yes you can store settings in a separate config file, to do so you need to define the configSource property of appSettings element
E.g.
<appSettings configSource="settings.config" />
and in the settings.config file
<?xml version="1.0" encoding="UTF-8"?>
<appSettings>
<add key="settingKey" value="environmentValue" />
</appSettings>
However, for the sake of environment specific settings, you may want to look at config transforms. Setting up a transform config for each environment then deploying to that environment with the specified build configuration.
E.g. Web.Dev.config (provided you have setup a 'Dev' build configuration)
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
<appSettings>
<add key="settingKey"
value="devEnvironmentValue"
xdt:Transform="SetAttributes" xdt:Locator="Match(key)"/>
</appSettings>
</configuration>
More details of build configuration and config transforms here: http://msdn.microsoft.com/en-us/library/dd465318(v=vs.100).aspx
Or you could take advantage of TFS features and parameterize the environment variables, I don't have a lot of experience with this, but the following should help: http://ig.obsglobal.com/2013/02/tfs-and-continuous-deployment-part-4-parameterized-deployments/

Hiding private details from open source projects

I have a .net github project that is basically a wrapper around a web API. In the test project, I am calling to the API using an API key. I need to keep this key private, how do I accomplish this in a visual studio project?
In some other projects, like python, I can have git ignore the file (config.py) and use something like config.example.py. But in visual studio's case, the project will not compile because of the missing file Config.cs. What is the proper way to solve this? I'm thinking of using this same method of ignoring the file and have them execute a build script that should rename Config.example.cs to Config.cs?
This is the perfect for .config files. Depending on whether its a web or console application, you will have a web.config or app.config file in your project.
You can use the appSettings section to store your API key.
To make things even easier, you can actually have this section read from another file, ie: specialappsettings.config and then just ignore that single file from your repository.
Modify your web.config (or app.config):
<configuration>
<appSettings file="specialappsettings.config">
</appSettings>
<system.web>
<!-- standard web settings go here -->
</system.web>
</configuration>
Create a new specialappsettings.config file:
<appSettings>
<add key="APIKey" value="YourApiKeyValue" />
<add key="AnotherKey" value="AnotherValue" />
</appSettings>
This can be accessed in your code via:
var apiKey = ConfigurationManager.AppSettings["APIKey"];
Notes:
You can keep your settings within the original web.config file as
well but this lets you ignore just the specific settings file from
your git repository without affecting the rest of the project's
necessary configuration details.
The same "key" can be saved in
either file however the external file will override the original
web.config file value.
You are probably looking for the App.config file for a project. It will be copied to <application>.exe.config when you compile it. Users can edit that config file as needed.
In that config file, you can add your API keys:
<configuration>
<appSettings>
<add key="APIKey" value="12345"/>
</appSettings>
</configuration>
Then you can access it from your code using ConfigurationManager.AppSettings:
string apiKey = ConfigurationManager.AppSettings["APIKey"];
One option is to use .config files instead of having secret keys hardcoded in sources.
More info Using Settings in C# and step-by-step guide
<configuration>
<appSettings>
<add key="SecretKey" value="0" />
</appSettings>
</configuration>
var secretKey = ConfigurationManager.AppSettings.Get("SecretKey");
Perhaps you can store the key outside of the Config.cs file and load it at run time.
Bonus, other people using your code won't have to recompile the project to change to their API key.

How to manage configuration from several class libraries in .NET?

I'm looking for a best practice for managing configuration on a project with multiple class libraries. I'm looking for maintainability and ease of implementation.
Let's assume a simple example: A console project with 2 class libraries. Each class library need their own configuration settings, and there are some settings that are common to several.
Class Library 1
CL1Setting
GlobalSetting
Class Library 2
CL2Setting
GlobalSetting
A first approach would be to create all the necessary settings on the main project:
GlobalSetting
CL1Setting
CL2Setting
But this present several problems:
It can get cluttered fast if there are lots of settings.
It is not easy to maintain: How to know which settings are needed for each library?
It can create naming conflicts. What if CL1Setting and CL2Setting would have the same name?
An ideal solution for me (although I'm afraid not possible) would be having custom library settings in separate files, or at least different sections. Something like this:
<configuration>
<appSettings>
<add key="globalSetting" value="cl1Global"/>
</appSettings>
<appSettings file="CL1.config" >
<add key="cl1setting" value="cl1setting1"/>
</appSettings>
<appSettings file="CL2.config">
<add key="cl2setting" value="cl2setting2"/>
</appSettings>
</configuration>
Any suggestions?
EDIT
As Ken Henderson suggests, config sections are another approach. However, although with their own advantages, they require coding, so I don't find it ideal though. (This will probably end up being the best option though)
EDIT 2
joseph.ferris suggestion to look at Configuration Section Designer on CodePlex (csd.codeplex.com) was good. I found further problems, reported here (in case some is interested) http://csd.codeplex.com/discussions/278354
I think what you are looking for is a custom configuration section instead of appSettings. This is commonly used by 3rd party libraries (log4net is the first that comes to mind) to provide a way to configure their settings via your app/web config file. Note that this also provides the basis for how MS creates their configuration sections.
I've successfully used this in several different projects including one that included the ability to add new implementations of algorithms to an analysis program.
You could use your own naming convention to reduce the risk of appSettings naming collisions. And/or create custom configuration sections.
<configuration>
<appSettings>
<add key="Shared.Setting1" value="..."/>
<add key="CL1.setting1" value="..."/>
<add key="CL1.setting2" value="..."/>
<add key="CL2.setting1" value="..."/>
<add key="CL2.setting2" value="..."/>
</appSettings>
</configuration>
I'm not sure an administrator would need to know which setting belongs to which library, but a naming convention helps promote a logical grouping - I would use prefixes that are meaningful to an administrator, rather than say a class library name - e.g. "Logging." for appSettings related to logging.
Microsoft uses colon as a delimiter for namespace in some of their code.
Example their Azure samples. Here they use ida: as prefix.
ConfigurationManager.AppSettings["ida:ClientId"];
In Microsoft ASP.NET in the Web.config file you can see:
<appSettings>
<add key="webpages:Enabled" value="false" />
</appSettings>

Categories