Recently, I was working with a client who has just started with the adoption of cloud technologies and they have a long roadmap before they reach Kubernetes or a container-based development approach.
There were a few batch jobs that I was supposed to write, that would perform some push/pull from the existing LOBs to Azure. This was to minimize my efforts so that I don't have to maintain different configs for each region like DEV, QA, and PROD. I wrote a custom config section to be able to slice the different app settings based on the region. Here are some details and codes.
Custom Config Section Entry in the App.Config
- <configSections>
- <section name ="serverConfiguration" type ="ServerConfiguration.ServerSettingHandler, ServerConfiguration"/>
- </configSections>
- <serverConfiguration>
- <server name ="Dev">
- <settings>
- <add key ="ck" value ="ckDEV" />
- <add key ="abc" value ="mlDEV" />
- <add key ="cde" value ="p3DEV" />
- <add key ="efg" value ="oppDEV" />
- </settings>
- </server>
- <server name ="QA">
- <settings>
- <add key ="ck" value ="ckQA" />
- <add key ="abc" value ="mlQA" />
- <add key ="cde" value ="p3QA" />
- <add key ="efg" value ="oppQA" />
- </settings>
- </server>
- <server name ="PRD">
- <settings>
- <add key ="ck" value ="ckPRD" />
- <add key ="abc" value ="mlPRD" />
- <add key ="cde" value ="p3PRD" />
- <add key ="efg" value ="oppPRD" />
- </settings>
- </server>
- </serverConfiguration>
Fetch the Specific Setting Value
- var server = ServerConfigManager.GetServerSetting("dev","ck");
- Console.WriteLine(server);
- // Prints
- // ckDEV
Fetch the All Setting Value
Other Wrappers
If you decide to name the server with the Machine name, then you can also make use of the below method for fetching the details.
Attached code has all the source files.
- var server = ServerConfigManager.GetServer("Dev");
- foreach (KeyValuePair<string, string> setting in server?.Settings)
- {
- Console.WriteLine($"Key : {setting.Key} Value : {setting.Value}");
- }
- // Prints
- /*
- Key : ck Value : ckDEV
- Key : abc Value : mlDEV
- Key : cde Value : p3DEV
- Key : efg Value : oppDEV
- */
If you decide to name the server with the Machine name, then you can also make use of the below method for fetching the details.
- // The GetCurrentServer uses the Environment.MachineName to look in the Config sections and Fetches the value.
- var server = ServerConfigManager.GetCurrentServer()
I know this has been available in C# for almost a decade or so, but this blog may be a good read to refresh your knowledge on this old technique.
Gajendra JangidPosted Mar 28, 2018, 6:52 AM
Nice blog..................
Sameer ShaikPosted Mar 22, 2018, 7:50 AM
You selected a good topic, i think u can write a better explanation for this.
SandyPosted Mar 22, 2018, 7:22 AM
What is the role of config.debug and config.release and also if we have some keys in application settings then how can I maintain configuration?