ConfigurationManager.GetSection returns null - c#

Here is my app.config
<configuration>
<configSections>
<section name="procedureList" type="System.Configuration.NameValueSectionHandler, System, Version=4.0.30319, Culture=neutral, PublicKeyToken=b77a5c561934e089"/>
</configSections>
<procedureList>
<add key="NAS.spBusObjGetLineProd" value="#area='Melt Shop';#endDt=?date?;#dayonly=1;#obj='Melt Shop Business Objective" />
<add key="NAS.spBusObjGetLineProd" value="#area='Cold Mill';#endDt=?date?;#dayonly=1;#obj='Cold Mill Business Objective" />
</procedureList>
<appSettings>
<add key="Connstr" value=""/>
<add key="Userid" value=""/>
<add key="Timeout" value=""/>
</appSettings>
</configuration>
But when I call it in code, I'm getting a null back
public void samplemethod()
{
NameValueCollection nvc = ConfigurationManager.GetSection("procedureList") as NameValueCollection;
string[] keys = nvc.AllKeys;
}
I would appreciate any help pointing out what I've done wrong

Using section handlers to group settings in the configuration file
For example you can follow something like the following
private void ReadSettings()
{
NameValueCollection loc =
(NameValueCollection )ConfigurationSettings.GetConfig("procedureList");
}
MSDN ConfigurationManager.GetConfig Method

If you are testing your class you must copy the configuration to the app.config in your Test project.

using immediate window check which config file it is pointing to. in my case i had app.config which i am expecting it to read, but on using the command. ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None) it is pointing to something else like nuintrunner.exe.config as that info is loaded into bin. this help in loading the right configuration file

Related

Reading settings from app.config in .net 4.5

I've added a reference to System.Configuration. I've created App1.config in my project and populated it with the following code:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="ResistanceA" value="0.04"/>
<add key="ResistanceB" value="0.04"/>
<add key="ResistanceC" value="0.01"/>
<add key="TempBattLow" value="40"/>
<add key="TempBattHigh" value="45"/>
<add key="TempLoad" value="40"/>
</appSettings>
</configuration>
Then I try to read the values using the following code,
using System.Configuration;
string str = ConfigurationManager.AppSettings.Get("ResistanceA");
However I do not get the data. Any idea what I am doing wrong? Thanks.
Make sure the (app name here).config file actually appears in the same folder as your (app name here).exe file. Being that you called it App1.config, I'm guessing that you have more than one.
Visual Studio renames App.Config to the actual (app name here).config file during a build, not App1.config.

Get winform Webbrowsercontrol Source from app config file

Can someone please show me how to get winforms Webbrowsercontrol source from appconfig file ?.
I tried with following but it's not working
webBrowser2.Navigate = ConfigurationManager.AppSettings["dateandtime"];
and this is my how app config file look like
<?xml version="1.0"?>
<configuration>
<configSections>
</configSections>
<appSettings>
<add key="serverip" value="127.0.0.1" />
<add key="dbport" value="3306" />
<add key="defdatabase" value="waq115" />
<add key="dateandtime" value="http://free.timeanddate.com/clock/i4daxch9/n77/fs18/fcfff/tc212426/pc212426" />
</appSettings>
<startup><supportedRuntime version="v2.0.50727"/></startup>
</configuration>
Navigate() is a method not a variable, So the following line of code will not compile,
webBrowser2.Navigate = ConfigurationManager.AppSettings["dateandtime"];
You have to read the URL from the application configuration file and pass it as an argument to Navigate("URL") method as follows.
webBrowser1.Navigate(ConfigurationManager.AppSettings["dateandtime"]);

Is the config file name "quartz.config" fixed (means hard-code, cannot be changed)?

I know that Quartz.Net has several ways to loads it configuration upon startup: (from http://jvilalta.blogspot.com/2011/03/how-does-quartznet-configuration-work.html )
The hosting application’s configuration file
A file specified in an environment variable
The quartz.config file
The embedded configuration file
Notice the quartz.config file.
My question:
Is the config file name "quartz.config" fixed (means hard-code,
cannot be changed)?
If no, how can I change it? e.g. I want to read from
FinancialQuartz.config instead of quartz.config.
If no option to change the name "quartz.config". How can I specify
when to read from FinancialQuartz.config or
CalculationQuartz.config? (I have no real scenario for this
question, just wonder)
Regards,
I'm confused.
In DotNet. You can point the app.config or web.config file to your file of choice, like below.
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="quartz" type="System.Configuration.NameValueSectionHandler, System, Version=1.0.5000.0,Culture=neutral, PublicKeyToken=b77a5c561934e089" />
</sectionGroup>
</configSections>
<quartz configSource="MyQuartzSettings.config" />
And "MyQuartzSettings.config" looks something like this (one example of many)
<quartz>
<add key="quartz.plugin.jobInitializer.type" value="Quartz.Plugin.Xml.XMLSchedulingDataProcessorPlugin" />
<add key="quartz.scheduler.instanceName" value="DefaultQuartzScheduler" />
<add key="quartz.threadPool.type" value="Quartz.Simpl.SimpleThreadPool, Quartz" />
<add key="quartz.threadPool.threadCount" value="10" />
<add key="quartz.threadPool.threadPriority" value="2" />
<add key="quartz.jobStore.misfireThreshold" value="60000" />
<add key="quartz.jobStore.type" value="Quartz.Simpl.RAMJobStore, Quartz" />
<add key="quartz.plugin.jobInitializer.fileNames" value="Quartz_Jobs_001.xml" />
<add key="quartz.plugin.jobInitializer.failOnFileNotFound" value="true" />
<add key="quartz.plugin.jobInitializer.scanInterval" value="120" />
</quartz>
Is that what you're talking about?
In addition to the answer given by #granadaCoder, you can also set the quartz.config environment variable to the name of the file you want to load. Note that the configSource attribute is not quartz.net specific but a feature of the .Net framework: SectionInformation.ConfigSource Property
I think it's fixed now. But there's a workaround for it.
Read the configuration from other ways into a System.Collections.Specialized.NameValueCollection.
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddIniFile("someotherfile.ini", false, true);
var config = builder.Build();
var quartzProperties = new System.Collections.Specialized.NameValueCollection();
foreach (var p in config.GetSection("Quartz").GetChildren().AsEnumerable())
{
quartzProperties.Add(p.Key, p.Value);
}
IScheduler scheduler = new StdSchedulerFactory(quartzProperties).GetScheduler();
scheduler.Start();

Save Configuration settings dynamically [duplicate]

update app.config file programmatically with
Configuration config =
ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
this is my xml
<configuration>
<configSections>
<section name="nhibernateSettings" type="ProjectBase.Data.OpenSessionInViewSection, ProjectBase.Data" />
</configSections>
<appSettings>
<add key="NHibernateConfigPath" value="D:\PROJEKTI\crawler\WebCrawlerSuite\ViaMura.Web\NHibernate.config" />
<!--<add key="NHibernateConfigPath" value="C:\_ZAGON\ViaMura\CurrencyApp\at\NHibernate.config" />-->
<add key="ClientSettingsProvider.ServiceUri" value="" />
</appSettings>
<connectionStrings>
<add name="connectionString" connectionString="Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=Viamura_at;Data Source=.\SQL2008" providerName="System.Data.SqlClient" />
<!--<add name="connectionString" connectionString="server=193.37.152.24\SQL2008;User Id=DBUser;password=Lualah8991;database=Viamura_at" providerName="System.Data.SqlClient" />-->
</connectionStrings>
<nhibernateSettings>
<!-- List every session factory that will be needed; transaction management and closing sessions
will be managed with the open-session-in-view module -->
<sessionFactories>
<clearFactories />
<sessionFactory name="WebCrawlerFactory" factoryConfigPath="D:\PROJEKTI\crawler\WebCrawlerSuite\ViaMura.Web\NHibernate.config" isTransactional="true" />
<!--<sessionFactory name="WebCrawlerFactory" factoryConfigPath="C:\_ZAGON\ViaMura\CurrencyApp\at\NHibernate.config" isTransactional="true" />-->
</sessionFactories>
</nhibernateSettings>
how can I programmatically edit WebCrawlerFactory? I am using
Configuration config =
ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
You can use the following code:
private void UpdateConfig(string key, string value, string fileName)
{
var configFile = ConfigurationManager.OpenExeConfiguration(fileName);
configFile.AppSettings.Settings[key].Value = value;
configFile.Save();
}
Where: fileName is the full path + application name (c:\project\application.exe)
In your case, change the AppSetting by Sections:
configFile.Sections["nhibernateSettings"]
The ProjectBase.Data.OpenSessionInViewSection indicates that there is already a custom config section defined that will allow access to the config settings. It may, however be protected or internal to NHibernate.
See if you can reference that class to access the settings.
You could also create a custom configuration section yourself, however it would cause NHibernate to be improperly configured since it would not be able to load the config section properly.
see How to: Create Custom Configuration Sections Using ConfigurationSection

web.config c# .net web application

How to read a personal section in a web.config ?
<MyPersonalSection>
<add name="toto" enable="true" URL="http://localhost:43242" />
<add name="titi" enable="false" URL="http://localhost:98762" />
<MyPersonalSection/>
I'd like to get the enable value and/or URL value with the name value.
I also have this mistake : Unrecognized configuration section MyPersonalSection
I been trying
var config = ConfigurationManager.GetSection("MyPersonalSection");
Here is a cool example for that.
You don't need to write a custom configuration handler to get what you want. There are built-in configuration handlers that you can use if you simply want key-value entries. But, you'll have to use key instead of name and value instead of URL. For example:
<configuration>
<configSections>
<section name="MyPersonalSection" type="System.Configuration.NameValueSectionHandler" />
</configSections>
<MyPersonalSection>
<add key="toto" value="http://localhost:43242" />
<add key="titi" value="http://localhost:98762" />
</MyPersonalSection>
</configuration>
And you can access them via code:
var myValues = ConfigurationSettings.GetConfig("MyPersonalSection") as NameValueCollection;
var url = myValues["toto"];
I would suggest naming your keys in a way that makes it clear what the value should be, like "totoUrl" and "titiUrl".
If you want something other than string value pairs, you'll have to write your own custom handler.
You can add appSettings section in your web.config with key that you will need. For example:
<configuration>
<appSettings>
<add key="FirstUrl" value="http://localhost:43242"/>
<add key="SecondUrl" value="http://localhost:98762" />
</appSettings>
...
</configuration>
So, since aspx.cs file, you can declare directive
using System.Configuration;
And later, you can retrieve FirstUrl value in this way:
var myUrl = ConfigurationManager.AppSettings["FirstUrl"];

Categories