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"/>
Related
I have had to add a monoSettings section to my Web.config file as I need to support colons in the url (similar to this question: ASP.NET special characters in URL (colon) not working even with requestPathInvalidCharacters="").
Now when I run my web-api service in visual studio (which I do for ad-hoc testing) it gives an error:
"The configuration section 'monoSettings' cannot be read because it is missing a section declaration"
I'm just wondering what is the best way to support this config in my Mono service without impacting being able to run in on Windows? Can I just flag it as optional or unimportant so that it won't fail when trying to read the config? Or is it just better to have a different build configuration for Mono - but I'd then have to maintain two versions of web.config with just this one minor difference.
I resolved this issue by adding a configSection to my Web.config as follows:
<configuration>
<configSections>
<sectionGroup name="system.web">
<section name="monoSettings" type="DataSetSectionHandler,SectionHandlers" />
</sectionGroup>
</configSections>
<system.web>
<monoSettings verificationCompatibility="1" />
<httpRuntime requestPathInvalidCharacters="<,>,*,%,&,\,?" />
</system.web>
</configuration>
My app.config.
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
</configSections>
<Something SettingsLocation="D:\test\test\file.json" />
<Something />
</configuration>
I need to update SettingsLocation programatically.
I found this some answers, but it is not clear to me.
Thanks fo help.
Each application has it’s own configuration file, be it a windows based application or web based.
This application configuration file defines information which can be used by application to make decisions, to load some other information or may contain the custom configuration which can be empowered to do anything.
There can also be scenarios where an application may want to change\modify the existing setting in the application configuration file and those changes should not only take effect immediately but should also be persisted.
Possible solution is already shown here
I have an app.config file in Winforms application that holds a connection string. This is to go out to multiple tenant (clients) as a separate file. These clients have different database sources. This config file also holds other version information such as EF, Telerik reporting etc...
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.1" />
and
<section name="Telerik.Reporting"
type="Telerik.Reporting.Configuration.ReportingConfigurationSection, Telerik.Reporting, Version=8.1.14.804, Culture=neutral, PublicKeyToken=a9d7983dfcc261be"
allowLocation="true" allowDefinition="Everywhere" />
The problem I have is when we have an updated version of EF or Telerik reporting with our application and we deploy (auto-deploy) this we need to overwrite the app.config file in the client directory to update the versions in the client config file. They then lose their connection setting and I do not want the client to have to go and re-enter it.
My question:
Is there a best practice to overcome this issue? Should I hold the connection string somewhere else?
Yep, the best thing to do is to move your connection strings section to an another config file and reference that file within your app.config.
For example create a new file called connectionStrings.config:
<connectionStrings>
<add name="Default" connectionString="[client_connection_string] "/>
</connectionStrings>
And in your app.config file:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings configSource="connectionStrings.config" />
</configuration>
A full example can be found here.
Use an external configuration file that is referenced from the application config file. E.g. include this section in your config file.
<configuration>
<connectionStrings configSource="connections.config"/>
</configuration>
The external config file is described http://msdn.microsoft.com/en-us/library/ms254494(v=vs.110).aspx
Note that storing connection settings in plaintext on a workstation is still a bad idea.
Using Windows registry for stuff like this is a definite no-no these days.
you can try to hold all connection data that you need in separate xml file so it dont get overwrite when you preform a deploy of updated version.
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.
in a small c# project, I'm trying to create a simple custom configsection.
I followed the instructions in CodeProject: Unraveling the Mysteries of .NET 2.0 Configuration and everything work nicely... apart from the fact that I don't get xsd validation and intellisense on the config.
My config is shown below.
<configuration>
<configSections>
<section name="pizza" type="TestConfig.Configuration.PizzaConfigurationSection, TestConfig.Configuration"/>
</configSections>
<pizza name="Margherita" timeToCook="00:10:00" price="15.12">
<cook firstName="Nicola" lastName="Carrer" rank="7" />
<toppings>
<add name="Mozzarella" percentage="0.6" />
<add name="Tomato sauce" percentage="0.28" />
<add name="Oregano" percentage="0.02" />
<add name="Mushrooms" percentage="0.1" />
</toppings>
</pizza>
</configuration>
On this article (XSDExtractor) I found a tool that creates an xsd file for the configsection. It works fine, i.e. it provides intellisense and validation, for the main attributes (e.g. "price") and the single elements ("cook"). However I could not make it work for the collections (the "toppings").
My questions:
Is there any other tool that provides xsd generation of ConfigurationSection classes?
Has someone run XSDExtractor successfully on a ConfigurationSection with a collection property?
Thanks a lot,
Nicola
I haven't used XSDExtractor but one tool which I strongly recommend is Configuration Section Designer. It's a Visual Studio add-in that allows you to graphically design .NET Configuration Sections and automatically generates all the required code and a schema definition (XSD) for them.