app.config custom configuration - 'System.TypeInitializationException'

2.4k views Asked by At

I tried following this instruction app.config Custom Configuration

However, i got stuck. This is my app.config code:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <section name="Configuration" type="DP.Configuration, MyAssembly" />
  </configSections>
  <startup> 
      <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2"/>
  </startup>
  <Configuration
      inputLoc="C:\Input"
   />
</configuration>

here is the configuration class:

    using System.Configuration;

    namespace DP
    {
        public class Configuration : ConfigurationSection
        {
            private static readonly Configuration settings = ConfigurationManager.GetSection("Configuration") as Configuration;

        public static Configuration Settings
        {
            get
            {
                return settings;
            }
        }

        [ConfigurationProperty("inputLoc", IsRequired = true)]
        [StringValidator(InvalidCharacters = "  ~!@#$%^&*()[]{}/;’\"|", MinLength = 1, MaxLength = 256)]
        public string InputLocation
        {
            get { return (string)this["inputLoc"]; }
            set { this["inputLoc"] = value; }
        }
    }
}

And when i call inputFolder = ClientConfiguration.Settings.InputLocation; I get the System.TypeInitializationException.

Error Code:

An unhandled exception of type 'System.TypeInitializationException' occurred in DP.exe

Additional information: The type initializer for 'DP.configuration' threw an exception.

System.TypeInitializationException was unhandled
  _HResult=-2146233036
  _message=The type initializer for 'DP.Configuration' threw an exception.
  HResult=-2146233036
  IsTransient=false
  Message=The type initializer for 'DP.Configuration' threw an exception.
  Source=DP
  TypeName=DP.Configuration
  StackTrace:
       at DP.Configuration.get_Settings()
       at DP.Program.Main(String[] args) in c:\Program.cs:line 1012
       at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
       at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()
  InnerException: System.Configuration.ConfigurationErrorsException
       _HResult=-2146232062
       _message=An error occurred creating the configuration section handler for Configuration: Could not load file or assembly 'MyAssembly' or one of its dependencies. The system cannot find the file specified.
       HResult=-2146232062
       IsTransient=false
       Message=An error occurred creating the configuration section handler for Configuration: Could not load file or assembly 'MyAssembly' or one of its dependencies. The system cannot find the file specified. (C:\DP.vshost.exe.Config line 4)
       Source=System.Configuration
       BareMessage=An error occurred creating the configuration section handler for Configuration: Could not load file or assembly 'MyAssembly' or one of its dependencies. The system cannot find the file specified.
       Filename=C:\DP.vshost.exe.Config
       Line=4
       StackTrace:
            at System.Configuration.BaseConfigurationRecord.FindAndEnsureFactoryRecord(String configKey, Boolean& isRootDeclaredHere)
            at System.Configuration.BaseConfigurationRecord.GetSectionRecursive(String configKey, Boolean getLkg, Boolean checkPermission, Boolean getRuntimeObject, Boolean requestIsHere, Object& result, Object& resultRuntimeObject)
            at System.Configuration.BaseConfigurationRecord.GetSection(String configKey)
            at System.Configuration.ConfigurationManager.GetSection(String sectionName)
            at DP.Configuration..cctor() in c:\\Configuration.cs:line 7
       InnerException: System.IO.FileNotFoundException
            _HResult=-2147024894
            _message=Could not load file or assembly 'MyAssembly' or one of its dependencies. The system cannot find the file specified.
            HResult=-2147024894
            IsTransient=false
            Message=Could not load file or assembly 'MyAssembly' or one of its dependencies. The system cannot find the file specified.
            Source=System.Configuration
            FileName=MyAssembly
            FusionLog==== Pre-bind state information ===
LOG: DisplayName = MyAssembly
 (Partial)
WRN: Partial binding information was supplied for an assembly:
WRN: Assembly Name: MyAssembly | Domain ID: 1
WRN: A partial bind occurs when only part of the assembly display name is provided.
WRN: This might result in the binder loading an incorrect assembly.
WRN: It is recommended to provide a fully specified textual identity for the assembly,
WRN: that consists of the simple name, version, culture, and public key token.
WRN: See whitepaper http://go.microsoft.com/fwlink/?LinkId=109270 for more information and common solutions to this issue.
LOG: Appbase = file:///C://x64/Debug/
LOG: Initial PrivatePath = NULL
Calling assembly : System.Configuration, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a.
===
LOG: This bind starts in default load context.
LOG: Using application configuration file: C:\DP.vshost.exe.Config
LOG: Using host configuration file: 
LOG: Using machine configuration file from C:\Windows\Microsoft.NET\Framework64\v4.0.30319\config\machine.config.
LOG: Policy not being applied to reference at this time (private, custom, partial, or location-based assembly bind).
LOG: Attempting download of new URL file:///C://x64/Debug/MyAssembly.DLL.
LOG: Attempting download of new URL file:///C://x64/Debug/MyAssembly/MyAssembly.DLL.
LOG: Attempting download of new URL file:///C://x64/Debug/MyAssembly.EXE.
LOG: Attempting download of new URL file:///C://x64/Debug/MyAssembly/MyAssembly.EXE.

            StackTrace:
                 at System.Configuration.TypeUtil.GetTypeWithReflectionPermission(IInternalConfigHost host, String typeString, Boolean throwOnError)
                 at System.Configuration.RuntimeConfigurationRecord.RuntimeConfigurationFactory.Init(RuntimeConfigurationRecord configRecord, FactoryRecord factoryRecord)
                 at System.Configuration.RuntimeConfigurationRecord.RuntimeConfigurationFactory.InitWithRestrictedPermissions(RuntimeConfigurationRecord configRecord, FactoryRecord factoryRecord)
                 at System.Configuration.RuntimeConfigurationRecord.CreateSectionFactory(FactoryRecord factoryRecord)
                 at System.Configuration.BaseConfigurationRecord.FindAndEnsureFactoryRecord(String configKey, Boolean& isRootDeclaredHere)
            InnerException: 
3

There are 3 answers

0
lynx On

Basically i was putting in the wrong assemble name. I fixed this by putting in the c

1
mungflesh On

See this question: configurationsection-stringvalidator-failing

It looks like you need to add a default value attribute in your ConfigurationProperty attribute, ie.

[ConfigurationProperty("inputLoc", IsRequired = true, DefaultValue="something")]
1
applegal On

Instead of ... inputFolder = ClientConfiguration.Settings.InputLocation;

Try this ... inputFolder = Configuration.Settings.InputLocation;