Enumeration error on results fetched using nhibernate session create sql query - nhibernate

I am using sharp arch ver 1.0.
In the NHibernate PostUpdateEvent I am trying to access database.
public class PostUpdateListener : IPostUpdateEventListener
{
public void OnPostUpdate(PostUpdateEvent postUpdateEvent)
{
var session = NHibernateSession.Current;
var results = session.CreateSQLQuery("Select * from Storefront").List<object>();
for (int i = 0; i < results.Count; i++)
{
}
}
When I try to save any entity and in the postupdateevent i run this select query, it gives the enumeration error on OnFlush. NHibernate\Listeners\FlushFixEventListener .cs Line: 35
I read that using foreach loop runs enumeration operation so better to run for loop. But I tried with the for loop. still makes no difference.
The save operation is processed with SharArch NHibernate Transaction attribute. If I remove the Transaction attribute the query in the postupdatelistener works fine.
here is the stack trace.
[InvalidOperationException: Collection was modified; enumeration operation may not execute.]
System.ThrowHelper.ThrowInvalidOperationException(ExceptionResource resource) +56
System.Collections.Generic.Enumerator.MoveNextRare() +58
System.Collections.Generic.Enumerator.MoveNext() +93
NHibernate.Engine.ActionQueue.ExecuteActions(IList list) in d:\horn.horn\orm\nhibernate\Working-2.1\src\NHibernate\Engine\ActionQueue.cs:112
NHibernate.Engine.ActionQueue.ExecuteActions() in d:\horn.horn\orm\nhibernate\Working-2.1\src\NHibernate\Engine\ActionQueue.cs:147
NHibernate.Event.Default.AbstractFlushingEventListener.PerformExecutions(IEventSource session) in d:\horn.horn\orm\nhibernate\Working-2.1\src\NHibernate\Event\Default\AbstractFlushingEventListener.cs:241
NHibernate.Event.Default.DefaultFlushEventListener.OnFlush(FlushEvent event) in d:\horn.horn\orm\nhibernate\Working-2.1\src\NHibernate\Event\Default\DefaultFlushEventListener.cs:19
Infrastructure.NHibernate.Listeners.FlushFixEventListener.OnFlush(FlushEvent event) in D:\Solutions\Infrastructure\NHibernate\Listeners\FlushFixEventListener .cs:35
NHibernate.Impl.SessionImpl.Flush() in d:\horn.horn\orm\nhibernate\Working-2.1\src\NHibernate\Impl\SessionImpl.cs:1478
Infrastructure.NHibernate.LinqRepository1.Save(T entity) in D:\Solutions\Infrastructure\NHibernate\LinqRepository.cs:95
Tasks.Shared.ContentEntityTasks4.Save(TSaveEntityRequestDetails details) in D:\Solutions\Tasks\Shared\ContentEntityTasks.cs:96
Web.Controllers.Entity.EntityController.Edit(EntityViewModel entityViewModel, HttpPostedFileBase fileName, HttpPostedFileBase mainImageFileName, HttpPostedFileBase thumbnailFileName) in D:\Solutions\Web.Controllers\Entity\EntityController.cs:379
lambda_method(ExecutionScope , ControllerBase , Object[] ) +185
System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary2 parameters) +236
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary2 parameters) +31
System.Web.Mvc.<>c_DisplayClassa.b_7() +85
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func1 continuation) +235491
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func1 continuation) +235491
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func1 continuation) +235491
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func1 continuation) +235491
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodWithFilters(ControllerContext controllerContext, IList1 filters, ActionDescriptor actionDescriptor, IDictionary2 parameters) +288
System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName) +235670
System.Web.Mvc.Controller.ExecuteCore() +174
System.Web.Mvc.MvcHandler.ProcessRequest(HttpContextBase httpContext) +209
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +599
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +171

It seems like what is happening is the session is deciding to flush due to the CreateSQLQuery call. That causes the post update event to be added to the list of internal events that need to be fired (guessing at this one).
You should be able to fix it by accessing a child session, instead of the main NH session, by using the event. Like this:
public class PostUpdateListener : IPostUpdateEventListener
{
public void OnPostUpdate(PostUpdateEvent postUpdateEvent)
{
var session = postUpdateEvent.Session.GetSession(EntityMode.Poco)
var results = session.CreateSQLQuery("Select * from Storefront").List<object>();
for (int i = 0; i < results.Count; i++)
{
}
}
}
If you also require adding or updating entities inside this event, for the purposes of an audit log for example, then you'll also want to ensure you flush the inner session.

Related

How do you resolve ODATA returning an open bracket of array and 'StatusCode could not be set' error

I am working on a .NET ODATA API that exposes data from SQL Views and is consumed by a 'Salesforce Connect' Connector.
If I execute a query with an ODATA filter applied my query works fine but when I test some filters i get the following output:
Please note the 'open bracket response'. The response is 200 so I get an OK. But in my .NET logging I see the following error in my console:
fail: BARCO.ODataApi.Api.Web.AppExceptionHandlerMiddleware[0]
Request resulted in SqlException: Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding.
System.Data.SqlClient.SqlException (0x80131904): Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding.
---> System.ComponentModel.Win32Exception (258): The wait operation timed out.
at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
at System.Data.SqlClient.SqlDataReader.TryConsumeMetaData()
at System.Data.SqlClient.SqlDataReader.get_MetaData()
at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString)
at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite, SqlDataReader ds)
at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean asyncWrite, String method)
at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method)
at System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior)
at System.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior behavior)
at System.Data.Common.DbCommand.ExecuteReader()
at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteReader(RelationalCommandParameterObject parameterObject)
at Microsoft.EntityFrameworkCore.Query.Internal.SingleQueryingEnumerable`1.Enumerator.InitializeReader(Enumerator enumerator)
at Microsoft.EntityFrameworkCore.Query.Internal.SingleQueryingEnumerable`1.Enumerator.<>c.<MoveNext>b__19_0(DbContext _, Enumerator enumerator)
at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerExecutionStrategy.Execute[TState,TResult](TState state, Func`3 operation, Func`3 verifySucceeded)
at Microsoft.EntityFrameworkCore.Query.Internal.SingleQueryingEnumerable`1.Enumerator.MoveNext()
at Microsoft.AspNetCore.OData.Formatter.Serialization.ODataResourceSetSerializer.WriteResourceSetAsync(IEnumerable enumerable, IEdmTypeReference resourceSetType, ODataWriter writer, ODataSerializerContext writeContext)
at Microsoft.AspNetCore.OData.Formatter.Serialization.ODataResourceSetSerializer.WriteObjectInlineAsync(Object graph, IEdmTypeReference expectedType, ODataWriter writer, ODataSerializerContext writeContext)
at Microsoft.AspNetCore.OData.Formatter.Serialization.ODataResourceSetSerializer.WriteObjectAsync(Object graph, Type type, ODataMessageWriter messageWriter, ODataSerializerContext writeContext)
at Microsoft.AspNetCore.OData.Formatter.ODataOutputFormatterHelper.WriteToStreamAsync(Type type, Object value, IEdmModel model, ODataVersion version, Uri baseAddress, MediaTypeHeaderValue contentType, HttpRequest request, IHeaderDictionary requestHeaders, IODataSerializerProvider serializerProvider)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeResultAsync>g__Logged|22_0(ResourceInvoker invoker, IActionResult result)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextResultFilterAsync>g__Awaited|30_0[TFilter,TFilterAsync](ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResultExecutedContextSealed context)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.ResultNext[TFilter,TFilterAsync](State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeResultFilters()
--- End of stack trace from previous location ---
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeFilterPipelineAsync>g__Awaited|20_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Logged|17_1(ResourceInvoker invoker)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Logged|17_1(ResourceInvoker invoker)
at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
at BARCO.ODataApi.Api.Web.UnitOfWorkMiddleware.Invoke(HttpContext context) in C:\Github\BARCO\BarcoODataApi\BarcoODataApi\src\BARCO.ODataApi.Api\Web\UnitOfWorkMiddleWare.cs:line 46
at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
at BARCO.ODataApi.Api.Web.ClientConfigurationMiddleware.Invoke(HttpContext context) in C:\Github\BARCO\BarcoODataApi\BarcoODataApi\src\BARCO.ODataApi.Api\Web\ClientConfigurationMiddleware.cs:line 66
at Swashbuckle.AspNetCore.SwaggerUI.SwaggerUIMiddleware.Invoke(HttpContext httpContext)
at Swashbuckle.AspNetCore.Swagger.SwaggerMiddleware.Invoke(HttpContext httpContext, ISwaggerProvider swaggerProvider)
at BARCO.ODataApi.Api.Web.AppExceptionHandlerMiddleware.Invoke(HttpContext context) in C:\Github\BARCO\BarcoODataApi\BarcoODataApi\src\BARCO.ODataApi.Api\Web\AppExceptionHandlerMiddleware.cs:line 37
ClientConnectionId:6b3c22ec-a535-4e66-99df-0cf41053a3f9
Error Number:-2,State:0,Class:11
fail: Microsoft.AspNetCore.Server.Kestrel[13]
Connection id "0HMFRFUHVRJMQ", Request id "0HMFRFUHVRJMQ:00000002": An unhandled exception was thrown by the application.
System.InvalidOperationException: StatusCode cannot be set because the response has already started.
at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.HttpProtocol.ThrowResponseAlreadyStartedException(String value)
at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.HttpProtocol.set_StatusCode(Int32 value)
at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.HttpProtocol.Microsoft.AspNetCore.Http.Features.IHttpResponseFeature.set_StatusCode(Int32 value)
at Microsoft.AspNetCore.Http.DefaultHttpResponse.set_StatusCode(Int32 value)
at BARCO.ODataApi.Api.Web.AppExceptionHandlerMiddleware.SetResponseExceptionStatusCode(HttpContext context, Exception exception) in C:\Github\BARCO\BarcoODataApi\BarcoODataApi\src\BARCO.ODataApi.Api\Web\AppExceptionHandlerMiddleware.cs:line 101
at BARCO.ODataApi.Api.Web.AppExceptionHandlerMiddleware.Invoke(HttpContext context) in C:\Github\BARCO\BarcoODataApi\BarcoODataApi\src\BARCO.ODataApi.Api\Web\AppExceptionHandlerMiddleware.cs:line 47
at Microsoft.AspNetCore.Watch.BrowserRefresh.BrowserRefreshMiddleware.InvokeAsync(HttpContext context)
at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.HttpProtocol.ProcessRequests[TContext](IHttpApplication`1 application)
Is there a way to provide more detailed logging so I can understand what exactly is going wrong in my application or where the error is? Since receiving a response of "value":"[" is really weird and I have never seen this kind of response. I searched online already but there does not seem to be any questions out there with the same issue concerning this response.
One of my first questions i posted so please let me know if there is a need for additional information on my question.
Thanks in advance!
EDIT:
Salesforce Connect Backend Query translation:
SELECT TOP(#__TypedProperty_2) ...
FROM ... AS [v]
WHERE CASE
WHEN ( #__TypedProperty_0 LIKE N'' )
OR ( Charindex(#__TypedProperty_0, [v].[assetid]) > 0 ) THEN
Cast(1 AS BIT)
ELSE Cast(0 AS BIT)
END = #__TypedProperty_1
ORDER BY ...

Possible problem with aspnetzero & power tools

i created an entity, and when i add a row, all works OK, when i do a view (sometimes), update or delete, i get an 'internal error'. i have no idea what is the problem.
its a simple entity:pic1
i have downloaded the code from -1 month agoand happens on all entities i add with the power tools. any assistance is greatly appreciated.
INFO 2019-02-18 22:03:44,609 [64 ] ore.Mvc.Internal.ControllerActionInvoker - Executed action OrthoResInfo.Web.Areas.App.Controllers.TblTable1sController.CreateOrEditModal (OrthoResInfo.Web.Mvc) in 624.4343ms
INFO 2019-02-18 22:03:44,609 [64 ] ft.AspNetCore.Routing.EndpointMiddleware - Executed endpoint 'OrthoResInfo.Web.Areas.App.Controllers.TblTable1sController.CreateOrEditModal (OrthoResInfo.Web.Mvc)'
ERROR 2019-02-18 22:03:44,610 [64 ] nostics.DeveloperExceptionPageMiddleware - An unhandled exception has occurred while executing the request.
System.Reflection.AmbiguousMatchException: Ambiguous match found.
at System.RuntimeType.GetPropertyImpl(String name, BindingFlags bindingAttr, Binder binder, Type returnType, Type[] types, ParameterModifier[] modifiers)
at System.Type.GetProperty(String name, BindingFlags bindingAttr)
at System.Linq.Expressions.Expression.PropertyOrField(Expression expression, String propertyOrFieldName)
at Abp.Domain.Repositories.AbpRepositoryBase2.CreateEqualityExpressionForId(TPrimaryKey id) in D:\Github\aspnetboilerplate\src\Abp\Domain\Repositories\AbpRepositoryBase.cs:line 266
at Abp.EntityFrameworkCore.Repositories.EfCoreRepositoryBase3.FirstOrDefaultAsync(TPrimaryKey id) in D:\Github\aspnetboilerplate\src\Abp.EntityFrameworkCore\EntityFrameworkCore\Repositories\EfCoreRepositoryBaseOfTEntityAndTPrimaryKey.cs:line 118
at Abp.Threading.InternalAsyncHelper.AwaitTaskWithPostActionAndFinallyAndGetResult[T](Task1 actualReturnValue, Func1 postAction, Action1 finalAction)
at OrthoResInfo.Nstable1.TblTable1sAppService.GetTblTable1ForEdit(EntityDto1 input) in D:\ASPNetZero\Github\OrthoResInfo\src\OrthoResInfo.Application\Nstable1\TblTable1sAppService.cs:line 74
at Abp.Threading.InternalAsyncHelper.AwaitTaskWithPostActionAndFinallyAndGetResult[T](Task1 actualReturnValue, Func1 postAction, Action1 finalAction)
at Abp.Threading.InternalAsyncHelper.AwaitTaskWithFinallyAndGetResult[T](Task1 actualReturnValue, Action1 finalAction)
at OrthoResInfo.Web.Areas.App.Controllers.TblTable1sController.CreateOrEditModal(Nullable1 id) in D:\ASPNetZero\Github\OrthoResInfo\src\OrthoResInfo.Web.Mvc\Areas\App\Controllers\TblTable1sController.cs:line 42
at lambda_method(Closure , Object )
at Microsoft.AspNetCore.Mvc.Internal.ActionMethodExecutor.TaskOfActionResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)
at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.InvokeActionMethodAsync()
at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.InvokeNextActionFilterAsync()
at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Rethrow(ActionExecutedContext context)
at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.InvokeInnerFilterAsync()
at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeNextExceptionFilterAsync()
at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Rethrow(ExceptionContext context)
at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeNextResourceFilter()
at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Rethrow(ResourceExecutedContext context)
at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeFilterPipelineAsync()
at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeAsync()
at Microsoft.AspNetCore.Routing.EndpointMiddleware.Invoke(HttpContext httpContext)
at Microsoft.AspNetCore.Routing.EndpointRoutingMiddleware.Invoke(HttpContext httpContext)
at Microsoft.AspNetCore.Builder.RouterMiddleware.Invoke(HttpContext httpContext)
at Microsoft.AspNetCore.Localization.RequestLocalizationMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware.Invoke(HttpContext context)
at IdentityServer4.Hosting.IdentityServerMiddleware.Invoke(HttpContext context, IEndpointRouter router, IUserSession session, IEventService events) in C:\local\identity\server4\IdentityServer4\src\Hosting\IdentityServerMiddleware.cs:line 72
at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.Cors.Infrastructure.CorsMiddleware.InvokeCore(HttpContext context)
at IdentityServer4.Hosting.BaseUrlMiddleware.Invoke(HttpContext context) in C:\local\identity\server4\IdentityServer4\src\Hosting\BaseUrlMiddleware.cs:line 36
well, after alot of time, i found this post: Getting Ambiguous match found exception while calling DeleteAsync
i had added IsDeleted and Id to my entities; hence the code when generated was bad.

Microsoft.FxCop.Sdk.InvalidMetadataException

<FxCopReport Version="10.0">
<Exceptions>
<Exception Keyword="CA0001" Kind="Engine">
<Type>Microsoft.FxCop.Sdk.InvalidMetadataException </Type>
<ExceptionMessage>
The following error was encountered while reading module 'myproject': Method type parameter in position 0 is not valid.
</ExceptionMessage>
<StackTrace>
at Microsoft.FxCop.Sdk.Reader.HandleError(ModuleNode mod, String errorMessage) at Microsoft.FxCop.Sdk.Reader.ParseTypeSignature(MemoryCursor sigReader, Boolean& pinned, Boolean& isTypeArgument) at Microsoft.FxCop.Sdk.Reader.ParseTypeList(MemoryCursor sigReader) at Microsoft.FxCop.Sdk.Reader.ParseTypeSignature(MemoryCursor sigReader, Boolean& pinned, Boolean& isTypeArgument) at Microsoft.FxCop.Sdk.Reader.ParseTypeList(MemoryCursor sigReader) at Microsoft.FxCop.Sdk.Reader.ParseTypeSignature(MemoryCursor sigReader, Boolean& pinned, Boolean& isTypeArgument) at Microsoft.FxCop.Sdk.Reader.ParseParameterTypes(TypeNodeCollection& varArgTypes, MemoryCursor sigReader, Int32 paramCount, Boolean& genericParameterEncountered) at Microsoft.FxCop.Sdk.Reader.GetMemberFromRef(Int32 i, TypeNodeCollection& varArgTypes, Int32 numGenericArgs) at Microsoft.FxCop.Sdk.Reader.GetMethodDefOrRef(Int32 codedIndex, Int32 numberOfGenericArguments) at Microsoft.FxCop.Sdk.Reader.GetMethodFromSpec(Int32 i) at Microsoft.FxCop.Sdk.Reader.GetMemberFromToken(Int32 tok, TypeNodeCollection& varArgTypes) at Microsoft.FxCop.Sdk.InstructionParser.ParseInstruction() at Microsoft.FxCop.Sdk.InstructionParser.ParseInstructions() at Microsoft.FxCop.Sdk.Reader.ParseMethodInstructions(Method method, Int32 methodIndex, Int32 RVA) at Microsoft.FxCop.Sdk.Reader.GetMethodInstructions(Method method, Object i) at Microsoft.FxCop.Sdk.Reader.GetMethodBody(Method method, Object i, Boolean asInstructionList) at Microsoft.FxCop.Sdk.Method.get_Instructions() at Microsoft.FxCop.Sdk.RuleUtilities.HasImperativeSecurityAction(Method method, SecurityAction action) at Microsoft.FxCop.Sdk.RuleUtilities.HasSecurityAction(Method method, SecurityAction action) at Microsoft.FxCop.Sdk.RuleUtilities.HasSecurityAction(Method method, SecurityAction[] actions) at Microsoft.FxCop.Engines.Introspection.LoadVisitor.RecordCallSites(Method caller) at Microsoft.FxCop.Engines.Introspection.LoadVisitor.VisitMember(Member member, TargetMember target) at Microsoft.FxCop.Engines.Introspection.BaseVisitor.VisitMembers(MemberCollection members, TargetMemberDictionary targets, Boolean visitNestedTypes) at Microsoft.FxCop.Engines.Introspection.BaseVisitor.VisitType(TypeNode type, TargetType target) at Microsoft.FxCop.Engines.Introspection.LoadVisitor.VisitType(TypeNode type, TargetType target) at Microsoft.FxCop.Engines.Introspection.BaseVisitor.VisitTypes(TypeNodeCollection types, TargetNamespaceDictionary targets) at Microsoft.FxCop.Engines.Introspection.LoadVisitor.VisitModule(ModuleNode module, TargetModule target) at Microsoft.FxCop.Engines.Introspection.BaseVisitor.VisitAssembly(AssemblyNode assembly, TargetFile target) at Microsoft.FxCop.Engines.Introspection.LoadVisitor.VisitAssembly(AssemblyNode assembly, TargetFile target) at Microsoft.FxCop.Engines.Introspection.LoadVisitor.Load(TargetFile target, Boolean buildTree, Boolean queueItems, AssemblyNode loadedAssembly) at Microsoft.FxCop.Engines.Introspection.LoadVisitor.LoadAssemblies(Queue queue, ExceptionCollection exceptions)
</StackTrace>
</Exception>
<Exception Keyword="CA0001" Kind="Engine">
<Type>Microsoft.FxCop.Sdk.FxCopException </Type>
<ExceptionMessage>
An unhandled exception occurred while analyzing assemblies:
</ExceptionMessage>
<InnerType>Microsoft.FxCop.Sdk.InvalidMetadataException </InnerType>
<InnerExceptionMessage>
The following error was encountered while reading module 'myproject': Method type parameter in position 0 is not valid.
</InnerExceptionMessage>
<InnerStackTrace>
at Microsoft.FxCop.Sdk.Reader.HandleError(ModuleNode mod, String errorMessage) at Microsoft.FxCop.Sdk.Reader.ParseTypeSignature(MemoryCursor sigReader, Boolean& pinned, Boolean& isTypeArgument) at Microsoft.FxCop.Sdk.Reader.ParseTypeList(MemoryCursor sigReader) at Microsoft.FxCop.Sdk.Reader.ParseTypeSignature(MemoryCursor sigReader, Boolean& pinned, Boolean& isTypeArgument) at Microsoft.FxCop.Sdk.Reader.ParseTypeList(MemoryCursor sigReader) at Microsoft.FxCop.Sdk.Reader.ParseTypeSignature(MemoryCursor sigReader, Boolean& pinned, Boolean& isTypeArgument) at Microsoft.FxCop.Sdk.Reader.ParseParameterTypes(TypeNodeCollection& varArgTypes, MemoryCursor sigReader, Int32 paramCount, Boolean& genericParameterEncountered) at Microsoft.FxCop.Sdk.Reader.GetMemberFromRef(Int32 i, TypeNodeCollection& varArgTypes, Int32 numGenericArgs) at Microsoft.FxCop.Sdk.Reader.GetMethodDefOrRef(Int32 codedIndex, Int32 numberOfGenericArguments) at Microsoft.FxCop.Sdk.Reader.GetMethodFromSpec(Int32 i) at Microsoft.FxCop.Sdk.Reader.GetMemberFromToken(Int32 tok, TypeNodeCollection& varArgTypes) at Microsoft.FxCop.Sdk.InstructionParser.ParseInstruction() at Microsoft.FxCop.Sdk.InstructionParser.ParseInstructions() at Microsoft.FxCop.Sdk.Reader.ParseMethodInstructions(Method method, Int32 methodIndex, Int32 RVA) at Microsoft.FxCop.Sdk.Reader.GetMethodInstructions(Method method, Object i) at Microsoft.FxCop.Sdk.Reader.GetMethodBody(Method method, Object i, Boolean asInstructionList) at Microsoft.FxCop.Sdk.Method.get_Instructions() at Microsoft.FxCop.Engines.Introspection.AnalysisVisitor.UpdateSourceContext(SourceContext& sourceContext, Method method) at Microsoft.FxCop.Engines.Introspection.AnalysisVisitor.LogProblems(Method method, TargetMember target, Rule rule, ProblemCollection problems) at Microsoft.FxCop.Engines.Introspection.AnalysisVisitor.LogProblems(Member member, TargetMember target, Rule rule, ProblemCollection problems) at Microsoft.FxCop.Engines.Introspection.AnalysisVisitor.CheckMember(Member memberToAnalyze, Member member, TargetMember target) at Microsoft.FxCop.Engines.Introspection.AnalysisVisitor.VisitMember(Member member, TargetMember target) at Microsoft.FxCop.Engines.Introspection.BaseVisitor.VisitMembers(MemberCollection members, TargetMemberDictionary targets, Boolean visitNestedTypes) at Microsoft.FxCop.Engines.Introspection.AnalysisVisitor.VisitType(TypeNode type, TargetType target) at Microsoft.FxCop.Engines.Introspection.AnalysisVisitor.Analyze(Queue queue) at Microsoft.FxCop.Engines.Introspection.IntrospectionAnalysisEngine.AnalyzeThread()
</InnerStackTrace>
</Exception>
</Exceptions>
</FxCopReport>
I got the following errors when running fxcop code analysis, anyone seen these before, i am not sure why it's telling "Method type parameter in position 0 is not valid"?
Are you using Code Contracts or PostSharp or some other post-compilation step that fiddles with the IL?
I've just started getting this - in my case, it went away when I changed the Code Contract's Runtime Checks from "Full" to "Pre and Post", so it looks like something dodgy in ccrewrite.exe.

System.ObjectDisposedException: Store must be open for this operation

there is an MVC4 application on IIS7 Windows2008 machine. the application runs as ApplicationPoolIdentity and the appropriate user has access to the ProgramData\IsolatedStorage folder.
it has also permission on the C:\Documents and Settings\Default User\Local Settings\Application Data\IsolatedStorage folder as well.
but still receive exception while writing big excel files with openxml.
ERROR MHDB.MvcApplication - System.ObjectDisposedException: Store must be open for this operation.
at System.IO.IsolatedStorage.IsolatedStorageFileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, IsolatedStorageFile isf)
at System.IO.IsolatedStorage.IsolatedStorageFileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, IsolatedStorageFile isf)
at MS.Internal.IO.Packaging.PackagingUtilities.SafeIsolatedStorageFileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, ReliableIsolatedStorageFileFolder folder)
at MS.Internal.IO.Packaging.PackagingUtilities.CreateUserScopedIsolatedStorageFileStreamWithRandomName(Int32 retryCount, String& fileName)
at MS.Internal.IO.Packaging.SparseMemoryStream.EnsureIsolatedStoreStream()
at MS.Internal.IO.Packaging.SparseMemoryStream.SwitchModeIfNecessary()
at MS.Internal.IO.Packaging.CompressEmulationStream.Write(Byte[] buffer, Int32 offset, Int32 count)
at MS.Internal.IO.Packaging.CompressStream.Write(Byte[] buffer, Int32 offset, Int32 count)
at MS.Internal.IO.Zip.ProgressiveCrcCalculatingStream.Write(Byte[] buffer, Int32 offset, Int32 count)
at MS.Internal.IO.Zip.ZipIOModeEnforcingStream.Write(Byte[] buffer, Int32 offset, Int32 count)
at System.Xml.XmlUtf8RawTextWriter.FlushBuffer()
at System.Xml.XmlUtf8RawTextWriter.RawText(Char* pSrcBegin, Char* pSrcEnd)
at System.Xml.XmlUtf8RawTextWriter.WriteEndElement(String prefix, String localName, String ns)
at System.Xml.XmlWellFormedWriter.WriteEndElement()
at DocumentFormat.OpenXml.OpenXmlCompositeElement.WriteContentTo(XmlWriter w)
at DocumentFormat.OpenXml.OpenXmlElement.WriteTo(XmlWriter xmlWriter)
at DocumentFormat.OpenXml.OpenXmlCompositeElement.WriteContentTo(XmlWriter w)
at DocumentFormat.OpenXml.OpenXmlElement.WriteTo(XmlWriter xmlWriter)
at DocumentFormat.OpenXml.OpenXmlCompositeElement.WriteContentTo(XmlWriter w)
at DocumentFormat.OpenXml.OpenXmlPartRootElement.WriteTo(XmlWriter xmlWriter)
at DocumentFormat.OpenXml.OpenXmlPartRootElement.SaveToPart(OpenXmlPart openXmlPart)
at DocumentFormat.OpenXml.Packaging.OpenXmlPackage.SavePartContents()
at DocumentFormat.OpenXml.Packaging.OpenXmlPackage.Dispose(Boolean disposing)
at DocumentFormat.OpenXml.Packaging.OpenXmlPackage.Dispose()
at BL.OpenXML.Export(DataTable dt, Stream fs, Boolean createNewDocument)
at BL.BusinessLogic.CreateOpReport(UnitOfWork uow, String user, String orgapath, List`1 orgaids, Boolean isfin, String cycle, String startperiod, String endperiod)
at MHDB.Controllers.HomeController.GetFileAsStream()
at MHDB.Controllers.HomeController.ExportExcel()
at lambda_method(Closure , ControllerBase , Object[] )
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__DisplayClass13.<InvokeActionMethodWithFilters>b__10()
at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation)
at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodWithFilters(ControllerContext controllerContext, IList`1 filters, ActionDescriptor actionDescriptor, IDictionary`2 parameters)
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.Async.AsyncResultWrapper.<>c__DisplayClass1.<MakeVoidDelegate>b__0()
at System.Web.Mvc.MvcHandler.<>c__DisplayClass8.<BeginProcessRequest>b__3(IAsyncResult asyncResult)
at System.Web.Mvc.Async.AsyncResultWrapper.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar)
at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
thanks for any help!
Due to the System.IO.Packaging when you write files larger than 10MB internally it will no longer hold the data temporarily in memory until next save but will switch over to Isolated Storage. That on its own can cause a lot of problems because IsolateStorage is not meant to be used with multiple thread/multiple instances of the same application and you could be facing some permission issues with this as well.
Considering that this is a web app I think it may relate to multiple user writing at same time but all being resolved to the same Isolated Storage location..
I have stumbled upon this problem with multiple instances of same app all being resolved to same location. I am still looking for an elegant solution but I was able to force each instance to be resolved to a different IsolatedStorage location and be unique by using this:
var rootDirUserField= typeof(IsolatedStorageFile).GetField("s_RootDirUser", BindingFlags.NonPublic | BindingFlags.Static);
rootDirUserField.SetValue(null, "<unique location in isolated storage>");
This works because the static field IsolatedStorageFile.s_RootDirUser is used in resolving a new directory to use. My fix was specific to the User | Domain | Assembly scope.
I am keen to get a better solution to fix this problem.

How do I read this stack trace I'm only getting from scrapers?

The following is the stack trace error I get when I try to run my site through a validator like http://validator.w3.org/ or the facebook open graph debugger. The thing is, the page appears to load just fine in the browser, or in the mobile app web view. The only way I can see this error is by having the validator show me error pages (option). Any suggestions about how to read the stack trace? I see the reference to one of my controllers Literrater.Controllers.BookController.Index(Int32 id, String slug) but I havent changed anything and it used to work, and it works fine in the browser. So, I'm confused. Do I need to check redirect happening or something?
The follow page has the problem. http://literrater.azurewebsites.net/book/33625/birdsong-a-novel-of-love-and-war
[RuntimeBinderException: Cannot convert null to 'bool' because it is a non-nullable value type]
CallSite.Target(Closure , CallSite , Object ) +115
System.Dynamic.UpdateDelegates.UpdateAndExecute1(CallSite site, T0 arg0) +661
Literrater.Controllers.BookController.Index(Int32 id, String slug) +13725
lambda_method(Closure , ControllerBase , Object[] ) +146
System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) +14
System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) +182
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +27
System.Web.Mvc.Async.<>c__DisplayClass42.<BeginInvokeSynchronousActionMethod>b__41() +28
System.Web.Mvc.Async.<>c__DisplayClass8`1.<BeginSynchronous>b__7(IAsyncResult _) +10
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +50
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult) +32
System.Web.Mvc.Async.<>c__DisplayClass39.<BeginInvokeActionMethodWithFilters>b__33() +58
System.Web.Mvc.Async.<>c__DisplayClass4f.<InvokeActionMethodFilterAsynchronously>b__49() +225
System.Web.Mvc.Async.<>c__DisplayClass4f.<InvokeActionMethodFilterAsynchronously>b__49() +225
At this moment, your page is not loading and producing the error:
Exception Details: Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: Cannot convert null to 'bool' because it is a non-nullable value type
Source Error:
Line 32: <div class="status-wrapper">
Line 33: <h2 class="sub-title">Collections</h2>
Line 34: #{Model.CollectionVM.FacebookStatus = ViewBag.FacebookStatus;}
Line 35: #Html.Partial("_MiniBookStatus", Model.CollectionVM)
Line 36:
Source File: d:\home\site\wwwroot\Views\Book\Index.cshtml Line: 34
It looks like maybe you did not initialize the ViewBag.FacebookStatus value in your controller. With those ViewBag values, if you don't set the value in all code paths, then you may have a case like this where the it's null.
As an example:
protected ActionResult Test()
{
ViewBag.SomeString = string.Empty;
ViewBag.SomeBool = false;
//some code
if (condition)
{
ViewBag.SomeBool = true;
}
else
{
ViewBag.SomeString = "Yea I'm a string!";
}
return View();
}
It's good practice to init the ViewBag values or it can come back to bite you in the Razor view because Intellisense won't pick it up, and it won't cause a build error or warning.