I'm getting a weird exception when trying to initialize NLog instance as a static class member (update: this is happening in a desktop app which is targeting .NET 4.0).
The problem is, I'm getting it only on one specific client machine, and can't reproduce on any of my development configurations. Can someone point me in a direction, what should I look for?
PS: User tried to run the app with administrator rights as well, getting same exception.
System.Configuration.ConfigurationErrorsException: An error occurred creating the configuration section handler for nlog: Request for permission of type "System.Security.Permissions.FileIOPermission, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" failed. (C:\Users\XXX\Desktop\Test.exe.Config line 9) ---> System.Security.SecurityException: Request for permission of type "System.Security.Permissions.FileIOPermission, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" failed.
in System.Security.CodeAccessSecurityEngine.Check(Object demand, StackCrawlMark& stackMark, Boolean isPermSet)
in System.Security.CodeAccessPermission.Demand()
in System.AppDomainSetup.VerifyDir(String dir, Boolean normalize)
in NLog.Internal.Fakeables.AppDomainWrapper..ctor(AppDomain appDomain)
in NLog.Internal.Fakeables.AppDomainWrapper.get_CurrentDomain()
in NLog.Config.ConfigSectionHandler.System.Configuration.IConfigurationSectionHandler.Create(Object parent, Object configContext, XmlNode section)
in System.Configuration.RuntimeConfigurationRecord.RuntimeConfigurationFactory.CreateSectionImpl(RuntimeConfigurationRecord configRecord, FactoryRecord factoryRecord, SectionRecord sectionRecord, Object parentConfig, ConfigXmlReader reader)
in System.Configuration.RuntimeConfigurationRecord.RuntimeConfigurationFactory.CreateSectionWithRestrictedPermissions(RuntimeConfigurationRecord configRecord, FactoryRecord factoryRecord, SectionRecord sectionRecord, Object parentConfig, ConfigXmlReader reader)
in System.Configuration.RuntimeConfigurationRecord.CreateSection(Boolean inputIsTrusted, FactoryRecord factoryRecord, SectionRecord sectionRecord, Object parentConfig, ConfigXmlReader reader)
in System.Configuration.BaseConfigurationRecord.CallCreateSection(Boolean inputIsTrusted, FactoryRecord factoryRecord, SectionRecord sectionRecord, Object parentConfig, ConfigXmlReader reader, String filename, Int32 line)
--- End of inner exception stack trace ---
in System.Configuration.BaseConfigurationRecord.EvaluateOne(String[] keys, SectionInput input, Boolean isTrusted, FactoryRecord factoryRecord, SectionRecord sectionRecord, Object parentResult)
in System.Configuration.BaseConfigurationRecord.Evaluate(FactoryRecord factoryRecord, SectionRecord sectionRecord, Object parentResult, Boolean getLkg, Boolean getRuntimeObject, Object& result, Object& resultRuntimeObject)
in System.Configuration.BaseConfigurationRecord.GetSectionRecursive(String configKey, Boolean getLkg, Boolean checkPermission, Boolean getRuntimeObject, Boolean requestIsHere, Object& result, Object& resultRuntimeObject)
in System.Configuration.BaseConfigurationRecord.GetSectionRecursive(String configKey, Boolean getLkg, Boolean checkPermission, Boolean getRuntimeObject, Boolean requestIsHere, Object& result, Object& resultRuntimeObject)
in System.Configuration.BaseConfigurationRecord.GetSectionRecursive(String configKey, Boolean getLkg, Boolean checkPermission, Boolean getRuntimeObject, Boolean requestIsHere, Object& result, Object& resultRuntimeObject)
in System.Configuration.BaseConfigurationRecord.GetSection(String configKey)
in System.Configuration.ConfigurationManager.GetSection(String sectionName)
in NLog.Config.XmlLoggingConfiguration.get_AppConfig()
in NLog.LogFactory.get_Configuration()
in NLog.LogFactory.GetLogger(LoggerCacheKey cacheKey)
in NLog.LogFactory.GetLogger(String name)
in NLog.LogManager.GetCurrentClassLogger()
Update (config file)
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
<section name="Test.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</sectionGroup>
<section name="nlog" type="NLog.Config.ConfigSectionHandler, NLog"/>
</configSections>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<targets>
<target name="logfile" xsi:type="File" fileName="log-${machinename}.txt" layout="${longdate} ${level:uppercase=True} ${logger} ${message} ${exception:format=ToString,StackTrace}" />
</targets>
<rules>
<logger name="*" minlevel="Debug" writeTo="logfile" />
</rules>
</nlog>
<applicationSettings>
<Test.Properties.Settings>
<setting name="servers" serializeAs="Xml">
<value>
<ArrayOfString xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<string>111</string>
<string>222</string>
</ArrayOfString>
</value>
</setting>
</Test.Properties.Settings>
</applicationSettings>
</configuration>
NLog is instantiated this way (static field on a class):
private static NLog.Logger _logger = NLog.LogManager.GetCurrentClassLogger();
SOLUTION is to remove "untrusted origin" flag from application .config file using "unblock" button in file properties, or Sysinternals Streams tool
Thanks to #giammin who pointed me in right direction (trust level)!
Stupid me. It turns out that the cause of the problem was pretty obvious: it was result of Attachment Manager work. "Untrusted origin" flag (Zone.Identifier alternate data stream) was set on downloaded archive which contained app files.
What was unexpected for me in this, is that:
I thought that only IE implements this "protective measure". Turns out, I was wrong - user downloaded the file via Chrome, which also sets this flag. Firefox doesn't set it (I checked on the latest versions to date).
Flag was copied to files from archive (zip) after extraction. This happened, I believe, because user extracted files using built-in Windows archive tool.
The direct cause of this problem was not a flag on assembly or executable files, but rather a flag on .config file itself. Once it was removed, problem disappeared. Flags on .exe/.dll files do not contribute to the problem in any way.
I'm still not sure why this only happens on .net 4.0, and disappears when .net 4.5 is installed (application files are exactly the same).
to debug nlog you can use its internal logging:
<nlog autoReload="true" throwExceptions="true" internalLogFile="c:\log.txt" internalLogLevel="Trace">
---UPDATE---
Another check could be to move the config to an external file:
<configSections>
...
<section name="nlog" type="NLog.Config.ConfigSectionHandler, NLog"/>
</configSections>
<nlog configSource="NLog.config" />
NLog.config:
<?xml version="1.0"?>
<nlog autoReload="true" throwExceptions="true" internalLogFile="c:\log.txt" internalLogLevel="Trace">
...
</nlog>
Anyway It seems that the application is not running in FullTrust.
----UPDATE2----
Try to add this requirePermission="false" in
<section name="nlog" type="NLog.Config.ConfigSectionHandler, NLog" requirePermission="false"/>
Related
I get this error trying to initialize SqlConnection instance.
First I tried with ConnectionString parameter, now I see it occurs even without it in the constructor. The code used to work, but fails after I changed my PC, so I suppose it has something to do with windows settings (windows 7) or user rights
My code:
using (SqlConnection conn = new SqlConnection())
{
SqlConnectionStringBuilder builder =
new SqlConnectionStringBuilder("Server=server1;Integrated Security=SSPI;Initial Catalog=db1");
conn.ConnectionString = builder.ConnectionString;
}
I already tried switching target framework back and forth as some suggest with no result (using 4.5.2 at the moment)
update
The exception thrown on the using line:
System.TypeInitializationException occurred HResult=0x80131534
Message=The type initializer for 'System.Data.SqlClient.SqlConnection'
threw an exception. Source=
StackTrace: at System.Data.SqlClient.SqlConnection..ctor() at
Reg_CB_Report.Program.GetSql(String ExecText) in
H:\MY\code\c#\Reg_CB_Report\Reg_CB_Report\Program.cs:line 228 at
Reg_CB_Report.Program.Main(String[] args) in
H:\MY\code\c#\Reg_CB_Report\Reg_CB_Report\Program.cs:line 83
Inner Exception 1: ArgumentException: The parameter is incorrect.
(Exception from HRESULT: 0x80070057 (E_INVALIDARG))
update2
App.config:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2"/>
</startup>
</configuration>
tried recreating it - no result
StackTrace:
StackTrace " at System.Security.Policy.PEFileEvidenceFactory.GetLocationEvidence(SafePEFileHandle peFile, SecurityZone& zone, StringHandleOnStack retUrl)\r\n at System.Security.Policy.PEFileEvidenceFactory.GenerateLocationEvidence()\r\n at System.Security.Policy.PEFileEvidenceFactory.GenerateEvidence(Type evidenceType)\r\n at System.Security.Policy.AssemblyEvidenceFactory.GenerateEvidence(Type evidenceType)\r\n at System.Security.Policy.Evidence.GetHostEvidenceNoLock(Type type)\r\n at System.Security.Policy.Evidence.GetHostEvidence(Type type, Boolean markDelayEvaluatedEvidenceUsed)\r\n at System.Security.Policy.AppDomainEvidenceFactory.GenerateEvidence(Type evidenceType)\r\n at System.Security.Policy.Evidence.GetHostEvidenceNoLock(Type type)\r\n at System.Security.Policy.Evidence.RawEvidenceEnumerator.MoveNext()\r\n at System.Security.Policy.Evidence.EvidenceEnumerator.MoveNext()\r\n at System.Configuration.ClientConfigPaths.GetEvidenceInfo(AppDomain appDomain, String exePath, String& typeName)\r\n at System.Configuration.ClientConfigPaths.GetTypeAndHashSuffix(AppDomain appDomain, String exePath)\r\n at System.Configuration.ClientConfigPaths..ctor(String exePath, Boolean includeUserConfig)\r\n at System.Configuration.ClientConfigPaths.GetPaths(String exePath, Boolean includeUserConfig)\r\n at System.Configuration.ClientConfigurationHost.RequireCompleteInit(IInternalConfigRecord record)\r\n at System.Configuration.BaseConfigurationRecord.GetSectionRecursive(String configKey, Boolean getLkg, Boolean checkPermission, Boolean getRuntimeObject, Boolean requestIsHere, Object& result, Object& resultRuntimeObject)\r\n at System.Configuration.BaseConfigurationRecord.GetSection(String configKey)\r\n at System.Data.SqlClient.SqlConnection..cctor()" string
It looks like you're trying to use the latest version of the SqlClient NuGet package (4.6) on the oldest supported runtime. A missing security update may be involved as well.
The type initializer mentioned in the exception is the static constructor which tries to load the SqlColumnEncryptionEnclaveProviders configuration section. I've never encountered that section either.
One option is to go back to an earlier SqlClient package that works. Another option is target .NET 4.7.2 and later. Finally, you can add the missing section yourself, as the link to the SharePoint bug shows :
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<configSections>
<section name="SqlColumnEncryptionEnclaveProviders"
type="System.Data.SqlClient.SqlColumnEncryptionEnclaveProviderConfigurationSection, System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
</configSections>
</configuration>
This isn't the only bug introduced by SqlClient 4.6. There was another one, again involving the parameterless constructor.
I have 2 websites, one is a sub directory of another but is an Application
ex: /root & /root/Services
They both use Entity Framework 6.x but the child website is throwing The type initializer for System.Data.Entity.Internal.AppConfig' threw an exception because it appears to be seeing to many entries for the same EF Database Provider because of the nested web.config
Is there a way to clear the providers collection so that I do not get this error? I've tried putting in which had no effect.
If I comment out providers section it works
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
</entityFramework>
But I don't want to do this because not every environment is going to have nested websites. and NuGet tends puts it back in.
Can I adjust this programmatically?
Here's the full exception and stack trace
System.TypeInitializationException was unhandled by user code
HResult=-2146233036
Message=**The type initializer for 'System.Data.Entity.Internal.AppConfig' threw an exception.**
Source=EntityFramework
TypeName=System.Data.Entity.Internal.AppConfig
StackTrace:
at System.Data.Entity.Internal.AppConfig.get_DefaultInstance()
at System.Data.Entity.Internal.LazyInternalConnection..ctor(String nameOrConnectionString)
at System.Data.Entity.DbContext..ctor(String nameOrConnectionString)
at co.Repository.Data.coContext..ctor() in coModel.Context.Generated.cs:line 23
at co.Repository.RepositoryBase`1.SingleOrDefault(Expression`1 predicate) in co.Repository\RepositoryBase.cs:line 13
at UserFactory.GetOneByUserName(String siteCode, String userName) in UserFactory.cs:line 151
at UserService.GetOneByUserName(String siteCode, String userName) in UserService.cs:line 59
at SyncInvokeGetOneByUserName(Object , Object[] , Object[] )
at System.ServiceModel.Dispatcher.SyncMethodInvoker.Invoke(Object instance, Object[] inputs, Object[]& outputs)
at System.ServiceModel.Dispatcher.DispatchOperationRuntime.InvokeBegin(MessageRpc& rpc)
InnerException: System.Configuration.ConfigurationErrorsException
HResult=-2146232062
Message=An error occurred creating the configuration section handler for entityFramework: **The provider for invariant name 'System.Data.SqlClient' is specified multiple times in the application configuration. The invariant name must be unique for each configured provider.** (web.config line 339)
Source=System.Configuration
BareMessage=An error occurred creating the configuration section handler for entityFramework: The provider for invariant name 'System.Data.SqlClient' is specified multiple times in the application configuration. The invariant name must be unique for each configured provider.
Filename=web.config
Line=339
StackTrace:
at System.Configuration.BaseConfigurationRecord.EvaluateOne(String[] keys, SectionInput input, Boolean isTrusted, FactoryRecord factoryRecord, SectionRecord sectionRecord, Object parentResult)
at System.Configuration.BaseConfigurationRecord.Evaluate(FactoryRecord factoryRecord, SectionRecord sectionRecord, Object parentResult, Boolean getLkg, Boolean getRuntimeObject, Object& result, Object& resultRuntimeObject)
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 System.Data.Entity.Internal.AppConfig..ctor()
at System.Data.Entity.Internal.AppConfig..cctor()
InnerException: System.InvalidOperationException
HResult=-2146233079
Message=The provider for invariant name 'System.Data.SqlClient' is specified multiple times in the application configuration. The invariant name must be unique for each configured provider.
Source=EntityFramework
StackTrace:
at System.Data.Entity.Internal.ConfigFile.ProviderCollection.BaseAdd(ConfigurationElement element)
at System.Configuration.ConfigurationElementCollection.OnDeserializeUnrecognizedElement(String elementName, XmlReader reader)
at System.Configuration.ConfigurationElement.DeserializeElement(XmlReader reader, Boolean serializeCollectionKey)
at System.Configuration.ConfigurationElement.DeserializeElement(XmlReader reader, Boolean serializeCollectionKey)
at System.Configuration.RuntimeConfigurationRecord.RuntimeConfigurationFactory.CreateSectionImpl(RuntimeConfigurationRecord configRecord, FactoryRecord factoryRecord, SectionRecord sectionRecord, Object parentConfig, ConfigXmlReader reader)
at System.Configuration.RuntimeConfigurationRecord.RuntimeConfigurationFactory.CreateSectionWithRestrictedPermissions(RuntimeConfigurationRecord configRecord, FactoryRecord factoryRecord, SectionRecord sectionRecord, Object parentConfig, ConfigXmlReader reader)
at System.Configuration.RuntimeConfigurationRecord.CreateSection(Boolean inputIsTrusted, FactoryRecord factoryRecord, SectionRecord sectionRecord, Object parentConfig, ConfigXmlReader reader)
at System.Configuration.BaseConfigurationRecord.CallCreateSection(Boolean inputIsTrusted, FactoryRecord factoryRecord, SectionRecord sectionRecord, Object parentConfig, ConfigXmlReader reader, String filename, Int32 line)
InnerException:
I had the same issue.
I resolved this error by simply updating the version number from:
Version=5.0.0.0
to:
Version=6.0.0.0
Example:
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral,
PublicKeyToken=b77a5c561934e089" requirePermission="false" />
I had an issue with EF 4.3.1 with a nested site.
Both sites were using the same library and connection strings...the error was caused by apparent duplicates in the
<connectionStrings>
It was presumably loading the connection strings from the parent site, and then failing to load the sub-site's strings.
In your sub-site, add:
<connectionStrings>
<clear/>
...your normal connection strings
</connectionStrings>
In EF6 you can use Code Base configuration - take a look at this article for more details.
EDIT
I checked in a change to EF6 code where exact duplicates are ignored. This should solve your problem. Note that this did not fit in the 6.0.2 release and should be included in the next release after 6.0.2.
We're getting an odd error in our Test environment with a custom configuration section.
This is for a Windows Service running on a Enterprise Server 2008 r2 64 bit with SQL Server 2008 in both dev and test environments.
This section configures our shared code library to send email out to interested parties whenever an error is handled and published with code like this:
catch(Exception ex)
{
ExceptionManager.Publish(ex);
}
The error specifics (full detail - names changed to preserve the innocent)
4 <configSections>
5 <section name="exceptionManagement"
6 type="Company.Shared.ExceptionManagement.ExceptionManagerSectionHandler, Company.Shared" />
7 </configSections>
8 <exceptionManagement>
9 <publisher assembly="Company.Shared" type="Company.Shared.ExceptionManagement.DefaultPublisher"
10 logName="CPODSOracleDataExchange" applicationName="CPODSOracleDataExchange Service" />
11 <publisher assembly="Company.Shared" type="Company.Shared.ExceptionManagement.ExceptionManagerSMTPPublisher"
12 from="CPODSOracleDataExchangeService#Company.com"
13 defaultRecipients="dev1#Company.com,dev2#Company.com"
14 applicationName="CPODSOracleDataExchange Service" />
15 </exceptionManagement>
1) Exception Information
*********************************************
Exception Type: System.Configuration.ConfigurationErrorsException
Message: An error occurred creating the configuration section handler for exceptionManagement: Request failed. (E:\CITApps\Services\CPODS.OracleDataExchangeService\Company.CPODS.OracleDataExchangeService.exe.Config line 5)
BareMessage: An error occurred creating the configuration section handler for exceptionManagement: Request failed.
Filename: E:\CITApps\Services\CPODS.OracleDataExchangeService\Company.CPODS.OracleDataExchangeService.exe.Config
Line: 5
Errors: System.Configuration.ConfigurationException[]
Data: System.Collections.ListDictionaryInternal
TargetSite: System.Configuration.FactoryRecord FindAndEnsureFactoryRecord(System.String, Boolean ByRef)
HelpLink: NULL
Source: System.Configuration
StackTrace Information
*********************************************
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 Company.Shared.ExceptionManagement.ExceptionManager.Publish(Exception exception, NameValueCollection additionalInfo)
2) Exception Information
*********************************************
Exception Type: System.Security.SecurityException
Action: Demand
PermissionType: System.Security.PermissionSet
FirstPermissionThatFailed: NULL
PermissionState: <PermissionSet class="System.Security.PermissionSet"
version="1"
Unrestricted="true"/>
Demanded: <PermissionSet class="System.Security.PermissionSet"
version="1"
Unrestricted="true"/>
GrantedSet:
RefusedSet:
DenySetInstance: NULL
PermitOnlySetInstance: <PermissionSet class="System.Security.PermissionSet"
version="1">
<IPermission class="System.Security.Permissions.FileDialogPermission, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
version="1"
Access="Open"/>
<IPermission class="System.Security.Permissions.IsolatedStorageFilePermission, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
version="1"
Allowed="ApplicationIsolationByUser"
UserQuota="1024000"/>
<IPermission class="System.Security.Permissions.SecurityPermission, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
version="1"
Flags="Execution"/>
<IPermission class="System.Security.Permissions.UIPermission, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
version="1"
Window="SafeTopLevelWindows"
Clipboard="OwnClipboard"/>
<IPermission class="System.Drawing.Printing.PrintingPermission, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
version="1"
Level="SafePrinting"/>
<IPermission class="System.Security.Permissions.MediaPermission, WindowsBase, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
version="1"
Audio="SafeAudio"
Video="SafeVideo"
Image="SafeImage"/>
<IPermission class="System.Security.Permissions.WebBrowserPermission, WindowsBase, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
version="1"
Level="Safe"/>
</PermissionSet>
FailedAssemblyInfo: NULL
Method: Void InitWithRestrictedPermissions(System.Configuration.RuntimeConfigurationRecord, System.Configuration.FactoryRecord)
Zone: NoZone
Url:
Message: Request failed.
Data: System.Collections.ListDictionaryInternal
TargetSite: System.Object CreateInstance(System.RuntimeType, Boolean, Boolean, Boolean ByRef, System.RuntimeMethodHandleInternal ByRef, Boolean ByRef)
HelpLink: NULL
Source: mscorlib
StackTrace Information
*********************************************
at System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor, Boolean& bNeedSecurityCheck)
at System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache)
at System.RuntimeType.CreateInstanceDefaultCtor(Boolean publicOnly, Boolean skipVisibilityChecks, Boolean skipCheckThis, Boolean fillCache)
at System.Activator.CreateInstance(Type type, Boolean nonPublic)
at System.Configuration.TypeUtil.CreateInstanceWithReflectionPermission(Type type)
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)
The configuration file section in question (with line numbers):
4 <configSections>
5 <section name="exceptionManagement"
6 type="Company.Shared.ExceptionManagement.ExceptionManagerSectionHandler, Company.Shared" />
7 </configSections>
8 <exceptionManagement>
9 <publisher assembly="Company.Shared" type="Company.Shared.ExceptionManagement.DefaultPublisher"
10 logName="CPODSOracleDataExchange" applicationName="CPODSOracleDataExchange Service" />
11 <publisher assembly="Company.Shared" type="Company.Shared.ExceptionManagement.ExceptionManagerSMTPPublisher"
12 from="CPODSOracleDataExchangeService#Company.com"
13 defaultRecipients="dev1#Company.com,dev2#Company.com"
14 applicationName="CPODSOracleDataExchange Service" />
15 </exceptionManagement>
This exact same configuration works fine in our DEV environment. These are identical environments to the best of my knowledge, and both services are running under the same code base.
Any ideas as to what the permissions failure is? One thing we are working on doing is creating the custom log but even when we remove the default publisher which tries to write to a custom log that doesn't exist, the process still fails.
Turns out this was an obscure installation issue.
We uninstalled the service with the old exe, and reinstalled using 64 bit 4.0 framework and the issue went away.
Its the framework setting in the build configuration
Not directly related to your scenario, but if you get the same exception whilst attempting to run a .NET 4.0 app from a network share, then you need to install this hotfix:
http://support.microsoft.com/kb/2580188
I have the following configuration file in a application console:
<?xml version="1.0"?>
<configuration>
<configSections>
<sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net"/>
<section name="hibernate-configuration" type="NHibernate.Cfg.ConfigurationSectionHandler, NHibernate"/>
<section name="ConsoleApplication1.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</sectionGroup>
</configSections>
<startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/></startup><applicationSettings>
<ConsoleApplication1.Properties.Settings>
<setting name="AppName" serializeAs="String">
<value>Simple Application</value>
</setting>
</ConsoleApplication1.Properties.Settings>
</applicationSettings>
<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
<session-factory name="NHibernate.Test">
<property name="connection.driver_class">
NHibernate.Driver.SqlClientDriver
</property>
<property name="connection.connection_string">
Data Source=.\SQLEXPRESS;Initial Catalog=TravelAssistant;Integrated Security=True
</property>
<property name="adonet.batch_size">10</property>
<property name="show_sql">true</property>
<property name="dialect">NHibernate.Dialect.MsSql2005Dialect</property>
<property name="use_outer_join">true</property>
<property name="command_timeout">60</property>
<property name="query.substitutions">true 1, false 0, yes 'Y', no 'N'</property>
<property name="proxyfactory.factory_class">
NHibernate.ByteCode.LinFu.ProxyFactoryFactory, NHibernate.ByteCode.LinFu
</property>
</session-factory>
</hibernate-configuration>
</configuration>
The nhibernate section I haved copied from an dummy application (console application) where it worked just fine. When I run my app (a slightly bigger one with more class library projects involved and referenced) I get the following exception:
System.Configuration.ConfigurationErrorsException was unhandled
Message=Configuration system failed to initialize
Source=System.Configuration
BareMessage=Configuration system failed to initialize
Line=0
StackTrace:
at System.Configuration.ClientConfigurationSystem.EnsureInit(String configKey)
at System.Configuration.ClientConfigurationSystem.PrepareClientConfigSystem(String sectionName)
at System.Configuration.ClientConfigurationSystem.System.Configuration.Internal.IInternalConfigSystem.RefreshConfig(String sectionName)
at System.Configuration.ConfigurationManager.RefreshSection(String sectionName)
at System.Configuration.ClientSettingsStore.ReadSettings(String sectionName, Boolean isUserScoped)
at System.Configuration.LocalFileSettingsProvider.GetPropertyValues(SettingsContext context, SettingsPropertyCollection properties)
at System.Configuration.SettingsBase.GetPropertiesFromProvider(SettingsProvider provider)
at System.Configuration.SettingsBase.GetPropertyValueByName(String propertyName)
at System.Configuration.SettingsBase.get_Item(String propertyName)
at System.Configuration.ApplicationSettingsBase.GetPropertyValue(String propertyName)
at System.Configuration.ApplicationSettingsBase.get_Item(String propertyName)
at TravelAssistant.OnlineAPIs.Properties.Settings.get_HotelsAllStarsURL() in C:\Users\Tamas_Ionut\Documents\Visual Studio 2010\Projects\TravelAssistant\TravelAssistant.OnlineAPIs\Properties\Settings.Designer.cs:line 49
at TravelAssistant.OnlineAPIs.Implementations.CoreModels.Lodging.HotelLodgingProvider.ConstructURL(Location location, Decimal lowPrice, Decimal highPrice, List`1 numberOfStars, Int32 lowCustomerRating, Int32 highCustomerRating, DateTime checkIn, DateTime checkOut, Int32 numberOfAdults) in C:\Users\Tamas_Ionut\Documents\Visual Studio 2010\Projects\TravelAssistant\TravelAssistant.OnlineAPIs\Implementations\CoreModels\Lodging\HotelLodgingProvider.cs:line 77
at TravelAssistant.OnlineAPIs.Implementations.CoreModels.Lodging.HotelLodgingProvider.RetrieveHotels(Location location, Decimal lowPrice, Decimal highPrice, List`1 numberOfStars, Int32 lowCustomerRating, Int32 highCustomerRating, DateTime checkIn, DateTime checkOut, Int32 numberOfAdults) in C:\Users\Tamas_Ionut\Documents\Visual Studio 2010\Projects\TravelAssistant\TravelAssistant.OnlineAPIs\Implementations\CoreModels\Lodging\HotelLodgingProvider.cs:line 148
at ConsoleApplication1.Program.Main(String[] args) in C:\Users\Tamas_Ionut\Documents\Visual Studio 2010\Projects\TravelAssistant\ConsoleApplication1\Program.cs:line 23
at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
InnerException: System.Configuration.ConfigurationErrorsException
Message=Unrecognized configuration section hibernate-configuration. (C:\Users\Tamas_Ionut\Documents\Visual Studio 2010\Projects\TravelAssistant\ConsoleApplication1\bin\Debug\ConsoleApplication1.vshost.exe.Config line 18)
Source=System.Configuration
BareMessage=Unrecognized configuration section hibernate-configuration.
Filename=C:\Users\Tamas_Ionut\Documents\Visual Studio 2010\Projects\TravelAssistant\ConsoleApplication1\bin\Debug\ConsoleApplication1.vshost.exe.Config
Line=18
StackTrace:
at System.Configuration.ConfigurationSchemaErrors.ThrowIfErrors(Boolean ignoreLocal)
at System.Configuration.BaseConfigurationRecord.ThrowIfParseErrors(ConfigurationSchemaErrors schemaErrors)
at System.Configuration.BaseConfigurationRecord.ThrowIfInitErrors()
at System.Configuration.ClientConfigurationSystem.EnsureInit(String configKey)
InnerException:
The dummy app where I haved tested the same Db connection with hibernate worked just fine.
If I remove the nhibernate section the rest of the app runs just fine.
Could someone give me a hint where is the issue? (the nhibernate versions are corect)
Thanks,
Tamas
Did you add all the required NHibernate references to the project? This looks to me like the app can't load the NH configuration section handler and thus doesn't recognize the entire <hibernate-configuration> block.
I have a strange error on a specific Windows Server 2008 R2 machine (it works on other 2008 R2 machines) when starting a Windows Service. The service uses Common.Logging and log4net. However, on this specific machine the config section handler for Common.Logging can not be created.
It fails with the following stack traces (formatted for better readability). What surprises me most is the SecurityException. What can cause this?
Does anyone have a clue?
System.TypeInitializationException: The type initializer for
'MyWindowsService.Program' threw an exception.
--->
Common.Logging.ConfigurationException: Failed obtaining configuration for
Common.Logging from configuration section 'common/logging'.
--->
System.Configuration.ConfigurationErrorsException: An error occurred creating
the configuration section handler for common/logging: Request failed.
(C:\Path\MyWindowsService.exe.Config line 7)
--->
System.Security.SecurityException: Request failed.
at System.RuntimeTypeHandle.CreateInstance(
RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached,
RuntimeMethodHandleInternal& ctor, Boolean& bNeedSecurityCheck)
at System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean skipCheckThis,
Boolean fillCache)
at System.RuntimeType.CreateInstanceDefaultCtor(Boolean publicOnly,
Boolean skipVisibilityChecks, Boolean skipCheckThis, Boolean fillCache)
at System.Activator.CreateInstance(Type type, Boolean nonPublic)
at System.Configuration.TypeUtil.CreateInstanceWithReflectionPermission(Type type)
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)
--- End of inner exception stack trace ---
It continues with:
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 Common.Logging.LogManager.<>c__DisplayClass6.<BuildLoggerFactoryAdapter>b__3()
at Common.Logging.Configuration.ArgUtils.<>c__DisplayClass13.<Guard>b__12()
at Common.Logging.Configuration.ArgUtils.Guard[T](Function`1 function,
String messageFormat, Object[] args)
--- End of inner exception stack trace ---
at Common.Logging.Configuration.ArgUtils.Guard[T](Function`1 function,
String messageFormat, Object[] args)
at Common.Logging.LogManager.BuildLoggerFactoryAdapter()
at Common.Logging.LogManager.get_Adapter()
at Common.Logging.LogManager.GetLogger(Type type)
at MyWindowsService.Program..cctor()
--- End of inner exception stack trace ---
at MyWindowsService.Program.Main(String[] args)
My configuration looks like this (the Common.Logging part of it anyway).
<configSections>
<sectionGroup name="common">
<section name="logging"
type="Common.Logging.ConfigurationSectionHandler, Common.Logging" />
</sectionGroup>
</configSections>
<common>
<logging>
<factoryAdapter
type="Common.Logging.Log4Net.Log4NetLoggerFactoryAdapter,Common.Logging.Log4net">
<arg key="configType" value="INLINE" />
</factoryAdapter>
</logging>
</common>
I've seen strange things happening when customers downloaded our zip (ASP.NET application) file from our website. Because of the security feature "This file came from another computer and might be blocked to help protect this computer".
Unblocking the files solved all strange problems, this would explain why this is only happening on some computers with exactly the same configuration.
The Unblock option is shown only when the file is actually blocked in the General tab of the file properties dialog:
You might also check in Visual Studio 2013 if the Project > Properties > Application Tab > Startup Object dropdown is configured to point to the Program class of the windows service. If the value isn't set, the service will fail to start with System.TypeInitializationException.
Seems like you need to give permissions to the service account to access the config file.
EDIT: Actually on second glance it doesn't seem like that's the problem, because it's actually reading the config file, but you should double check the permissions anyways.
UPDATE: This is a known issue with .NET 4.0, but there is a workaround - see http://social.msdn.microsoft.com/Forums/en-US/clr/thread/1e14f665-10a3-426b-a75d-4e66354c5522.
Turned out for me to be because I was running the executable from a network mapped drive which .NET considers unsecure