Configure the connection string for multiple windows service - c#

I am having multiple windows service in my current project. And all are having different app.config files & connection string is defined in the same config file.
Now I want to update the app.config in such a way that all the windows services share the connection string from the single file.
My directory structure is as given below :
RootFolder ->
Service A
Service B
I have tried using below 2 approaches but didn't work out :
AppSettings's "File" attribute. - Is there anything can be done that
I can assign the few key value's in AppSettings section & I can use
those in connectionstring section.
ConnectionString's "ConfigSource" Attribute - This attribute contains only relative path so it is not working for me.
Thank you so much in advance. Let me know if any further information is required.

One method can be using a symbolic link for the common app.config file.
So you put the common app.config file containing the connectionStrings section somewhere accessible by all services and in your services' installation directories you create a symbolic link pointing to that file using mklink
Such as:
mklink common.app.config.link "C:\Root\App.config"
And in the app.config of the Windows services you point to that link:
<connectionStrings configSource="common.app.config.link">
</connectionStrings>
It requires a bit maintenance but I guess it can be automated as well if you put mklink command in a script.
Hope this helps.
UPDATE:
Common app.config : X:\common.app.config
Project 1 Installation Path: X:\Project1\
Project 2 Installation Path: X:\Project2\
In X:\Project1\ create the link
mklink common.app.config X:\common.app.config
In X:\Project1\App.config file update the configSource
So bottomline is in configSource you give the path of link which is pointing to the actual file. If you're only providing the name of the link make sure it's in the same folder as you exe file, as shown in the image

Related

Asssembly with EF context class connection string in an assembly

Hope you can help with this one, although so for here does seem to b a resolution.
I have a class library which connects to a SQL Server database using an EF context class with a connection string in the app.config file.
I then reference this dll in an ASP.NET app but have to add the connection sting again in the web.config file
I would have though by referencing the dll and thus the connection string, I would not require to add the connection string again.
Perhaps I am missing something or has anyone else found a resolution to this ?
The connection string is read from the executables app.config (i.e. windows forms/WPF/console applications). For web applications the connection string is taken from the web.config file of the startup project (i.e. where the global.aspx.cs) is located.
You cannot use the app.config from your model DLL directly. You have to put the connection strings in the "main" projects.
What might help is some kind of scripting, but that's up to you.
You could try to use the configSource attribute and configure and external file:
<ConnectionString configSource="shared.config" />
The content of the file replaces the content of the element though. Another thing is that you need to include the file in your web app project and toggle copy to output.
And another warning:
the external connection strings file must be in the same directory as
the root web.config file, so you'll have to take precautions to ensure
you don't check it into your source repository.
More about that and best practices about deploying sensitive data can be found here:
http://www.asp.net/identity/overview/features-api/best-practices-for-deploying-passwords-and-other-sensitive-data-to-aspnet-and-azure#con

How to ensure ConfigurationManager points to correct App.config

Recently created a new class library project and added a App.config file to it. App.config file contains DB connection string. But the current code
ConfigurationManager.ConnectionStrings["DBConnectionName"] gives me "null" .
But ConfigurationManager.ConnectionStrings[0] gives me result with name "LocalSqlServer" . But my App.config does not have any entry like this.
I don't see any other config files in my project . Then why this is happening ?
How could i ensure am pointing to correct App.Config?
App.Config and other config files are read from the entry point of the program. Thus, if it is an application, the app.config file stored in the windows application project is read.
LocalSqlServer is the default SQL server when no other connection string is defined. This is the reason why it exists inside ConnectionStrings property.
Please add the connection string to App.config of your main application, the executable. Alternatively, if you want to define your own config file then make use of ConfigurationManager.OpenExeConfiguration Method.
More details in following link:
http://msdn.microsoft.com/en-us/library/ms224437.aspx

What is App.config in C#.NET? How to use it?

I have done a project in C#.NET where my database file is an Excel workbook. Since the location of the connection string is hard coded in my coding, there is no problem for installing it in my system, but for other systems there is.
Is there a way to prompt the user to set a path once after the setup of the application is completed?
The answers I got was "Use App.Config"... can anyone tell what is this App.config and how to use it in my context here?
At its simplest, the app.config is an XML file with many predefined configuration sections available and support for custom configuration sections. A "configuration section" is a snippet of XML with a schema meant to store some type of information.
Overview (MSDN)
Connection String Configuration (MSDN)
Settings can be configured using built-in configuration sections such as connectionStrings or appSettings. You can add your own custom configuration sections; this is an advanced topic, but very powerful for building strongly-typed configuration files.
Web applications typically have a web.config, while Windows GUI/service applications have an app.config file.
Application-level config files inherit settings from global configuration files like machine.config. Web also applications inherit settings from applicationHost.config.
Reading from the App.Config
Connection strings have a predefined schema that you can use. Note that this small snippet is actually a valid app.config (or web.config) file:
<?xml version="1.0"?>
<configuration>
<connectionStrings>
<add name="MyKey"
connectionString="Data Source=localhost;Initial Catalog=ABC;"
providerName="System.Data.SqlClient"/>
</connectionStrings>
</configuration>
Once you have defined your app.config, you can read it in code using the ConfigurationManager class. Don't be intimidated by the verbose MSDN examples; it's actually quite simple.
string connectionString = ConfigurationManager.ConnectionStrings["MyKey"].ConnectionString;
Writing to the App.Config
Frequently changing the *.config files is usually not a good idea, but it sounds like you only want to perform one-time setup.
See: Change connection string & reload app.config at run time which describes how to update the connectionStrings section of the *.config file at runtime.
Note that ideally you would perform such configuration changes from a simple installer.
Location of the App.Config at Runtime
Q: Suppose I manually change some <value> in app.config, save it and then close it. Now when I go to my bin folder and launch the .exe file from here, why doesn't it reflect the applied changes?
A: When you compile an application, its app.config is copied to the bin directory1 with a name that matches your exe. For example, if your exe was named "test.exe", there should be a ("text.exe.config" in .net framework) or ("text.dll.config" in .net core) in your bin directory. You can change the configuration without a recompile, but you will need to edit the config file that was created at compile time, not the original app.config.
1: Note that web.config files are not moved, but instead stay in the same location at compile and deployment time. One exception to this is when a web.config is transformed.
.NET Core
New configuration options were introduced with .NET Core and continue with the unified .NET (version 5+). The way that *.config files works hasn't fundamentally changed, but developers are free to choose new, more flexible configuration paradigms.
As with .NET Framework configuration .NET Core can get quite complex, but implementation can be as simple as a few lines of configuration with a few lines of c# to read it.
Configuration in ASP.NET Core
Configuration in .NET Core
Simply, App.config is an XML based file format that holds the Application Level Configurations.
Example:
<?xml version="1.0"?>
<configuration>
<appSettings>
<add key="key" value="test" />
</appSettings>
</configuration>
You can access the configurations by using ConfigurationManager as shown in the piece of code snippet below:
var value = System.Configuration.ConfigurationManager.AppSettings["key"];
// value is now "test"
Note: ConfigurationSettings is obsolete method to retrieve configuration information.
var value = System.Configuration.ConfigurationSettings.AppSettings["key"];
App.Config is an XML file that is used as a configuration file for your application. In other words, you store inside it any setting that you may want to change without having to change code (and recompiling). It is often used to store connection strings.
See this MSDN article on how to do that.
Just to add something I was missing from all the answers - even if it seems to be silly and obvious as soon as you know:
The file has to be named "App.config" or "app.config" and can be located in your project at the same level as e.g. Program.cs.
I do not know if other locations are possible, other names (like application.conf, as suggested in the ODP.net documentation) did not work for me.
PS. I started with Visual Studio Code and created a new project with "dotnet new". No configuration file is created in this case, I am sure there are other cases.
PPS. You may need to add a nuget package to be able to read the config file, in case of .NET CORE it would be "dotnet add package System.Configuration.ConfigurationManager --version 4.5.0"
You can access keys in the App.Config using:
ConfigurationSettings.AppSettings["KeyName"]
Take alook at this Thread
Just adding one more point
Using app.config some how you can control application access, you want apply particular change to entire application use app config file and you can access the settings like below
ConfigurationSettings.AppSettings["Key"]
Application settings enable you to store application information dynamically. Settings allow you to store information on the client computer that shouldn't be included in the application code (for example a connection string), user preferences, and other information you need at runtime.
To add an application configuration file to a C# project:
In Solution Explorer, right-click the project node, and then select Add > New Item.
The Add New Item dialog box appears.
Expand Installed > Visual C# Items.
In the middle pane, select the Application Configuration File template.
Select the Add button.
A file named App.config is added to your project.
take a look at this article

Can multiple C# apps use one App.Config file?

We have many C# console apps that run on scheduled tasks. All of these apps have their own config file, which contain settings like our smtp server. If our smtp server ever changed, we would have to manually go into each config file and change it. Can multiple apps look at 1 config file on the C: drive, or is that considered bad practice? Using the database to store values is a no no.
You can point to external config files inside your application's configuration file like the following, and have all your applications use the same set of settings from a single file:
<appSettings file="c:\CommonSettings.config">
<add key="MyKey" value="12"/>
</appSettings>
For more information, you can read following articles:
AppSettings can Reference an External Config File
How to share custom application configuration settings across projects in .NET
It is not directly possible to share one application configuration file because the .config filename needs to match the executable name (so for example.exe it would be example.exe.config).
It makes sense to have separate values for the different applications, as they are separate applications.
If there are configuration sections that you do want to share, you can use the configSource attribute to point to a file. The appSettings section also has a specific file attribute that you can use in the same manner.
If there are certain configuration values that are shared across all applications, you can consider placing them in the machine.config file for the version of the framework you are using.
Can you use custom xml files to store configuration data ?
There's no necessity to use app.config.
Using Cinchoo framework you can achieve this, by simply creating custom configuration object and use it all the console applications. All of them will read from same configuration file. For more information, please visit http://www.cinchoo.com

Multiple App.Config Files in .NET Class library project

I am creating one class library project.
Now by default I have one App.Config file so that I am putting all environment specific data in that Config file.
Now based on the Environment (whether Dev / Test / Production), I am planning to have three App.Config files in VS 2010 such as
App.Dev.Config
App.Test.Config
App.Prod.Config
Wondering how would the application know which config file to use.
Anyone implemented this scenario. Any Code samples / Articles would be helpful.
Thanks
The app will use the config file named YourExcecutable.exe.config which is by default the file App.config included in your (executable) project.
Note, that .NET only loads one config file for the whole application. You cannot use multiple configuration files (i.e. one per library project) without coding.
Option: You can use postbuild events and different solution configurations to copy one or another App.Config file to the output folder
Option: You can use the ConfigurationManager Class to load an alternate config file by code.
Loading a different application configuration file at run time can be done using the concept of mapped configuration file. To start with, you need to add reference to System.Configuration.dll in your project.
Set the value of Copy to Output Directory property to Copy if newer (Refer screenshot). This has to be done only for non-default configuration files e.g. App1.config, App2.config, etc. Leave the default configuration file namely App.config as it is . Due to this change, all the non-default application configuration files will be available in the project output directory (\bin\debug) when the project is built. Default value of this property is Do not copy.
Here is the code snippet on how to read configuration data from non-default configuration files:
ExeConfigurationFileMap configFileMap = new ExeConfigurationFileMap();
configFileMap.ExeConfigFilename = "App1.config"; // app1.config should be present in root directory from where application exe is kicked off
// Get the mapped configuration file
var config = ConfigurationManager.OpenMappedExeConfiguration(configFileMap, ConfigurationUserLevel.None);
//get the relevant section from the config object
AppSettingsSection section = (AppSettingsSection)config.GetSection("appSettings");
//get key value pair
var keyValueConfigElement = section.Settings["appSettingsKey"];
var appSettingsValue = keyValueConfigElement.Value;
If you have multiple application (aka app) configuration files then you can keep a setting in default App.config file with the help of which you can make a decision at run time about which non-default configuration file to load e.g. App1.config
Note: Now look at below code:
ConfigurationManager.AppSettings["DeployEnv"]
This code will still read the data from the default App.config file. This behavior can't be changed. There is no way to prohibit the Loading of default App.config file. You have to use alternate means as discussed in this post to read the data from non-default configuration files
Now there is an even better solution: SlowCheetah - XML Transforms

Categories

Resources