Web.Config custom section returns null - c#

Well I have following entries in my web config for SagePay Integration in an ASP.net MVC project.
<configuration>
<configSections>
<section name="SagePayConfiguration" type="System.Configuration.IgnoreSectionHandler" requirePermission="true" restartOnExternalChanges="true" allowLocation="true"/>
</configSections>
<SagePayConfiguration>
<!--Mandatory
Set to TEST for the Test Server and LIVE for the live environment-->
<add key="sagepay.api.env" value="TEST" />
.
.
</SagePayConfiguration>
However I am getting null when trying to access it from C# code.
SagePayConfiguration sagePayConfiguration = (SagePayConfiguration)System.Configuration.ConfigurationManager.GetSection("SagePayConfiguration");
Any help what I am missing here?

You must cast the ConfigrationItem to "System.Configuration.IgnoreSectionHandler" or set the type Attribute in web.conf to an existing Type in your assembly.
<section name="<SectionName>" type="<your type (FQN)>, <Assembly>" />
After that you can access it
YourType o = ((YourType)ConfigurationManager.GetSection("sectionName"));
EDIT:
The Type must derive from ConfigurationSection.

Related

Inconsistent ConfigurationManager behaviour

I have learnt about custom configurations using the ConfigurationManager. For some reason you have to use the assembly reference in the section element of the app.config, otherwise the ConfigurationManager won't load the app.config. But in an ASP.NET app this works fine. Why?
Consider this custom configuration class:
namespace CustomConfiguration
{
class MySection : ConfigurationSection
{
[ConfigurationProperty("link", IsKey = true)]
public string Link
{
get => (string) this["link"];
set => this["link"] = value;
}
}
}
Using this app.config, I can easily get the link-attribute of myCustomSection in my program:
<configuration>
<configSections>
<section name="myCustomSection" type="CustomConfiguration.MySection, myAssembly" />
</configSections>
...
<myCustomSection link="link i can access in my code" >
</myCustomSection>
</configuration>
Removing the assembly reference in section-element of app.config will result in a ConfigurationErrorsException, because the ConfigurationManager can't load my CustomConfiguration.MySection class in it's own System.Configuration assembly.
E.g.:
<section name="myCustomSection" type="CustomConfiguration.MySection" />
But Microsofts documentation says I should be able to do this.
And in fact I can do this in an ASP.NET app. Not supplying an assembly-name in a type attribute for a section still works and system.configuration magically looks in the right app assembly. Why?
The ASP.NET hosting environment has a different assembly loading behaviour;
it loads all referenced assemblies (from then bin and GAC) at the moment of startup.
For that reason, the assembly of the CustomConfiguration.MySection section can be resolved automatically without specifying it in the type definition.
If you include the settings below in you web.config file, your assembly myAssembly will not be loaded at initial startup anymore.
Then it will also be required to specify the assembly part in the type definition via CustomConfiguration.MySection, myAssembly. Here you get the same behaviour as in a non web-based application.
<configuration>
<!-- ... -->
<system.web>
<compilation>
<assemblies>
<remove assembly="myAssembly" />
</assemblies>
</compilation>
</system.web>
<!-- ... -->
</configuration>
The referenced documentation in your question shows that a section (shown belown) can be declared in an app.config file (of non web-based application), but this will only work for the out-of-the-box supplied configuration classes/handlers, like eg. System.Configuration.SingleTagSectionHandler, which resides in the core System assemby (System.dll).
For all other (custom) sections, a full assembly-qualified name is required.
<configuration>
<configSections>
<section name="sampleSection"
type="System.Configuration.SingleTagSectionHandler" />
</configSections>
<sampleSection setting1="Value1"
setting2="value two"
setting3="third value" />
</configuration>

Custom app.config section fails to cast to NameValueCollection

This tutorial makes what I'm trying to do look dead easy. All I want to do is read a custom attribute out of my web.config. Here's the relevant part:
<configSections>
<section name="Authentication.WSFedShell" type="System.Configuration.DictionarySectionHandler, System, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
</configSections>
<Authentication.WSFedShell>
<add key="Authentication.PrincipalType" value="ClientCertificate" />
</Authentication.WSFedShell>
In the immediate window I can execute:
System.Configuration.ConfigurationManager.GetSection("Authentication.WSFedShell")
which returns the string
["Authentication.PrincipalType"]: "ClientCertificate"
However, when I try to cast it (with as NameValueCollection), as this tutorial says to do, I get null returned and my code blows up. There's gotta be a cleaner way to get the value "ClientCertificate" than manually parsing the string result.
How do I read "ClientCertificate" from app.config?
Why can't you use AppSetting like
<configuration>
<appSettings>
<add key="Authentication.PrincipalType" value="ClientCertificate"/>
</appSettings>
</configuration>
System.Configuration.ConfigurationManager.AppSettings["Authentication.PrincipalType"]
Most probably the issue with your section is the Type attribute. But anyways, you need to cast the result of GetSection() to your type defined for section like
System.Configuration.DictionarySectionHandler config = (System.Configuration.DictionarySectionHandler)System.Configuration.ConfigurationManager.GetSection("Authentication.WSFedShell");

section type in app.config

I was going through how to create section groups and sections in configsection of app.config.
So, lets take a sample
<configSections>
<sectionGroup name="trackGroup">
<section name="trackInfo" type="System.Configuration.AppSettingsSection, System.Configuration, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
</configSections>
<trackGroup>
<trackInfo>
<add key = "ASHUM" value="ASH-UM"/>
</trackInfo>
</trackGroup>
So now while I was going through various articles I found that everyone uses different types for section
So, I found here the different types:
http://msdn.microsoft.com/en-us/library/aa309408%28v=vs.71%29.aspx
But the type I am using is not mentioned here.
I got this type from a random example and as far as I get it it is actually defining settings for appsetting section.
Can someone help me what does the type means in my sample I mean what is version, public token,culture how we define these?
Also I wanted to know which type is more better to be used?
Like i have to access these settings during runtime and even modify some during runtime.
Also I suppose that these different types has different ways by which we can access them?
Like in case above in my sample I am accessing the keys and values as:
static void getFull(string sectionName)
{
System.Collections.Specialized.NameValueCollection section = (System.Collections.Specialized.NameValueCollection)System.Configuration.ConfigurationManager.GetSection(sectionName);
if (section != null)
{
foreach (string key in section.AllKeys)
{
Console.WriteLine(key + ": " + section[key]);
}
}
}
But if we use types like those in the MSDN link provided how I am going to access the keys and values?
This is something I do for creating config sections. It also allows externalizing sections.
App.config
<?xml version="1.0"?>
<configuration>
<configSections>
<section name="TrackInfo" type="System.Configuration.AppSettingsSection, System.Configuration, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/>
</configSections>
<TrackInfo configSource="TrackInfo.config"/>
</configuration>
TrackInfo.config
<?xml version="1.0" encoding="utf-8" ?>
<TrackInfo>
<add key="SOME_KEY" value="SOME_VALUE" />
</TrackInfo>
C#
NameValueCollection section = (NameValueCollection)ConfigurationManager.GetSection( "TrackInfo" );
if( null == section ) throw new Exception( "Missing TrackInfo.config" );
string val = section["SOME_KEY"];

Read 3rd party config section

In a web.config file, I have a 3rd party settings section :
<configuration>
<configSections>
<sectionGroup name="TheProduct">
<section name="TheSection" type="TheCompany.TheProduct.TheSectionConfigurationHandler, TheCompany.TheProduct, Version=1.0.0.0, Culture=neutral, PublicKeyToken=b1e9bee111e9429c" />
</sectionGroup>
</configSections>
<TheProduct>
<TheSection somevalue="true" />
</TheProduct>
</configuration>
I want to read the value of this section from another application, but when I try to find the section, I always get null.
Here is my code :
var config = ConfigurationManager.OpenExeConfiguration(
#"C:\inetpub\wwwroot\TheProduct\web.config"
);
var settings = config.GetSection("TheProduct/TheSection"); // always null
What is the correct way to retrieve the config section ?
[Edit] If the calling app, which defines the same section, I can do :
var settings = ConfigurationManager.GetSection("TheProduct/TheSection");
and it's working. Mybe I'm not opening the web.config file using the correct way ?
Using the configuration manager requires that your application be able to instantiate the actual strongly-typed configuration objects. If you can't add a reference to the defining assembly, then your only choice is to use one of the XML api's (either System.Xml or System.Linq.Xml) to read it manually, in which case you won't be using the configuration manager at all.

How can I access web.config from an ASP.NET Custom Control?

Inside my web.config file I've got code like this:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
...
<section name="UninstallSurveySettings" type="dashboard.UninstallSurveyConfig" />
</configSections>
...
<UninstallSurveySettings>
<add key="fileLocation" value="C:\inetpub\wwwroot\output\" />
</UninstallSurveySettings>
...
</configuration>
I need to be able to access this field from my custom control. The control can be dropped into any website and needs to check that site's web.config for the fileLocation value in UninstallSurveySetting.
I've tried a couple different approaches with no luck. Any help on this would be greatly appreciated.
Much easier to use AppSettings.
Web.config:
<configuration>
<appSettings>
<add key="fileLocation" value="C:\inetpub\wwwroot\output\" />
</appSettings>
</configuration>
Code:
string location = System.Configuration.ConfigurationManager.AppSettings["fileLocation"];
If your section will become more complex, then:
var section = (NameValueFileSectionHandler)ConfigurationManager.GetSection("UninstallSurveySettings");
if (section != null)
{
// access section members
}
P.S.
Maybe you want to use ConfigurationSection class instead of handler.
In ASP.NET MVC 3 the tag cannot be a direct child of (it results in a configuration error).
How about adding your key to the section. Then you can easily access it via the ConfigurationManager.AppSettings collection.
using System.Configuration.ConfigurationManager and you will be able to get what you want from the web.config
I was able to solve this by creating a configuration class for it and placing this code in the web.config:
<section name="UninstallSurveyConfig" type="dashboard.UninstallSurveyConfig" />
..
<UninstallSurveyConfig dirFileLocation="C:\inetpub\wwwroot\build\output" webFileLocation="~/output" />

Categories