Skip to main content

Notifications

Announcements

No record found.

Microsoft Dynamics CRM (Archived)

[CRM SDK 2011 Exception] - System.ObjectDisposedException: Cannot access a disposed object.

Posted on by Microsoft Employee

Hi,

i've this problem and, searching on google i've found many article but I could not fix it.

This is the error:

2016-10-27 23:20:42,287 [32] ERROR (:0)- Mapper.ToCrmPrivateCustomer - toCrmPrivateCustomer EXCEPTION: An error occured while processing this request.
Microsoft.Xrm.Sdk.SaveChangesException: An error occured while processing this request. ---> System.ServiceModel.Security.MessageSecurityException: Message security verification failed. ---> System.ObjectDisposedException: Cannot access a disposed object.
Object name: 'System.ServiceModel.Security.SymmetricSecurityProtocol'.
   at System.ServiceModel.Channels.CommunicationObject.ThrowIfClosedOrNotOpen()
   at System.ServiceModel.Security.MessageSecurityProtocol.VerifyIncomingMessage(Message& message, TimeSpan timeout, SecurityProtocolCorrelationState[] correlationStates)
   --- End of inner exception stack trace ---

Server stack trace: 
   at System.ServiceModel.Security.MessageSecurityProtocol.VerifyIncomingMessage(Message& message, TimeSpan timeout, SecurityProtocolCorrelationState[] correlationStates)
   at System.ServiceModel.Channels.SecurityChannelFactory`1.SecurityRequestChannel.ProcessReply(Message reply, SecurityProtocolCorrelationState correlationState, TimeSpan timeout)
   at System.ServiceModel.Channels.SecurityChannelFactory`1.SecurityRequestChannel.Request(Message message, TimeSpan timeout)
   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.ServiceChannelProxy.Invoke(IMessage message)

Exception rethrown at [0]: 
   at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
   at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
   at Microsoft.Xrm.Sdk.IOrganizationService.Execute(OrganizationRequest request)
   at Microsoft.Xrm.Sdk.Client.OrganizationServiceProxy.ExecuteCore(OrganizationRequest request)
   at Microsoft.Xrm.Sdk.Client.OrganizationServiceContext.Execute(OrganizationRequest request)
   at Microsoft.Xrm.Sdk.Client.OrganizationServiceContext.SaveChange(OrganizationRequest request, IList`1 results)
   --- End of inner exception stack trace ---
   at Microsoft.Xrm.Sdk.Client.OrganizationServiceContext.SaveChanges(SaveChangesOptions options)
   at EAI.CRM.Wrapper.Connector.Mapper.ToCrmPrivateCustomer(PRIVATECUSTOMER_EAI_Request request, IDictionary`2 dictionary)

And this is my code:


    public class EAIService : IEAIService
    {
        private readonly ILog _log;
        private readonly IEAItoCRMConnector _connector;
        //private readonly IServiceHandler _handler;

        public EAIService()
            : this(DependencyFactory.Resolve<ILog>(), DependencyFactory.Resolve<IEAItoCRMConnector>())
        {}

        public EAIService(ILog log, IEAItoCRMConnector connector)
        {
            _log = log;
            _connector = connector;
        }
		
        public ResponseBase SUBSCRIBE_EAI_CAMPAIGN_RESPONSE(Campaign_Response_EAI_Request request)
        {
            ResponseBase response;
            try
            {
                _log.Info("SUBSCRIBE_EAI_SHOPCALLRESULT");
                _log.Debug(Environment.NewLine + Util.GetContent(request));

                var checker = DependencyFactory.Resolve<ICampaignResponseChecker>();
                response = ServiceHandler.Manage(
                    () => _connector.Subscribe(request, checker),
                    ErrCallBack);

                _log.Info(Environment.NewLine + Util.GetContent(response));
            }
            catch (Exception ex)
            {
                _log.Error(ex.Message, ex);
                response = new ResponseBase(CONST.ERROR, ex.Message);
            }
            finally
            {
                _log.Info("END-SUBSCRIBE-CUSTOMER");
            }
            return response;
        }
        private ResponseBase ErrCallBack(string message, int code)
        {
            _log.Error(message);
            return new ResponseBase { retMessage = message, retCode = code };
        }
    }


    public class ServiceHandler : IServiceHandler
    {
        public static T Manage<T>(Func<T> invoke, Func<string, int, T> errCallBack) where T : class, new()
        {
            var code = int.MinValue;
            var message = string.Empty;
            object result = null;
            try
            {
                result = invoke.Invoke();
            }
            catch (FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault> ex)
            {
                message = WriteFaultDetail(ex.Detail);
            }
            catch (System.TimeoutException ex)
            {
                var inner = string.Concat("Inner Fault: {0}",
                    null == ex.InnerException ? "No Inner Fault" : ex.InnerException.Message);

                message = string.Concat(WriteMessage(ex.Message, ex.Source), inner);
            }
            catch (System.Exception ex)
            {
                message = WriteMessage(ex.Message, ex.Source);

                // Display the details of the inner exception.
                if (ex.InnerException != null)
                {
                    message = string.Concat(message, ex.InnerException.Message);

                    FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault> fe = ex.InnerException
                        as FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault>;
                    if (fe != null)
                    {
                        message = string.Concat(message, WriteFaultDetail(fe.Detail));
                    }
                }
                var pi = ex.GetType().GetProperty("Code");
                if (pi != null)
                    code = (int)pi.GetValue(ex);
            }
            return (T)(result ?? errCallBack(message, code));
        }
    }


    public class EAItoCRMConnector : IEAItoCRMConnector
    {
        private readonly IDictionary<Guid, IDictionary<string, object>> _additionalData;
        private readonly Mapper _mapper;
        private ILog _logger;
        private IXrmContext _xrm;

        public EAItoCRMConnector(IXrmContext context, ILog log)
        {
            _additionalData = new Dictionary<Guid, IDictionary<string, object>>();
            _mapper = new Mapper(context, log);
            _logger = log;
            _xrm = context;
        }

		public ResponseBase Subscribe(PrivateCustomer_EAI_Request request, IPrivateCustomerChecker checker)
        {
            //
            _logger.Info("SUBSCRIBE_EAI_PRIVATECUSTOMER :: Subscribe");

            var obj = _mapper.ToCrmPrivateCustomer(request, _additionalData[key]) as PrivateCustomerResponse;
            Debug.Assert(obj != null, "obj != null");
            return obj.ResponseBase;

        }

        public PrivateCustomerResponse ToCrmPrivateCustomer(PrivateCustomer_EAI_Request request, IDictionary<string, object> dictionary)
        {
            _log.Info("ToCrmPrivateCustomer Start...");
            var isUpdate = false;
            Contact contact = Util.GetLookupValueRef<Contact>(dictionary, "customer");
            try
            {
                _log.Info("ToCrmPrivateCustomer Init ");

                if (contact == null)
                {
                    contact = new Contact();
                    contact.Goal_customercode = string.Concat(request.CompanyCode, request.DivisionCode, request.CustomerCode);
                    _log.Info("ToCrmPrivateCustomer: CREATE NEW CUSTOMER");
                }
                else
                {
                    isUpdate = true;
                    _log.Info("ToCrmPrivateCustomer: UPDATE EXISTING CUSTOMER");
                }
                if (isUpdate)
                {
                    _log.Info("ToCrmPrivateCustomer: UPDATE");
                    _xrm.UpdateObject(contact);
                }
                else
                {
                    _log.Info("ToCrmPrivateCustomer: ADD");
                    _xrm.AddObject(contact);
                }
                _xrm.SaveChanges();
                _log.Info("ToCrmPrivateCustomer succeeded");

                return new PrivateCustomerResponse()
                {
                    PrivateCustomer = contact,
                    ResponseBase =
                        new ResponseBase(CONST.OK,
                            "PrivateCustomer with CUSTOMERCODE: " + request.CustomerCode + " succesfully managed on CRM")
                };
            }
            catch (Exception ex)
            {
                if (contact != null && _xrm.IsAttached(contact))
                    _xrm.Detach(contact);

                _log.Error("toCrmPrivateCustomer EXCEPTION: " + ex.Message, ex);
                
                throw;
            }

        }
}   }

Where Dependencies are configured in Global.asax and web.config:

        protected void Application_Start(object sender, EventArgs e)
        {
            var connectionSettings = ConfigurationManager.ConnectionStrings["CRMInterface"];
            logger = LogManager.GetLogger("EAIService");
            log4net.Config.XmlConfigurator.Configure();

            var proxyInstance = new CrmDataService(typeof(xrmContext), "CrmES", true);

            DependencyFactory.Register(() =>
            {
                DependencyFactory.Container.RegisterInstance<ICrmDataService>(proxyInstance)
                    
                    .RegisterType<xrmContext>(new InjectionConstructor(proxyInstance.Proxy))
                    .RegisterType<IXrmContext, xrmContext>(new InjectionConstructor(proxyInstance.Proxy))
                    //.RegisterType<IEAItoCRMConnector, EAItoCRMConnector>()
                    //.RegisterType<ICRMtoEAIConnector, CRMtoEAIConnector>()
                    .RegisterInstance<ILog>(logger)
                    .RegisterType<IDataAccess, DataAccessLayer>(new InjectionConstructor(connectionSettings.ProviderName,
                        connectionSettings.ConnectionString));
            });
        }


*This post is locked for comments

  • RE: [CRM SDK 2011 Exception] - System.ObjectDisposedException: Cannot access a disposed object.

    Hallo Frank

    Thanks for your answer. I'm aware about this. But everytime I get this error: "System.ServiceModel.Security.MessageSecurityException: Message security verification failed", the data in CRM is saved correctly. It happens only sporadically, especially wenn multiple users are registering at the same time. The IOrganisationService.Create throws this error, but the Registration Process seems to be correct, I can see the Contact in CRM with all the informations I provide in the Web Form.  In the Try/Catch of the CreateRecord function I have added another call to crm and I check for the last created contact where creation date in the last minute is. If I find the Contact, then I ignore this error.

    I wonder why is happening from time to time? In my case is impossible to reproduce it manually, even if I provide the exact same data.

  • Community Member Profile Picture
    Community Member Microsoft Employee on at
    RE: [CRM SDK 2011 Exception] - System.ObjectDisposedException: Cannot access a disposed object.

    Hi Frank, thanks for suggestion. I'm not a owner of CRM, but I can ask for check. Stay tuned

  • Frank Bursitzke Profile Picture
    Frank Bursitzke 30 on at
    RE: [CRM SDK 2011 Exception] - System.ObjectDisposedException: Cannot access a disposed object.

    Can you check, whether there are any plug-ins registered on the entity you are working with?

    If yes - make sure those plug-ins also handle the FaultException<OrganizationServiceFault> and raise an InvalidPluginExecutionException. Plug-Ins should never swallow exceptions or throw any other exceptions than InvalidPluginExecutionExceptions, because this leaves your OrganizationService Proxy in a broken (or closed) state which *might* result in the error your seeing (or some strange error message about missing transaction).

  • RE: [CRM SDK 2011 Exception] - System.ObjectDisposedException: Cannot access a disposed object.

    Hello

    I'm facing the same Problem wen I use the IOrganisationService in a Webservice. Even creating every time a new Instance of the IOrganisationService does not help. The strange thing is that wen this happens on the Create Message, the record is created properly. I have no clue why is it happening.

    Did you find any solution to this?

Under review

Thank you for your reply! To ensure a great experience for everyone, your content is awaiting approval by our Community Managers. Please check back later.

Helpful resources

Quick Links

December Spotlight Star - Muhammad Affan

Congratulations to a top community star!

Top 10 leaders for November!

Congratulations to our November super stars!

Tips for Writing Effective Suggested Answers

Best practices for providing successful forum answers ✍️

Leaderboard

#1
André Arnaud de Calavon Profile Picture

André Arnaud de Cal... 291,280 Super User 2024 Season 2

#2
Martin Dráb Profile Picture

Martin Dráb 230,214 Most Valuable Professional

#3
nmaenpaa Profile Picture

nmaenpaa 101,156

Leaderboard

Featured topics

Product updates

Dynamics 365 release plans