LINQ to SQL: intermittent AccessViolationException wrapped in TargetInvocationException - c#

Since a few weeks we are experiencing W3WP-crashes with our ASP.Net web application. These started after our webservers were updated. Our application did not change and has been stable for years.
Our situation seems to be a lot like this earlier question. And this question might also be related, though in our case the queries run fine in 99.9% of the times used.
We use a lot of uncompiled LINQ queries and tried if compiling them would prevent these crashes. The number of crashes decreased drastically, but they still do occur.
Also wrapping our queries in a try catch and then catching the TargetInvocationException does not work. The exception is not caught.
When a crash happens, we get a WER-report and can retreive a crash dump.
A stack trace from a dump for an uncompiled query typically looks like this:
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.Delegate.DynamicInvokeImpl(Object[] args)
at System.Data.Linq.SqlClient.QueryConverter.VisitInvocation(InvocationExpression invoke)
at System.Data.Linq.SqlClient.QueryConverter.VisitInner(Expression node)
at System.Data.Linq.SqlClient.QueryConverter.VisitExpression(Expression exp)
at System.Data.Linq.SqlClient.QueryConverter.VisitBinary(BinaryExpression b)
at System.Data.Linq.SqlClient.QueryConverter.VisitInner(Expression node)
at System.Data.Linq.SqlClient.QueryConverter.VisitExpression(Expression exp)
at System.Data.Linq.SqlClient.QueryConverter.VisitBinary(BinaryExpression b)
at System.Data.Linq.SqlClient.QueryConverter.VisitInner(Expression node)
at System.Data.Linq.SqlClient.QueryConverter.Visit(Expression node)
at System.Data.Linq.SqlClient.QueryConverter.VisitWhere(Expression sequence, LambdaExpression predicate)
at System.Data.Linq.SqlClient.QueryConverter.VisitSequenceOperatorCall(MethodCallExpression mc)
at System.Data.Linq.SqlClient.QueryConverter.VisitInner(Expression node)
at System.Data.Linq.SqlClient.QueryConverter.VisitWhere(Expression sequence, LambdaExpression predicate)
at System.Data.Linq.SqlClient.QueryConverter.VisitSequenceOperatorCall(MethodCallExpression mc)
at System.Data.Linq.SqlClient.QueryConverter.VisitInner(Expression node)
at System.Data.Linq.SqlClient.QueryConverter.VisitSelect(Expression sequence, LambdaExpression selector)
at System.Data.Linq.SqlClient.QueryConverter.VisitSequenceOperatorCall(MethodCallExpression mc)
at System.Data.Linq.SqlClient.QueryConverter.VisitInner(Expression node)
at System.Data.Linq.SqlClient.QueryConverter.VisitDistinct(Expression sequence)
at System.Data.Linq.SqlClient.QueryConverter.VisitSequenceOperatorCall(MethodCallExpression mc)
at System.Data.Linq.SqlClient.QueryConverter.VisitInner(Expression node)
at System.Data.Linq.SqlClient.QueryConverter.ConvertOuter(Expression node)
at System.Data.Linq.SqlClient.SqlProvider.BuildQuery(Expression query, SqlNodeAnnotations annotations)
at System.Data.Linq.SqlClient.SqlProvider.System.Data.Linq.Provider.IProvider.Execute(Expression query)
at System.Data.Linq.DataQuery'1.System.Collections.Generic.IEnumerable.GetEnumerator()
at System.Linq.Buffer'1..ctor(IEnumerable'1 source)
at System.Linq.Enumerable.ToArray[TSource](IEnumerable'1 source)
The stack trace from a dump for a compiled query looks like:
at System.RuntimeMethodHandle.InvokeMethod(System.Object, System.Object[], System.Signature, Boolean)
at System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(System.Object, System.Object[], System.Object[])
at System.Delegate.DynamicInvokeImpl(System.Object[])
at System.Data.Linq.SqlClient.SqlProvider.AssignParameters(System.Data.Common.DbCommand, System.Collections.ObjectModel.ReadOnlyCollection`1, System.Object[], System.Object)
at System.Data.Linq.SqlClient.SqlProvider.Execute(System.Linq.Expressions.Expression, QueryInfo, System.Data.Linq.SqlClient.IObjectReaderFactory, System.Object[], System.Object[], System.Data.Linq.SqlClient.ICompiledSubQuery[], System.Object)
at System.Data.Linq.SqlClient.SqlProvider.ExecuteAll(System.Linq.Expressions.Expression, QueryInfo[], System.Data.Linq.SqlClient.IObjectReaderFactory, System.Object[], System.Data.Linq.SqlClient.ICompiledSubQuery[])
at System.Data.Linq.SqlClient.SqlProvider+CompiledQuery.Execute(System.Data.Linq.Provider.IProvider, System.Object[])
at System.Data.Linq.CompiledQuery.ExecuteQuery(System.Data.Linq.DataContext, System.Object[])
Does anyone know what might have changed the behavior our application? We know it was "an update" (but not exactly which one), but we are more interested in it's technical background.
Of course, we would also welcome a solution to prevent our application from crashing.

I thought I would post a solution, that we found to this issue, because we started experiencing the problem recently.
We have many servers that run our code just fine but only 1 was crashing a couple of times a week with this error. I believe this server was on .net 4.5.2.
We opened a ticket with Microsoft since the unhandled exception was happening in their stack.
They looked at our dump and came back with this solution which worked.
A new fix is available at
https://support.microsoft.com/en-us/kb/3139544
It would be better if you move to .net 4.6.1
I hope this solution will help anyone else that finds themselves reading this.

Hard to tell without seeing any of your Linq Code but I would venture a wild guess that an it's an internal (casting) error with the linq library you are using.
As you mentioned that you upgraded recently
(which .NET version did you upgrade from and to ?)
I had similar issue which was resolved by installing windows updates, which you say you have done with some resulting success?
Try to identify the user inputs that cause error. Try to handle the casting yourself rather than relying on Linq

Related

Linq Expression Could Not Be Translated - DistinctBy Breaking Linq [duplicate]

In my .NET 6,0 app I'm trying to use (new to .NET 6.0 https://learn.microsoft.com/en-us/dotnet/api/system.linq.queryable.distinctby?view=net-6.0) method DistinctBy, something like this:
return context.Table
.Where(x => x.IsLive)
.DistinctBy(x => x.Field1)
.ToList();
Buld is fine, no errors, but at runtime I get this:
Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware[1]
An unhandled exception has occurred while executing the request.
System.NotSupportedException: LINQ to Entities does not recognize the method 'System.Linq.IQueryable`1[MyType] DistinctBy[DbFundHistoPrice,String](System.Linq.IQueryable`1[VanEck.Repositories.Entities.Website.Funds.DbFundHistoPrice], System.Linq.Expressions.Expression`1[System.Func`2[VanEck.Repositories.Entities.Website.Funds.DbFundHistoPrice,System.String]])' method, and this method cannot be translated into a store expression.
at System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.MethodCallTranslator.DefaultTranslator.Translate(ExpressionConverter parent, MethodCallExpression call)
at System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.MethodCallTranslator.TypedTranslate(ExpressionConverter parent, MethodCallExpression linq)
at System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.TranslateExpression(Expression linq)
at System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.Convert()
at System.Data.Entity.Core.Objects.ELinq.ELinqQueryState.GetExecutionPlan(Nullable`1 forMergeOption)
at System.Data.Entity.Core.Objects.ObjectQuery`1.<>c__DisplayClass41_0.<GetResults>b__1()
at System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction[T](Func`1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess)
at System.Data.Entity.Core.Objects.ObjectQuery`1.<>c__DisplayClass41_0.<GetResults>b__0()
at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute[TResult](Func`1 operation)
at System.Data.Entity.Core.Objects.ObjectQuery`1.<System.Collections.Generic.IEnumerable<T>.GetEnumerator>b__31_0()
at System.Data.Entity.Internal.LazyEnumerator`1.MoveNext()
at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
*my call here*
Other queries without new .NET 6 methods work fine (upgrading from 5 so there are some).
What am I missing here? Somethig in startup or in project settings?
I know that these extensions can be trimmed during build but I see no reason for that here since the method is actually used.
It seems you are using older ORM (EF 6?) which does not support this method.
DistinctBy is not supported even by EF Core (which I recommend upgrading to) at the moment. See this issue - Translate LINQ DistinctBy. You can try rewriting it with GroupBy(e => e.Field1).Select(g => g.First()).
See also:
Support new .NET LINQ features issue

Why does Expression.TryFault() always fail to Expression.Lambda<>().Compile() in netfx?

Given the following code:
using System;
using System.Linq.Expressions;
Console.WriteLine(Expression.Lambda<Func<string>>(Expression.TryFault(Expression.Constant("hi"), Expression.Constant("alternative"))).Compile()());
I am targeting net462 (repro project here).
Unhandled Exception: System.NotSupportedException: The requested operation is invalid for DynamicMethod.
at System.Reflection.Emit.DynamicILGenerator.BeginFaultBlock()
at System.Linq.Expressions.Compiler.LambdaCompiler.EmitTryExpression(Expression expr)
at System.Linq.Expressions.Compiler.LambdaCompiler.EmitExpression(Expression node, CompilationFlags flags)
at System.Linq.Expressions.Compiler.LambdaCompiler.EmitLambdaBody(CompilerScope parent, Boolean inlined, CompilationFlags flags)
at System.Linq.Expressions.Compiler.LambdaCompiler.Compile(LambdaExpression lambda, DebugInfoGenerator debugInfoGenerator)
at System.Linq.Expressions.Expression`1.Compile()
at Program.<Main>$(String[] args)
Why isn’t this emission supported?
I know that my example here is not a good example of when one would want to use Expression.TryFault(). However, the semantics fit exactly what I want in a certain scenario (running some code only if an exception is thrown by a particular expression without actually catching the original exception (I am actually trying to generate a more specific exception by rerunning parts of the original expression in a bunch of try/catch with the idea that the exception case will be exceptional and rarely run)).
Why does netfx throw here? I thought that even though C# doesn’t support fault blocks, netfx did. What is DynamicMethod and why is it special? Is there any suggestion for a way to express these semantics without encountering this error?

NullReferenceException in EF Core when using StringComparison overload for predicates

We are converting a project from using EF to using EF Core. We have the following line of code which used to work but now does not:
// throws NullReferenceException
var u = db.Users.FirstOrDefault(x => x.PresenterID.Equals(uid, StringComparison.OrdinalIgnoreCase));
However, if we don't use the StringComparison overload, it works:
// this works
var u = db.Users.FirstOrDefault(x => x.PresenterID.Equals(uid));
This is a large project and we would like to avoid finding and modifying all code that does such comparisons. Why does this throw a NullReferencException and can it be avoided without changing our code? Here is the stack trace. Thanks.
at lambda_method(Closure , User ) at
System.Linq.Enumerable.WhereEnumerableIterator1.MoveNext() at
System.Linq.Enumerable.FirstOrDefault[TSource](IEnumerable1 source)
at
Microsoft.EntityFrameworkCore.Query.Internal.LinqOperatorProvider.ResultEnumerable1.GetEnumerator()
at
Microsoft.EntityFrameworkCore.Query.Internal.LinqOperatorProvider.<_TrackEntities>d__172.MoveNext()
at
Microsoft.EntityFrameworkCore.Query.Internal.LinqOperatorProvider.ExceptionInterceptor1.EnumeratorExceptionInterceptor.MoveNext()
at System.Linq.Enumerable.First[TSource](IEnumerable1 source) at
Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.<>c__DisplayClass15_1`1.b__0(QueryContext
qc) at
Our.Project.Service.ContractsFolderService.ValidateContractUsers(BIContract
xmlContract, IDataContext db) in
C:\Projects\Out.Project\Main\Service\ContractsFolderService.cs:line
436
According to this open issue on the EntityFrameworkCore Github repo, that overload is not yet supported with LINQ to SQL. See this specific comment which gives some detail on the problem preventing this overload from being translated: https://github.com/aspnet/EntityFrameworkCore/issues/1222#issuecomment-443116169
I'm guessing that the null reference exception is occurring because its pulling back all the results to evaluate your string comparison on the client side, and for one or more of those results PresenterID is null.

Linq Errors on ToList(), Any(), Count(), Sum()

I am getting the following errors, they are all related to system.linq. The strange thing is that the method seems to work sometimes, the errors are not happening consistently.
Count() Code:
using (var dbContext = new Entities(GlobalStuff.EntityConnection))
{
heartBeat.NumSlipsInSecurityUploadQueue = dbContext.SecurityUploadQueues.Count();
heartBeat.NumSlipsInDataStreamQueue = dbContext.DataStreamQueues.Count();
}
SecurityUploadQueues Property:
Public ReadOnly Property SecurityUploadQueues() As ObjectSet(Of SecurityUploadQueue)
Get
If (_SecurityUploadQueues Is Nothing) Then
_SecurityUploadQueues = MyBase.CreateObjectSet(Of SecurityUploadQueue)("SecurityUploadQueues")
End If
Return _SecurityUploadQueues
End Get
End Property
Private _SecurityUploadQueues As ObjectSet(Of SecurityUploadQueue)
The SecurityUploadQueue property is an EntityObject
Count() Error:
Error Uploading HeartBeat System.InvalidOperationException: Sequence contains more than one element
at System.Linq.Enumerable.Single[TSource](IEnumerable1 source)
at System.Data.Objects.ELinq.ObjectQueryProvider.<>c__111.b__11_3(IEnumerable1 sequence)
at System.Data.Objects.ELinq.ObjectQueryProvider.ExecuteSingle[TResult](IEnumerable1 query, Expression queryRoot)
at System.Data.Objects.ELinq.ObjectQueryProvider.System.Linq.IQueryProvider.Execute[S](Expression expression)
at System.Linq.Queryable.Count[TSource](IQueryable`1 source)
at SettlerService.SettlerService.UploadHeartBeat()
Any() Code:
var dataToUpload = (from bet in dbContext.DataStreamQueues select bet).Take(200);
if (dataToUpload.Any())
Any() Error:
System.InvalidOperationException: The specified cast from a
materialized 'System.Int32' type to the 'System.Boolean' type is not
valid. at
System.Data.Common.Internal.Materialization.Shaper.ErrorHandlingValueReader1.GetValue(DbDataReader
reader, Int32 ordinal) at lambda_method(Closure , Shaper ) at
System.Data.Common.Internal.Materialization.Coordinator1.ReadNextElement(Shaper
shaper) at
System.Data.Common.Internal.Materialization.Shaper1.SimpleEnumerator.MoveNext()
at System.Linq.Enumerable.Single[TSource](IEnumerable1 source) at
System.Data.Objects.ELinq.ObjectQueryProvider.<>c__111.<GetElementFunction>b__11_3(IEnumerable1
sequence) at
System.Data.Objects.ELinq.ObjectQueryProvider.ExecuteSingle[TResult](IEnumerable1
query, Expression queryRoot)
at System.Data.Objects.ELinq.ObjectQueryProvider.System.Linq.IQueryProvider.Execute[S](Expression expression)
at System.Linq.Queryable.Any[TSource](IQueryable1 source)
at SettlerService.SettlerService.UploadDataStream()
I've done some googling and can't find much on this issue. I thought it might be related to the version of the system.core library (which system.linq is part of) but couldn't see an issue. I am using .Net 4.7.2
The second error implies that there is one columns in your DataStreamQueues database table with type of Int32 but the type of the equivalent property in DataStreamQueues entity is bool; so check if all columns and properties types match.
Regarding the first exception, it's a bit strange! because this exception suggests that somewhere in your code you are calling Single() method on a set that has multiple items and as Single() expects only one item, it throws an exception, however I don't see any calls to Single() in the provided code.

How can I see the types by which an InvalidCastException is raised in C#?

In my LINQ-to-SQL DAL, I'm getting a "Specified Cast Was Not Valid."
Here is the exact error:
System.InvalidCastException was unhandled by user code Message="Specified cast is not valid." Source="System.Data.Linq" StackTrace:
at System.Data.Linq.IdentityManager.StandardIdentityManager.SingleKeyManager`2.TryCreateKeyFromValues(Object[] values, V& v)
at System.Data.Linq.IdentityManager.StandardIdentityManager.IdentityCache`2.Find(Object[] keyValues)
at System.Data.Linq.IdentityManager.StandardIdentityManager.Find(MetaType type, Object[] keyValues)
at System.Data.Linq.CommonDataServices.GetCachedObject(MetaType type, Object[] keyValues)
at System.Data.Linq.ChangeProcessor.GetOtherItem(MetaAssociation assoc, Object instance)
at System.Data.Linq.ChangeProcessor.BuildEdgeMaps()
at System.Data.Linq.ChangeProcessor.SubmitChanges(ConflictMode failureMode)
at System.Data.Linq.DataContext.SubmitChanges(ConflictMode failureMode)
at System.Data.Linq.DataContext.SubmitChanges()
at DomainModel.Repository.Concrete.SqlClientRepository.InsertClientByUsername(String username, Client clientInfo) in C:\Documents and Settings\Owner\Desktop\CollectionTree v1.1\DomainModel\Repository\Concrete\SqlClientRepository.cs:line 99
at WebUI.Secure.Controllers.ClientAdminController.EditProfile(Client clientProfile) in C:\Documents and Settings\Owner\Desktop\CollectionTree v1.1\WebUI.Secure\Controllers\ClientAdminController.cs:line 69
at lambda_method(ExecutionScope , ControllerBase , Object[] )
at System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters)
at System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters)
at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters)
at System.Web.Mvc.ControllerActionInvoker.<>c__DisplayClassa.<InvokeActionMethodWithFilters>b__7()
at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation) InnerException:
It is happening on my db.SubmitChanges().
Anyway, where in this exception is what types it is having trouble casting? It would help narrow it down if I knew what specific types it was having issues with. I can hover over the exception in Visual Studio but I don't know what properties to look at.
You're SOL, at least for .NET < 4.0. I entered a Connect bug report on this ("InvalidCastException Should Display or Contain More Detail"), and they say it's fixed.
I haven't seen the fix yet.
I occasionally get an InvalidCastException via COM interop and ... I'm SOL? It seems an InvalidCastException in pure IL get the type information, but when it's handled in an interop wrapper conversion it skips that part. I'm guessing in the COM wrappers the problem is due to the fact that the HRESULT for E_NOINTERFACE doesn't contain information about the types involved, and the wrapper has no way to go back and look at the previous item that QueryInterface was looking for. Even if it did, it'd have to go looking for the Guid and hope an interop wrapper for the type was laying around to get meaningful information from it.
If LINQ-to-SQL uses COM interop behind the scenes, there's your answer. :)

Categories