We have some code that occasionally flushed out certain keys in the ASP.NET cache in order to make sure that we are getting up to date data from our Dynamics CRM system. It seems to work fine most of the time, however we are getting intermittent exceptions on page reloads that I suspect is related to this forced cache flushing.
Here is the error in the UnauthorizedAccessException:
Access to the path 'appDomain=/LM/W3SVC/1/ROOT-1-129326029589946795:key=Microsoft.Xrm.Client.Services.InMemoryCrmCacheProvider:Crm:Query=953227368' is denied.
In case it is helpful, here is how I am flushing the cache items:
private void Flush()
{
IDictionaryEnumerator cacheEnum = this.HttpContext.Cache.GetEnumerator();
while (cacheEnum.MoveNext())
{
var key = cacheEnum.Key.ToString();
if (key.StartsWith("Microsoft.Xrm.Client.Services.InMemoryCrmCacheProvider:Crm:Query"))
System.Web.HttpContext.Current.Cache.Remove(key);
}
}
My questions:
Is there some level of permission required to access or remove cache items? I googled this but did not find anything specific (even in MSDN).
Have you seen this error before? How did you resolve it?
UPDATE: here is the stacktrace.
Stacktrace:
at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
at System.Threading.Mutex.MutexTryCodeHelper.MutexTryCode(Object userData)
at System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(TryCode code, CleanupCode backoutCode, Object userData)
at System.Threading.Mutex..ctor(Boolean initiallyOwned, String name, Boolean& createdNew, MutexSecurity mutexSecurity)
at System.Threading.Mutex..ctor(Boolean initiallyOwned, String name, Boolean& createdNew)
at Microsoft.Xrm.Client.Threading.MutexExtensions.Lock(String key, Int32 millisecondsTimeout, Action`1 action)
at Microsoft.Xrm.Client.Threading.MutexExtensions.Get[T](String key, Int32 millisecondsTimeout, Func`2 loadFromCache, Func`2 loadFromService)
at Microsoft.Xrm.Client.Threading.MutexExtensions.Get[T](String key, Func`2 loadFromCache, Func`2 loadFromService, Action`2 addToCache)
at Microsoft.Xrm.Client.Services.InMemoryCrmCacheProvider.InnerExecute[TRequest,TResponse,TResult](TRequest request, Func`2 execute, Func`2 selector, String selectorCacheKey)
at Microsoft.Xrm.Client.Services.CachedOrganizationService.Execute[T](MetadataServiceRequest request, Func`5 execute, Func`2 selector, String selectorCacheKey)
at Microsoft.Xrm.Client.Services.CachedOrganizationService.Execute[T](MetadataServiceRequest request, Func`2 selector, String selectorCacheKey)
at Microsoft.Xrm.Client.Services.CachedOrganizationService.Execute(Object request)
at Microsoft.Xrm.Client.Services.IOrganizationServiceExtensions.RetrieveAllEntities(IOrganizationService service, MetadataItems metadataItems, Boolean retrieveAsIfPublished)
at Microsoft.Xrm.Client.Services.InMemoryCrmCacheProvider.GetId(DynamicEntity entity)
at Microsoft.Xrm.Client.Services.InMemoryCrmCacheProvider.<GetDependencies>d__48.MoveNext()
at Microsoft.Xrm.Client.Services.InMemoryCrmCacheProvider.<GetDependencies>d__41.MoveNext()
at System.Linq.Enumerable.<SelectManyIterator>d__14`2.MoveNext()
at Microsoft.Xrm.Client.Services.InMemoryCrmCacheProvider.<GetDependencies>d__2b.MoveNext()
at Microsoft.Xrm.Client.Services.InMemoryCrmCacheProvider.<GetDependencies>d__13.MoveNext()
at System.Linq.Enumerable.<DistinctIterator>d__81`1.MoveNext()
at Microsoft.Xrm.Client.Services.InMemoryCrmCacheProvider.GetCachePolicy(Object query, Object result)
at Microsoft.Xrm.Client.Services.InMemoryCrmCacheProvider.Insert(String key, Object query, Object result)
at Microsoft.Xrm.Client.Threading.MutexExtensions.<>c__DisplayClass5`1.<Get>b__4(String k)
at Microsoft.Xrm.Client.Threading.MutexExtensions.<>c__DisplayClass2`1.<Get>b__0(Mutex _)
at Microsoft.Xrm.Client.Threading.MutexExtensions.Lock(String key, Int32 millisecondsTimeout, Action`1 action)
at Microsoft.Xrm.Client.Threading.MutexExtensions.Get[T](String key, Int32 millisecondsTimeout, Func`2 loadFromCache, Func`2 loadFromService)
at Microsoft.Xrm.Client.Threading.MutexExtensions.Get[T](String key, Func`2 loadFromCache, Func`2 loadFromService, Action`2 addToCache)
at Microsoft.Xrm.Client.Services.InMemoryCrmCacheProvider.InnerExecute[TRequest,TResponse,TResult](TRequest request, Func`2 execute, Func`2 selector, String selectorCacheKey)
at Microsoft.Xrm.Client.Services.CachedOrganizationService.Execute[T](Request request, Func`2 selector, String selectorCacheKey)
at Microsoft.Xrm.Client.Services.CachedOrganizationService.RetrieveMultiple(QueryBase query)
at Microsoft.Xrm.Client.Services.IOrganizationServiceExtensions.Using[T](Func`1 create, Func`2 action)
at Microsoft.Xrm.Client.Linq.CrmQueryProvider.Execute[TElement](QueryExpression qe, LambdaExpression projection, Delegate postMethodCall, LambdaExpression filter, Type entityType)
at Microsoft.Xrm.Client.Linq.CrmQueryProvider.Execute[TElement](Expression expression)
at Microsoft.Xrm.Client.Linq.QueryProvider.System.Linq.IQueryProvider.Execute[TResult](Expression expression)
at System.Linq.Queryable.Single[TSource](IQueryable`1 source)
at FrontOfficeApp.Controllers.BillingController.GetBillingInstitutions(Requisition req)
at FrontOfficeApp.Controllers.BillingController.InstitutionalBillPartial(Int32 requisitionId)
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__DisplayClassd.<InvokeActionMethodWithFilters>b__a()
at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation)
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.MvcHandler.<>c__DisplayClass8.<BeginProcessRequest>b__4()
at System.Web.Mvc.Async.AsyncResultWrapper.<>c__DisplayClass1.<MakeVoidDelegate>b__0()
at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
Message=Access to the path 'appDomain=/LM/W3SVC/1/ROOT-1-119328537521157948:key=Microsoft.Xrm.Client.Services.InMemoryCrmCacheProvider:Crm:Query=913126368' is denied.
Data=System.Collections.ListDictionaryInternal
UPDATE2:
We just updated to the 4.0.13 version of the SDK in order to turn off caching (actually I could only get it to work by setting the duration to 1 second, see below). This allows us to get around the issue of CRM needing to be flushed, but we are still getting the caching errors in our environment, although they look a little different now:
Message=Access to the path 'appDomain=/LM/W3SVC/1/ROOT-1-129341239247458264:key=Microsoft.Xrm.Client.Services.InMemoryCrmCacheProvider:Crm:User=00000000-0000-0000-0000-000000000000,00000000-0000-0000-0000-000000000000:Query=923237368' is denied.
Data=System.Collections.ListDictionaryInternal
For what is is worth, the context configuration I am using is below. I am adding a bounty to this question as a last ditch attempt.
<microsoft.xrm.client>
<contexts default="Crm">
<add name="Crm" type="CRM.XrmDataContext" serviceName="Default" />
</contexts>
<services default="Default">
<add name="Default" cacheProviderName="Default" />
</services>
<cache defaultProvider="Default">
<providers>
<add name="Default"
type="Microsoft.Xrm.Client.Caching.InMemoryCacheProvider, Microsoft.Xrm.Client" duration="00:00:01" />
</providers>
</cache>
</microsoft.xrm.client>
We finally figured out the answer to this issue. The problem was related to impersonation (we had it turned on in the web.config) and the fact that we were accessing XRM using a singleton. Apparently, when multiple users tried to run simultaneous CRM queries through our software, the singleton would make the connection to CRM under their user context. Apparently while this is happening, the cache for the query results are "owned" by that user context. When another user tried to run a query at the same time, they would receive a 401 status code.
The fix ended up being to turn of impersonation and do some minor refactoring so that we did not need it anymore. I imagine we could instead have allowed multiple CRM instances--though we intentionally don't do that for performance reasons.
I hope this helps anyone else who might be seeing these funky errors.
I can't imagine that the exception is actually tied to the Cache.Remove call.
Just a guess, but is it possible that the exception is related to the CacheItemRemovedCallback and not the actual removal step (not sure if the call-back is executed synchronously on the same thread)?
Can you post the full stack trace for the exception?
Related
I'm transferring a .NET Framework 4.0 site from 1 web host to another. The site on the existing hosting seems to be working as intended. However, after transferring the site files and database to the new hosting and then fixing the web.config connection string to point to the new db, I'm getting errors when trying to access a page that pulls from the database.
I did not write the site, but it appears to be using a code-first setup.
Server Error in '/' Application.
An item with the same key has already been added.
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.ArgumentException: An item with the same key has already been added.
Source Error:
Line 130: if ((_Jobs == null))
Line 131: {
Line 132: _Jobs = base.CreateObjectSet<Job>("Jobs");
Line 133: }
Line 134: return _Jobs;
I've tried rebuilding the edmx file from the new database server after transferring the files. I know my connection string is working because I wrote a small test that connects to the database through the same connection string and it is able to retrieve data.
The only change I've made to the code base after copying it from it's working state is to the web.config's db connection string.
The only real notable difference from the old hosting versus the new hosting is that the old hosting was using SQLEXPRESS(unknown version), whereas the new hosting is using MSSQL 2008.
Stack Trace:
[ArgumentException: An item with the same key has already been added.]
System.ThrowHelper.ThrowArgumentException(ExceptionResource resource) +52
System.Collections.Generic.Dictionary`2.Insert(TKey key, TValue value, Boolean add) +9378779
System.Data.Metadata.Edm.ObjectItemAttributeAssemblyLoader.LoadRelationshipTypes() +650
System.Data.Metadata.Edm.ObjectItemAttributeAssemblyLoader.LoadTypesFromAssembly() +17
System.Data.Metadata.Edm.ObjectItemAssemblyLoader.Load() +25
System.Data.Metadata.Edm.ObjectItemAttributeAssemblyLoader.Load() +4
System.Data.Metadata.Edm.AssemblyCache.LoadAssembly(Assembly assembly, Boolean loadReferencedAssemblies, ObjectItemLoadingSessionData loadingData) +160
System.Data.Metadata.Edm.AssemblyCache.LoadAssembly(Assembly assembly, Boolean loadReferencedAssemblies, KnownAssembliesSet knownAssemblies, EdmItemCollection edmItemCollection, Action`1 logLoadMessage, Object& loaderCookie, Dictionary`2& typesInLoading, List`1& errors) +166
System.Data.Metadata.Edm.ObjectItemCollection.LoadAssemblyFromCache(ObjectItemCollection objectItemCollection, Assembly assembly, Boolean loadReferencedAssemblies, EdmItemCollection edmItemCollection, Action`1 logLoadMessage) +316
System.Data.Metadata.Edm.ObjectItemCollection.ImplicitLoadAssemblyForType(Type type, EdmItemCollection edmItemCollection) +84
System.Data.Metadata.Edm.MetadataWorkspace.ImplicitLoadAssemblyForType(Type type, Assembly callingAssembly) +151
System.Data.Objects.ObjectContext.GetTypeUsage(Type entityCLRType) +35
System.Data.Objects.ObjectContext.GetEntitySetForNameAndType(String entitySetName, Type entityCLRType, String exceptionParameterName) +33
System.Data.Objects.ObjectContext.CreateObjectSet(String entitySetName) +66
PR.PRModel.PREntities.get_Jobs() in \\n5200-2\iis7_www\p\e\personallyrecommended.com.au\www\App_Code\PRModel.Designer.cs:132
Careers.LoadJob() in \\n5200-2\iis7_www\p\e\personallyrecommended.com.au\www\Careers.aspx.cs:24
Careers.Page_Load(Object sender, EventArgs e) in \\n5200-2\iis7_www\p\e\personallyrecommended.com.au\www\Careers.aspx.cs:16
System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e) +14
System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +35
System.Web.UI.Control.OnLoad(EventArgs e) +91
System.Web.UI.Control.LoadRecursive() +74
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +2207
Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.272
Connection String:
<connectionStrings>
<add name="PREntities" connectionString="metadata=res://*/App_Code.PRModel.csdl|res://*/App_Code.PRModel.ssdl|res://*/App_Code.PRModel.msl;provider=System.Data.SqlClient;provider connection string="Data Source=myserver.com;Initial Catalog=mydatabase;Persist Security Info=True;User ID=username;Password=password;MultipleActiveResultSets=True"" providerName="System.Data.EntityClient" />
<add name="ConnectionStringDB" connectionString="Data Source=myserver.com;Initial Catalog=mydatabase;Persist Security Info=True;User ID=username;Password=password" providerName="System.Data.SqlClient" />
</connectionStrings>
I've just noticed that when running an application I periodically get an error message.
Server Error in '/' Application.
Buffer cannot be null.
Parameter name: buffer
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.ArgumentNullException: Buffer cannot be null.
Parameter name: buffer
Stack trace:
[ArgumentNullException: Buffer cannot be null.
Parameter name: buffer]
System.IO.MemoryStream..ctor(Byte[] buffer, Boolean writable) +12627669
MemcachedProviders.Session.Common.Deserialize(HttpContext context, Byte[] serializedItems, Int32 timeout) +47
MemcachedProviders.Session.Db.SQLDbOperations.GetItem(String strSessionId, String strApplicationName, Int32 iTime, HttpContext context, Boolean lockRecord, Boolean& locked, TimeSpan& lockAge, Object& lockId, SessionStateActions& actionFlags) +1221
MemcachedProviders.Session.SessionStateProvider.GetItemExclusive(HttpContext context, String id, Boolean& locked, TimeSpan& lockAge, Object& lockId, SessionStateActions& actions) +1069
System.Web.SessionState.SessionStateModule.GetSessionStateItem() +178
System.Web.SessionState.SessionStateModule.PollLockedSessionCallback(Object state) +299
[HttpException (0x80004005): Exception of type 'System.Web.HttpException' was thrown.]
System.Web.SessionState.SessionStateModule.EndAcquireState(IAsyncResult ar) +11513726
System.Web.AsyncEventExecutionStep.OnAsyncEventCompletion(IAsyncResult ar) +107
Our application uses Enyim memcached and MemcachedProviders and runs in a load balanced environment.
The application does alot of managing of PDF reports and compiling of responses then generating a final report pdf. So we use streams quite a bit.
This problem only appears to affect our management application as we also expose a webservice and I never get the error when looking at the service definition and WSDL.
From looking at the session table in the DB I can see that they are being created but, many of them have null in the SessionItems field and the locked flag set to 1.
The data time stamps seem to correlate to the null buffer error occurances.
Is this a case of a buffer set incorrectly or maxing out?
We've run into some issues with ASP.NET MVC 3 AntiForgeryToken HTML helper when having a custom configured MachineKey in Web.Config. The error is easy to reproduce if you change your MachineKey to the following (taken from Microsoft HowTo-guide on how to configure machine key).
<machineKey
validationKey="21F090935F6E49C2C797F69BBAAD8402ABD2EE0B667A8B44EA7DD4374267A75D7
AD972A119482D15A4127461DB1DC347C1A63AE5F1CCFAACFF1B72A7F0A281B"
decryptionKey="ABAA84D7EC4BB56D75D217CECFFB9628809BDB8BF91CFCD64568A145BE59719F"
validation="SHA1"
decryption="AES"/>
The exception thrown by AntiForgeryToken is as follow:
[IndexOutOfRangeException: Index was outside the bounds of the array.]
System.Web.Configuration.MachineKeySection.SetInnerOuterKeys(Byte[] validationKey, Byte[]& inner, Byte[]& outer) +11499173
System.Web.Configuration.MachineKeySection.ConfigureEncryptionObject() +228
System.Web.Configuration.MachineKeySection.EnsureConfig() +287
System.Web.Configuration.MachineKeySection.HashData(Byte[] buf, Byte[] modifier, Int32 start, Int32 length) +46
System.Web.Security.MachineKey.Encode(Byte[] data, MachineKeyProtection protectionOption) +58
System.Web.Helpers.AntiForgeryDataSerializer.<.ctor>b__2(Byte[] bytes) +13
System.Web.Helpers.AntiForgeryDataSerializer.Serialize(AntiForgeryData token) +365
System.Web.Helpers.AntiForgeryWorker.GetAntiForgeryTokenAndSetCookie(HttpContextBase httpContext, String salt, String domain, String path) +326
System.Web.Helpers.AntiForgeryWorker.GetHtml(HttpContextBase httpContext, String salt, String domain, String path) +28
System.Web.Helpers.AntiForgery.GetHtml(HttpContextBase httpContext, String salt, String domain, String path) +75
System.Web.Mvc.HtmlHelper.AntiForgeryToken(String salt, String domain, String path) +48
Is this a bug in the ASP.NET MVC 3 Html Helper to generate the AntiForgeryToken? Or am I missing something in regards to configuring machine keys?
It looks like I screwed up the keys - using http://aspnetresources.com/tools/machineKey I was able to generate a valid machineKey config section.
I use asp.net + MVC1.0 and in a web-page I have several forms, within each forms I have called the following function AntiForgeryToken() to generate a hidden value, and in Controller function I have a validate attribute.
When I use JMeter and capture the token using regular expression then post the token with my form to server, I found it throw such a exception:
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.FormatException: Invalid length for a Base-64 char array.
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.
Version Information: Microsoft .NET Framework Version:2.0.50727.3603; ASP.NET Version:2.0.50727.3082
[FormatException]: Invalid length for a Base-64 char array.
at System.Convert.FromBase64String(String s)
at System.Web.UI.ObjectStateFormatter.Deserialize(String inputString)
at System.Web.UI.ObjectStateFormatter.System.Web.UI.IStateFormatter.Deserialize(String serializedState)
at System.Web.Mvc.AntiForgeryDataSerializer.Deserialize(String serializedToken)
[HttpAntiForgeryException]: A required anti-forgery token was not supplied or was invalid.
at System.Web.Mvc.AntiForgeryDataSerializer.Deserialize(String serializedToken)
at System.Web.Mvc.ValidateAntiForgeryTokenAttribute.OnAuthorization(AuthorizationContext filterContext)
at System.Web.Mvc.ControllerActionInvoker.InvokeAuthorizationFilters(ControllerContext controllerContext, IList`1 filters, ActionDescriptor actionDescriptor)
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)
This error page might contain sensitive information because ASP.NET is configured to show verbose error messages using <customErrors mode="Off"/>. Consider using <customErrors mode="On"/> or <customErrors mode="RemoteOnly"/> in production environments.
And I am sure the the captured token is exactly same as what we generated, why this exception happened?
Just solved, because I didn't encode the token before post to server .
We added DynamicProxy to our ASP.NET web app a couple of weeks ago. The code ran fine in dev and QA, but when we pushed to production, we got the following exception (top of stack trace only):
[ArgumentNullException: Invalid internal state.]
System.Reflection.Emit.TypeBuilder._InternalSetMethodIL(Int32 methodHandle, Boolean isInitLocals, Byte[] body, Byte[] LocalSig, Int32 sigLength, Int32 maxStackSize, Int32 numExceptions, __ExceptionInstance[] exceptions, Int32[] tokenFixups, Int32[] rvaFixups, Module module) +0
System.Reflection.Emit.TypeBuilder.InternalSetMethodIL(Int32 methodHandle, Boolean isInitLocals, Byte[] body, Byte[] LocalSig, Int32 sigLength, Int32 maxStackSize, Int32 numExceptions, __ExceptionInstance[] exceptions, Int32[] tokenFixups, Int32[] rvaFixups, Module module) +56
System.Reflection.Emit.TypeBuilder.CreateTypeNoLock() +1033
System.Reflection.Emit.TypeBuilder.CreateType() +99
Castle.DynamicProxy.Generators.Emitters.AbstractTypeEmitter.CreateType(TypeBuilder type) +72
Castle.DynamicProxy.Generators.Emitters.AbstractTypeEmitter.BuildType() +96
Castle.DynamicProxy.Generators.ClassProxyGenerator.GenerateType(String name, Type[] interfaces, INamingScope namingScope) +854
Castle.DynamicProxy.Generators.ClassProxyGenerator.GenerateCode(Type[] interfaces, ProxyGenerationOptions options) +834
Castle.DynamicProxy.DefaultProxyBuilder.CreateClassProxyType(Type classToProxy, Type[] additionalInterfacesToProxy, ProxyGenerationOptions options) +133
Castle.DynamicProxy.ProxyGenerator.CreateClassProxyType(Type classToProxy, Type[] additionalInterfacesToProxy, ProxyGenerationOptions options) +52
Castle.DynamicProxy.ProxyGenerator.CreateClassProxy(Type classToProxy, Type[] additionalInterfacesToProxy, ProxyGenerationOptions options, Object[] constructorArguments, IInterceptor[] interceptors) +308
Castle.DynamicProxy.ProxyGenerator.CreateClassProxy(Type classToProxy, Type[] additionalInterfacesToProxy, ProxyGenerationOptions options, IInterceptor[] interceptors) +48
Castle.DynamicProxy.ProxyGenerator.CreateClassProxy(Type classToProxy, ProxyGenerationOptions options, IInterceptor[] interceptors) +44
It worked fine when we first pushed the code, and an IIS reset fixed it, so I'm assuming it's thread related, but I couldn't find anything on the interwebs regarding best practices for thread-safety proxy generation. Suggestions?
UPDATE: After reading some more on the issue, especially here, I realized one potential issue -- namely that I had not overwritten Equals/GetHashCode for the implementation of IProxyGenerationHook I had written, which would prevent DynamicProxy from caching it's types. As I can find next to nothing on the exception I saw in general let alone related to DP, I'm gonna assume that it was the lack of caching of types caused by my omission that was the root cause of the problem, though I'd love a confirmation.
For the record, my object creation is pretty vanilla:
private T CreateProxy(MyArgs args)
{
var options = new ProxyGenerationOptions(new MyMethodSelector());
options.AddMixinInstance(new MyMixin());
return Generator.CreateClassProxy(
TargetType,
options,
new[] { new MyInterceptor(args) }) as T;
}
actually DynamicProxy is thread safe so it is quite unlikely it is concurrency related.
First of all, which version of DynamicProxy are you using?
Are you able to reproduce the issue in isolation, outside of IIS?
This issue was reported two years ago, but it was fixed. Please make sure you have the latest version.