moq 4.5.29 -getting error " type initializer for 'Moq.Proxy.CastleProxyFactory' threw an exception." - moq

I am using xUnit 2.x and moq 4.5 and castle.core 3.3.0.0 . I have the IAssessmentsRepository interface in a different assembly ( but part of same solution) than my unit test are. I am giving reference to the assembly where IAssessmentsRepository reside. But when I try to mock, it gets error of "Type initilization" which means that moq is not able to load the type i.e. IAssessmentsRepository . Now I do not understand why ?? kindly suggest if anyone faced the same issue.
[Fact]
[UnitTest]
public void DeleteAssessment_ShouldCall_AssessmentsRepository_DeleteAssessment_Method()
{
//Arrange
var assessmentRepoMock = new Mock<Data.Assessments.IAssessmentsRepository>();
assessmentRepoMock.Setup(x => x.DeleteAssessment(It.IsAny<int>(), It.IsAny<string>())).Returns(true);
var assessmentService = new AssessmentService(assessmentRepoMock.Object);
//Act
var testResult = assessmentService.DeleteAssessment(It.IsAny<int>(), It.IsAny<string>());
//Assert
assessmentRepoMock.Verify(r => r.DeleteAssessment(It.IsAny<int>(), It.IsAny<string>()), Times.Once);
}
following is the stack trace of the error,
UHCNV.Web.Services.Icm.Services.Tests.UnitTests.AssessmentServiceTests.DeleteAssessment_ShouldCall_AssessmentsRepository_DeleteAssessment_Method [FAIL]
[xUnit.net 00:00:07.6027020] System.TypeInitializationException : The type initializer for 'Moq.Mock`1' threw an exception.
[xUnit.net 00:00:07.6033988] ---- System.TypeInitializationException : The type initializer for 'Moq.Proxy.CastleProxyFactory' threw an exception.
[xUnit.net 00:00:07.6038240] -------- System.Configuration.ConfigurationErrorsException : Configuration system failed to initialize
[xUnit.net 00:00:07.6042223] ------------ System.Configuration.ConfigurationErrorsException : Only one <configSections> element allowed per config file and if present must be the first child of the root <configuration> element. (C:\DEV2\LouisFinal\UpdatedOne\UHCNV.WEB.SERVICES.ICM\test\UHCNV.Web.Services.Icm.Services.Tests\bin\x86\Debug\UHCNV.Web.Services.Icm.Services.Tests.dll.config line 23)
[xUnit.net 00:00:07.6113488] Stack Trace:
[xUnit.net 00:00:07.6119217] at Moq.Mock`1.<InitializeInstance>b__24_0()
[xUnit.net 00:00:07.6123448] at Moq.PexProtector.Invoke(Action action)
[xUnit.net 00:00:07.6127299] at Moq.Mock`1.InitializeInstance()
[xUnit.net 00:00:07.6131116] at Moq.Mock`1.OnGetObject()
[xUnit.net 00:00:07.6134937] at Moq.Mock.GetObject()
[xUnit.net 00:00:07.6138850] at Moq.Mock.get_Object()
[xUnit.net 00:00:07.6142657] at Moq.Mock`1.get_Object()
[xUnit.net 00:00:07.6146855] test\UHCNV.Web.Services.Icm.Services.Tests\UnitTests\AssessmentServiceTests.cs(20,0): at UHCNV.Web.Services.Icm.Services.Tests.UnitTests.AssessmentServiceTests.DeleteAssessment_ShouldCall_AssessmentsRepository_DeleteAssessment_Method()
[xUnit.net 00:00:07.6150651] ----- Inner Stack Trace -----
[xUnit.net 00:00:07.6154568] at Moq.Proxy.CastleProxyFactory..ctor()
[xUnit.net 00:00:07.6158157] at Moq.Mock`1..cctor()
[xUnit.net 00:00:07.6161683] ----- Inner Stack Trace -----
[xUnit.net 00:00:07.6165556] at System.Configuration.ClientConfigurationSystem.EnsureInit(String configKey)
[xUnit.net 00:00:07.6169380] at System.Configuration.ClientConfigurationSystem.PrepareClientConfigSystem(String sectionName)
[xUnit.net 00:00:07.6173346] at System.Configuration.ClientConfigurationSystem.System.Configuration.Internal.IInternalConfigSystem.GetSection(String sectionName)
[xUnit.net 00:00:07.6177103] at System.Configuration.ConfigurationManager.GetSection(String sectionName)
[xUnit.net 00:00:07.6180813] at System.Configuration.PrivilegedConfigurationManager.GetSection(String sectionName)
[xUnit.net 00:00:07.6184595] at System.Diagnostics.DiagnosticsConfiguration.Initialize()
[xUnit.net 00:00:07.6188321] at System.Diagnostics.DiagnosticsConfiguration.get_Sources()
[xUnit.net 00:00:07.6191972] at System.Diagnostics.TraceSource.Initialize()
[xUnit.net 00:00:07.6195693] at Castle.Core.Logging.TraceLogger.IsSourceConfigured(TraceSource source)
[xUnit.net 00:00:07.6199486] at Castle.Core.Logging.TraceLogger.Initialize()
[xUnit.net 00:00:07.6204199] at Castle.Core.Logging.TraceLogger..ctor(String name, LoggerLevel level)
[xUnit.net 00:00:07.6208012] at Castle.DynamicProxy.ProxyGenerator..ctor(IProxyBuilder builder)
[xUnit.net 00:00:07.6211584] at Castle.DynamicProxy.ProxyGenerator..ctor()
[xUnit.net 00:00:07.6215447] at Moq.Proxy.CastleProxyFactory.CreateProxyGenerator()
[xUnit.net 00:00:07.6219298] at Moq.Proxy.CastleProxyFactory..cctor()
[xUnit.net 00:00:07.6222921] ----- Inner Stack Trace -----
[xUnit.net 00:00:07.6226725] at System.Configuration.ConfigurationSchemaErrors.ThrowIfErrors(Boolean ignoreLocal)
[xUnit.net 00:00:07.6230535] at System.Configuration.BaseConfigurationRecord.ThrowIfParseErrors(ConfigurationSchemaErrors schemaErrors)
[xUnit.net 00:00:07.6242699] at System.Configuration.BaseConfigurationRecord.ThrowIfInitErrors()
[xUnit.net 00:00:07.6247423] at System.Configuration.ClientConfigurationSystem.EnsureInit(String configKey)
[xUnit.net 00:00:07.6633781] UHCNV.Web.Services.Icm.Services.Tests.UnitTests.AssessmentServiceTests.GenerateAssessmentForm_ShouldCall_AssessmentsRepository_GenerateAssessmentForm_Method [FAIL]
[xUnit.net 00:00:07.6715323] System.TypeInitializationException : The type initializer for 'Moq.Mock`1' threw an exception.
[xUnit.net 00:00:07.6719637] ---- System.TypeInitializationException : The type initializer for 'Moq.Proxy.CastleProxyFactory' threw an exception.
[xUnit.net 00:00:07.6723726] -------- System.Configuration.ConfigurationErrorsException : Configuration system failed to initialize
[xUnit.net 00:00:07.6727605] ------------ System.Configuration.ConfigurationErrorsException : Only one <configSections> element allowed per config file and if present must be the first child of the root <configuration> element. (C:\DEV2\LouisFinal\UpdatedOne\UHCNV.WEB.SERVICES.ICM\test\UHCNV.Web.Services.Icm.Services.Tests\bin\x86\Debug\UHCNV.Web.Services.Icm.Services.Tests.dll.config line 23)
[xUnit.net 00:00:07.6796134] Stack Trace:
[xUnit.net 00:00:07.6801181] at Moq.Mock`1.<InitializeInstance>b__24_0()
[xUnit.net 00:00:07.6805315] at Moq.PexProtector.Invoke(Action action)
[xUnit.net 00:00:07.6809086] at Moq.Mock`1.InitializeInstance()
[xUnit.net 00:00:07.6813035] at Moq.Mock`1.OnGetObject()
[xUnit.net 00:00:07.6816928] at Moq.Mock.GetObject()
[xUnit.net 00:00:07.6820733] at Moq.Mock.get_Object()
[xUnit.net 00:00:07.6824593] at Moq.Mock`1.get_Object()
[xUnit.net 00:00:07.6828478] test\UHCNV.Web.Services.Icm.Services.Tests\UnitTests\AssessmentServiceTests.cs(40,0): at UHCNV.Web.Services.Icm.Services.Tests.UnitTests.AssessmentServiceTests.GenerateAssessmentForm_ShouldCall_AssessmentsRepository_GenerateAssessmentForm_Method()
[xUnit.net 00:00:07.6832594] ----- Inner Stack Trace -----
[xUnit.net 00:00:07.6836425] at Moq.Proxy.CastleProxyFactory..ctor()
[xUnit.net 00:00:07.6841577] at Moq.Mock`1..cctor()
[xUnit.net 00:00:07.6845556] ----- Inner Stack Trace -----
[xUnit.net 00:00:07.6856442] at System.Configuration.ClientConfigurationSystem.EnsureInit(String configKey)
[xUnit.net 00:00:07.6860674] at System.Configuration.ClientConfigurationSystem.PrepareClientConfigSystem(String sectionName)
[xUnit.net 00:00:07.6864632] at System.Configuration.ClientConfigurationSystem.System.Configuration.Internal.IInternalConfigSystem.GetSection(String sectionName)
[xUnit.net 00:00:07.6869201] at System.Configuration.ConfigurationManager.GetSection(String sectionName)
[xUnit.net 00:00:07.6873166] at System.Configuration.PrivilegedConfigurationManager.GetSection(String sectionName)
[xUnit.net 00:00:07.6877093] at System.Diagnostics.DiagnosticsConfiguration.Initialize()
[xUnit.net 00:00:07.6881252] at System.Diagnostics.DiagnosticsConfiguration.get_Sources()
[xUnit.net 00:00:07.6885259] at System.Diagnostics.TraceSource.Initialize()
[xUnit.net 00:00:07.6889303] at Castle.Core.Logging.TraceLogger.IsSourceConfigured(TraceSource source)
[xUnit.net 00:00:07.6893368] at Castle.Core.Logging.TraceLogger.Initialize()
[xUnit.net 00:00:07.6897193] at Castle.Core.Logging.TraceLogger..ctor(String name, LoggerLevel level)
[xUnit.net 00:00:07.6901234] at Castle.DynamicProxy.ProxyGenerator..ctor(IProxyBuilder builder)
[xUnit.net 00:00:07.6905143] at Castle.DynamicProxy.ProxyGenerator..ctor()
[xUnit.net 00:00:07.6909231] at Moq.Proxy.CastleProxyFactory.CreateProxyGenerator()
[xUnit.net 00:00:07.6913291] at Moq.Proxy.CastleProxyFactory..cctor()
[xUnit.net 00:00:07.6917210] ----- Inner Stack Trace -----
[xUnit.net 00:00:07.6921119] at System.Configuration.ConfigurationSchemaErrors.ThrowIfErrors(Boolean ignoreLocal)
[xUnit.net 00:00:07.6925092] at System.Configuration.BaseConfigurationRecord.ThrowIfParseErrors(ConfigurationSchemaErrors schemaErrors)
[xUnit.net 00:00:07.6929139] at System.Configuration.BaseConfigurationRecord.ThrowIfInitErrors()
[xUnit.net 00:00:07.6933131] at System.Configuration.ClientConfigurationSystem.EnsureInit(String configKey)
[xUnit.net 00:00:07.7185612] Finished: UHCNV.Web.Services.Icm.Services.Tests

I found the root cause of the issue which is kind of weird. It was related to my app.config file in the test project. My app.config was as below when I was facing the issue:
<configuration>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-9.0.0.0" newVersion="9.0.0.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
<configSections>
</configSections>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
</startup>
</configuration>
All I needed to do was to make sure configSections tag would be the first child of my root element so I updated my app.config file as below:
<configuration>
<configSections>
</configSections>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-9.0.0.0" newVersion="9.0.0.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
</startup>
</configuration>
And voila, problem resolved. The error message was so confusing.

Related

An exception of type 'Grpc.Core.RpcException' occured by upgrading grpc to v 2.33.1 of with TargetFrameworkVersion 4.8

I am getting the exception below when i tried to upgrade grpc version to 2.33.1
TargetFrameworkVersion : 4.8
The content of this exception did not tell me any thing, can any body give any help
Thanks.
Used Package References :
<ItemGroup>
<PackageReference Include="Google.Protobuf" Version="3.14.0" />
<PackageReference Include="Grpc.Core.Api" Version="2.33.1" />
<PackageReference Include="Grpc.Tools" Version="2.33.1" />
</ItemGroup>
Message: An exception of type 'Grpc.Core.RpcException' occurred and was caught.
2021-11-05T19:00:30.966+01:00
Exception Messages:
RpcException : Status(StatusCode="Cancelled", Detail="Cancelled", DebugException="Grpc.Core.Internal.CoreErrorDetailException: {"created":"#1636135230.919000000","description":"Error received from peer ipv6:[::1]:28000","file":"T:\src\github\grpc\workspace_csharp_ext_windows_x64\src\core\lib\surface\call.cc","file_line":1062,"grpc_message":"Cancelled","grpc_status":1}")
Type : Grpc.Core.RpcException, Grpc.Core.Api, Version=2.0.0.0, Culture=neutral, PublicKeyToken=d754f35622e28bad
Message : Status(StatusCode="Cancelled", Detail="Cancelled", DebugException="Grpc.Core.Internal.CoreErrorDetailException: {"created":"#1636135230.919000000","description":"Error received from peer ipv6:[::1]:28000","file":"T:\src\github\grpc\workspace_csharp_ext_windows_x64\src\core\lib\surface\call.cc","file_line":1062,"grpc_message":"Cancelled","grpc_status":1}")
Context Messages:
Exception occurred from calling /ServiceGrpc/Init.
Source : mscorlib
Status : Status(StatusCode="Cancelled", Detail="Cancelled", DebugException="Grpc.Core.Internal.CoreErrorDetailException: {"created":"#1636135230.919000000","description":"Error received from peer ipv6:[::1]:28000","file":"T:\src\github\grpc\workspace_csharp_ext_windows_x64\src\core\lib\surface\call.cc","file_line":1062,"grpc_message":"Cancelled","grpc_status":1}")
StatusCode : Cancelled
Trailers : Grpc.Core.Metadata
TargetSite : Void Throw()
Stack Trace : at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Grpc.Core.Internal.AsyncCall2.UnaryCall(TRequest msg) in T:\src\github\grpc\src\csharp\Grpc.Core\Internal\AsyncCall.cs:line 78 at Grpc.Core.DefaultCallInvoker.BlockingUnaryCall[TRequest,TResponse](Method2 method, String host, CallOptions options, TRequest request) in T:\src\github\grpc\src\csharp\Grpc.Core\DefaultCallInvoker.cs:line 46
at Grpc.Core.Interceptors.InterceptingCallInvoker.b__3_0[TRequest,TResponse](TRequest req, ClientInterceptorContext`2 ctx) in T:\src\github\grpc\src\csharp\Grpc.Core.Api\Interceptors\InterceptingCallInvoker.cs:line 51

The "LinkAssemblies" task failed unexpectedly in Plugin.FirebasePushNotification

I am trying to release the application on Android using Linker to reduce the apk size.
When I use None I donĀ“t have problem.
When I use SDK Assemblies Only I get the next error:
Severity Code Description Project File Line Suppression State
Error The "LinkAssemblies" task failed unexpectedly.
Mono.Linker.MarkException: Error processing method: 'System.Void Plugin.FirebasePushNotification.FirebasePushNotificationManager::Subscribe(System.String)' in assembly: 'Plugin.FirebasePushNotification.dll' ---> Mono.Cecil.ResolutionException: Failed to resolve System.Void Firebase.Messaging.FirebaseMessaging::SubscribeToTopic(System.String)
at Mono.Linker.Steps.MarkStep.HandleUnresolvedMethod(MethodReference reference)
at Mono.Linker.Steps.MarkStep.MarkMethod(MethodReference reference)
at Mono.Linker.Steps.MarkStep.MarkInstruction(Instruction instruction)
at Mono.Linker.Steps.MarkStep.MarkMethodBody(MethodBody body)
at Mono.Linker.Steps.MarkStep.ProcessMethod(MethodDefinition method)
at Mono.Linker.Steps.MarkStep.ProcessQueue()
--- End of inner exception stack trace ---
at Mono.Linker.Steps.MarkStep.ProcessQueue()
at Mono.Linker.Steps.MarkStep.ProcessPrimaryQueue()
at Mono.Linker.Steps.MarkStep.Process()
at MonoDroid.Tuner.MonoDroidMarkStep.Process(LinkContext context)
at Mono.Linker.Pipeline.Process(LinkContext context)
at MonoDroid.Tuner.Linker.Process(LinkerOptions options, ILogger logger, LinkContext& context)
at Xamarin.Android.Tasks.LinkAssemblies.Execute(DirectoryAssemblyResolver res)
at Xamarin.Android.Tasks.LinkAssemblies.Execute()
at Microsoft.Build.BackEnd.TaskExecutionHost.Microsoft.Build.BackEnd.ITaskExecutionHost.Execute()
at Microsoft.Build.BackEnd.TaskBuilder.<ExecuteInstantiatedTask>d__26.MoveNext()

ApplicationInsights Telemetry exception in system automation

In a project we call Powershell scripts in C#.
using (var runspace = RunspaceFactory.CreateRunspace())
{
runspace.Open();
var pipeline = runspace.CreatePipeline();
..
pipeline.Invoke();
..
This works without any issues until ApplicationInsights Telemetry package is installed. Version 1.2.x had this issue so I upgrade to 2.0.0, but still the same exception.
Stacktrace below:
System.Management.Automation.CmdletInvocationException
The type initializer for
'Microsoft.WindowsAzure.Commands.Common.MetricHelper' threw an
exception. System.Management.Automation.CmdletInvocationException: The
type initializer for
'Microsoft.WindowsAzure.Commands.Common.MetricHelper' threw an
exception. ---> System.TypeInitializationException: The type
initializer for 'Microsoft.WindowsAzure.Commands.Common.MetricHelper'
threw an exception. ---> System.Reflection.TargetInvocationException:
Exception has been thrown by the target of an invocation. --->
System.InvalidOperationException: Type
'Microsoft.ApplicationInsights.DependencyCollector.DependencyTrackingTelemetryModule,
Microsoft.AI.DependencyCollector, Version=2.0.0.0, Culture=neutral,
PublicKeyToken=31bf3856ad364e35' does not implement the required
interface
Microsoft.ApplicationInsights.Extensibility.ITelemetryModule. at
Microsoft.ApplicationInsights.Extensibility.Implementation.TelemetryConfigurationFactory.CreateInstance(Type
interfaceType, String typeName) at
Microsoft.ApplicationInsights.Extensibility.Implementation.TelemetryConfigurationFactory.LoadInstance(XElement
definition, Type expectedType, Object instance) at
Microsoft.ApplicationInsights.Extensibility.Implementation.TelemetryConfigurationFactory.LoadInstances[T](XElement
definition, ICollection`1 instances) --- End of inner exception
stack trace --- at System.RuntimeMethodHandle.InvokeMethod(Object
target, Object[] arguments, Signature sig, Boolean constructor) at
System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj,
Object[] parameters, Object[] arguments) at
System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags
invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at
Microsoft.ApplicationInsights.Extensibility.Implementation.TelemetryConfigurationFactory.LoadInstance(XElement
definition, Type expectedType, Object instance) at
Microsoft.ApplicationInsights.Extensibility.Implementation.TelemetryConfigurationFactory.LoadProperties(XElement
instanceDefinition, Object instance) at
Microsoft.ApplicationInsights.Extensibility.Implementation.TelemetryConfigurationFactory.LoadInstance(XElement
definition, Type expectedType, Object instance) at
Microsoft.ApplicationInsights.Extensibility.Implementation.TelemetryConfigurationFactory.Initialize(TelemetryConfiguration
configuration) at
Microsoft.ApplicationInsights.Extensibility.TelemetryConfiguration.get_Active()
at Microsoft.ApplicationInsights.TelemetryClient..ctor() at
Microsoft.WindowsAzure.Commands.Common.MetricHelper..cctor() ---
End of inner exception stack trace --- at
Microsoft.WindowsAzure.Commands.Common.MetricHelper.GenerateSha256HashString(String
originInput) at
Microsoft.WindowsAzure.Commands.Utilities.Common.AzurePSCmdlet.InitializeQosEvent()
at
Microsoft.WindowsAzure.Commands.Utilities.Common.AzurePSCmdlet.BeginProcessing()
at
Microsoft.WindowsAzure.Commands.Utilities.Profile.SubscriptionCmdletBase.BeginProcessing()
at System.Management.Automation.Cmdlet.DoBeginProcessing() at
System.Management.Automation.CommandProcessorBase.DoBegin() --- End
of inner exception stack trace --- at
System.Management.Automation.Runspaces.PipelineBase.Invoke(IEnumerable
input)
For now I deinstalled the NuGet package for ApplicationInsights, because I don't know a solution. Perhaps it's a bug in ApplicationInsights?

Could not load file or assembly 'DotNetOpenAuth.AspNet' or one of its dependencies

I have an Asp.net project, and in said projects web.config i have
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="DotNetOpenAuth.AspNet" publicKeyToken="2780ccd10d57b246" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-4.3.0.0" newVersion="4.3.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="DotNetOpenAuth.Core" publicKeyToken="2780ccd10d57b246" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-4.3.0.0" newVersion="4.3.0.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
(already followed a should-be-fix from another post)
but on runtime i get
Could not load file or assembly 'DotNetOpenAuth.AspNet' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)
When I open up the properties of my project, and go to refrences, i can see that there is a DotNetOpenAuth.Core entry, a DotNetOpenAuth.AspNet entry, a DotNetOpenAuth.OAuth entry,a DotNetOpenAuth.OAuth.Consumer entry, a DotNetOpenAuth.OpenId entry, and a DotNetOpenAuth.OpenId.RelyingParty entry, and theyre all set to Copy Local = true.
What could possibly be going wrong?
EDIT:
heres the full error log, looks like its still trying to load 4.3.0.0 to me
Assembly Load Trace: The following information can be helpful to determine why the assembly 'DotNetOpenAuth.AspNet' could not be loaded.
=== Pre-bind state information ===
LOG: User = MegaBadTouch\James
LOG: DisplayName = DotNetOpenAuth.AspNet
(Partial)
WRN: Partial binding information was supplied for an assembly:
WRN: Assembly Name: DotNetOpenAuth.AspNet | 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/James/Documents/Visual Studio 2012/Projects/Archive/Archive/
LOG: Initial PrivatePath = C:\Users\James\Documents\Visual Studio 2012\Projects\Archive\Archive\bin
Calling assembly : (Unknown).
===
LOG: This bind starts in default load context.
LOG: Using application configuration file: C:\Users\James\Documents\Visual Studio 2012\Projects\Archive\Archive\web.config
LOG: Using host configuration file: C:\Users\James\Documents\IISExpress\config\aspnet.config
LOG: Using machine configuration file from C:\Windows\Microsoft.NET\Framework\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/James/AppData/Local/Temp/Temporary ASP.NET Files/root/47d58003/7c1d4013/DotNetOpenAuth.AspNet.DLL.
LOG: Attempting download of new URL file:///C:/Users/James/AppData/Local/Temp/Temporary ASP.NET Files/root/47d58003/7c1d4013/DotNetOpenAuth.AspNet/DotNetOpenAuth.AspNet.DLL.
LOG: Attempting download of new URL file:///C:/Users/James/Documents/Visual Studio 2012/Projects/Archive/Archive/bin/DotNetOpenAuth.AspNet.DLL.
LOG: Using application configuration file: C:\Users\James\Documents\Visual Studio 2012\Projects\Archive\Archive\web.config
LOG: Using host configuration file: C:\Users\James\Documents\IISExpress\config\aspnet.config
LOG: Using machine configuration file from C:\Windows\Microsoft.NET\Framework\v4.0.30319\config\machine.config.
LOG: Redirect found in application configuration file: 4.0.0.0 redirected to 4.1.0.0.
LOG: Post-policy reference: DotNetOpenAuth.AspNet, Version=4.1.0.0, Culture=neutral, PublicKeyToken=2780ccd10d57b246
LOG: Attempting download of new URL file:///C:/Users/James/AppData/Local/Temp/Temporary ASP.NET Files/root/47d58003/7c1d4013/DotNetOpenAuth.AspNet.DLL.
LOG: Attempting download of new URL file:///C:/Users/James/AppData/Local/Temp/Temporary ASP.NET Files/root/47d58003/7c1d4013/DotNetOpenAuth.AspNet/DotNetOpenAuth.AspNet.DLL.
LOG: Attempting download of new URL file:///C:/Users/James/Documents/Visual Studio 2012/Projects/Archive/Archive/bin/DotNetOpenAuth.AspNet.DLL.
WRN: Comparing the assembly name resulted in the mismatch: Minor Version
ERR: Failed to complete setup of assembly (hr = 0x80131040). Probing terminated.
Stack Trace:
[FileLoadException: Could not load file or assembly 'DotNetOpenAuth.AspNet' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)]
[FileLoadException: Could not load file or assembly 'DotNetOpenAuth.AspNet, Version=4.1.0.0, Culture=neutral, PublicKeyToken=2780ccd10d57b246' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)]
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.nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, RuntimeAssembly locationHint, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks) +34
System.Reflection.RuntimeAssembly.InternalLoadAssemblyName(AssemblyName assemblyRef, Evidence assemblySecurity, RuntimeAssembly reqAssembly, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks) +152
System.Reflection.RuntimeAssembly.InternalLoad(String assemblyString, Evidence assemblySecurity, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean forIntrospection) +77
System.Reflection.RuntimeAssembly.InternalLoad(String assemblyString, Evidence assemblySecurity, StackCrawlMark& stackMark, Boolean forIntrospection) +16
System.Reflection.Assembly.Load(String assemblyString) +28
System.Web.Configuration.CompilationSection.LoadAssemblyHelper(String assemblyName, Boolean starDirective) +38
[ConfigurationErrorsException: Could not load file or assembly 'DotNetOpenAuth.AspNet, Version=4.1.0.0, Culture=neutral, PublicKeyToken=2780ccd10d57b246' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)]
System.Web.Configuration.CompilationSection.LoadAssemblyHelper(String assemblyName, Boolean starDirective) +752
System.Web.Configuration.CompilationSection.LoadAllAssembliesFromAppDomainBinDirectory() +218
System.Web.Configuration.CompilationSection.LoadAssembly(AssemblyInfo ai) +130
System.Web.Compilation.BuildManager.GetReferencedAssemblies(CompilationSection compConfig) +170
System.Web.Compilation.BuildManager.GetPreStartInitMethodsFromReferencedAssemblies() +91
System.Web.Compilation.BuildManager.CallPreStartInitMethods(String preStartInitListPath) +258
System.Web.Compilation.BuildManager.ExecutePreAppStart() +135
System.Web.Hosting.HostingEnvironment.Initialize(ApplicationManager appManager, IApplicationHost appHost, IConfigMapPathFactory configMapPathFactory, HostingEnvironmentParameters hostingParameters, PolicyLevel policyLevel, Exception appDomainCreationException) +516
[HttpException (0x80004005): Could not load file or assembly 'DotNetOpenAuth.AspNet, Version=4.1.0.0, Culture=neutral, PublicKeyToken=2780ccd10d57b246' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)]
System.Web.HttpRuntime.FirstRequestInit(HttpContext context) +9874840
System.Web.HttpRuntime.EnsureFirstRequestInit(HttpContext context) +101
System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest wr, HttpContext context) +254
I had the same error It was that one of the references that you have added might have got missed . all you need to do is drop the references and add them back manually . or copy your code into a new solution it would work .I copied my code into a " new empty project " and ran it . it had no problems then .
Open a new empty project with new classes and aspx and copy just your code into it , it should work .
I changed the versions to 4.1.0.0 and it worked for me.
<dependentAssembly>
<assemblyIdentity name="DotNetOpenAuth.Core" publicKeyToken="2780CCD10D57B246" culture="neutral" />
<bindingRedirect oldVersion="1.0.0.0-4.1.0.0" newVersion="4.1.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="DotNetOpenAuth.AspNet" publicKeyToken="2780CCD10D57B246" culture="neutral" />
<bindingRedirect oldVersion="1.0.0.0-4.1.0.0" newVersion="4.1.0.0" />
</dependentAssembly>
</assemblyBinding>

Ninject ASP.NET extension throwing TypeLoadException

I'm trying to use Ninject 3 in an ASP.NET webforms application. We've been using it without the Ninject.Web extension for a while by creating a new injection kernel everywhere we needed one. It didn't occur to me until now that that's not the right way to do things. I wrote a little test application that is successfully using Ninject.Web, but when I tried to do the same thing in our real application, I'm receiving a TypeLoadException as soon as the page loads. It doesn't even make it into my code where I can set a breakpoint. Here's the exception and stack trace:
Could not load type
'System.Runtime.CompilerServices.ExtensionAttribute' from assembly
'mscorlib, Version=4.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.Runtime.CompilerServices.ExtensionAttribute' from assembly
'mscorlib, Version=4.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.Runtime.CompilerServices.ExtensionAttribute' from assembly
'mscorlib, Version=4.0.0.0, Culture=neutral,
PublicKeyToken=b77a5c561934e089'.]
System.ModuleHandle.ResolveType(RuntimeModule module, Int32 typeToken,
IntPtr* typeInstArgs, Int32 typeInstCount, IntPtr* methodInstArgs,
Int32 methodInstCount, ObjectHandleOnStack type) +0
System.ModuleHandle.ResolveTypeHandleInternal(RuntimeModule module,
Int32 typeToken, RuntimeTypeHandle[] typeInstantiationContext,
RuntimeTypeHandle[] methodInstantiationContext) +525
System.ModuleHandle.ResolveTypeHandle(Int32 typeToken,
RuntimeTypeHandle[] typeInstantiationContext, RuntimeTypeHandle[]
methodInstantiationContext) +19
System.Reflection.RuntimeModule.ResolveType(Int32 metadataToken,
Type[] genericTypeArguments, Type[] genericMethodArguments) +315
System.Reflection.CustomAttribute.FilterCustomAttributeRecord(CustomAttributeRecord
caRecord, MetadataImport scope, Assembly& lastAptcaOkAssembly,
RuntimeModule decoratedModule, MetadataToken decoratedToken,
RuntimeType attributeFilterType, Boolean mustBeInheritable, Object[]
attributes, IList derivedAttributes, RuntimeType& attributeType,
IRuntimeMethodInfo& ctor, Boolean& ctorHasParameters, Boolean&
isVarArg) +208
System.Reflection.CustomAttribute.GetCustomAttributes(RuntimeModule
decoratedModule, Int32 decoratedMetadataToken, Int32 pcaCount,
RuntimeType attributeFilterType, Boolean mustBeInheritable, IList
derivedAttributes, Boolean isDecoratedTargetSecurityTransparent) +1171
System.Reflection.CustomAttribute.GetCustomAttributes(RuntimeAssembly
assembly, RuntimeType caType) +146
WebActivator.AssemblyExtensions.GetActivationAttributes(Assembly
assembly) +114
WebActivator.ActivationManager.RunActivationMethods() +286
WebActivator.ActivationManager.RunPreStartMethods() +38
WebActivator.ActivationManager.Run() +56
[InvalidOperationException: The pre-application start initialization
method Run on type WebActivator.ActivationManager threw an exception
with the following error message: Could not load type
'System.Runtime.CompilerServices.ExtensionAttribute' from assembly
'mscorlib, Version=4.0.0.0, Culture=neutral,
PublicKeyToken=b77a5c561934e089'..]
System.Web.Compilation.BuildManager.InvokePreStartInitMethods(ICollection`1
methods) +11567502
System.Web.Compilation.BuildManager.CallPreStartInitMethods() +465
System.Web.Hosting.HostingEnvironment.Initialize(ApplicationManager
appManager, IApplicationHost appHost, IConfigMapPathFactory
configMapPathFactory, HostingEnvironmentParameters hostingParameters,
PolicyLevel policyLevel, Exception appDomainCreationException) +1167
[HttpException (0x80004005): The pre-application start initialization
method Run on type WebActivator.ActivationManager threw an exception
with the following error message: Could not load type
'System.Runtime.CompilerServices.ExtensionAttribute' from assembly
'mscorlib, Version=4.0.0.0, Culture=neutral,
PublicKeyToken=b77a5c561934e089'..]
System.Web.HttpRuntime.FirstRequestInit(HttpContext context) +11556592
System.Web.HttpRuntime.EnsureFirstRequestInit(HttpContext context)
+141 System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest
wr, HttpContext context) +4813333
None of my searching has turned up anything terribly helpful, but the main avenue I've explored is a potential conflict between the version of .NET that Ninject was built against and the version that I'm actually running. I've never installed .NET 4.5 on my system, so I'm certain that I'm building against 4.0. I then built the most recent version of Ninject (3.0.2) and the extensions from source to be sure that it's using 4.0 as well. I also tried adding all the libraries that I'm using in the real app to my test app to see if there's a conflict but that didn't turn up anything. (However, I didn't go so far as to put in code that exercises them. I don't know if that would change anything.)
Has anyone seen this kind of problem before or have any ideas that I can try? Is there more info I can provide that would be helpful?
Alternatively, is there some other way I can use Ninject in an ASP.NET application instead of the ninject.web extension? Would wrapping the Ninject kernel up in a singleton work just as well?

Resources