NHibernate - Unrecognized configuration section hibernate-configuration - c#

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.

Related

SqlConnection() parameterless exception

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.

Could not load file or assembly 'BookMe' or one of its dependencies

I have a problem with projects. Every time, I create project which uses EntityFramework i have this problem.
There is assembly trace:
=== Pre-bind state information ===
LOG: DisplayName = BookMe
(Partial)
WRN: Partial binding information was supplied for an assembly:
WRN: Assembly Name: BookMe | Domain ID: 2
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:/Users/mscib/Documents/GitHub/BookMe/BookMe.WebUI/
LOG: Initial PrivatePath = C:\Users\mscib\Documents\GitHub\BookMe\BookMe.WebUI\bin
Calling assembly : EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089.
===
LOG: This bind starts in default load context.
LOG: Using application configuration file: C:\Users\mscib\Documents\GitHub\BookMe\BookMe.WebUI\web.config
LOG: Using host configuration file: C:\Users\mscib\Documents\IISExpress\config\aspnet.config
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:/Windows/Microsoft.NET/Framework64/v4.0.30319/Temporary ASP.NET Files/root/ea956ac0/519f841f/BookMe.DLL.
LOG: Attempting download of new URL file:///C:/Windows/Microsoft.NET/Framework64/v4.0.30319/Temporary ASP.NET Files/root/ea956ac0/519f841f/BookMe/BookMe.DLL.
LOG: Attempting download of new URL file:///C:/Users/mscib/Documents/GitHub/BookMe/BookMe.WebUI/bin/BookMe.DLL.
LOG: Attempting download of new URL file:///C:/Users/mscib/Documents/GitHub/BookMe/BookMe.WebUI/bin/BookMe/BookMe.DLL.
LOG: Attempting download of new URL file:///C:/Windows/Microsoft.NET/Framework64/v4.0.30319/Temporary ASP.NET Files/root/ea956ac0/519f841f/BookMe.EXE.
LOG: Attempting download of new URL file:///C:/Windows/Microsoft.NET/Framework64/v4.0.30319/Temporary ASP.NET Files/root/ea956ac0/519f841f/BookMe/BookMe.EXE.
LOG: Attempting download of new URL file:///C:/Users/mscib/Documents/GitHub/BookMe/BookMe.WebUI/bin/BookMe.EXE.
LOG: Attempting download of new URL file:///C:/Users/mscib/Documents/GitHub/BookMe/BookMe.WebUI/bin/BookMe/BookMe.EXE.
Stack trace:
[FileNotFoundException: Could not load file or assembly 'BookMe' or one of its dependencies. Nie można odnaleźć określonego pliku.]
System.RuntimeTypeHandle.GetTypeByName(String name, Boolean throwOnError, Boolean ignoreCase, Boolean reflectionOnly, StackCrawlMarkHandle stackMark, IntPtr pPrivHostBinder, Boolean loadTypeFromPartialName, ObjectHandleOnStack type) +0
System.RuntimeTypeHandle.GetTypeByName(String name, Boolean throwOnError, Boolean ignoreCase, Boolean reflectionOnly, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean loadTypeFromPartialName) +95
System.RuntimeType.GetType(String typeName, Boolean throwOnError, Boolean ignoreCase, Boolean reflectionOnly, StackCrawlMark& stackMark) +53
System.Type.GetType(String typeName, Boolean throwOnError) +43
System.Data.Entity.Internal.InitializerConfig.TryGetInitializer(Type requiredContextType, String contextTypeName, String initializerTypeName, Boolean isDisabled, Func`1 initializerArgs, Func`3 exceptionMessage) +46
[InvalidOperationException: Failed to set database initializer of type 'BookMe.Domain.Concrete.BookMeInitializer, BookMe' for DbContext type 'BookMe.Domain.Concrete.BookMeContext, BookMe' specified in the application configuration. See inner exception for details.]
System.Data.Entity.Internal.InitializerConfig.TryGetInitializer(Type requiredContextType, String contextTypeName, String initializerTypeName, Boolean isDisabled, Func`1 initializerArgs, Func`3 exceptionMessage) +314
System.Data.Entity.Internal.<>c__DisplayClass6.<TryGetInitializerFromEntityFrameworkSection>b__1(ContextElement e) +255
System.Linq.WhereSelectEnumerableIterator`2.MoveNext() +223
System.Linq.Enumerable.FirstOrDefault(IEnumerable`1 source, Func`2 predicate) +115
System.Data.Entity.Internal.InitializerConfig.TryGetInitializer(Type contextType) +23
System.Data.Entity.Infrastructure.DependencyResolution.AppConfigDependencyResolver.GetServiceFactory(Type type, String name) +511
System.Collections.Concurrent.ConcurrentDictionary`2.GetOrAdd(TKey key, Func`2 valueFactory) +84
System.Data.Entity.Infrastructure.DependencyResolution.AppConfigDependencyResolver.GetService(Type type, Object key) +175
System.Linq.WhereSelectArrayIterator`2.MoveNext() +75
System.Linq.Enumerable.FirstOrDefault(IEnumerable`1 source, Func`2 predicate) +115
System.Data.Entity.Infrastructure.DependencyResolution.CompositeResolver`2.GetService(Type type, Object key) +38
System.Data.Entity.Internal.InternalContext.PerformDatabaseInitialization() +169
System.Data.Entity.Internal.RetryAction`1.PerformAction(TInput input) +174
System.Data.Entity.Internal.LazyInternalContext.InitializeDatabaseAction(Action`1 action) +269
System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType) +38
System.Data.Entity.Internal.Linq.InternalSet`1.Initialize() +77
System.Data.Entity.Internal.Linq.InternalSet`1.GetEnumerator() +21
System.Linq.WhereSelectEnumerableIterator`2.MoveNext() +83
ASP._Page_Views_Test_Index_cshtml.Execute() in C:\Users\mscib\Documents\GitHub\BookMe\BookMe.WebUI\Views\Test\Index.cshtml:8
System.Web.WebPages.WebPageBase.ExecutePageHierarchy() +252
System.Web.Mvc.WebViewPage.ExecutePageHierarchy() +148
System.Web.WebPages.StartPage.ExecutePageHierarchy() +88
System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer, WebPageRenderingBase startPage) +107
System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext context) +375
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive(IList`1 filters, Int32 filterIndex, ResultExecutingContext preContext, ControllerContext controllerContext, ActionResult actionResult) +88
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive(IList`1 filters, Int32 filterIndex, ResultExecutingContext preContext, ControllerContext controllerContext, ActionResult actionResult) +831
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultWithFilters(ControllerContext controllerContext, IList`1 filters, ActionResult actionResult) +81
System.Web.Mvc.Async.<>c__DisplayClass21.<BeginInvokeAction>b__1e(IAsyncResult asyncResult) +185
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +38
System.Web.Mvc.Controller.<BeginExecuteCore>b__1d(IAsyncResult asyncResult, ExecuteCoreState innerState) +29
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +65
System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +52
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +36
System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +38
System.Web.Mvc.MvcHandler.<BeginProcessRequest>b__5(IAsyncResult asyncResult, ProcessRequestState innerState) +43
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +65
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +38
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +607
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +134
I tried tones of solutions. I changed premision to Temporary Asp Net, also I deleted it. I checked assemblies. I can't figure out what i can do.
Thanks for help,
msciborski.
EDIT:
My solutions contains 3 projects:
Domain, WebUI, UnitTests. WebUI is set as startup project and there is web.config:
<?xml version="1.0" encoding="utf-8"?>
<!--
For more information on how to configure your ASP.NET application, please visit
http://go.microsoft.com/fwlink/?LinkId=301880
-->
<configuration>
<configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<connectionStrings>
<add name="BookMeDb" connectionString="Data Source=(LocalDb)\MSSQLLocalDB;Initial Catalog=BookMe1;Integrated Security=SSPI;" providerName="System.Data.SqlClient" />
</connectionStrings>
<appSettings>
<add key="webpages:Version" value="3.0.0.0" />
<add key="webpages:Enabled" value="false" />
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>
<system.web>
<compilation debug="true" targetFramework="4.6" />
<httpRuntime targetFramework="4.6" />
<globalization uiCulture="en-US"/>
</system.web>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="0.0.0.0-5.2.3.0" newVersion="5.2.3.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
<system.codedom>
<compilers>
<compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:6 /nowarn:1659;1699;1701" />
<compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:14 /nowarn:41008 /define:_MYTYPE=\"Web\" /optionInfer+" />
</compilers>
</system.codedom>
<entityFramework>
<contexts>
<context type="BookMe.Domain.Concrete.BookMeContext, BookMe">
<databaseInitializer type="BookMe.Domain.Concrete.BookMeInitializer, BookMe" />
</context>
</contexts>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="mssqllocaldb" />
</parameters>
</defaultConnectionFactory>
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
</entityFramework>
</configuration>
EDIT2:
There is my .sln file:
You have to update EntityFramework config to specify the correct assembly name. Instead of type="BookMe.Domain.Concrete.BookMeContext, BookMe", you have to use type="BookMe.Domain.Concrete.BookMeContext, BookMe.Domain". You have to do that wherever you have similar entries.
<entityFramework>
<contexts>
<context type="BookMe.Domain.Concrete.BookMeContext, BookMe.Domain">
<databaseInitializer type="BookMe.Domain.Concrete.BookMeInitializer, BookMe.Domain" />
</context>
</contexts>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="mssqllocaldb" />
</parameters>
</defaultConnectionFactory>
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
</entityFramework>
UPDATE: At the minimum the format of type in config file follows the following pattern
type="Fully.Qualified.TypeName, AssemblyName"

ConfigurationErrorsException/SecurityException/FileIOPermission reading application .config file during NLog instantiation

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"/>

"An error occurred creating the configuration section handler for" -

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

cannot use a dll that has subsonic dataaccess

i generated my dataaccess dll using subsonic 3.0. i have a new proj referenced to this dll and am tryign to insert data to my mysql database.
i get the following configuration error. however when i look at my App.config, i have a connectionstring that defines my database connection.
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name="dbTorontoTrader"
connectionString="server=localhost;database=dbtorontotrader;user id=root; password=password"
providerName="MySql.Data.MySqlClient"/>
<!-- For MySQL -->
</connectionStrings>
<system.data>
<DbProviderFactories>
<add name="MySQL Data Provider" invariant="MySql.Data.MySqlClient" description=".Net Framework Data Provider for MySQL" type="MySql.Data.MySqlClient.MySqlClientFactory, MySql.Data, Version=5.1.5.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d" />
</DbProviderFactories>
</system.data>
</configuration>
System.Configuration.ConfigurationErrorsException was unhandled
Message="Failed to find or load the registered .Net Framework Data Provider."
Source="System.Data"
BareMessage="Failed to find or load the registered .Net Framework Data Provider."
Line=0
StackTrace:
at System.Data.Common.DbProviderFactories.GetFactory(DataRow providerRow)
at System.Data.Common.DbProviderFactories.GetFactory(String providerInvariantName)
at SubSonic.DataProviders.DbDataProvider..ctor(String connectionString, String providerName)
at SubSonic.DataProviders.ProviderFactory.LoadProvider(String connectionString, String providerName)
at SubSonic.DataProviders.ProviderFactory.GetProvider(String connectionStringName)
at TorontoTrader.Data.Ver2.dbTorontoTraderDB..ctor() in E:\TradingTools\CODE\TorontoTraderDataVer2\TorontoTraderDataVer2\Context.cs:line 37
at TorontoTrader.Data.Ver2.scans_log.GetRepo(String connectionString, String providerName) in E:\TradingTools\CODE\TorontoTraderDataVer2\TorontoTraderDataVer2\ActiveRecord.cs:line 10338
at TorontoTrader.Data.Ver2.scans_log.GetRepo() in E:\TradingTools\CODE\TorontoTraderDataVer2\TorontoTraderDataVer2\ActiveRecord.cs:line 10354
at TorontoTrader.Data.Ver2.scans_log.SingleOrDefault(Expression`1 expression) in E:\TradingTools\CODE\TorontoTraderDataVer2\TorontoTraderDataVer2\ActiveRecord.cs:line 10359
at ConsoleApplication1.Program.Main(String[] args) in E:\TradingTools\CODE\TorontoTraderDataVer2\ConsoleApplication1\Program.cs:line 13
at System.AppDomain._nExecuteAssembly(Assembly 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)
at System.Threading.ThreadHelper.ThreadStart()
InnerException:
your app config should look like this:
<configuration>
<connectionStrings>
<add name="dbTorontoTrader" connectionString="server=localhost;database=dbtorontotrader;user id=root; password=password" providerName="MySql.Data.MySqlClient"/>
</connectionStrings>
</configuration>
Make note of the element that is missing
You need to add connectionstrings element.
Your app.config should look like this:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name="dbTorontoTrader"
connectionString="server=localhost;database=dbtorontotrader;user id=root; password=password"
providerName="MySql.Data.MySqlClient"/>
</connectionStrings>
</configuration>

Categories

Resources