Exception has been thrown by the target of an invocation, in jenkins' groovy script - jenkins

I need to maintain a jenkins groovy script (we are not sure however if it ever worked).The script for a pipeline build has multiple stages ('revision' and 'build' stages before 'unit tests' have succeeded), one of which is the following:
stage('Unit Tests')
{
stages
{
stage('Tests')
{
parallel
{
stage('TRKengineTest')
{
steps
{
bat '"C:\\Program Files (x86)\\NUnit.org\\nunit-console\\nunit3-console.exe" TRKengine\\TRKengine.Test\\bin\\Release\\netcoreapp3.1\\TRKengine.Test.dll --result=TRKengine.Test.xml;format=nunit2 --timeout=180000 --workers=1'
echo "Something to do?"
}
}
stage('TRKengineGUItest')
{
steps
{
//bat '"C:\\Program Files (x86)\\NUnit.org\\nunit-console\\nunit3-console.exe" TRKengine\\TRKengineGUI.Test\\bin\\Release\\netcoreapp3.1\\TRKengineGUI.Test.dll --result=TRKengineGUI.Test.xml;format=nunit2 --timeout=180000 -v --workers=1'
echo "Nothing to do"
}
}
}
}
stage('Testresults')
{
steps
{
nunit testResultsPattern: 'TRKengine.Test.xml, TRKengineGUI.Test.xml'
}
}
}
}
The bat command returns a -100 error. More precisely:
C:\Jenkins\workspace\TRKengine_trunk>"C:\Program Files (x86)\NUnit.org\nunit-console\nunit3-console.exe" TRKengine\TRKengine.Test\bin\Release\netcoreapp3.1\TRKengine.Test.dll --result=TRKengine.Test.xml;format=nunit2 --timeout=180000 -v --workers=1
NUnit Console Runner 3.6.1
Copyright (C) 2017 Charlie Poole
Runtime Environment
OS Version: Microsoft Windows NT 10.0.14393.0
CLR Version: 4.0.30319.42000
Test Files
TRKengine\TRKengine.Test\bin\Release\netcoreapp3.1\TRKengine.Test.dll
Errors, Failures and Warnings
1) Error :
Exception has been thrown by the target of an invocation.
Server stack trace:
at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)
at System.Reflection.RuntimeConstructorInfo.Invoke(BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at System.RuntimeType.CreateInstanceImpl(BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes, StackCrawlMark& stackMark)
at System.Activator.CreateInstance(Type type, BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes)
at System.Activator.CreateInstance(String assemblyString, String typeName, Boolean ignoreCase, BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes, Evidence securityInfo, StackCrawlMark& stackMark)
at System.Activator.CreateInstance(String assemblyName, String typeName, Boolean ignoreCase, BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes, Evidence securityInfo)
at System.AppDomain.CreateInstance(String assemblyName, String typeName, Boolean ignoreCase, BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes, Evidence securityAttributes)
at System.AppDomain.CreateInstanceAndUnwrap(String assemblyName, String typeName, Boolean ignoreCase, BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes, Evidence securityAttributes)
at System.AppDomain.CreateInstanceAndUnwrap(String assemblyName, String typeName, Boolean ignoreCase, BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes, Evidence securityAttributes)
at NUnit.Engine.Drivers.NUnit3FrameworkDriver.Load(String testAssemblyPath, IDictionary`2 settings)
at NUnit.Engine.Runners.DirectTestRunner.LoadPackage()
at NUnit.Engine.Runners.DirectTestRunner.EnsurePackageIsLoaded()
at NUnit.Engine.Runners.DirectTestRunner.RunTests(ITestEventListener listener, TestFilter filter)
at System.Runtime.Remoting.Messaging.StackBuilderSink._PrivateProcessMessage(IntPtr md, Object[] args, Object server, Object[]& outArgs)
at System.Runtime.Remoting.Messaging.StackBuilderSink.SyncProcessMessage(IMessage msg)
Exception rethrown at [0]:
at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
at NUnit.Engine.ITestEngineRunner.Run(ITestEventListener listener, TestFilter filter)
at NUnit.Engine.Runners.ProcessRunner.RunTests(ITestEventListener listener, TestFilter filter)
Test Run Summary
Overall result: Failed
Test Count: 0, Passed: 0, Failed: 0, Warnings: 0, Inconclusive: 0, Skipped: 0
Start time: 2020-07-15 11:32:42Z
End time: 2020-07-15 11:32:43Z
Duration: 0.556 seconds
Results (nunit2) saved as TRKengine.Test.xml
script returned exit code -100
I have tried a couple of things:
1)First of all, it seems like the path of nunit-console.exe is wrong but as I found out, it can be used in recent releases of nunit.
2)The path of the test.dll is correct, as I manually navigated there and ..netcoreapp3.1\TRKengine.Test.dll is indeed there.
3)I have spotted --result=TRKengine.Test.xml;format=nunit2 in other exampels across the internet.
4)I experimented with removing any combinations of the remaining parameters, workers/timeout -v etc, without success.
So the line where the error appears, seems to be correct, and my intuition is that probably the mistake has already happened somewhere else.
I am not sure what "invocation" means. I have also checked How do you run NUnit tests from Jenkins? that seems related and it feels like Winston33 's proposition is exactly like what is happening here.
Something that is a bit worrying is that my machine is 64 bits but the path is ..x86.
I also have access to code and all projects inside the solution build successfully
I am a total beginner in both jenkins and groovy, so if I had not disclosed any necessary information please notify me.
Any help would be greatly appreciated.

The error message: Exception has been thrown by the target of an invocation is a common message for C# based products
means that nunit tries to call the target test dll dynamically but it (dll) throws some exception that unfortunately you don't see.
check the nunit issue that is very close to yours https://github.com/nunit/nunit/issues/1509
there is suggestion to set following nunit parameters
--trace=Debug to see more information about error
--inprocess to run tests in a single process
there several log files should be created that could contain helpful information to understand why the error occurred.

Related

Jni4net with Java 11

I am using the jni4net to bridge a .net dll to java. It is working fine with in the Java8 environment. Unfortunately, with java 8 I am getting the following error:
I have tried to compile generated jvm with java-11, but still the same problem.
Can't bind bridge:Can't initialize proxy java.lang.System
Can't bind bridge:net.sf.jni4net.jni.JNIException: Can't initialize proxy
java.lang.System ---> System.Reflection.TargetInvocationException: Ein
Aufrufziel hat einen Ausnahmefehler verursacht. ---> java.lang.LinkageError:
runFinalizersOnExit
bei net.sf.jni4net.jni.JNIEnv.ExceptionTest()
bei net.sf.jni4net.jni.JNIEnv.GetStaticMethodID(Class clazz, String name,
String sig)
bei java.lang.System.InitJNI(JNIEnv __env, Class __class)
--- Ende der internen Ausnahmestapelüberwachung ---
bei System.RuntimeMethodHandle.InvokeMethod(Object target, Object[]
arguments, Signature sig, Boolean constructor)
bei System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj,
Object[] parameters, Object[] arguments)
bei System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags
invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
bei System.Reflection.MethodBase.Invoke(Object obj, Object[] parameters)
bei net.sf.jni4net.utils.Registry.RegisterStaticAndMethods(RegistryRecord
record, JNIEnv env)
--- Ende der internen Ausnahmestapelüberwachung ---
bei net.sf.jni4net.utils.Registry.RegisterStaticAndMethods(RegistryRecord
record, JNIEnv env)
bei net.sf.jni4net.utils.Registry.BindJvm(RegistryRecord record, ClassLoader
classLoader, JNIEnv env)
bei net.sf.jni4net.utils.Registry.BindJvm(RegistryRecord record, JNIEnv env)
bei net.sf.jni4net.utils.Registry.RegisterType(Type type, Boolean bindJVM,
JNIEnv env)
bei net.sf.jni4net.utils.Registry.RegisterAssembly(Assembly assembly,
Boolean bindJVM)
bei net.sf.jni4net.Bridge.RegisterAssembly(Assembly assembly)
bei net.sf.jni4net.Bridge.BindCore(JNIEnv env, BridgeSetup newSetup)
bei net.sf.jni4net.Bridge.initDotNetImpl(IntPtr envi, IntPtr clazz)
Can't initialize jni4net BridgeC
I have managed to compile and execute the same with java 11.
Try downloading the JNI4NET libs inside your project.
As a temporary solution you can use ProcessBuilder and define in it environment the JAVA_HOME variable with the path to java 8.

Role based authorization in asp.net mvc3

Hi am new ASP.NET MVC. Currently am learning MVCmusicstore tutorial from asp.net official website.But Iam getting error while executing the project after implementing role based authorization in it.The stack trace is given below.Please advice
Stack Trace:
[FileLoadException: Could not load file or assembly 'System.Runtime.DurableInstancing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies.
The handle is invalid. (Exception from HRESULT: 0x80070006 (E_HANDLE))]
System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor, Boolean& bNeedSecurityCheck) +0
System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache) +98
System.RuntimeType.CreateInstanceDefaultCtor(Boolean publicOnly, Boolean skipVisibilityChecks, Boolean skipCheckThis, Boolean fillCache) +241
System.Activator.CreateInstance(Type type, Boolean nonPublic) +69
System.RuntimeType.CreateInstanceImpl(BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes) +1136
System.Activator.CreateInstance(Type type, BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes) +111
System.Activator.CreateInstance(Type type, BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture) +23
System.Web.HttpRuntime.CreateNonPublicInstance(Type type, Object[] args) +60
System.Web.Configuration.HttpModulesSection.CreateModules() +221
System.Web.HttpApplication.InitModules() +28
System.Web.HttpApplication.InitInternal(HttpContext context, HttpApplicationState state, MethodInfo[] handlers) +828
System.Web.HttpApplicationFactory.GetNormalApplicationInstance(HttpContext context) +304
System.Web.HttpApplicationFactory.GetApplicationInstance(HttpContext context) +107
System.Web.HttpRuntime.ProcessRequestInternal(HttpWorkerRequest wr) +327
It looks like you are missing a reference to the following assembly:
System.Runtime.DurableInstancing
Right-click on the project, select "Add Reference" and add this assembly.

Publish web on Azure. Operation could destabilize the runtime in MVC3

I published my web project to Azure and when I pull it up in the browser I see the error below.
I fixed the same error by disabling IntelliTrace, when I published my Web ROLE to windows azure. But I could not find where to disable it in Publish web settings.
http://www.windowsazure.com/media/devcenter/dotnet/dev-net-getting-started-039.png
[VerificationException: Operation could destabilize the runtime.]
FluentValidation.AbstractValidator`1..ctor() in c:\Projects\FluentValidation\src\FluentValidation\AbstractValidator.cs:36
Poll.Areas.Shared.Validators.Account.LogOnValidator..ctor() in D:\Code\Poll\Poll\Areas\Shared\Validators\Account\LogOnValidator.cs:15
[TargetInvocationException: Exception has been thrown by the target of an invocation.]
System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor, Boolean& bNeedSecurityCheck) +0
System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark) +113
System.RuntimeType.CreateInstanceDefaultCtor(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark) +232
System.Activator.CreateInstance(Type type, Boolean nonPublic) +83
System.Activator.CreateInstance(Type type) +6
FluentValidation.Internal.InstanceCache.GetOrCreateInstance(Type type, Func2 factory) in c:\Projects\FluentValidation\src\FluentValidation\Internal\InstanceCache.cs:58
FluentValidation.Internal.InstanceCache.GetOrCreateInstance(Type type) in c:\Projects\FluentValidation\src\FluentValidation\Internal\InstanceCache.cs:37
FluentValidation.Attributes.AttributedValidatorFactory.GetValidator(Type type) in c:\Projects\FluentValidation\src\FluentValidation\Attributes\AttributedValidatorFactory.cs:48
FluentValidation.Mvc.FluentValidationModelValidatorProvider.GetValidators(ModelMetadata metadata, ControllerContext context) in c:\Projects\FluentValidation\src\FluentValidation.Mvc3\FluentValidationModelValidatorProvider.cs:75
System.Web.Mvc.<>c__DisplayClass7.<GetValidators>b__6(ModelValidatorProvider provider) +21
System.Linq.<SelectManyIterator>d__142.MoveNext() +234
System.Linq.d__142.MoveNext() +397
System.Web.Mvc.HtmlHelper.GetUnobtrusiveValidationAttributes(String name, ModelMetadata metadata) +297
System.Web.Mvc.Html.InputExtensions.InputHelper(HtmlHelper htmlHelper, InputType inputType, ModelMetadata metadata, String name, Object value, Boolean useViewData, Boolean isChecked, Boolean setId, Boolean isExplicitValue, IDictionary2 htmlAttributes) +794
System.Web.Mvc.Html.InputExtensions.HiddenHelper(HtmlHelper htmlHelper, ModelMetadata metadata, Object value, Boolean useViewData, String expression, IDictionary2 htmlAttributes) +124
System.Web.Mvc.Html.InputExtensions.HiddenFor(HtmlHelper1 htmlHelper, Expression1 expression, IDictionary2 htmlAttributes) +90
System.Web.Mvc.Html.InputExtensions.HiddenFor(HtmlHelper1 htmlHelper, Expression1 expression) +54
I fixed this problem by "Enable package manager restore". Right click on solution -> Enable package manager restore
If you think it's IntelliTrace, and you've enabled it, you can disable it by:
Right click on your Cloud Project
Select Publish
Go to Settings
Advanced
(Un)check the "IntelliTrace" checkbox
This dialog is only available when you chose the "Publish" action for the context menu.
You can continue to use IntelliTrace by taking a look at the top of your exception stack and add exception module in advanced settings. Explained here.

Unable to Create DbContext per Request with Simple Injector

Simple Inject is throwing the following exception when attempting to register my DbContext.
The supplied connection string is not valid, because it contains insufficient mapping or metadata information.
Parameter name: connectionString
I'm new to DI and could be missing something fairly obvious. The connection string looks fine. It is the same one that gets used to create the DbContext normally. I was attempting the solution here
public static class SimpleInjectorInitializer
{
/// <summary>Initialize the container and register
// it as MVC3 Dependency Resolver.</summary>
public static void Initialize()
{
var container = new Container();
InitializeContainer(container);
container.RegisterMvcControllers(
Assembly.GetExecutingAssembly());
container.RegisterMvcAttributeFilterProvider();
container.Verify();
DependencyResolver.SetResolver(
new SimpleInjectorDependencyResolver(container));
}
private static void InitializeContainer(
Container container)
{
}
}
Update: I still haven't solved my issue, but it is very similar to this issue with Ninject
Stack Trace:
System.InvalidOperationException was unhandled by user code
Message=The configuration is invalid. Creating the instance for type _AccountController failed. Error occurred while trying to get an instance of type _AccountController. The type initializer for 'Web.Controllers._AccountController' threw an exception.
Source=SimpleInjector
StackTrace:
at SimpleInjector.Helpers.Verify(IInstanceProducer instanceProducer, Type serviceType)
at SimpleInjector.Container.ValidateRegistrations()
at SimpleInjector.Container.Verify()
at Web.App_Start.SimpleInjectorInitializer.Initialize() in C:\workspace\BrowsarServer\QARSite\Web\App_Start\SimpleInjectorInitializer.cs:line 24
InnerException: SimpleInjector.ActivationException
Message=Error occurred while trying to get an instance of type _AccountController. The type initializer for 'Web.Controllers._AccountController' threw an exception.
Source=SimpleInjector
StackTrace:
at SimpleInjector.InstanceProducers.InstanceProducer.ThrowErrorWhileTryingToGetInstanceOfType(Exception innerException)
at SimpleInjector.InstanceProducers.InstanceProducer.GetInstance()
at SimpleInjector.Helpers.Verify(IInstanceProducer instanceProducer, Type serviceType)
InnerException: System.TypeInitializationException
Message=The type initializer for 'Web.Controllers._AccountController' threw an exception.
Source=Web
TypeName=Web.Controllers._AccountController
StackTrace:
at Web.Controllers._AccountController..ctor()
at lambda_method(Closure )
at SimpleInjector.InstanceProducers.InstanceProducer.GetInstance()
InnerException: System.ArgumentException
Message=The supplied connection string is not valid, because it contains insufficient mapping or metadata information.
Parameter name: connectionString
Source=System.Data.Entity
ParamName=connectionString
StackTrace:
at System.Data.Objects.ObjectContext..ctor(EntityConnection connection, Boolean isConnectionConstructor)
at System.Data.Objects.ObjectContext..ctor(String connectionString, String defaultContainerName)
at Web.Models.BrowsarEntities..ctor() in C:\workspace\BrowsarServer\QARSite\Web\Models\Browsar.Designer.cs:line 90
at Web.Controllers._AccountController..cctor() in C:\workspace\BrowsarServer\QARSite\Web\Controllers\_AccountController.cs:line 15
InnerException: System.InvalidOperationException
Message=Unable to determine application context. The ASP.NET application path could not be resolved.
Source=System.Data.Entity
StackTrace:
at System.Data.Metadata.Edm.AspProxy.GetBuildManagerReferencedAssemblies()
at System.Data.Metadata.Edm.DefaultAssemblyResolver.GetAllDiscoverableAssemblies()
at System.Data.Metadata.Edm.DefaultAssemblyResolver.GetWildcardAssemblies()
at System.Data.Metadata.Edm.MetadataArtifactLoaderCompositeResource.LoadResources(String assemblyName, String resourceName, ICollection`1 uriRegistry, MetadataArtifactAssemblyResolver resolver)
at System.Data.Metadata.Edm.MetadataArtifactLoaderCompositeResource.CreateResourceLoader(String path, ExtensionCheck extensionCheck, String validExtension, ICollection`1 uriRegistry, MetadataArtifactAssemblyResolver resolver)
at System.Data.Metadata.Edm.MetadataArtifactLoader.Create(String path, ExtensionCheck extensionCheck, String validExtension, ICollection`1 uriRegistry, MetadataArtifactAssemblyResolver resolver)
at System.Data.Metadata.Edm.MetadataCache.SplitPaths(String paths)
at System.Data.Common.Utils.Memoizer`2.<>c__DisplayClass2.<Evaluate>b__0()
at System.Data.Common.Utils.Memoizer`2.Result.GetValue()
at System.Data.Common.Utils.Memoizer`2.Evaluate(TArg arg)
at System.Data.EntityClient.EntityConnection.GetMetadataWorkspace(Boolean initializeAllCollections)
at System.Data.Objects.ObjectContext.RetrieveMetadataWorkspaceFromConnection()
at System.Data.Objects.ObjectContext..ctor(EntityConnection connection, Boolean isConnectionConstructor)
InnerException: System.Reflection.TargetInvocationException
Message=Exception has been thrown by the target of an invocation.
Source=mscorlib
StackTrace:
at System.RuntimeMethodHandle._InvokeMethodFast(IRuntimeMethodInfo method, Object target, Object[] arguments, SignatureStruct& sig, MethodAttributes methodAttributes, RuntimeType typeOwner)
at System.RuntimeMethodHandle.InvokeMethodFast(IRuntimeMethodInfo method, Object target, Object[] arguments, Signature sig, MethodAttributes methodAttributes, RuntimeType typeOwner)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, Boolean skipVisibilityChecks)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at System.Data.Metadata.Edm.AspProxy.GetBuildManagerReferencedAssemblies()
InnerException: System.InvalidOperationException
Message=This method cannot be called during the application's pre-start initialization stage.
Source=System.Web
StackTrace:
at System.Web.Compilation.BuildManager.EnsureTopLevelFilesCompiled()
at System.Web.Compilation.BuildManager.GetReferencedAssemblies()
InnerException:
The root cause is burried deep down in the inner exceptions. When inspecting the stack trace, you will be able to find the cause of this. The reason is in the following two inner exceptions:
InvalidOperationException: Unable to determine application context.
The ASP.NET application path could not be resolved.
and:
InvalidOperationException: This method cannot be called during the
application's pre-start initialization stage.
In other words, this exception is caused by a timing problem. I'm not sure if you can change your connection string to solve this, but you can also move your initalization to a later moment in starting the application. You can do this as follows:
Remove the [assembly: WebActivator.PreApplicationStartMethod] (top line) of the SimpleInjectorInitializer.cs class.
Add a call to the SimpleInjectorInitializer.Initialize() method in the Application_Start() event of the global asax.
After doing this, initializing (and especially, verifying) of the object graph is done after the pre-init state, which seems to be too early for EF in an ASP.NET environment.
Another option is to remove the container.Verify(); call from the SimpleInjectorInitializer.Initialize method, since it is the early verification process that is killing you. However, please read this Verify the container’s configuration first, to see alternatives, before doing so.
Although you use a class DbContext it looks like it is derived from ObjectContext. In that case you should use an EntityConnectionStringBuilder to build the connection string.
You may be missing some of the metadata information in your connection string. For example entity framework has some special metadata in the connection string, see sample below:
<add name="MyEntities" connectionString="metadata=res://*/MyEntitiesStore.csdl|res://*/MyEntitiesStore.ssdl|res://*/MyEntitiesStore.msl;provider=System.Data.SqlClient;provider connection string="Data Source=<your server>;Initial Catalog=<your DB>;Integrated Security=False;User ID=<user>;Password=<pass>;MultipleActiveResultSets=True""
providerName="System.Data.EntityClient" />

ASP.NET-MVC (IIS6) Error on high traffic: Specified cast is not valid

I just launched my tiny webapp on my humble dedicated server (Win2003)... running ASP.NET MVC, LINQ2SQL, SQL Express 2005, and IIS6 (setup with wildcard mapping)
The website runs smoothly 90% of the times. However, on relatively high traffic, LINQ2SQL throws the error:
Specified cast is not valid
This error is ONLY thrown at high traffic. I have NO IDEA how or exactly why this happens. Caching did not remove this problem entirely.
Anyone seen this problem before? are there any secret SQL Server tweaking I should've done?
Or at least, any ideas on how to diagnose this issue? because i'm out!
Naimi
Stacktrace (from Event Log):
at System.Data.SqlClient.SqlBuffer.get_SqlGuid()
at System.Data.SqlClient.SqlDataReader.GetGuid(Int32 i)
at Read_Friend(ObjectMaterializer`1 )
at System.Data.Linq.SqlClient.ObjectReaderCompiler.ObjectReader`2.MoveNext()
at Dudlers.Web.Models.DudlersDataContext.GetFriendRequests(Guid userId) in C:\Web\Models\DudlersDataContext.cs:line 562
at Dudlers.Web.Controllers.BaseController.View(String viewName, String masterName, Object viewData) in C:\Web\Controllers\BaseController.cs:line 39
at System.Web.Mvc.Controller.View(String viewName)
at Dudlers.Web.Controllers.CatController.Index() in C:\Web\Controllers\CatController.cs:line 25
at lambda_method(ExecutionScope , ControllerBase , Object[] )
at System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters)
at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(MethodInfo methodInfo, IDictionary`2 parameters)
at System.Web.Mvc.ControllerActionInvoker.c__DisplayClassb.b__8()
at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation)
at System.Web.Mvc.ControllerActionInvoker.c__DisplayClassb.c__DisplayClassd.b__a()
at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodWithFilters(MethodInfo methodInfo, IDictionary`2 parameters, IList`1 filters)
at System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName)
at System.Web.Mvc.Controller.ExecuteCore()
at System.Web.Mvc.ControllerBase.Execute(RequestContext requestContext)
at System.Web.Mvc.ControllerBase.System.Web.Mvc.IController.Execute(RequestContext requestContext)
at System.Web.Mvc.MvcHandler.ProcessRequest(HttpContextBase httpContext)
at System.Web.Mvc.MvcHandler.ProcessRequest(HttpContext httpContext)
at System.Web.Mvc.MvcHandler.System.Web.IHttpHandler.ProcessRequest(HttpContext httpContext)
at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
We had a similar problem with LINQ that we get "Unable to cast object of type 'System.Int32' to type 'System.String'" and "Specified cast is not valid."
Examples of stacktraces
System.InvalidCastException: Unable to cast object of type 'System.Int32' to type 'System.String'.
at System.Data.SqlClient.SqlBuffer.get_String()
at System.Data.SqlClient.SqlDataReader.GetString(Int32 i)
at Read_Person(ObjectMaterializer`1 )
at System.Data.Linq.SqlClient.ObjectReaderCompiler.ObjectReader`2.MoveNext()
at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
at RF.Ias.Services.Person.BusinessLogic.PersonTransactionScripts.GetPersons(IEnumerable`1 personIds, Boolean includeAddress, Boolean includeContact)
at CompositionAopProxy_5b0727341ad64f29b816c1b73d11dd44.GetPersons(IEnumerable`1 personIds, Boolean includeAddress, Boolean includeContact)
at RF.Ias.Services.Person.ServiceImplementation.PersonService.GetPersons(GetPersonRequest request)
System.InvalidCastException: Specified cast is not valid.
at System.Data.SqlClient.SqlBuffer.get_Int32()
at System.Data.SqlClient.SqlDataReader.GetInt32(Int32 i)
at Read_GetRolesForOrganisationResult(ObjectMaterializer`1 )
at System.Data.Linq.SqlClient.ObjectReaderCompiler.ObjectReader`2.MoveNext()
at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
at RF.Ias.Services.Role.DataAccess.RoleDataAccess.GetRolesForOrganisation(GetRolesForOrganisationCriteria criteria, Int32 pageIndex, Int32 pageSize, Int32& recordCount)
at RF.Ias.Services.Role.BusinessLogic.RoleTransactionScripts.GetRolesForOrganisation(GetRolesForOrganisationCriteria criteria, Int32 pageIndex, Int32 pageSize, Int32& recordCount)
at CompositionAopProxy_4bd29c6074f54d10a2c09bd4ab27ca66.GetRolesForOrganisation(GetRolesForOrganisationCriteria criteria, Int32 pageIndex, Int32 pageSize, Int32& recordCount)
at RF.Ias.Services.Role.ServiceImplementation.RoleService.GetRolesForOrganisation(GetRolesForOrganisationRequest request)
We used to get these exceptions if we first got a exception like this "System.InvalidOperationException: There is already an open DataReader associated with this Command which must be closed first." or " A transport-level error has occurred when receiving results from the server. (provider: TCP Provider, error: 0 - An existing connection was forcibly closed by the remote host.)".
The first exception occur for a different instance of the DataCOntext then for all those that then are following.
After some research and asking in this thread , I found that the reason was that I did not dispose the DataContexts. After I started to do that, it dissappered.
Sounds like maybe a race condition, or perhaps a rare bug that is only correlated with high traffic because that when most of your requests occur.

Resources