nHibernate second-level cache with memcached and random invalid casts - asp.net-mvc-3

I have an MVC3 application using nHibernate and memcached as the second level cache provider. We've been intermittently (but much more frequently lately) getting weird casting issues. It happens randomly and invalidating the memcached cache will fix the problem for while.
It only happens in our Production environment because we don't run memcached in our other environments. However I run memcached locally and have tried to get this to occur locally with no luck.
We are using memcached 1.2.6 on Windows. Here's the stack trace. I know it's not going to be enough information to determine anything but if anyone has any ideas about how I could debug this that would be appreciated. I'm trying to get remote debugging on our Production machine but it's a busy time of year and risky.
Unable to cast object of type 'System.Int32' to type 'System.String'.
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.InvalidCastException: Unable to cast object of type 'System.Int32' to type 'System.String'.
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:
[InvalidCastException: Unable to cast object of type 'System.Int32' to type 'System.String'.]
(Object , Object[] , SetterCallback ) +4270
NHibernate.Tuple.Entity.PocoEntityTuplizer.SetPropertyValuesWithOptimizer(Object entity, Object[] values) +80
[PropertyAccessException: Invalid Cast (check your mapping for property type mismatches); setter of MyApplication.Business.Data.Program]
NHibernate.Tuple.Entity.PocoEntityTuplizer.SetPropertyValuesWithOptimizer(Object entity, Object[] values) +207
NHibernate.Tuple.Entity.PocoEntityTuplizer.SetPropertyValues(Object entity, Object[] values) +97
NHibernate.Cache.Entry.CacheEntry.Assemble(Object[] values, Object result, Object id, IEntityPersister persister, IInterceptor interceptor, ISessionImplementor session) +306
NHibernate.Cache.Entry.CacheEntry.Assemble(Object instance, Object id, IEntityPersister persister, IInterceptor interceptor, ISessionImplementor session) +147
NHibernate.Event.Default.DefaultLoadEventListener.AssembleCacheEntry(CacheEntry entry, Object id, IEntityPersister persister, LoadEvent event) +434
NHibernate.Event.Default.DefaultLoadEventListener.LoadFromSecondLevelCache(LoadEvent event, IEntityPersister persister, LoadType options) +800
NHibernate.Event.Default.DefaultLoadEventListener.DoLoad(LoadEvent event, IEntityPersister persister, EntityKey keyToLoad, LoadType options) +560
NHibernate.Event.Default.DefaultLoadEventListener.Load(LoadEvent event, IEntityPersister persister, EntityKey keyToLoad, LoadType options) +229
NHibernate.Event.Default.DefaultLoadEventListener.ProxyOrLoad(LoadEvent event, IEntityPersister persister, EntityKey keyToLoad, LoadType options) +438
NHibernate.Event.Default.DefaultLoadEventListener.OnLoad(LoadEvent event, LoadType loadType) +943
NHibernate.Impl.SessionImpl.FireLoad(LoadEvent event, LoadType loadType) +99
NHibernate.Impl.SessionImpl.Get(String entityName, Object id) +117
NHibernate.Impl.SessionImpl.Get(Object id) +70
MyApplication.Business.Repositories.Repository`1.Get(Object id) +148

We've been encountering the same issue and we have pinpointed the problem to invalid cache entries in the second level cache. In our case the problem arises when we add or remove columns/properties from tables/entities that are cached in the second level cache and deploy the change. The code expects five columns (for argument's sake) whereas the cache stores six columns.
One strategy that we employed in our repository is to catch the exception and invalidate the cache. We then retry the get.
public override T Get(int id)
{
try
{
return base.Get(id);
}
catch (InvalidCastException)
{
_sessionFactory.EvictEntity(typeof (T).Name);
return Get(id);
}
}
Hope this helps!

Most probably this is caused by different dataset returned by the queries on the production environment and your local. The object mapper is getting different data than what its expecting. When trying to convert the data then you are getting these exceptions.

Related

Cannot delete Custom Entities and it's not about relations

I created a fresh new entity which has no additional fields or relations to anything and also without any records.
Just after i created the entity and when i try to delete it, it gives me the following error:
An error has occurred.
And in the log file which can be downloaded from the error dialog:
System.ArgumentNullException: Value cannot be null. Parameter name: collection
And when enabled tracing the error was:
Process: w3wp |Organization:0220cef0-4f09-e711-80d8-000c2950db72 |Thread: 244 |Category: Platform.Metadata |User: 00000000-0000-0000-0000-000000000000 |Level: Error |ReqId: 17d8623e-7539-48af-9652-b8550acfb76f | EntityService.Delete ilOffset = 0x1A8
>EntityService.Update caught exception: System.ArgumentNullException: Value cannot be null.
Parameter name: collection
at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
at Microsoft.Crm.BusinessEntities.CascadeEngine.LogRecordSetCount(Int32 count, IEnumerable`1 entityIds, Int32 parentEntityObjectTypeCode, String perfCounterName)
at Microsoft.Crm.BusinessEntities.CascadeEngine.CascadeDeleteDB(IEnumerable`1 parentEntityIds, Int32 parentEntityObjectTypeCode, ExecutionContext context)
at Microsoft.Crm.BusinessEntities.CascadeEngine.Delete(IEnumerable`1 entityIds, Int32 entityObjectTypeCode, ExecutionContext context)
at Microsoft.Crm.BusinessEntities.CascadeEngine.DeleteAll(Int32 entityObjectTypeCode, ExecutionContext context)
at Microsoft.Crm.Metadata.EntityService.Delete(Guid entityId, MetadataHelper metadataHelper, Boolean suppressSecurityCacheFlush, ExecutionContext context)
Well i don't know whats wrong. Please let me know if you know anything. Thanks.
One thing to check is if there are any dependencies, which you can do by selecting the entity in a solution and clicking Show Dependencies:
I did noticed something that this error only happens when Persian language pack is installed, but when its just CRM with no language packs everything is fine.
So at least i know what to do now and it's not something useful to be discussed further here.
Thanks.

How to find issue while installing Managed Package in Cloud CRM Dynamics 365?

I am facing an issue while installing my Managed package in Cloud CRM Dynamics 365. As I am not able to track the issue, it's a headache.
Let me explain the key points:
I have set customizable false for all the components
I have registered Plug-in in Sandbox mode. I have used plugin registration tool for license and a few other functions.
I have tried two ways.
First: When I tried to install the first time, I got unprocess status from workflow.
Second: To solve above issue, I have tried by removing Licence process related component. Now I am getting unprocess status from Plugin Assembly of Updating Sales Order.
The worst thing is I am not getting any error message or error code in log file.
Finally, here are a few logs. Can anybody suggest a solution?
--------------------------------------------------------------------------------------------------------
AsynchronousProcessingService Failed to add the item to the sync item collection for the mailbox : {8CBF53D0-896B-E611-80F2-FC15B4288714}. Exception details : Unhandled Exception: Microsoft.Crm.CrmArgumentException: Invalid input.
at Microsoft.Crm.Asynchronous.EmailConnector.ExchangeItemFinder.AddItemToSyncItemChangeInfoCollection(Item item, String itemId, SyncItemChangeType itemChangeType, ItemObjectType itemObjectType, String crmId)
Inner Exception: System.ArgumentException: Invalid input.
AsynchronousProcessingService Failed to add the item to the ItemFinder sync error collection for the mailbox : {8CBF53D0-896B-E611-80F2-FC15B4288714}. Exception details : Unhandled Exception: Microsoft.Crm.CrmArgumentException: Invalid input.
at Microsoft.Crm.Asynchronous.EmailConnector.ExchangeItemFinder.AddItemToItemFinderSyncErrors(String itemId, SyncItemChangeType itemChangeType, ItemObjectType itemObjectType, Exception ex)
Inner Exception: System.ArgumentException: Invalid input.
--------------------------------------------------------------------------------------------------------
WebApplicationServer MessageProcessor fail to process message 'InitializeFrom' for 'none'.
--------------------------------------------------------------------------------------------------------
WebApplicationServer InitializeFrom cannot be invoked from source entity of type account with id 89abd2b1-248f-e611-80f3-fc15b4282658 to target entity type task because there is no entity map defined between these two entities.
--------------------------------------------------------------------------------------------------------
WebApplicationServer Web Service Plug-in failed in SdkMessageProcessingStepId: 27cbbb1b-ea3e-db11-86a7-000a3a5473e8; EntityName: none; Stage: 30; MessageName: InitializeFrom; AssemblyName: Microsoft.Crm.Extensibility.InternalOperationPlugin, Microsoft.Crm.ObjectModel, Version=8.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35; ClassName: Microsoft.Crm.Extensibility.InternalOperationPlugin; Exception: Unhandled Exception: System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation.
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 System.Reflection.MethodBase.Invoke(Object obj, Object[] parameters)
at System.Web.Services.Protocols.LogicalMethodInfo.Invoke(Object target, Object[] values)
at Microsoft.Crm.Extensibility.InternalOperationPlugin.Execute(IServiceProvider serviceProvider)
at Microsoft.Crm.Extensibility.V5PluginProxyStep.ExecuteInternal(PipelineExecutionContext context)
at Microsoft.Crm.Extensibility.VersionedPluginProxyStepBase.Execute(PipelineExecutionContext context)
Inner Exception: Microsoft.Crm.CrmException: There is no entity map defined for the given entities
at Microsoft.Crm.ObjectModel.CustomizationService.InitializeFrom(BusinessEntityMoniker moniker, String targetEntityName, TargetFieldType targetFieldType, Boolean mapReadSecuredOnSourceAndTarget, ExecutionContext context)
at Microsoft.Crm.ObjectModel.CustomizationService.InitializeFrom(BusinessEntityMoniker moniker, String targetEntityName, TargetFieldType targetFieldType, ExecutionContext context)
--------------------------------------------------------------------------------------------------------
WebApplicationServer MessageProcessor fail to process message 'InitializeFrom' for 'none'.
--------------------------------------------------------------------------------------------------------
WebApplicationServer MSCRM Error Report:
Error: There is no entity map defined for the given entities
Error Number: 0x80040E01
Error Message: There is no entity map defined for the given entities
Error Details: There is no entity map defined for the given entities
Source File: Not available
Line Number: Not available
Request URL:
Stack Trace Info: [CrmException: There is no entity map defined for the given entities]
at Microsoft.Crm.Application.Platform.ServiceCommands.PlatformCommand.XrmExecuteInternal()
at Microsoft.Crm.Application.Platform.ServiceCommands.InitializeFromCommand.Execute()
*Update
Try turning off the plugins and workflows related to the entities and try again. Looks like you code have a bug in your plugin as well.
Based on the error message's it appears TFS does not permission to save the configuration file in the user roaming path:
Error Message: SaveConfigToFile() - fail - \\tpapsvmgmt01\UserMyDocs\sbrown\AppData\Roaming\Microsoft\PackageDeployer\Default_PackageDeployer.exe
Also, what version of the SDK are you using? It states you are using a pre 8.0 version. Ensure you have the latest SDK dll's.
PackageDeployment Information 8 4/4/2017 10:06:45 AM Executing Solution Import Pre v8.0
Microsoft.Xrm.Tooling.Connector.CrmServiceClient Verbose 16 4/4/2017 10:08:43 AM Failed to Execute Command - ImportSolution
Microsoft.Xrm.Tooling.Connector.CrmServiceClient Error 2 4/4/2017 10:08:43 AM Source : mscorlib
Method : HandleReturnMessage
Date : 4/4/2017
Time : 10:08:43 AM
Error : Message: Import failed
ErrorCode: -2147188706
Trace:
Stack Trace : Server stack trace:
at System.ServiceModel.Channels.ServiceChannel.HandleReply(ProxyOperationRuntime operation, ProxyRpc& rpc)
at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout)
at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation)
at System.ServiceModel.Channels.Servic
Could be the configuration setting that are being used to
Authentic because it is throwing error invoking channel proxy command.

Telerik RadGrid.MasterTableView.ExportToExcel() Error: The query results enumerated more than once

I have a RadGrid which is populated with some data. I have a button which will Export to Excel via a serverside callback. The server side code is below. And the error below that. Any suggestions?
RadGrid1.Rebind();
RadGrid1.ExportSettings.IgnorePaging = true;
RadGrid1.MasterTableView.ExportToExcel();
The error is:
The query results cannot be enumerated more than once.
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.InvalidOperationException: The query results cannot be enumerated more than once.
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:
[InvalidOperationException: The query results cannot be enumerated more than once.]
System.Data.Linq.SqlClient.OneTimeEnumerable1.GetEnumerator() +884205
System.Data.Linq.SqlClient.SingleResult1.GetEnumerator() +76
System.Linq.Buffer1..ctor(IEnumerable1 source) +302
System.Linq.d__0.MoveNext() +164
System.Linq.WhereSelectEnumerableIterator`2.MoveNext() +163
Telerik.Web.UI.GridResolveEnumerable.GetCollectionItemType(Boolean noItemsInEnumerator, Type& collectionItemType, Object& collectionFirstObject) +330
Telerik.Web.UI.GridResolveEnumerable.ParseProperties() +120
Telerik.Web.UI.GridResolveEnumerable.Initialize() +16
Telerik.Web.UI.GridResolveEnumerable.EnsureInitialized() +28
Telerik.Web.UI.GridEnumerableFromDataView..ctor(GridTableView owner, IEnumerable enumerable, Boolean CaseSensitive, Boolean autoGenerateColumns, GridColumnCollection presentColumns, String[] additionalField, Boolean retrieveAllFields) +242
Telerik.Web.UI.GridDataSourceHelper.CreateGridEnumerable(GridTableView owner, IEnumerable enumerable, Boolean caseSensitive, Boolean autoGenerateColumns, GridColumnCollection presentColumns, String[] additionalField, Boolean retrieveAllFields) +223
Telerik.Web.UI.GridDataSourceHelper.GetResolvedDataSource(GridTableView owner, Object dataSource, String dataMember, Boolean caseSensitive, Boolean autoGenerateColumns, GridColumnCollection presentColumns, String[] additionalField, Boolean retrieveAllFields) +595
Telerik.Web.UI.GridTableView.get_ResolvedDataSource() +243
Telerik.Web.UI.GridTableView.CreateChildControls(IEnumerable dataSource, Boolean useDataSource) +42
System.Web.UI.WebControls.CompositeDataBoundControl.PerformDataBinding(IEnumerable data) +72
System.Web.UI.WebControls.DataBoundControl.OnDataSourceViewSelectCallback(IEnumerable data) +147
System.Web.UI.WebControls.DataBoundControl.PerformSelect() +261
Telerik.Web.UI.GridTableView.PerformSelect() +9
Telerik.Web.UI.GridTableView.DataBind() +363
Telerik.Web.UI.RadGrid.DataBind() +73
Telerik.Web.UI.RadGrid.AutoDataBind(GridRebindReason rebindReason) +2488
Telerik.Web.UI.RadGrid.RebindForExport() +119
Telerik.Web.UI.Grid.Export.TableViewExporter.PrepareForExport() +315
System.EventHandler.Invoke(Object sender, EventArgs e) +0
System.Web.UI.Control.OnPreRender(EventArgs e) +11056782
System.Web.UI.Control.PreRenderRecursiveInternal() +108
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +3394
You don't want to call Rebind() before the export. Is there a reason for that? Are you changing/manipulating the data right before the export?
If not, there is no need to call Rebind(), since that is really only meant to refresh the data source.

How do I track down ValidateAntiForgeryToken not supplied issue?

I was looking at our logs and came across an error:
A required anti-forgery token was not supplied or was invalid.
It seems like one of the developers may have not added the token onto a page or did not send it via an AJAX call. The problem is I have no idea where in our code base this originated. It was logged by the [HandleError] logging code we added but we have no way of knowing which method caused this.
The stack trace only shows us the following which doesn't seem very helpful:
at System.Web.Helpers.AntiForgeryWorker.Validate(HttpContextBase
context, String salt) at
System.Web.Mvc.ControllerActionInvoker.InvokeAuthorizationFilters(ControllerContext
controllerContext, IList`1 filters, ActionDescriptor actionDescriptor)
at
System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext
controllerContext, String actionName)
The OnException method in our BaseController looks as follows:
protected override void OnException(ExceptionContext filterContext)
{
Exception ex = filterContext.Exception;
//
// Custom logging code here was removed for brevity
if (filterContext.Exception.Data.Contains("Description") == false)
filterContext.Exception.Data.Add("Description", "Oops. Something went wrong!");
//Displays a friendly error, doesn't require HandleError
filterContext.ExceptionHandled = true;
//Displays a friendly error, *requires* HandlError
base.OnException(filterContext);
}
My question is:
Is there a way to get the source of the exception, ie. to know what controller or source file threw the exception using ExceptionContext.
Appreciate the help.
Based on BuildStarted's response, the answer lies in the RouteData property of filterContext. I have an object dumper that writes out the properties of any object and here is what I see in our logs now.
RouteData:
[0]: [controller, Assess]
[1]: [action, Setup]
[2]: [id, 2]
So now I know the exact method that caused this.

.ToList throwing exception

I have a sorted dictionary, which stores some data. Every two minutes or so I do the following:
sorteddcitionary.Values.ToList() ----> This line throw exception sometimes. It is not consistent. The exception is as follows:
System.IndexOutOfRangeException: Index was outside the bounds of the array.
at System.Collections.Generic.SortedDictionary`2.ValueCollection.<>c__DisplayClass11.CopyTo>b__10(Node node)
at System.Collections.Generic.TreeSet`1.InOrderTreeWalk(TreeWalkAction`1 action)
at System.Collections.Generic.SortedDictionary`2.ValueCollection.CopyTo(TValue[] array, Int32 index)
at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
at Aditi.BMCMUtility.UnModCacheMaster.MessageAddition(PrivateMessage message, Nullable`1 cnt)
Any idea why this exception is coming from .Net LINQ code ?
It is within a lock. I am posting the code snippet. (This is after bzlm's response.)
try
{
lock (locker)
{
MessageCache.Add(message.MessageID, message);
privMsgList = MessageCache.Values.ToList(); /// Line which throws exception
while (MessageCache.Count > cnt.Value)
{
MessageCache.Remove((MessageCache.First().Key));
}
}
}
catch(Exception ex)
{}
It could be that the collection is being modified at the same time as it is being iterated. If this code is accessed by more than one thread simultaneously, you might need to lock the list for modifications while iterating it.
Locking during the ToList is not sufficient. You must also lock (the same object!) during the modification.

Resources