Quantcast
Channel: Microsoft Dynamics CRM Forum - Recent Threads
Viewing all articles
Browse latest Browse all 46379

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

$
0
0

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));
            });
        }



Viewing all articles
Browse latest Browse all 46379

Trending Articles