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

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

Related

Cannot locate dll even though I put the dll in folder

I add the file to the directory but it is still telling me that it cannot find the file. What am I suppose to do now to fix this error?
Configuration Error
Description: An error occurred during the processing of a configuration file required to service this request. Please review the specific error details below and modify your configuration file appropriately.
Parser Error Message: Could not load file or assembly 'CrystalDecisions.Web, Version=13.0.32.4286, Culture=neutral, PublicKeyToken=692fbea5521e1304' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)
Source Error:
Line 18:
Line 19:
Line 20:
Line 21:
Line 22:
Source File: C:\inetpub\wwwroot\POS\web.config Line: 20
Assembly Load Trace: The following information can be helpful to determine why the assembly 'CrystalDecisions.Web, Version=13.0.32.4286, Culture=neutral, PublicKeyToken=692fbea5521e1304' could not be loaded.
=== Pre-bind state information ===
LOG: DisplayName = CrystalDecisions.Web, Version=13.0.32.4286, Culture=neutral, PublicKeyToken=692fbea5521e1304
(Fully-specified)
LOG: Appbase = file:///C:/inetpub/wwwroot/POS/
LOG: Initial PrivatePath = C:\inetpub\wwwroot\POS\bin
Calling assembly : (Unknown).
===
LOG: This bind starts in default load context.
LOG: Using application configuration file: C:\inetpub\wwwroot\POS\web.config
LOG: Using host configuration file: C:\Users\okdok\Documents\IISExpress\config\aspnet.config
LOG: Using machine configuration file from C:\Windows\Microsoft.NET\Framework64\v4.0.30319\config\machine.config.
LOG: Post-policy reference: CrystalDecisions.Web, Version=13.0.32.4286, Culture=neutral, PublicKeyToken=692fbea5521e1304
LOG: Attempting download of new URL file:///C:/Users/okdok/AppData/Local/Temp/Temporary ASP.NET Files/vs/28ae311b/78674aee/CrystalDecisions.Web.DLL.
LOG: Attempting download of new URL file:///C:/Users/okdok/AppData/Local/Temp/Temporary ASP.NET Files/vs/28ae311b/78674aee/CrystalDecisions.Web/CrystalDecisions.Web.DLL.
LOG: Attempting download of new URL file:///C:/inetpub/wwwroot/POS/bin/CrystalDecisions.Web.DLL.
WRN: Comparing the assembly name resulted in the mismatch: Revision Number
ERR: Failed to complete setup of assembly (hr = 0x80131040). Probing terminated.
<assemblies>
<add assembly="CrystalDecisions.Web, Version=13.0.2000.0, Culture=neutral, PublicKeyToken=692FBEA5521E1304" />
<add assembly="CrystalDecisions.Shared, Version=13.0.2000.0, Culture=neutral, PublicKeyToken=692FBEA5521E1304" />
<add assembly="CrystalDecisions.ReportSource, Version=13.0.2000.0, Culture=neutral, PublicKeyToken=692FBEA5521E1304" />
<add assembly="CrystalDecisions.ReportAppServer.Controllers, Version=13.0.2000.0, Culture=neutral, PublicKeyToken=692FBEA5521E1304" />
<add assembly="CrystalDecisions.ReportAppServer.DataDefModel, Version=13.0.2000.0, Culture=neutral, PublicKeyToken=692FBEA5521E1304" />
<add assembly="CrystalDecisions.CrystalReports.Engine, Version=13.0.2000.0, Culture=neutral, PublicKeyToken=692FBEA5521E1304" />
<add assembly="CrystalDecisions.ReportAppServer.ClientDoc, Version=13.0.2000.0, Culture=neutral, PublicKeyToken=692fbea5521e1304" />
<add assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Data.DataSetExtensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089" />
<add assembly="Microsoft.ReportViewer.WebForms, Version=10.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A" />
<add assembly="Microsoft.ReportViewer.Common, Version=10.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A" />
<add assembly="Microsoft.Build.Framework, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A" />
<add assembly="System.Management, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A" />
<add assembly="System.Transactions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089" />
</assemblies>
Also do you know what I should do about this error:
Could not load file or assembly 'Microsoft.ReportingServices.Interfaces' or one of its dependencies. An attempt was made to load a program with an incorrect format.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.BadImageFormatException: Could not load file or assembly 'Microsoft.ReportingServices.Interfaces' or one of its dependencies. An attempt was made to load a program with an incorrect format.
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Assembly Load Trace: The following information can be helpful to determine why the assembly 'Microsoft.ReportingServices.Interfaces' could not be loaded.
=== Pre-bind state information ===
LOG: DisplayName = Microsoft.ReportingServices.Interfaces
(Partial)
WRN: Partial binding information was supplied for an assembly:
WRN: Assembly Name: Microsoft.ReportingServices.Interfaces | 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:/inetpub/wwwroot/POS/
LOG: Initial PrivatePath = C:\inetpub\wwwroot\POS\bin
Calling assembly : (Unknown).
===
LOG: This bind starts in default load context.
LOG: Using application configuration file: C:\inetpub\wwwroot\POS\web.config
LOG: Using host configuration file: C:\Users\okdok\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:/Users/okdok/AppData/Local/Temp/Temporary ASP.NET Files/vs/28ae311b/78674aee/Microsoft.ReportingServices.Interfaces.DLL.
LOG: Attempting download of new URL file:///C:/Users/okdok/AppData/Local/Temp/Temporary ASP.NET Files/vs/28ae311b/78674aee/Microsoft.ReportingServices.Interfaces/Microsoft.ReportingServices.Interfaces.DLL.
LOG: Attempting download of new URL file:///C:/inetpub/wwwroot/POS/bin/Microsoft.ReportingServices.Interfaces.DLL.
ERR: Failed to complete setup of assembly (hr = 0x8007000b). Probing terminated.
Stack Trace:
[BadImageFormatException: Could not load file or assembly 'Microsoft.ReportingServices.Interfaces' or one of its dependencies. An attempt was made to load a program with an incorrect format.]
System.Reflection.RuntimeAssembly._nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, RuntimeAssembly locationHint, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks) +0
System.Reflection.RuntimeAssembly.InternalLoadAssemblyName(AssemblyName assemblyRef, Evidence assemblySecurity, RuntimeAssembly reqAssembly, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks) +232
System.Reflection.RuntimeAssembly.InternalLoad(String assemblyString, Evidence assemblySecurity, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean forIntrospection) +113
System.Reflection.RuntimeAssembly.InternalLoad(String assemblyString, Evidence assemblySecurity, StackCrawlMark& stackMark, Boolean forIntrospection) +23
System.Reflection.Assembly.Load(String assemblyString) +35
System.Web.Configuration.CompilationSection.LoadAssemblyHelper(String assemblyName, Boolean starDirective) +49
[ConfigurationErrorsException: Could not load file or assembly 'Microsoft.ReportingServices.Interfaces' or one of its dependencies. An attempt was made to load a program with an incorrect format.]
System.Web.Configuration.CompilationSection.LoadAssemblyHelper(String assemblyName, Boolean starDirective) +762
System.Web.Configuration.CompilationSection.LoadAllAssembliesFromAppDomainBinDirectory() +259
System.Web.Configuration.CompilationSection.LoadAssembly(AssemblyInfo ai) +167
System.Web.Compilation.BuildManager.GetReferencedAssemblies(CompilationSection compConfig) +238
System.Web.Compilation.BuildManager.GetPreStartInitMethodsFromReferencedAssemblies() +78
System.Web.Compilation.BuildManager.CallPreStartInitMethods(String preStartInitListPath, Boolean& isRefAssemblyLoaded) +334
System.Web.Compilation.BuildManager.ExecutePreAppStart() +178
System.Web.Hosting.HostingEnvironment.Initialize(ApplicationManager appManager, IApplicationHost appHost, IConfigMapPathFactory configMapPathFactory, HostingEnvironmentParameters hostingParameters, PolicyLevel policyLevel, Exception appDomainCreationException) +746
[HttpException (0x80004005): Could not load file or assembly 'Microsoft.ReportingServices.Interfaces' or one of its dependencies. An attempt was made to load a program with an incorrect format.]
System.Web.HttpRuntime.FirstRequestInit(HttpContext context) +552
System.Web.HttpRuntime.EnsureFirstRequestInit(HttpContext context) +122
System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest wr, HttpContext context) +737

Deploying Entity Framework WPF Application

I've made a WPF application that uses EF6 code first database.
I've been doing it all in Visual Studio and using the default LocalDb.
The client wants to test what i've doe so far. I've tried ClickOnce application installation to my development PC. The program simply doesn't start, no window opens.... absolutely nothing happens.
I've deployed a simple WPF app and it works right away so i surmise it's the EF component.
How do i get some sort of output log, or debugging so i can see what the error is?
Any ideas on how to fix the error?
Where does it get installed to?
How can i attach the debugger?
MY CONNECTION DETAILS from App.config
<?xml version="1.0" encoding="utf-8"?>
<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="EEHA_Inspector.Properties.Settings.EEHA_Inspector_Model_EEHA_DbContextConnectionString"
connectionString="Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=EEHA_Inspector.Model.EEHA_DbContext;Integrated Security=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
</startup>
<entityFramework>
<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>
Any help would be greatly appreciated.
UPDATE #2 - Windows Log Exception
Application: EEHA_Inspector.exe
Framework Version: v4.0.30319
Description: The process was terminated due to an unhandled exception.
Exception Info: System.Data.SqlClient.SqlException
at System.Data.ProviderBase.DbConnectionPool.TryGetConnection(System.Data.Common.DbConnection, UInt32, Boolean, Boolean, System.Data.Common.DbConnectionOptions, System.Data.ProviderBase.DbConnectionInternal ByRef)
at System.Data.ProviderBase.DbConnectionPool.TryGetConnection(System.Data.Common.DbConnection, System.Threading.Tasks.TaskCompletionSource`1<System.Data.ProviderBase.DbConnectionInternal>, System.Data.Common.DbConnectionOptions, System.Data.ProviderBase.DbConnectionInternal ByRef)
at System.Data.ProviderBase.DbConnectionFactory.TryGetConnection(System.Data.Common.DbConnection, System.Threading.Tasks.TaskCompletionSource`1<System.Data.ProviderBase.DbConnectionInternal>, System.Data.Common.DbConnectionOptions, System.Data.ProviderBase.DbConnectionInternal, System.Data.ProviderBase.DbConnectionInternal ByRef)
at System.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(System.Data.Common.DbConnection, System.Data.ProviderBase.DbConnectionFactory, System.Threading.Tasks.TaskCompletionSource`1<System.Data.ProviderBase.DbConnectionInternal>, System.Data.Common.DbConnectionOptions)
at System.Data.ProviderBase.DbConnectionClosed.TryOpenConnection(System.Data.Common.DbConnection, System.Data.ProviderBase.DbConnectionFactory, System.Threading.Tasks.TaskCompletionSource`1<System.Data.ProviderBase.DbConnectionInternal>, System.Data.Common.DbConnectionOptions)
at System.Data.SqlClient.SqlConnection.TryOpenInner(System.Threading.Tasks.TaskCompletionSource`1<System.Data.ProviderBase.DbConnectionInternal>)
at System.Data.SqlClient.SqlConnection.TryOpen(System.Threading.Tasks.TaskCompletionSource`1<System.Data.ProviderBase.DbConnectionInternal>)
at System.Data.SqlClient.SqlConnection.Open()
at System.Data.Entity.Infrastructure.Interception.DbConnectionDispatcher.<Open>b__36(System.Data.Common.DbConnection, System.Data.Entity.Infrastructure.Interception.DbConnectionInterceptionContext)
at System.Data.Entity.Infrastructure.Interception.InternalDispatcher`1[[System.__Canon, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]].Dispatch[[System.__Canon, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.__Canon, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]](System.__Canon, System.Action`2<System.__Canon,System.__Canon>, System.__Canon, System.Action`3<System.__Canon,System.__Canon,System.__Canon>, System.Action`3<System.__Canon,System.__Canon,System.__Canon>)
at System.Data.Entity.Infrastructure.Interception.DbConnectionDispatcher.Open(System.Data.Common.DbConnection, System.Data.Entity.Infrastructure.Interception.DbInterceptionContext)
at System.Data.Entity.Core.EntityClient.EntityConnection.<Open>b__2()
at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy+<>c__DisplayClass1.<Execute>b__0()
at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute[[System.__Canon, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]](System.Func`1<System.__Canon>)
at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute(System.Action)
at System.Data.Entity.Core.EntityClient.EntityConnection.Open()
Exception Info: System.Data.Entity.Core.EntityException
at System.Data.Entity.Core.EntityClient.EntityConnection.Open()
at System.Data.Entity.Core.Objects.ObjectContext.EnsureConnection(Boolean)
at System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction[[System.__Canon, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]](System.Func`1<System.__Canon>, System.Data.Entity.Infrastructure.IDbExecutionStrategy, Boolean, Boolean)
at System.Data.Entity.Core.Objects.ObjectQuery`1+<>c__DisplayClass7[[System.__Canon, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]].<GetResults>b__5()
at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute[[System.__Canon, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]](System.Func`1<System.__Canon>)
at System.Data.Entity.Core.Objects.ObjectQuery`1[[System.__Canon, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]].GetResults(System.Nullable`1<System.Data.Entity.Core.Objects.MergeOption>)
at System.Data.Entity.Core.Objects.ObjectQuery`1[[System.__Canon, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]].<System.Collections.Generic.IEnumerable<T>.GetEnumerator>b__0()
at System.Data.Entity.Internal.LazyEnumerator`1[[System.__Canon, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]].MoveNext()
at System.Linq.Enumerable.FirstOrDefault[[System.__Canon, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]](System.Collections.Generic.IEnumerable`1<System.__Canon>)
at System.Data.Entity.Core.Objects.ELinq.ObjectQueryProvider.<GetElementFunction>b__1[[System.__Canon, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]](System.Collections.Generic.IEnumerable`1<System.__Canon>)
at System.Data.Entity.Core.Objects.ELinq.ObjectQueryProvider.ExecuteSingle[[System.__Canon, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]](System.Collections.Generic.IEnumerable`1<System.__Canon>, System.Linq.Expressions.Expression)
at System.Data.Entity.Core.Objects.ELinq.ObjectQueryProvider.System.Linq.IQueryProvider.Execute[[System.__Canon, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]](System.Linq.Expressions.Expression)
at System.Data.Entity.Internal.Linq.DbQueryProvider.Execute[[System.__Canon, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]](System.Linq.Expressions.Expression)
at System.Linq.Queryable.FirstOrDefault[[System.__Canon, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]](System.Linq.IQueryable`1<System.__Canon>)
at System.Data.Entity.Internal.EdmMetadataRepository.QueryForModelHash(System.Func`2<System.Data.Common.DbConnection,System.Data.Entity.Internal.EdmMetadataContext>)
at System.Data.Entity.Internal.InternalContext.QueryForModelHash()
at System.Data.Entity.Internal.ModelCompatibilityChecker.CompatibleWithModel(System.Data.Entity.Internal.InternalContext, System.Data.Entity.Internal.ModelHashCalculator, Boolean, System.Data.Entity.Internal.DatabaseExistenceState)
at System.Data.Entity.Internal.InternalContext.CompatibleWithModel(Boolean, System.Data.Entity.Internal.DatabaseExistenceState)
at System.Data.Entity.CreateDatabaseIfNotExists`1[[System.__Canon, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]].InitializeDatabase(System.__Canon)
at System.Data.Entity.Internal.InternalContext+<>c__DisplayClassf`1[[System.__Canon, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]].<CreateInitializationAction>b__e()
at System.Data.Entity.Internal.InternalContext.PerformInitializationAction(System.Action)
Exception Info: System.Data.DataException
at System.Data.Entity.Internal.InternalContext.PerformInitializationAction(System.Action)
at System.Data.Entity.Internal.InternalContext.PerformDatabaseInitialization()
at System.Data.Entity.Internal.LazyInternalContext.<InitializeDatabase>b__4(System.Data.Entity.Internal.InternalContext)
at System.Data.Entity.Internal.RetryAction`1[[System.__Canon, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]].PerformAction(System.__Canon)
at System.Data.Entity.Internal.LazyInternalContext.InitializeDatabaseAction(System.Action`1<System.Data.Entity.Internal.InternalContext>)
at System.Data.Entity.Internal.LazyInternalContext.InitializeDatabase()
at System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(System.Type)
at System.Data.Entity.Internal.Linq.InternalSet`1[[System.__Canon, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]].Initialize()
at System.Data.Entity.Internal.Linq.InternalSet`1[[System.__Canon, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]].get_InternalContext()
at System.Data.Entity.Infrastructure.DbQuery`1[[System.__Canon, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]].System.Linq.IQueryable.get_Provider()
at System.Linq.Queryable.Where[[System.__Canon, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]](System.Linq.IQueryable`1<System.__Canon>, System.Linq.Expressions.Expression`1<System.Func`2<System.__Canon,Boolean>>)
at EEHA_Inspector.Model.LoadObvCollection+<Equips>d__4.MoveNext()
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(System.Threading.Tasks.Task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(System.Threading.Tasks.Task)
at EEHA_Inspector.ViewModel.EquipRegVm+<Load>d__55.MoveNext()
at System.Runtime.CompilerServices.AsyncMethodBuilderCore+<>c.<ThrowAsync>b__6_0(System.Object)
at System.Windows.Threading.ExceptionWrapper.InternalRealCall(System.Delegate, System.Object, Int32)
at System.Windows.Threading.ExceptionWrapper.TryCatchWhen(System.Object, System.Delegate, System.Object, Int32, System.Delegate)
at System.Windows.Threading.DispatcherOperation.InvokeImpl()
at System.Windows.Threading.DispatcherOperation.InvokeInSecurityContext(System.Object)
at System.Threading.ExecutionContext.RunInternal(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean)
at System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean)
at System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object)
at MS.Internal.CulturePreservingExecutionContext.Run(MS.Internal.CulturePreservingExecutionContext, System.Threading.ContextCallback, System.Object)
at System.Windows.Threading.DispatcherOperation.Invoke()
at System.Windows.Threading.Dispatcher.ProcessQueue()
at System.Windows.Threading.Dispatcher.WndProcHook(IntPtr, Int32, IntPtr, IntPtr, Boolean ByRef)
at MS.Win32.HwndWrapper.WndProc(IntPtr, Int32, IntPtr, IntPtr, Boolean ByRef)
at MS.Win32.HwndSubclass.DispatcherCallbackOperation(System.Object)
at System.Windows.Threading.ExceptionWrapper.InternalRealCall(System.Delegate, System.Object, Int32)
at System.Windows.Threading.ExceptionWrapper.TryCatchWhen(System.Object, System.Delegate, System.Object, Int32, System.Delegate)
at System.Windows.Threading.Dispatcher.LegacyInvokeImpl(System.Windows.Threading.DispatcherPriority, System.TimeSpan, System.Delegate, System.Object, Int32)
at MS.Win32.HwndSubclass.SubclassWndProc(IntPtr, Int32, IntPtr, IntPtr)
at MS.Win32.UnsafeNativeMethods.DispatchMessage(System.Windows.Interop.MSG ByRef)
at System.Windows.Threading.Dispatcher.PushFrameImpl(System.Windows.Threading.DispatcherFrame)
at System.Windows.Threading.Dispatcher.PushFrame(System.Windows.Threading.DispatcherFrame)
at System.Windows.Application.RunDispatcher(System.Object)
at System.Windows.Application.RunInternal(System.Windows.Window)
at System.Windows.Application.Run(System.Windows.Window)
at EEHA_Inspector.App.Main()
UPDATE #2 - Windows Log Information
Fault bucket 129273820369, type 5
Event Name: CLR20r3
Response: Not available
Cab Id: 0
Problem signature:
P1: EEHA_Inspector.exe
P2: 1.0.0.0
P3: 58222f01
P4: System.Data
P5: 4.6.1586.0
P6: 575a1428
P7: 29fe
P8: 108
P9: System.Data.DataException
P10:
Attached files:
\\?\C:\ProgramData\Microsoft\Windows\WER\Temp\WERCB7E.tmp.WERInternalMetadata.xml
These files may be available here:
C:\ProgramData\Microsoft\Windows\WER\ReportArchive\AppCrash_EEHA_Inspector.e_11252b12b7f6697437e3ba42fb9b6e25caa6b8_5e1d3f42_3a80d3bb
Analysis symbol:
Rechecking for solution: 0
Report Id: 91f3e855-2996-40fe-b5fd-957527bbdc9d
Report Status: 0
Hashed bucket: f5ea3fa3886ba4e09d8362936de86fe8
UPDATE #2 -Application Error in Windows Log
Faulting application name: EEHA_Inspector.exe, version: 1.0.0.0, time stamp: 0x58222f01
Faulting module name: KERNELBASE.dll, version: 10.0.14393.0, time stamp: 0x57898e34
Exception code: 0xe0434352
Fault offset: 0x000d96c2
Faulting process id: 0x5458
Faulting application start time: 0x01d239ffc4803847
Faulting application path: C:\Users\agibson\AppData\Local\Apps\2.0\1RVHJ9WW.8JB\BDB4M51Q.L3R\eeha..tion_fe2d9ab6a328f11f_0001.0000_19df975805717e2b\EEHA_Inspector.exe
Faulting module path: C:\Windows\System32\KERNELBASE.dll
Report Id: 91f3e855-2996-40fe-b5fd-957527bbdc9d
Faulting package full name:
Faulting package-relative application ID:
UPDATE 3 ===================================================
OnModelOveride in the DbContext
namespace EEHA_Inspector.Model
{
/// <summary>
/// Database Definition.
/// </summary>
public class EEHA_DbContext : DbContext
{
...............
/// <summary>
/// Fluent API - Entity Building Configuration. Used to define extra conditions when building the model.
/// These are more powerful than data annotations but also more complex.
/// </summary>
/// <param name="modelBuilder"></param>
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
/* FLUENT API MODEL OVERIDE - INTERMEDIARY TABLES
* Creates an intermediate mapping tables to hold many-to-many relationships between
* two tables. This is since one table can have multiple objects from another table.
* This intermediate table is used just as a look up table.
* Although its a look up table, databases must be configured to show the link two ways
* since its not possible to have a many-to-many unidirectional relationship.
* By mapping these intermediary table; the lookup table stays clear of the relationship;
* while this intermediary table handles the needed mapping to make it possible.
* E.g. An Equip object contains a collection of Protections; while a Protection
* does not contain any reference to an Equip; since this is handled in a 3rd mapping table,
* created by these Fluent API model builder commands. */
// Equipment Many-To-Many Look Up to ProtectionCodes
modelBuilder.Entity<Equip>()
.HasMany(e => e.Protections)
.WithMany()
.Map(x =>
{
x.MapLeftKey("EquipId");
x.MapRightKey("ProtectionId");
x.ToTable("EquipMapToProtections");
});
// InspectCheck Many-To-Many Look Up to InspectGrades
modelBuilder.Entity<InspectCheck>()
.HasMany(i => i.InspectGrades)
.WithMany()
.Map(x =>
{
x.MapLeftKey("InspectCheckId");
x.MapRightKey("InspectGradeId");
x.ToTable("InspectCheckMapToInspectGrades");
});
}
}
}
UPDATE 3.1
Initialiser Setup
/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App : Application
{
public App()
{
// Set the database initializer
Database.SetInitializer<EEHA_DbContext>(new EEHA_DbInit());
}
}
SEED OVERIDE
#if DEBUG
#define DESTROY_DB_ONSTART //TODO remove when development progresses. Will make the database get dropped upon every start up
#endif
namespace EEHA_Inspector.Model
{
/// <summary>
/// Custom Initialiser for the HA Database.
/// Set the initialiliser in the App.xaml.cs class contructor (make one if not there).
/// <code>Database.SetInitializer<EEHA_DbContext>(new EEHA_DbInit());</code>
/// </summary>
#if DESTROY_DB_ONSTART
class EEHA_DbInit : DropCreateDatabaseAlways<EEHA_DbContext>
#else
class EEHA_DbInit : CreateDatabaseIfNotExists<EEHA_DbContext>
#endif
{
#if DESTROY_DB_ONSTART
/// <summary>
/// Overide the Initialize to force a close of all connections when in testing
/// </summary>
/// <param name="Db">The DbContext to operate on.</param>
public override void InitializeDatabase(EEHA_DbContext Db)
{
#if DEBUG
this.KillAllConnections(Db);
#endif
base.InitializeDatabase(Db);
}
#endif
protected override void Seed(EEHA_DbContext Db)
{
.....changes to Db
Db.SaveChanges();
base.Seed(Db);
Db.SaveChanges(); //TODO needed?
}
UPDATE 4 - Using DbConfig
Earlier today i ran the SQLExpress install manually and just went with the defaults for all options.
I've converted to DbConfig based on what i could find on the msdn update. This works again in visual studio. Making the Db at the name i gave to the DbContext Constructor.
Just to be sure i uninstalled the programs ClickOnce install. Reinstalled. When i was fiddling earlier i noticed this, but i now get a dialog box saying "Cannot Start Application || Application cannot be started. Contact the application Vendor". Unlike earlier where the app would run and then crash. This new way gives me no custom exception log, but i do get details shown below:
Cannot Start Application Error - Details button .log
PLATFORM VERSION INFO
Windows : 10.0.14393.0 (Win32NT)
Common Language Runtime : 4.0.30319.42000
System.Deployment.dll : 4.6.1586.0 built by: NETFXREL2
clr.dll : 4.6.1586.0 built by: NETFXREL2
dfdll.dll : 4.6.1586.0 built by: NETFXREL2
dfshim.dll : 10.0.14393.0 (rs1_release.160715-1616)
SOURCES
Deployment url : file:///C:/TempPath/EEHA/EEHA_Inspector.application
IDENTITIES
Deployment Identity : EEHA_Inspector.application, Version=1.0.0.17, Culture=neutral, PublicKeyToken=fe2d9ab6a328f11f, processorArchitecture=msil
APPLICATION SUMMARY
* Installable application.
ERROR SUMMARY
Below is a summary of the errors, details of these errors are listed later in the log.
* Activation of C:\TempPath\EEHA\EEHA_Inspector.application resulted in exception. Following failure messages were detected:
+ External component has thrown an exception.
COMPONENT STORE TRANSACTION FAILURE SUMMARY
No transaction error was detected.
WARNINGS
There were no warnings during this operation.
OPERATION PROGRESS STATUS
* [9/11/2016 8:03:58 PM] : Activation of C:\TempPath\EEHA\EEHA_Inspector.application has started.
* [9/11/2016 8:03:58 PM] : Processing of deployment manifest has successfully completed.
ERROR DETAILS
Following errors were detected during this operation.
* [9/11/2016 8:03:58 PM] System.Runtime.InteropServices.SEHException
- External component has thrown an exception.
- Source: System.Deployment
- Stack trace:
at System.Deployment.Internal.Isolation.IStateManager.Scavenge(UInt32 Flags, UInt32& Disposition)
at System.Deployment.Application.ComponentStore.SubmitStoreTransaction(StoreTransactionContext storeTxn, SubscriptionState subState)
at System.Deployment.Application.ComponentStore.SetPendingDeployment(SubscriptionState subState, DefinitionIdentity deployId, DateTime checkTime)
at System.Deployment.Application.SubscriptionStore.SetLastCheckTimeToNow(SubscriptionState subState)
at System.Deployment.Application.ApplicationActivator.PerformDeploymentActivation(Uri activationUri, Boolean isShortcut, String textualSubId, String deploymentProviderUrlFromExtension, BrowserSettings browserSettings, String& errorPageUrl)
at System.Deployment.Application.ApplicationActivator.ActivateDeploymentWorker(Object state)
COMPONENT STORE TRANSACTION DETAILS
* Transaction at [9/11/2016 8:03:58 PM]
+ System.Deployment.Internal.Isolation.StoreOperationSetDeploymentMetadata
- Status: Set
- HRESULT: 0x0
+ System.Deployment.Internal.Isolation.StoreTransactionOperationType (27)
- HRESULT: 0x0
Db Context Constructor
public EEHA_DbContext() : base("TestEEHACodeDb")
{
}
The DbConfig Class
namespace EEHA_Inspector.Model
{
public class EEHA_DbConfig : DbConfiguration
{
public EEHA_DbConfig()
{
SetExecutionStrategy("System.Data.SqlClient", () => new SqlAzureExecutionStrategy());
SetDefaultConnectionFactory(new LocalDbConnectionFactory("v11.0"));
}
}
}
App.config Removed connection string. Do i remove more?
<?xml version="1.0" encoding="utf-8"?>
<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="EEHA_Inspector.Properties.Settings.EEHA_Inspector_Model_EEHA_DbContextConnectionString"
connectionString="Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=EEHA_Inspector.Model.EEHA_DbContext;Integrated Security=True"
providerName="System.Data.SqlClient" />
--><!--<add name="EEHA_Inspector.Properties.Settings.EEHA_Inspector_Model_EEHA_DbContextConnectionString"
connectionString="Data Source=./SQLEXPRESS;Initial Catalog=EEHA_Inspector.Model.EEHA_DbContext;Integrated Security=True"
providerName="System.Data.SqlClient" />--><!--
</connectionStrings>-->
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
</startup>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<!--<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework">-->
<parameters>
<parameter value="mssqllocaldb" />
</parameters>
</defaultConnectionFactory>
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
</entityFramework>
</configuration>
SOLUTION/ / WRAP UP
Thanks to grek40. Particularly his exception catching code. This allowed me to start making changes to find the errors. Prior to that, the windows logs didn't help at all.
What put me past the hurdle was using the DbContext definition he suggested. For some reason using the default DbContext constructor and a connection string seemed to make ClickOnce install expect to find an mdf file; even though attaching one wasn't specified.
The exception catch code also allowed my my debugging in release mode to find some odd exceptions (once that didn't apply to debug mode, or that made any sense to me). I've now turned off the offending code so i could proceed; the click once install now works.
I want to make sure that you actually do everything possible to catch and log the occuring exception.
Make sure to register an exception handler in App.xaml with DispatcherUnhandledException
<Application
x:Class="[Your Stuff]"
DispatcherUnhandledException="Application_DispatcherUnhandledException">
</Application>
Implement some logging in the handler (inside App.xaml.cs). It should be something that summarizes the exception messages of all inner exceptions as well as their stack traces. Just write that information to some sort of log file (C:\Temp\MyAppCrashes.log in my example).
private void Application_DispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
{
var sb = new StringBuilder();
AppendExceptionMessages(sb, e.Exception);
AppendExceptionStacktraces(sb, e.Exception);
File.AppendAllText(#"C:\Temp\MyAppCrashes.log", sb.ToString());
}
private void AppendExceptionMessages(StringBuilder sb, Exception e)
{
while (e != null)
{
sb.AppendLine("============== Exception ===============").AppendLine(e.Message);
e = e.InnerException;
}
}
private void AppendExceptionStacktraces(StringBuilder sb, Exception e)
{
while (e != null)
{
sb.AppendLine("======== Exception Stacktrace ==========").AppendLine(e.StackTrace);
e = e.InnerException;
}
}
I hope this reveals some more information, if it's not enough, make sure to register a Startup handler in App.xaml instead of a StartupUri. In the startup, before creating any window, create an instance of your db context, call db.Database.Exists() and db.Database.Initialize(true), make sure to check the Exists return value and wrap the calls in try-catch. Ofcourse, write logging details if any exception is caught.
So far for now, hope you find anything with that approach.

The type initializer for 'System.Data.Entity.Internal.AppConfig' threw an exception in WCF RIA Services

I have recently updated EntityFramework in my Wcf Application from v5 to v6. After publishing the service , service works fine for few hours. Later all services throws an exception like below, I tried all the solutions that are suggested , please Can any one help me,
<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/"><s:Body><s:Fault><faultcode xmlns:a="http://schemas.microsoft.com/net/2005/12/windowscommunicationfoundation/dispatcher">
a:InternalServiceFault</faultcode><faultstring xml:lang="en-US">The type initializer for 'System.Data.Entity.Internal.AppConfig' threw an exception.</faultstring><detail>
<ExceptionDetail xmlns="http://schemas.datacontract.org/2004/07/System.ServiceModel" xmlns:i="http://www.w3.org/2001/XMLSchema-instance"><HelpLink i:nil="true"/><InnerException>
<HelpLink i:nil="true"/><InnerException><HelpLink i:nil="true"/><InnerException i:nil="true"/><Message>Could not load file or assembly 'EntityFramework, Version=6.0.0.0, Culture=neutral,
PublicKeyToken=b77a5d561934e089' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)</Message>
<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)</StackTrace><Type>System.IO.FileLoadException</Type></InnerException>
<Message>An error occurred creating the configuration section handler for entityFramework: Could not load file or assembly 'EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5d561934e089' or one of its dependencies.
The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040) (C:\inetpub\wwwroot\apps.sysinformation.net\HelpDesk\web.config line 5)</Message><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.Data.Entity.Internal.AppConfig..ctor()
at System.Data.Entity.Internal.AppConfig..cctor()</StackTrace><Type>System.Configuration.ConfigurationErrorsException</Type></InnerException><Message>The type initializer for 'System.Data.Entity.Internal.AppConfig' threw an exception.</Message>
<StackTrace> at System.Data.Entity.DbContext..ctor(String nameOrConnectionString)
at service1..ctor(Boolean proxyCreationEnabled)
at service1.ValidateUserIT()
at service1.GetTickets_ForDashBoard()
at SyncInvokeGetTickets_ForDashBoard(Object , Object[] , Object[] )
at System.ServiceModel.Dispatcher.SyncMethodInvoker.Invoke(Object instance, Object[] inputs, Object[]& outputs)
at System.ServiceModel.Dispatcher.DispatchOperationRuntime.InvokeBegin(MessageRpc& rpc)
at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage5(MessageRpc& rpc)
at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage31(MessageRpc& rpc)
at System.ServiceModel.Dispatcher.MessageRpc.Process(Boolean isOperationContextSet)</StackTrace><Type>System.TypeInitializationException</Type></ExceptionDetail></detail></s:Fault></s:Body></s:Envelope>

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

IIS8: Could not load type 'System.ServiceModel.Activation.HttpModule'

There are lots of questions answering this, but none of the answers are working for me.
Originally, I was getting a 405 when I was trying to PUT or DELETE (probably other verbs too). Looking at some questions, the solution seemed to be to change the Handler Mappings.
I changed the following:
ExtensionlessUrlHandler-ISAPI-4.0_32bit
ExtensionlessUrlHandler-ISAPI-4.0_64bit
WebDAV
I noticed that the verbs were already in the One of the following verbs box, so in desperation I changed it to accept all verbs.
Now, I can't even load the webpage, let alone make any exotic requests like a DELETE, I immediately get a yellow screen of death:
Server Error in '/' Application.
Could not load type 'System.ServiceModel.Activation.HttpModule' from assembly 'System.ServiceModel, Version=3.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.TypeLoadException: Could not load type 'System.ServiceModel.Activation.HttpModule' from assembly 'System.ServiceModel, Version=3.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'.
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Stack Trace:
[TypeLoadException: Could not load type 'System.ServiceModel.Activation.HttpModule' from assembly 'System.ServiceModel, Version=3.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'.]
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) +153
System.Type.GetType(String typeName, Boolean throwOnError, Boolean ignoreCase) +100
System.Web.Compilation.BuildManager.GetType(String typeName, Boolean throwOnError, Boolean ignoreCase) +124
System.Web.Configuration.ConfigUtil.GetType(String typeName, String propertyName, ConfigurationElement configElement, XmlNode node, Boolean checkAptcaBit, Boolean ignoreCase) +76
[ConfigurationErrorsException: Could not load type 'System.ServiceModel.Activation.HttpModule' from assembly 'System.ServiceModel, Version=3.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'.]
System.Web.Configuration.ConfigUtil.GetType(String typeName, String propertyName, ConfigurationElement configElement, XmlNode node, Boolean checkAptcaBit, Boolean ignoreCase) +12687536
System.Web.Configuration.Common.ModulesEntry.SecureGetType(String typeName, String propertyName, ConfigurationElement configElement) +69
System.Web.Configuration.Common.ModulesEntry..ctor(String name, String typeName, String propertyName, ConfigurationElement configElement) +66
System.Web.HttpApplication.BuildIntegratedModuleCollection(List`1 moduleList) +300
System.Web.HttpApplication.GetModuleCollection(IntPtr appContext) +1262
System.Web.HttpApplication.RegisterEventSubscriptionsWithIIS(IntPtr appContext, HttpContext context, MethodInfo[] handlers) +133
System.Web.HttpApplication.InitSpecial(HttpApplicationState state, MethodInfo[] handlers, IntPtr appContext, HttpContext context) +304
System.Web.HttpApplicationFactory.GetSpecialApplicationInstance(IntPtr appContext, HttpContext context) +404
System.Web.Hosting.PipelineRuntime.InitializeApplication(IntPtr appContext) +475
[HttpException (0x80004005): Could not load type 'System.ServiceModel.Activation.HttpModule' from assembly 'System.ServiceModel, Version=3.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'.]
System.Web.HttpRuntime.FirstRequestInit(HttpContext context) +12881108
System.Web.HttpRuntime.EnsureFirstRequestInit(HttpContext context) +159
System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest wr, HttpContext context) +12722297
Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.18045
So far I have:
Checked ASP.NET 4.5 is installed via Web PI
Running dism /online /enable-feature /featurename:IIS-ASPNET45
Running "%WINDIR%\Microsoft.Net\Framework\v3.0\Windows Communication Foundation\ServiceModelReg.exe" -r
Running C:\Windows\Microsoft.NET\Framework64\v4.0.30319>aspnet_regiis -I
More iisresets than I can could
Replacing the ServiceModel in the applicationHost.config:
<add name="ServiceModel" type="System.ServiceModel.Activation.HttpModule, System.ServiceModel, Version=3.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" preCondition="managedHandler" />
replaced with:
<add name="ServiceModel" type="System.ServiceModel.Activation.HttpModule, System.ServiceModel, Version=3.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" preCondition="managedHandler,runtimeVersionv4.0" />
What else can I do, or where should I be looking?
Thanks
Dave
you also have to activate servicemodel 4.0 with
dism /online /enable-Feature /all /FeatureName:WCF-HTTP-Activation45
and in de IIS manager (server -> feature -> modules)
check if you see servicemodel 4.0 and then remove servicemodel.
I had the same problem after installing Synfusion Essential Studio on my computer.
I resolved by performing the following steps:
Open IIS Manager console
On the Server panel go to Modules, features view
Make sure ServiceModule-4.0 is there. If it's not there, perform the steps prescribed above (1-6)
Remove ServiceModel module
Just thought this might help someone.
This error can occur when there are multiple versions of the .NET Framework on the computer that is running IIS, and IIS was installed after .NET Framework 4.0 or before the Service Model in Windows Communication Foundation was registered.
here is the link to resolve this.
http://msdn.microsoft.com/en-us/library/hh169179%28v=nav.71%29.aspx
This link works for me.
http://www.codeproject.com/Articles/613812/Solve-IIS-Error-Could-not-load-type-System-Servi
You have to remove the ServerModel module and the svc-integrated handler.
Adding this to my application's web.config worked for me:
<system.webServer>
<modules runAllManagedModulesForAllRequests="true">
<add name="ServiceModel-4.0" type="System.ServiceModel.Activation.ServiceHttpModule, System.ServiceModel.Activation, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" preCondition="managedHandler" />
</modules>
</system.webServer>

Categories

Resources