Exemple #1
0
        public override void ExecuteCRMWorkFlowActivity(CodeActivityContext executionContext, LocalWorkflowContext crmWorkflowContext)
        {
            #region local variables
            SCII.Helper objCommon;
            //EntityReference _Contact;
            int _errorCode = 400; //Bad Request

            string _errorMessageDetail = string.Empty;



            int?          optionSetValue;
            Guid          orgId = Guid.Empty;
            Entity        existingAccountRecord = new Entity();
            StringBuilder _errorMessage         = new StringBuilder();
            string        _uniqueReference      = string.Empty;
            string        _crn        = string.Empty;
            bool          isOrgExists = false;
            #endregion

            LocalWorkflowContext localcontext = new LocalWorkflowContext(executionContext);
            Entity AccountObject = new Entity(SCS.AccountContants.ENTITY_NAME);

            try
            {
                objCommon = new SCII.Helper(executionContext);
                OrganizationServiceContext orgSvcContext = new OrganizationServiceContext(objCommon.service);

                localcontext.Trace("started execution");


                localcontext.Trace("attempt to seriallised");

                string jsonPayload = ReqPayload.Get(executionContext);
                SCII.UpdateOrganisationRequest accountPayload = JsonConvert.DeserializeObject <SCII.UpdateOrganisationRequest>(jsonPayload);
                //if (accountPayload.clearlist != null)
                //    //localcontext.Trace("TRACE TO CHECK:" + accountPayload.clearlist[0].ToString());
                //    localcontext.Trace("TRACE TO CHECK:" + accountPayload.clearlist.fields[0].ToString());

                var ValidationContext = new ValidationContext(accountPayload, serviceProvider: null, items: null);
                ICollection <ValidationResult> ValidationResults       = null;
                ICollection <ValidationResult> ValidationResultUpdates = null;

                var     isValid       = objCommon.Validate(accountPayload, out ValidationResults);
                Boolean isValidUpdate = accountPayload.updates == null ? true :

                                        objCommon.Validate(accountPayload.updates, out ValidationResultUpdates);

                localcontext.Trace("TRACE TO valid:" + isValid);
                if (isValid && isValidUpdate)
                {
                    //check organisation id exists
                    if (!string.IsNullOrEmpty(accountPayload.organisationid) && !string.IsNullOrWhiteSpace(accountPayload.organisationid))
                    {
                        if (Guid.TryParse(accountPayload.organisationid, out orgId))
                        {
                            existingAccountRecord = objCommon.service.Retrieve(SCS.AccountContants.ENTITY_NAME, orgId, new Microsoft.Xrm.Sdk.Query.ColumnSet(SCS.AccountContants.UNIQUEREFERENCE, SCS.AccountContants.PARENTACCOUNTID));
                            if (existingAccountRecord != null && existingAccountRecord.Id != null)
                            {
                                AccountObject.Id = existingAccountRecord.Id;
                                _uniqueReference = (string)existingAccountRecord[SCS.AccountContants.UNIQUEREFERENCE];
                                isOrgExists      = true;
                            }
                        }
                    }
                    // if org exists then go on to update the organisation
                    if (isOrgExists && accountPayload.updates != null)
                    {
                        localcontext.Trace("length:" + accountPayload.updates.name.Length);
                        //if (accountPayload.updates.hierarchylevel != 0)

                        #region Cannot be Cleared Update Fields
                        if (accountPayload.updates.name != null)
                        {
                            AccountObject[SCS.AccountContants.NAME] = accountPayload.updates.name;
                        }
                        if (accountPayload.updates.type != null)
                        {
                            if (!String.IsNullOrEmpty(Enum.GetName(typeof(SCSE.defra_OrganisationType), accountPayload.updates.type)))
                            {
                                optionSetValue = accountPayload.updates.type;
                                localcontext.Trace("before assigning type  " + accountPayload.updates.type);
                                localcontext.Trace(optionSetValue.ToString());
                                localcontext.Trace("after  setting up option set value");
                                OptionSetValueCollection BusinessTypes = new OptionSetValueCollection();
                                BusinessTypes.Add(new OptionSetValue(optionSetValue.Value));
                                AccountObject[SCS.AccountContants.TYPE] = BusinessTypes;
                            }
                            else
                            {
                                _errorMessage = _errorMessage.Append(String.Format("Option set value {0} for orgnisation type does not exists.",
                                                                                   accountPayload.updates.type));
                            }
                        }

                        #endregion

                        #region Clear able update fields
                        //Flag to check if the clearing of data is required for the selected OrganisationRequest fields
                        bool clearRequired = accountPayload.clearlist != null &&
                                             accountPayload.clearlist.fields != null && accountPayload.clearlist.fields.Length > 0;

                        //Hierarchy Level
                        if (clearRequired && accountPayload.clearlist.fields.Contains(SCII.OrganisationClearFields.hierarchylevel))
                        {
                            AccountObject[SCS.AccountContants.HIERARCHYLEVEL] = null;
                        }
                        else if (accountPayload.updates.hierarchylevel != null)
                        {
                            localcontext.Trace("hierarchylevel level:" + accountPayload.updates.hierarchylevel);

                            if (!String.IsNullOrEmpty(Enum.GetName(typeof(SCSE.defra_OrganisationHierarchyLevel), accountPayload.updates.hierarchylevel)))
                            {
                                localcontext.Trace("before assinging value");

                                AccountObject[SCS.AccountContants.HIERARCHYLEVEL] = new OptionSetValue((int)accountPayload.updates.hierarchylevel);
                                localcontext.Trace("after assinging value");
                            }
                            else
                            {
                                _errorMessage = _errorMessage.Append(String.Format("Option set value {0} for orgnisation hirarchy level not found.",
                                                                                   accountPayload.updates.hierarchylevel));
                            }
                        }


                        if (clearRequired && accountPayload.clearlist.fields.Contains(SCII.OrganisationClearFields.crn))
                        {
                            localcontext.Trace("before clearing identifier value");
                            //AccountObject[SCS.AccountContants.COMPANY_HOUSE_ID] = null;

                            objCommon.ClearIdentifier(SCS.Identifers.COMPANYHOUSEIDENTIFIERNAME, AccountObject.Id);
                        }
                        else
                        {
                            //check if crn exists

                            if (accountPayload.updates.crn != null)
                            {
                                orgSvcContext = new OrganizationServiceContext(objCommon.service);
                                //var checkCRNExistis = from c in orgSvcContext.CreateQuery("account")
                                //                      where (string)c[SCS.AccountContants.COMPANY_HOUSE_ID] == accountPayload.updates.crn
                                //                      select new { organisationid = c.Id };

                                Guid?IdentifierId = objCommon.CheckIfSameIdenfierExists(SCS.Identifers.COMPANYHOUSEIDENTIFIERNAME, accountPayload.updates.crn, AccountObject.Id);

                                if (IdentifierId == null)
                                {
                                    //AccountObject[SCS.AccountContants.COMPANY_HOUSE_ID] = accountPayload.updates.crn;
                                    localcontext.Trace("updaing identifier in update org" + IdentifierId);
                                    objCommon.UpdateIdentifier(SCS.Identifers.COMPANYHOUSEIDENTIFIERNAME, accountPayload.updates.crn, AccountObject.Id);
                                }
                                else
                                {
                                    _errorCode = 412;
                                    throw new Exception("Company house id already exists.");
                                }
                            }
                        }
                        if (clearRequired && accountPayload.clearlist.fields.Contains(SCII.OrganisationClearFields.telephone))
                        {
                            AccountObject[SCS.AccountContants.TELEPHONE1] = null;
                        }
                        else
                        {
                            if (accountPayload.updates.telephone != null)
                            {
                                AccountObject[SCS.AccountContants.TELEPHONE1] = accountPayload.updates.telephone;
                            }
                        }
                        localcontext.Trace("after  setting other fields");
                        if (clearRequired && accountPayload.clearlist.fields.Contains(SCII.OrganisationClearFields.parentorganisationcrmid))
                        {
                            AccountObject[SCS.AccountContants.PARENTACCOUNTID] = null;
                        }
                        else
                        {
                            bool IsValidGuid;
                            Guid ParentAccountId;
                            if (!String.IsNullOrEmpty(accountPayload.updates.parentorganisationcrmid))
                            {
                                IsValidGuid = Guid.TryParse(accountPayload.updates.parentorganisationcrmid, out ParentAccountId);
                                if (IsValidGuid)
                                {
                                    var checkParentOrgExists = from c in orgSvcContext.CreateQuery(SCS.AccountContants.ENTITY_NAME)
                                                               where (string)c[SCS.AccountContants.ACCOUNTID] == accountPayload.updates.parentorganisationcrmid
                                                               select new
                                    {
                                        organisationid = c.Id
                                    };
                                    if (checkParentOrgExists.FirstOrDefault() != null)
                                    {
                                        if (existingAccountRecord.Contains(SCS.AccountContants.PARENTACCOUNTID))
                                        {
                                            localcontext.Trace("inside parent update:" + ParentAccountId);
                                            if (((EntityReference)existingAccountRecord[SCS.AccountContants.PARENTACCOUNTID]).Id.ToString() != accountPayload.updates.parentorganisationcrmid)
                                            {
                                                AccountObject[SCS.AccountContants.PARENTACCOUNTID] = new EntityReference(SCS.AccountContants.ENTITY_NAME, ParentAccountId);
                                            }
                                        }
                                        else
                                        {
                                            AccountObject[SCS.AccountContants.PARENTACCOUNTID] = new EntityReference(SCS.AccountContants.ENTITY_NAME, ParentAccountId);
                                        }
                                    }
                                    else
                                    {
                                        localcontext.Trace("throwing error becuase organisation does not exists.");
                                        throw new Exception("Parent account id does not exists.");
                                    }
                                }
                                else
                                {
                                    localcontext.Trace("throwing error becuase invalid Guid;");
                                    throw new Exception("parentorganisationcrmid is not valid guid;");
                                }
                            }
                        }
                        if (clearRequired && accountPayload.clearlist.fields.Contains(SCII.OrganisationClearFields.email))
                        {
                            AccountObject[SCS.AccountContants.EMAILADDRESS1] = null;
                        }
                        else
                        {
                            if (accountPayload.updates.email != null)
                            {
                                AccountObject[SCS.AccountContants.EMAILADDRESS1] = accountPayload.updates.email;
                            }
                        }
                        if (clearRequired && accountPayload.clearlist.fields.Contains(SCII.OrganisationClearFields.validatedwithcompanieshouse))
                        {
                            AccountObject[SCS.AccountContants.VALIDATED_WITH_COMPANYHOUSE] = null;
                        }
                        else
                        {
                            if (accountPayload.updates.validatedwithcompanieshouse != null)
                            {
                                localcontext.Trace("inside validated with companies house:" + accountPayload.updates.validatedwithcompanieshouse);
                                bool isValidCompaniesHouse = false;
                                if (Boolean.TryParse(accountPayload.updates.validatedwithcompanieshouse.ToString(), out isValidCompaniesHouse))
                                {
                                    AccountObject[SCS.AccountContants.VALIDATED_WITH_COMPANYHOUSE] = isValidCompaniesHouse;
                                }
                                else
                                {
                                    _errorMessage = _errorMessage.Append(String.Format("validated with companyhouse value {0} is not valid;",
                                                                                       accountPayload.updates.validatedwithcompanieshouse));
                                }
                            }
                        }
                        #endregion
                        localcontext.Trace("outside validated with companies house:" + accountPayload.updates.validatedwithcompanieshouse);
                        localcontext.Trace("before updating guid:" + AccountObject.Id.ToString());
                        objCommon.service.Update(AccountObject);
                        EntityReference AccountEntityReference = new EntityReference(SCS.AccountContants.ENTITY_NAME, AccountObject.Id);
                        if (clearRequired && accountPayload.clearlist.fields.Contains(SCII.OrganisationClearFields.email))
                        {
                            objCommon.UpsertContactDetails((int)SCII.EmailTypes.PrincipalEmailAddress, accountPayload.updates.email, AccountEntityReference, false, true);
                        }
                        else if (accountPayload.updates.email != null)
                        {
                            objCommon.UpsertContactDetails((int)SCII.EmailTypes.PrincipalEmailAddress, accountPayload.updates.email, AccountEntityReference, true, false);
                        }
                        //if phone is in clear list then deactivate the contact details record of principalphonenumber
                        if (clearRequired && accountPayload.clearlist.fields.Contains(SCII.OrganisationClearFields.telephone))
                        {
                            objCommon.UpsertContactDetails((int)SCII.PhoneTypes.PrincipalPhoneNumber, accountPayload.updates.telephone, AccountEntityReference, false, true);
                        }

                        else if (accountPayload.updates.telephone != null)
                        {
                            objCommon.UpsertContactDetails((int)SCII.PhoneTypes.PrincipalPhoneNumber, accountPayload.updates.telephone, AccountEntityReference, true, false);
                        }
                        localcontext.Trace("after updating guid:" + AccountObject.Id.ToString());

                        _errorCode = 200;
                    }
                    //if the organisation does not exists
                    else
                    {
                        _errorCode    = 404;
                        _errorMessage = _errorMessage.Append(String.Format("Oranisation with id {0} does not exists.",
                                                                           accountPayload.organisationid));
                    }
                }
                else
                {
                    localcontext.Trace("inside validation result");
                    _errorMessage = new StringBuilder();
                    //this will throw an error
                    foreach (ValidationResult vr in ValidationResults)
                    {
                        _errorMessage.Append(vr.ErrorMessage + " ");
                    }
                    if (ValidationResultUpdates != null)
                    {
                        foreach (ValidationResult vr in ValidationResultUpdates)
                        {
                            _errorMessage.Append(vr.ErrorMessage + " ");
                        }
                    }
                    _errorCode = 400;
                }
            }

            catch (Exception ex)
            {
                localcontext.Trace("inside exception");

                _errorCode          = 500;
                _errorMessage       = _errorMessage.Append("Error occured while processing request");
                _errorMessageDetail = ex.Message;
                localcontext.Trace(ex.Message);
            }
            finally
            {
                localcontext.Trace("finally block start");
                SCIIR.AccountResponse responsePayload = new SCIIR.AccountResponse()
                {
                    code     = _errorCode,
                    message  = _errorMessage.ToString(),
                    datetime = DateTime.UtcNow,
                    version  = "1.0.0.2",

                    status = _errorCode == 200 ? "success" : "failure",
                    data   = new SCIIR.AccountData()
                    {
                        accountid       = AccountObject.Id,
                        uniquereference = _uniqueReference,
                        error           = new SCIIR.ResponseErrorBase()
                        {
                            details = _errorMessageDetail == string.Empty ? _errorMessage.ToString() : _errorMessageDetail
                        }
                    }
                };

                string resPayload = JsonConvert.SerializeObject(responsePayload);
                ResPayload.Set(executionContext, resPayload);
                localcontext.Trace("finally block end");
            }
        }
Exemple #2
0
        protected override void Execute(CodeActivityContext context)
        {
            // Construct the Local plug-in context.
            LocalWorkflowContext localcontext = new LocalWorkflowContext(context);

            localcontext.Trace("started execution");

            #region "Load CRM Service from context"
            objCommon = new SCII.Helper(context);

            localcontext.Trace("CreateContact activity:Load CRM Service from context --- OK");
            #endregion

            #region "Create Execution"

            try
            {
                string jsonPayload = this.request.Get(context);
                SCII.UpdateContactRequest contactPayload = JsonConvert.DeserializeObject <SCII.UpdateContactRequest>(jsonPayload);
                Boolean duplicateRecordExist             = false;
                Entity  contact;
                var     ValidationContext = new ValidationContext(contactPayload, serviceProvider: null, items: null);
                ICollection <ValidationResult> ValidationResults = null;

                var isValid = objCommon.Validate(contactPayload, out ValidationResults);
                localcontext.Trace("just after validation");

                if (isValid)
                {
                    if (_errorMessage == string.Empty)
                    {
                        //search contact record based on key named B2COBJECTID
                        OrganizationServiceContext orgSvcContext = new OrganizationServiceContext(objCommon.service);
                        var ContactWithUPN = from c in orgSvcContext.CreateQuery(SCS.Contact.ENTITY)
                                             where ((Guid)c["contactid"]).Equals((contactPayload.contactid))
                                             select new { ContactId = c.Id, UniqueReference = c[SCS.Contact.UNIQUEREFERENCE] };

                        var contactRecordWithUPN = ContactWithUPN.FirstOrDefault() == null ? null : ContactWithUPN.FirstOrDefault();
                        if (contactRecordWithUPN != null)
                        {
                            _contactId       = contactRecordWithUPN.ContactId;
                            _uniqueReference = contactRecordWithUPN.UniqueReference.ToString();


                            //Search contact record based on key named emailaddress to prevent duplicates
                            localcontext.Trace("before checking for data fields");

                            if (!string.IsNullOrEmpty(contactPayload.updates.email))
                            {
                                localcontext.Trace("searching for contact ignoring current record");

                                //compare with record ignoring current record
                                var ContactWithEmail = from c in orgSvcContext.CreateQuery(SCS.Contact.ENTITY)
                                                       where ((string)c[SCS.Contact.EMAILADDRESS1]) == contactPayload.updates.email.Trim() &&
                                                       (string)c[SCS.Contact.UNIQUEREFERENCE] != _uniqueReference
                                                       select new { ContactId = c.Id, UniqueReference = c[SCS.Contact.UNIQUEREFERENCE] };
                                var contactRecordWithEmail = ContactWithEmail.FirstOrDefault() == null ? null : ContactWithEmail.FirstOrDefault();
                                duplicateRecordExist = contactRecordWithEmail == null ? false : true;
                                localcontext.Trace("duplicate check: " + duplicateRecordExist);
                            }
                            if (!duplicateRecordExist)
                            {
                                contact = new Entity(SCS.Contact.ENTITY, _contactId);
                                localcontext.Trace("update activity:ContactRecordGuidWithUPN is empty started, update ReqContact..");

                                #region Cannot be cleared
                                //Flag to check if the clearing of data is required for the selected OrganisationRequest fields



                                if (contactPayload.updates.firstname != null)
                                {
                                    contact[SCS.Contact.FIRSTNAME] = contactPayload.updates.firstname;
                                }
                                if (contactPayload.updates.lastname != null)
                                {
                                    contact[SCS.Contact.LASTNAME] = contactPayload.updates.lastname;
                                }
                                if (contactPayload.updates.email != null)
                                {
                                    contact[SCS.Contact.EMAILADDRESS1] = contactPayload.updates.email;
                                }
                                if (contactPayload.updates.tacsacceptedversion != null)
                                {
                                    contact[SCS.Contact.TACSACCEPTEDVERSION] = contactPayload.updates.tacsacceptedversion;
                                }

                                if (!string.IsNullOrEmpty(contactPayload.updates.tacsacceptedon) && !string.IsNullOrWhiteSpace(contactPayload.updates.tacsacceptedon))
                                {
                                    localcontext.Trace("date accepted on in string" + contactPayload.updates.tacsacceptedon);
                                    DateTime resultDate;
                                    if (DateTime.TryParse(contactPayload.updates.tacsacceptedon, out resultDate))
                                    {
                                        localcontext.Trace("date accepted on in dateformat" + resultDate);
                                        contact[SCS.Contact.TACSACCEPTEDON] = (resultDate);
                                    }
                                }

                                #endregion


                                #region These fields can be cleared
                                bool clearRequired = contactPayload.clearlist != null &&
                                                     contactPayload.clearlist.fields != null &&
                                                     contactPayload.clearlist.fields.Length > 0;

                                localcontext.Trace(String.Format("printing clear required value: {0}", clearRequired));
                                localcontext.Trace(String.Format("title value: {0}", contactPayload.updates.title.HasValue));

                                if (clearRequired && contactPayload.clearlist.fields.Contains(SCII.ContactClearFields.title))
                                {
                                    contact[SCS.Contact.TITLE] = null;
                                }
                                else if (contactPayload.updates.title.HasValue && !String.IsNullOrEmpty(Enum.GetName(typeof(SCSE.defra_Title), contactPayload.updates.title)))
                                {
                                    contact[SCS.Contact.TITLE] = new OptionSetValue(contactPayload.updates.title.Value);
                                    localcontext.Trace("assigning title");
                                }
                                localcontext.Trace("setting contact date params:started..");

                                if (clearRequired && contactPayload.clearlist.fields.Contains(SCII.ContactClearFields.middlename))
                                {
                                    contact[SCS.Contact.MIDDLENAME] = null;
                                }

                                else if (contactPayload.updates.middlename != null)
                                {
                                    contact[SCS.Contact.MIDDLENAME] = contactPayload.updates.middlename;
                                }

                                if (clearRequired && contactPayload.clearlist.fields.Contains(SCII.ContactClearFields.telephone1))
                                {
                                    contact[SCS.Contact.TELEPHONE1] = null;
                                }
                                else if (contactPayload.updates.telephone != null)
                                {
                                    contact[SCS.Contact.TELEPHONE1] = contactPayload.updates.telephone;
                                }


                                //set birthdate

                                if (clearRequired && contactPayload.clearlist.fields.Contains(SCII.ContactClearFields.dob))
                                {
                                    contact[SCS.Contact.GENDERCODE] = null;
                                }
                                else if (!string.IsNullOrEmpty(contactPayload.updates.dob) && !string.IsNullOrWhiteSpace(contactPayload.updates.dob))
                                {
                                    DateTime resultDob;
                                    if (DateTime.TryParse(contactPayload.updates.dob, out resultDob))
                                    {
                                        contact[SCS.Contact.BIRTHDATE] = resultDob;
                                    }
                                }

                                if (clearRequired && contactPayload.clearlist.fields.Contains(SCII.ContactClearFields.dob))
                                {
                                    contact[SCS.Contact.GENDERCODE] = null;
                                }
                                else if (contactPayload.updates.gender.HasValue && !String.IsNullOrEmpty(Enum.GetName(typeof(SCSE.Contact_GenderCode), contactPayload.updates.gender)))
                                {
                                    //Check whether the gendercode is found in GenderEnum mapping
                                    if (Enum.IsDefined(typeof(SCII.ContactGenderCodes), contactPayload.updates.gender))
                                    {
                                        //Check whether gendercode is found in Dynamics GenderEnum mapping
                                        string genderCode = Enum.GetName(typeof(SCSE.Contact_GenderCode), contactPayload.updates.gender);
                                        {
                                            SCSE.Contact_GenderCode dynamicsGenderCode = (SCSE.Contact_GenderCode)Enum.Parse(typeof(SCSE.Contact_GenderCode), genderCode);
                                            contact[SCS.Contact.GENDERCODE] = new OptionSetValue((int)dynamicsGenderCode);
                                        }
                                    }
                                    #endregion
                                }
                                localcontext.Trace("contactid: " + _contactId);
                                objCommon.service.Update(contact);
                                if (contactPayload.updates.email != null)
                                {
                                    localcontext.Trace("before memail upsert");
                                    objCommon.UpsertContactDetails((int)SCII.EmailTypes.PrincipalEmailAddress, contactPayload.updates.email, new EntityReference(D365.Common.schema.Contact.ENTITY, _contactId), true, false);
                                    localcontext.Trace("after email upsert");
                                }
                                //if phone is in clear list then deactivate the contact details record of principalphonenumber
                                if (clearRequired && contactPayload.clearlist.fields.Contains(SCII.ContactClearFields.telephone1))
                                {
                                    localcontext.Trace("clear telephone1");

                                    objCommon.UpsertContactDetails((int)SCII.PhoneTypes.PrincipalPhoneNumber, contactPayload.updates.telephone, new EntityReference(D365.Common.schema.Contact.ENTITY, _contactId), false, true);
                                    localcontext.Trace("after clear telephone1");
                                }

                                else if (contactPayload.updates.telephone != null)
                                {
                                    localcontext.Trace("before  telephone1 update");
                                    objCommon.UpsertContactDetails((int)SCII.PhoneTypes.PrincipalPhoneNumber, contactPayload.updates.telephone, new EntityReference(D365.Common.schema.Contact.ENTITY, _contactId), true, false);
                                    localcontext.Trace("after  telephone1 update");
                                }
                                _errorCode = 200;//Success
                                localcontext.Trace("CreateContact activity:ended. " + _contactId.ToString());
                            }
                            else
                            {
                                localcontext.Trace("CreateContact activity:ContactRecordGuidWithB2C/Email is found/duplicate.");
                                _errorCode    = 412;//Duplicate UPN
                                _errorMessage = "Duplicate Record";
                            }
                        }
                        else
                        {
                            {
                                localcontext.Trace("record does not exists");
                                _errorCode    = 404;//record does not exists
                                _errorMessage = "record does not exists.";
                            }
                        }
                    }
                }
                else
                {
                    localcontext.Trace("inside validation result");


                    StringBuilder ErrorMessage = new StringBuilder();
                    //this will throw an error
                    foreach (ValidationResult vr in ValidationResults)
                    {
                        ErrorMessage.Append(vr.ErrorMessage + " ");
                    }
                    //if (contactPayload.updates.address != null)
                    //    foreach (ValidationResult vr in ValidationResultsAddress)
                    //    {
                    //        ErrorMessage.Append(vr.ErrorMessage + " ");
                    //    }
                    _errorCode    = 400;
                    _errorMessage = ErrorMessage.ToString();
                }
                localcontext.Trace("CreateContact activity:setting output params like error code etc.. started");
                localcontext.Trace("CreateContact activity:setting output params like error code etc.. ended");
            }
            catch (Exception ex)
            {
                _errorCode          = 500;//Internal Error
                _errorMessage       = "Error occured while processing request";
                _errorMessageDetail = ex.Message;
                localcontext.Trace(ex.Message);
                //throw ex;
            }
            finally
            {
                localcontext.Trace("finally block start");
                SCIIR.ContactResponse responsePayload = new SCIIR.ContactResponse()
                {
                    code     = _errorCode,
                    message  = _errorMessage,
                    datetime = DateTime.UtcNow,
                    version  = "1.0.0.2",
                    program  = "UpdateContact",
                    status   = _errorCode == 200 || _errorCode == 412 ? "success" : "failure",
                    data     = new SCIIR.ContactData()
                    {
                        contactid       = _contactId == Guid.Empty ? null : _contactId.ToString(),
                        uniquereference = _uniqueReference == string.Empty ? null : _uniqueReference,
                        error           = new SCIIR.ResponseErrorBase()
                        {
                            details = _errorMessageDetail == string.Empty ? _errorMessage : _errorMessageDetail
                        }
                    }
                };

                string resPayload = JsonConvert.SerializeObject(responsePayload);
                response.Set(context, resPayload);
                localcontext.Trace("finally block end");
            }

            #endregion
            ExecuteCRMWorkFlowActivity(context, localcontext);
        }
Exemple #3
0
        public override void ExecuteCRMWorkFlowActivity(CodeActivityContext executionContext, LocalWorkflowContext crmWorkflowContext)
        {
            #region Local Properties
            SCII.Helper objCommon;
            //EntityReference _Contact;
            int    _errorCode          = 400; //Bad Request
            string _errorMessage       = string.Empty;
            string _errorMessageDetail = string.Empty;
            Guid   _contactId          = Guid.Empty;
            string _uniqueReference    = string.Empty;

            #endregion

            #region "Create Execution"
            objCommon = new SCII.Helper(executionContext);

            try
            {
                objCommon.tracingService.Trace("CreateContact activity:Load CRM Service from context --- OK");
                string jsonPayload = Payload.Get(executionContext);
                SCII.ContactRequest contactPayload = JsonConvert.DeserializeObject <SCII.ContactRequest>(jsonPayload);

                Entity contact = new Entity(SCS.Contact.ENTITY);//,"defra_upn", _UPN);

                _errorMessage = FieldValidation(contactPayload);
                var ValidationContext = new ValidationContext(contactPayload, serviceProvider: null, items: null);

                ICollection <ValidationResult> ValidationResults        = null;
                ICollection <ValidationResult> ValidationResultsAddress = null;

                var isValid = objCommon.Validate(contactPayload, out ValidationResults);


                Boolean isValidAddress = contactPayload.address == null ? true :

                                         objCommon.Validate(contactPayload.address, out ValidationResultsAddress);

                objCommon.tracingService.Trace("just after validation");

                if (isValid && isValidAddress)
                {
                    if (_errorMessage == string.Empty)
                    {
                        //search contact record based on key named B2COBJECTID to prevent duplicate contact
                        OrganizationServiceContext orgSvcContext = new OrganizationServiceContext(objCommon.service);
                        var ContactWithUPN = from c in orgSvcContext.CreateQuery(SCS.Contact.ENTITY)
                                             where ((string)c[SCS.Contact.B2COBJECTID]).Equals((contactPayload.b2cobjectid.Trim()))
                                             select new { ContactId = c.Id, UniqueReference = c[SCS.Contact.UNIQUEREFERENCE] };

                        var contactRecordWithUPN = ContactWithUPN.FirstOrDefault() == null ? null : ContactWithUPN.FirstOrDefault();
                        if (contactRecordWithUPN != null)
                        {
                            _contactId       = contactRecordWithUPN.ContactId;
                            _uniqueReference = contactRecordWithUPN.UniqueReference.ToString();
                        }

                        //Search contact record based on key named emailaddress to prevent duplicates
                        if (!string.IsNullOrEmpty(contactPayload.email))
                        {
                            var ContactWithEmail = from c in orgSvcContext.CreateQuery(SCS.Contact.ENTITY)
                                                   where ((string)c[SCS.Contact.EMAILADDRESS1]).Equals((contactPayload.email.Trim()))
                                                   select new { ContactId = c.Id, UniqueReference = c[SCS.Contact.UNIQUEREFERENCE] };

                            var contactRecordWithEmail = ContactWithEmail.FirstOrDefault() == null ? null : ContactWithEmail.FirstOrDefault();
                            if (contactRecordWithEmail != null)
                            {
                                _contactId       = contactRecordWithEmail.ContactId;
                                _uniqueReference = contactRecordWithEmail.UniqueReference.ToString();
                            }
                        }
                        if (_contactId == Guid.Empty)
                        {
                            objCommon.tracingService.Trace("CreateContact activity:ContactRecordGuidWithUPN is empty started, Creating ReqContact..");
                            if (contactPayload.title != null)
                            {
                                contact[SCS.Contact.TITLE] = new OptionSetValue((int)contactPayload.title);
                            }

                            if (contactPayload.firstname != null)
                            {
                                contact[SCS.Contact.FIRSTNAME] = contactPayload.firstname;
                            }
                            if (contactPayload.lastname != null)
                            {
                                contact[SCS.Contact.LASTNAME] = contactPayload.lastname;
                            }
                            if (contactPayload.middlename != null)
                            {
                                contact[SCS.Contact.MIDDLENAME] = contactPayload.middlename;
                            }
                            if (contactPayload.email != null)
                            {
                                contact[SCS.Contact.EMAILADDRESS1] = contactPayload.email;
                            }


                            if (contactPayload.b2cobjectid != null)
                            {
                                contact[SCS.Contact.B2COBJECTID] = contactPayload.b2cobjectid;
                            }
                            if (contactPayload.tacsacceptedversion != null)
                            {
                                contact[SCS.Contact.TACSACCEPTEDVERSION] = contactPayload.tacsacceptedversion;
                            }
                            if (contactPayload.telephone != null)
                            {
                                contact[SCS.Contact.TELEPHONE1] = contactPayload.telephone;
                            }

                            objCommon.tracingService.Trace("setting contact date params:started..");

                            //set tcsaccepteddate
                            if (!string.IsNullOrEmpty(contactPayload.tacsacceptedon) && !string.IsNullOrWhiteSpace(contactPayload.tacsacceptedon))
                            {
                                objCommon.tracingService.Trace("date accepted on in string" + contactPayload.tacsacceptedon);
                                DateTime resultDate;
                                if (DateTime.TryParseExact(contactPayload.tacsacceptedon, "dd/MM/yyyy HH:mm tt", new CultureInfo("en-Uk"), DateTimeStyles.None, out resultDate))
                                {
                                    objCommon.tracingService.Trace("date accepted on in dateformat" + resultDate);
                                    contact[SCS.Contact.TACSACCEPTEDON] = (resultDate);
                                }
                            }
                            //else if (contactPayload.tacsacceptedversion != null)
                            //{
                            //    contact[SCS.Contact.TACSACCEPTEDON] = DateTime.Now;
                            //}

                            //set birthdate
                            if (!string.IsNullOrEmpty(contactPayload.dob) && !string.IsNullOrWhiteSpace(contactPayload.dob))
                            {
                                DateTime resultDob;
                                if (DateTime.TryParseExact(contactPayload.dob, "dd/MM/yyyy", new CultureInfo("en-Uk"), DateTimeStyles.None, out resultDob))
                                {
                                    contact[SCS.Contact.BIRTHDATE] = resultDob;
                                }
                            }

                            if (contactPayload.gender != null)
                            {
                                contact[SCS.Contact.GENDERCODE] = new OptionSetValue((int)contactPayload.gender);
                            }

                            objCommon.tracingService.Trace("CreateContact activity:started..");
                            _contactId = objCommon.service.Create(contact);

                            //create contactdetail record for primary contact details
                            if (contactPayload.email != null)
                            {
                                objCommon.UpsertContactDetails((int)SCII.EmailTypes.PrincipalEmailAddress, contactPayload.email, new EntityReference(D365.Common.schema.Contact.ENTITY, _contactId), false, false);
                            }
                            if (contactPayload.telephone != null)
                            {
                                objCommon.UpsertContactDetails((int)SCII.PhoneTypes.PrincipalPhoneNumber, contactPayload.telephone, new EntityReference(D365.Common.schema.Contact.ENTITY, _contactId), false, false);
                            }
                            Entity contactRecord = objCommon.service.Retrieve(SCS.Contact.ENTITY, _contactId, new Microsoft.Xrm.Sdk.Query.ColumnSet(true));//Defra.CustMaster.D365.Common.schema.ReqContact.UNIQUEREFERENCE));
                            objCommon.tracingService.Trace((string)contactRecord[SCS.Contact.UNIQUEREFERENCE]);
                            _uniqueReference = (string)contactRecord[SCS.Contact.UNIQUEREFERENCE];
                            _errorCode       = 200;//Success
                            objCommon.tracingService.Trace("CreateContact activity:ended. " + _contactId.ToString());

                            //create contact address and contact details
                            if (contactPayload.address != null)
                            {
                                objCommon.CreateAddress(contactPayload.address, new EntityReference(D365.Common.schema.Contact.ENTITY, _contactId));
                            }
                        }
                        else
                        {
                            objCommon.tracingService.Trace("CreateContact activity:ContactRecordGuidWithB2C/Email is found/duplicate.");
                            _errorCode    = 412;//Duplicate UPN
                            _errorMessage = "Duplicate Record";
                        }
                    }
                }
                else
                {
                    objCommon.tracingService.Trace("inside validation result");


                    StringBuilder ErrorMessage = new StringBuilder();
                    //this will throw an error
                    foreach (ValidationResult vr in ValidationResults)
                    {
                        ErrorMessage.Append(vr.ErrorMessage + " ");
                    }
                    if (contactPayload.address != null)
                    {
                        foreach (ValidationResult vr in ValidationResultsAddress)
                        {
                            ErrorMessage.Append(vr.ErrorMessage + " ");
                        }
                    }
                    _errorCode    = 400;
                    _errorMessage = ErrorMessage.ToString();
                }
                objCommon.tracingService.Trace("CreateContact activity:setting output params like error code etc.. started");
                objCommon.tracingService.Trace("CreateContact activity:setting output params like error code etc.. ended");
            }
            catch (Exception ex)
            {
                _errorCode          = 500;//Internal Error
                _errorMessage       = "Error occured while processing request";
                _errorMessageDetail = ex.Message;
                objCommon.tracingService.Trace(ex.Message);
                //throw ex;
            }
            finally
            {
                objCommon.tracingService.Trace("finally block start");
                SCIIR.ContactResponse responsePayload = new SCIIR.ContactResponse()
                {
                    code     = _errorCode,
                    message  = _errorMessage,
                    datetime = DateTime.UtcNow,
                    version  = "1.0.0.2",
                    program  = "CreateContact",
                    status   = _errorCode == 200 || _errorCode == 412 ? "success" : "failure",
                    data     = new SCIIR.ContactData()
                    {
                        contactid       = _contactId == Guid.Empty ? null : _contactId.ToString(),
                        uniquereference = _uniqueReference == string.Empty ? null : _uniqueReference,
                        error           = new SCIIR.ResponseErrorBase()
                        {
                            details = _errorMessageDetail == string.Empty ? _errorMessage : _errorMessageDetail
                        }
                    }
                };

                string resPayload = JsonConvert.SerializeObject(responsePayload);
                Response.Set(executionContext, resPayload);
                objCommon.tracingService.Trace("finally block end");
            }
            #endregion
        }
Exemple #4
0
        protected override void Execute(CodeActivityContext executionContext)
        {
            #region local variables
            SCII.Helper objCommon;

            // EntityReference _Contact;
            int           errorCode             = 400; // Bad Request
            string        errorMessageDetail    = string.Empty;
            Guid          customerId            = Guid.Empty;
            Entity        existingAccountRecord = new Entity();
            StringBuilder errorMessage          = new StringBuilder();
            bool          isRecordIdExists      = false;
            AddressData   createdAddress        = new AddressData()
            {
                addressid = Guid.Empty, contactdetailsid = Guid.Empty
            };
            #endregion
            LocalWorkflowContext localcontext = new LocalWorkflowContext(executionContext);
            objCommon = new SCII.Helper(executionContext);
            try
            {
                localcontext.Trace("started execution");
                localcontext.Trace("attempt to seriallised");

                string jsonPayload = ReqPayload.Get(executionContext);
                SCII.AddressRequest addressPayload = JsonConvert.DeserializeObject <SCII.AddressRequest>(jsonPayload);
                if (addressPayload.address == null)
                {
                    errorMessage = errorMessage.Append("Address can not be empty");
                }
                else
                {
                    objCommon = new SCII.Helper(executionContext);
                    ValidationContext validationContext = new ValidationContext(addressPayload, serviceProvider: null, items: null);
                    ICollection <ValidationResult> validationResults        = null;
                    ICollection <ValidationResult> validationResultsAddress = null;

                    bool isValid        = objCommon.Validate(addressPayload, out validationResults);
                    bool isValidAddress = objCommon.Validate(addressPayload.address, out validationResultsAddress);

                    localcontext.Trace("TRACE TO valid:" + isValid);
                    string customerEntity   = addressPayload.recordtype == SCII.RecordType.contact ? SCS.Contact.ENTITY : SCS.AccountContants.ENTITY_NAME;
                    string customerEntityId = addressPayload.recordtype == SCII.RecordType.contact ? SCS.Contact.CONTACTID : SCS.AccountContants.ACCOUNTID;

                    // check for building name, it should be mandatory only if the building number is empty
                    if (string.IsNullOrEmpty(addressPayload.address.buildingname))
                    {
                        if (string.IsNullOrEmpty(addressPayload.address.buildingnumber))
                        {
                            errorMessage.Append("Provide either building name or building number, Building name is mandatory if the building number is empty;");
                        }
                    }

                    // check for postcode lengths, it should be 8 for UK and 25 for NON-UK
                    if (isValidAddress && isValid)
                    {
                        if (addressPayload.address.country.Trim().ToUpper() == "GBR")
                        {
                            if (addressPayload.address.postcode.Length > 8)
                            {
                                errorMessage.Append("postcode length can not be greater than 8 for UK countries;");
                            }
                        }
                        else
                        {
                            if (addressPayload.address.postcode.Length > 25)
                            {
                                errorMessage.Append("postcode length can not be greater than 25 for NON-UK countries;");
                            }
                        }

                        if (addressPayload.address.type != null)
                        {
                            if (!Enum.IsDefined(typeof(SCII.AddressTypes), addressPayload.address.type))
                            {
                                errorMessage.Append("Option set value for address of type not found;" + addressPayload.address.type);
                            }
                        }

                        if (errorMessage.Length == 0)
                        {
                            // check recordid exists
                            if (!string.IsNullOrEmpty(addressPayload.recordid) && !string.IsNullOrWhiteSpace(addressPayload.recordid))
                            {
                                if (Guid.TryParse(addressPayload.recordid, out customerId))
                                {
                                    localcontext.Trace("record id:" + customerEntity + ":" + customerId);
                                    OrganizationServiceContext orgSvcContext = new OrganizationServiceContext(objCommon.service);
                                    var checkRecordExists = from c in orgSvcContext.CreateQuery(customerEntity)
                                                            where (Guid)c[customerEntityId] == customerId
                                                            select new { recordId = c.Id };
                                    if (checkRecordExists != null && checkRecordExists.FirstOrDefault() != null)
                                    {
                                        customerId       = checkRecordExists.FirstOrDefault().recordId;
                                        isRecordIdExists = true;
                                    }
                                }
                            }

                            // if record exists then go on to add address
                            if (isRecordIdExists)
                            {
                                localcontext.Trace("length:" + addressPayload.recordid);
                                EntityReference customer = new EntityReference(customerEntity, customerId);
                                if (addressPayload.address != null)
                                {
                                    createdAddress = objCommon.CreateAddress(addressPayload.address, customer);
                                }

                                localcontext.Trace("after adding address:");
                                errorCode = 200;
                            }

                            // if the organisation does not exists
                            else
                            {
                                errorCode    = 404;
                                errorMessage = errorMessage.Append(string.Format("recordid with id {0} does not exists.", addressPayload.recordid));
                            }
                        }
                    }
                    else
                    {
                        localcontext.Trace("inside validation result");

                        // _errorMessage = new StringBuilder();

                        // this will throw an error
                        foreach (ValidationResult vr in validationResults)
                        {
                            errorMessage.Append(vr.ErrorMessage + " ");
                        }

                        foreach (ValidationResult vr in validationResultsAddress)
                        {
                            errorMessage.Append(vr.ErrorMessage + " ");
                        }

                        errorCode = 400;
                    }
                }
            }
            catch (Exception ex)
            {
                localcontext.Trace("inside exception");
                errorCode          = 500;
                errorMessage       = errorMessage.Append(" Error occured while processing request");
                errorMessageDetail = ex.Message;
                if (ex.Message.Contains("Contact details of same type already exist for this customer"))
                {
                    errorCode = 412;
                }
                localcontext.Trace(ex.Message);
            }
            finally
            {
                localcontext.Trace("finally block start");
                AddressResponse responsePayload = new AddressResponse()
                {
                    code     = errorCode,
                    message  = errorMessage.ToString(),
                    datetime = DateTime.UtcNow,
                    version  = "1.0.0.2",

                    status = errorCode == 200 ? "success" : "failure",
                    data   = new AddressData()
                    {
                        contactdetailsid = createdAddress.contactdetailsid,
                        addressid        = createdAddress.addressid,
                        error            = new SCIIR.ResponseErrorBase()
                        {
                            details = errorMessageDetail == string.Empty ? errorMessage.ToString() : errorMessageDetail
                        }
                    }
                };

                string resPayload = JsonConvert.SerializeObject(responsePayload);
                ResPayload.Set(executionContext, resPayload);
                localcontext.Trace("finally block end");
            }
        }
        public override void ExecuteCRMWorkFlowActivity(CodeActivityContext executionContext, LocalWorkflowContext crmWorkflowContext)
        {
            localcontext = crmWorkflowContext;
            String        PayloadDetails      = request.Get(executionContext);
            int           ErrorCode           = 400; //400 -- bad request
            int           RoleCountToCheck    = 0;
            String        _ErrorMessage       = string.Empty;
            String        _ErrorMessageDetail = string.Empty;
            Guid          ContactId           = Guid.Empty;
            Guid          AccountId           = Guid.Empty;
            StringBuilder ErrorMessage        = new StringBuilder();
            String        UniqueReference     = string.Empty;
            Guid?         ToConnectId         = Guid.Empty;
            Guid?         ConnectionDetailsId = Guid.Empty;

            SCII.Helper objCommon = new SCII.Helper(executionContext);
            try
            {
                localcontext.Trace("before seriallising1");
                SCII.CreateRelationshipRequest ConnectContact = JsonConvert.DeserializeObject <SCII.CreateRelationshipRequest>(PayloadDetails);
                localcontext.Trace("after seriallising");

                EntityReference FromEntityContact = null;
                EntityReference ToEntityAccount;

                var ValidationContext = new ValidationContext(ConnectContact, serviceProvider: null, items: null);
                ICollection <ValidationResult> ValidationResultsConnectContact = null;
                ICollection <ValidationResult> ValidationResultsRoles          = null;
                localcontext.Trace("before validating");

                Boolean isValid      = objCommon.Validate(ConnectContact, out ValidationResultsConnectContact);
                Boolean isValidRoles = objCommon.Validate(ConnectContact.relations, out ValidationResultsRoles);


                string FromEntityName = ConnectContact.fromrecordtype == SCII.RecordTypeName.contact ? SCS.Contact.ENTITY : SCS.AccountContants.ENTITY_NAME;
                string ToEntityName   = ConnectContact.torecordtype == SCII.RecordTypeName.contact ? SCS.Contact.ENTITY : SCS.AccountContants.ENTITY_NAME;

                if (isValid && isValidRoles)
                {
                    //get role ids
                    localcontext.Trace("inside valid schema");

                    localcontext.Trace(string.Format("contact id {0} org id {1}.", ConnectContact.fromrecordid, ConnectContact.torecordid));

                    #region Validate record exists
                    //check if account record exists
                    Boolean ContactExists = false;
                    if (!String.IsNullOrEmpty(ConnectContact.fromrecordid))
                    {
                        FromEntityContact = new EntityReference(FromEntityName, Guid.Parse(ConnectContact.fromrecordid));
                        ContactExists     = CheckIfRecordExists(FromEntityContact);
                    }
                    ToEntityAccount = new EntityReference(ToEntityName, Guid.Parse(ConnectContact.torecordid));
                    localcontext.Trace("before validating details new");

                    Boolean AccountExists = CheckIfRecordExists(ToEntityAccount);
                    localcontext.Trace("after validating");

                    if (ContactExists && AccountExists)
                    {
                        #region Getting connection role IDs

                        List <String> RoleNames = new List <string>();
                        if (ConnectContact.relations.fromrole != null)
                        {
                            RoleNames.Add(ConnectContact.relations.fromrole);
                            RoleCountToCheck = RoleCountToCheck + 1;
                        }
                        if (ConnectContact.relations.torole != null)
                        {
                            RoleNames.Add(ConnectContact.relations.torole);
                            RoleCountToCheck = RoleCountToCheck + 1;
                        }
                        RoleNames.Add(SCS.Connection.PRIMARYUSERROLENAME);
                        localcontext.Trace("before getting role name");

                        List <Entity> RolesList = GetRoles(RoleNames);
                        localcontext.Trace("after getting role name");

                        EntityReference FromEntityRole  = null;
                        EntityReference ToEntityRole    = null;
                        EntityReference PrimaryUserRole = null;

                        foreach (Entity ConnectionRoles in RolesList)
                        {
                            if (ConnectContact.relations.fromrole == (string)ConnectionRoles[SCS.Connection.NAME])
                            {
                                localcontext.Trace("received from role id");
                                FromEntityRole = new EntityReference(ConnectionRoles.LogicalName, ConnectionRoles.Id);
                            }

                            if (ConnectContact.relations.torole == (string)ConnectionRoles[SCS.Connection.NAME])
                            {
                                localcontext.Trace("received to role id");
                                ToEntityRole = new EntityReference(ConnectionRoles.LogicalName, ConnectionRoles.Id);
                            }

                            if (SCS.Connection.PRIMARYUSERROLENAME == (string)ConnectionRoles[SCS.Connection.NAME])
                            {
                                localcontext.Trace("received to primary role id");
                                PrimaryUserRole = new EntityReference(ConnectionRoles.LogicalName, ConnectionRoles.Id);
                            }
                        }

                        if (!String.IsNullOrEmpty(ConnectContact.relations.fromrole) && FromEntityRole == null)
                        {
                            //from role not found
                            ErrorCode     = 404;
                            _ErrorMessage = String.Format("From role {0} not found.", ConnectContact.relations.fromrole);
                        }

                        if (ToEntityRole == null)
                        {
                            //to role not found
                            ErrorCode     = 404;
                            _ErrorMessage = String.Format("To role {0} not found.", ConnectContact.relations.torole);
                        }

                        if (PrimaryUserRole == null)
                        {
                            //primary role not found
                            ErrorCode     = 404;
                            _ErrorMessage = String.Format("Primary rolenot found.");
                        }

                        #endregion

                        localcontext.Trace("after performing common chencks");
                        localcontext.Trace("error" + _ErrorMessage);
                        localcontext.Trace("roles count" + RoleCountToCheck);

                        Guid?ToEntityRoleID = ToEntityRole == null ? Guid.Empty : ToEntityRole.Id;

                        if (_ErrorMessage == string.Empty)
                        {
                            if (FromEntityRole != null && ToEntityRole != null)
                            {
                                localcontext.Trace("case when both role ids present");

                                // check if reverse connection exists
                                if (CheckIfReverseConnectionRoleExists(FromEntityRole, ToEntityRole))
                                {
                                    localcontext.Trace("checking for reverse connection");
                                    if (IsSameConnectionExists(FromEntityContact, ToEntityAccount, FromEntityRole.Id
                                                               , ToEntityRole.Id))
                                    {
                                        //connection already exists
                                        ErrorCode     = 412;
                                        _ErrorMessage = "Connection already exists";
                                    }

                                    else
                                    {
                                        //check if there is any other contact as a primary user for the same account
                                        localcontext.Trace("before primary check");
                                        if (!CheckifSingleRoleAlreadyExists(ToEntityAccount, PrimaryUserRole.Id))
                                        {
                                            //create primary connection
                                            localcontext.Trace("before creating primary connection");
                                            CreateSingleConnection(FromEntityContact, ToEntityAccount, PrimaryUserRole.Id);
                                        }

                                        if (FromEntityRole != null && ToEntityRoleID != null)
                                        {
                                            ToConnectId = CreateDoubleConnection(FromEntityContact, ToEntityAccount, FromEntityRole.Id, ToEntityRole.Id);
                                        }
                                        else if (FromEntityRole == null && ToEntityRole != null)
                                        {
                                            ToConnectId = CreateSingleConnection(FromEntityContact, ToEntityAccount, ToEntityRole.Id);
                                        }
                                        else if (FromEntityRole != null && ToEntityRole == null)
                                        {
                                            ToConnectId = CreateSingleConnection(FromEntityContact, ToEntityAccount, FromEntityRole.Id);
                                        }
                                        ErrorCode = 200;
                                    }
                                }
                                else
                                {
                                    _ErrorMessage = String.Format("From role {0} and reverse role {1} combination doesn't exists.",
                                                                  ConnectContact.relations.fromrole, ConnectContact.relations.torole);
                                }
                            }

                            else
                            {
                                //single conneciton
                                localcontext.Trace("checking if single connection exists");

                                if (CheckifSingleRoleAlreadyExists(ToEntityAccount, ToEntityRole.Id))

                                {
                                    //connection already
                                    ErrorCode     = 412;
                                    _ErrorMessage = "Connection already exists";
                                }

                                else
                                {
                                    //check if there are any other contact as a primary user for the same account

                                    if (!CheckifSingleRoleAlreadyExists(ToEntityAccount, PrimaryUserRole.Id))
                                    {
                                        //create primary connection
                                        CreateSingleConnection(FromEntityContact, ToEntityAccount, PrimaryUserRole.Id);
                                    }

                                    ToConnectId = CreateSingleConnection(FromEntityContact, ToEntityAccount, ToEntityRole.Id);
                                    ErrorCode   = 200;
                                }
                            }
                        }

                        #endregion
                    }

                    {
                        if (!ContactExists & !AccountExists)
                        {
                            ErrorCode     = 404;
                            _ErrorMessage = String.Format(@"Contact id {0} does not exists
                                and Account id{1} does not exists", ConnectContact.fromrecordid, ConnectContact.torecordid);
                        }
                        else
                        if (!ContactExists)
                        {
                            ErrorCode     = 404;
                            _ErrorMessage = String.Format("Contact id {0} does not exists", ConnectContact.fromrecordid);
                        }
                        else if (!AccountExists)
                        {
                            ErrorCode     = 404;
                            _ErrorMessage = String.Format("Account id {0} does not exists", ConnectContact.torecordid);
                        }
                    }
                }

                else
                {
                    localcontext.Trace("inside validation result");


                    //this will throw an error
                    foreach (ValidationResult vr in ValidationResultsConnectContact)
                    {
                        ErrorMessage.Append(vr.ErrorMessage + " ");
                    }
                    if (ConnectContact.relations != null)
                    {
                        foreach (ValidationResult vr in ValidationResultsRoles)
                        {
                            ErrorMessage.Append(vr.ErrorMessage + " ");
                        }
                    }
                    ErrorCode     = 400;
                    _ErrorMessage = ErrorMessage.ToString();
                }
            }

            #region Catch Exception
            catch (Exception ex)
            {
                crmWorkflowContext.Trace("inside catch");
                crmWorkflowContext.Trace("exception message: " + ex.Message);

                ErrorCode           = 500;
                _ErrorMessage       = ex.Message;
                _ErrorMessageDetail = ex.Message;
                // crmWorkflowContext.Trace(String.Format("message details {0}", ex.Message));
                //_ErrorMessageDetail = ex.Message ;
                ErrorCode = 400;
                this.response.Set(executionContext, _ErrorMessageDetail);
                //throw ex;
            }
            #endregion

            #region Finally Block
            finally
            {
                if (ToConnectId.HasValue && !ToConnectId.Value.Equals(Guid.Empty))
                {
                    localcontext.Trace("started retreiving connection detailsid");
                    Entity          connectionEntity  = localcontext.OrganizationService.Retrieve(SCS.Connection.CONNECTIONENTITY, new Guid(ToConnectId.ToString()), new ColumnSet("defra_connectiondetailsid"));
                    EntityReference connectionDetails = (EntityReference)connectionEntity.Attributes["defra_connectiondetailsid"];
                    ConnectionDetailsId = connectionDetails.Id;
                    localcontext.Trace("started retreiving connection detailsid:" + ConnectionDetailsId);
                }

                SCIIR.ConnectContactResponse responsePayload = new SCIIR.ConnectContactResponse()
                {
                    code     = ErrorCode,
                    message  = _ErrorMessage,
                    datetime = DateTime.UtcNow,
                    version  = "1.0.0.2",
                    program  = "Create relatioship",
                    status   = ErrorCode == 200 || ErrorCode == 412 ? "success" : "failure",
                    data     = new SCIIR.ConnectContactData()
                    {
                        connectionid        = ToConnectId.HasValue ? ToConnectId.Value.ToString() : string.Empty,
                        connectiondetailsid = ConnectionDetailsId.HasValue ? ConnectionDetailsId.Value.ToString() : string.Empty
                    }
                };

                string resPayload = JsonConvert.SerializeObject(responsePayload);
                response.Set(executionContext, resPayload);
                localcontext.Trace("finally block end");
            }
            #endregion
        }
Exemple #6
0
        public override void ExecuteCRMWorkFlowActivity(CodeActivityContext executionContext, LocalWorkflowContext crmWorkflowContext)
        {
            String        PayloadDetails = PayLoad.Get(executionContext);
            int?          optionSetValue;
            int           ErrorCode           = 400; //400 -- bad request
            String        _ErrorMessage       = string.Empty;
            String        _ErrorMessageDetail = string.Empty;
            Guid          ContactId           = Guid.Empty;
            Guid          CrmGuid             = Guid.Empty;
            StringBuilder ErrorMessage        = new StringBuilder();
            String        UniqueReference     = string.Empty;

            try
            {
                objCommon = new IdmNs.Helper(executionContext);
                objCommon.tracingService.Trace("Load CRM Service from context --- OK");
                Entity AccountObject = new Entity(Defra.CustMaster.D365.Common.schema.AccountContants.ENTITY_NAME);

                objCommon.tracingService.Trace("attempt to seriallised new");
                IdmNs.Organisation AccountPayload = JsonConvert.DeserializeObject <IdmNs.Organisation>(PayloadDetails);
                objCommon.tracingService.Trace("seriallised object working");
                var ValidationContext = new ValidationContext(AccountPayload, serviceProvider: null, items: null);
                ICollection <System.ComponentModel.DataAnnotations.ValidationResult> ValidationResults        = null;
                ICollection <System.ComponentModel.DataAnnotations.ValidationResult> ValidationResultsAddress = null;

                var     isValid        = objCommon.Validate(AccountPayload, out ValidationResults);
                Boolean isValidAddress = AccountPayload.address == null ? true :
                                         objCommon.Validate(AccountPayload.address, out ValidationResultsAddress);

                if (isValid & isValidAddress)
                {
                    objCommon.tracingService.Trace("length{0}", AccountPayload.name.Length);
                    if (AccountPayload.hierarchylevel != 0)
                    {
                        objCommon.tracingService.Trace("hierarchylevel level: {0}", AccountPayload.hierarchylevel);

                        if (!String.IsNullOrEmpty(Enum.GetName(typeof(defra_OrganisationHierarchyLevel), AccountPayload.hierarchylevel)))
                        {
                            objCommon.tracingService.Trace("before assinging value");

                            AccountObject[Defra.CustMaster.D365.Common.schema.AccountContants.HIERARCHYLEVEL] = new OptionSetValue(AccountPayload.hierarchylevel);
                            objCommon.tracingService.Trace("after assinging value");


                            if (!String.IsNullOrEmpty(Enum.GetName(typeof(defra_OrganisationType), AccountPayload.type)))
                            {
                                //check if crn exists

                                OrganizationServiceContext orgSvcContext = new OrganizationServiceContext(objCommon.service);
                                var checkCRNExistis = from c in orgSvcContext.CreateQuery("account")
                                                      where (string)c[Defra.CustMaster.D365.Common.schema.AccountContants.COMPANY_HOUSE_ID] == AccountPayload.crn
                                                      select new { organisationid = c.Id };

                                if (checkCRNExistis.FirstOrDefault() == null)
                                {
                                    objCommon.tracingService.Trace("After completing validation 12" + AccountPayload.type);
                                    optionSetValue = AccountPayload.type;
                                    objCommon.tracingService.Trace("before assigning type  " + AccountPayload.type);
                                    objCommon.tracingService.Trace(optionSetValue.ToString());
                                    objCommon.tracingService.Trace("after  setting up option set value");
                                    OptionSetValueCollection BusinessTypes = new OptionSetValueCollection();
                                    BusinessTypes.Add(new OptionSetValue(optionSetValue.Value));
                                    AccountObject[Defra.CustMaster.D365.Common.schema.AccountContants.TYPE]             = BusinessTypes;
                                    AccountObject[Defra.CustMaster.D365.Common.schema.AccountContants.NAME]             = AccountPayload.name == null ? string.Empty : AccountPayload.name;
                                    AccountObject[Defra.CustMaster.D365.Common.schema.AccountContants.COMPANY_HOUSE_ID] = AccountPayload.crn == string.Empty ? null : AccountPayload.crn;
                                    AccountObject[Defra.CustMaster.D365.Common.schema.AccountContants.TELEPHONE1]       = AccountPayload.telephone == null ? string.Empty : AccountPayload.telephone;
                                    objCommon.tracingService.Trace("after  setting other fields");

                                    bool IsValidGuid;
                                    Guid ParentAccountId;
                                    if (AccountPayload.parentorganisation != null && String.IsNullOrEmpty(AccountPayload.parentorganisation.parentorganisationcrmid))
                                    {
                                        IsValidGuid = Guid.TryParse(AccountPayload.parentorganisation.parentorganisationcrmid, out ParentAccountId);
                                        if (IsValidGuid)
                                        {
                                            AccountObject[Defra.CustMaster.D365.Common.schema.AccountContants.PARENTACCOUNTID] = ParentAccountId;
                                        }
                                    }

                                    AccountObject[Defra.CustMaster.D365.Common.schema.AccountContants.EMAILADDRESS1] = AccountPayload.email;
                                    objCommon.tracingService.Trace("before createing guid:");
                                    CrmGuid = objCommon.service.Create(AccountObject);
                                    objCommon.tracingService.Trace("after createing guid:{0}", CrmGuid.ToString());
                                    Entity AccountRecord = objCommon.service.Retrieve("account", CrmGuid, new Microsoft.Xrm.Sdk.Query.ColumnSet(Defra.CustMaster.D365.Common.schema.AccountContants.UNIQUEREFERENCE));
                                    UniqueReference = (string)AccountRecord[Defra.CustMaster.D365.Common.schema.AccountContants.UNIQUEREFERENCE];
                                    objCommon.CreateAddress(AccountPayload.address, new EntityReference(Defra.CustMaster.D365.Common.schema.AccountContants.ENTITY_NAME, CrmGuid));
                                    ErrorCode = 200;
                                }
                                else
                                {
                                    ErrorCode    = 412;
                                    ErrorMessage = ErrorMessage.Append(String.Format("Company house id already exists."));
                                }
                            }
                        }
                        else
                        {
                            ErrorCode    = 400;
                            ErrorMessage = ErrorMessage.Append(String.Format("Option set value {0} for orgnisation hirarchy level not found.",
                                                                             Defra.CustMaster.D365.Common.schema.AccountContants.HIERARCHYLEVEL.ToString()));
                        }
                    }

                    else
                    {
                        ErrorCode    = 400;
                        ErrorMessage = ErrorMessage.Append(String.Format("Option set value {0} for orgnisation type does not exists.",
                                                                         AccountPayload.type));
                    }
                }
                else
                {
                    objCommon.tracingService.Trace("inside validation result");
                    ErrorMessage = new StringBuilder();
                    //this will throw an error
                    foreach (System.ComponentModel.DataAnnotations.ValidationResult vr in ValidationResults)
                    {
                        ErrorMessage.Append(vr.ErrorMessage + " ");
                    }
                    foreach (System.ComponentModel.DataAnnotations.ValidationResult vr in ValidationResultsAddress)
                    {
                        ErrorMessage.Append(vr.ErrorMessage + " ");
                    }
                    ErrorCode = 400;
                }
            }
            catch (Exception ex)
            {
                objCommon.tracingService.Trace("inside exception");

                ErrorCode           = 500;
                _ErrorMessage       = "Error occured while processing request";
                _ErrorMessageDetail = ex.Message;
                ErrorCode           = 400;
                this.ReturnMessageDetails.Set(executionContext, _ErrorMessageDetail);
                objCommon.tracingService.Trace(ex.Message);
            }
            finally
            {
                objCommon.tracingService.Trace("finally block start");
                AccountResponse responsePayload = new AccountResponse()
                {
                    code     = ErrorCode,
                    message  = ErrorMessage.ToString(),
                    datetime = DateTime.UtcNow,
                    version  = "1.0.0.2",

                    status = ErrorCode == 200 ? "success" : "failure",
                    data   = new AccountData()
                    {
                        accountid    = CrmGuid,
                        uniquerefere = UniqueReference,
                        error        = new ResponseErrorBase()
                        {
                            details = _ErrorMessageDetail
                        }
                    }
                };
                objCommon.tracingService.Trace("attempting to serialise");

                string json = JsonConvert.SerializeObject(responsePayload);

                ReturnMessageDetails.Set(executionContext, json);
                // OutputCode.Set(executionContext, _errorCode);

                objCommon.tracingService.Trace("json {0}", json);
                objCommon.tracingService.Trace("finally block end");
            }
        }
Exemple #7
0
        public override void ExecuteCRMWorkFlowActivity(CodeActivityContext executionContext, LocalWorkflowContext crmWorkflowContext)
        {
            String        PayloadDetails = request.Get(executionContext);
            int?          optionSetValue;
            int           ErrorCode           = 400; //400 -- bad request
            String        _ErrorMessage       = string.Empty;
            String        _ErrorMessageDetail = string.Empty;
            Guid          ContactId           = Guid.Empty;
            Guid          CrmGuid             = Guid.Empty;
            StringBuilder ErrorMessage        = new StringBuilder();
            String        UniqueReference     = string.Empty;
            Guid?         ExistingID          = null;

            try
            {
                objCommon = new SCII.Helper(executionContext);
                objCommon.tracingService.Trace("Load CRM Service from context --- OK");
                Entity AccountObject = new Entity(Defra.CustMaster.D365.Common.schema.AccountContants.ENTITY_NAME);

                objCommon.tracingService.Trace("attempt to seriallised new");
                SCII.OrganisationRequest AccountPayload = JsonConvert.DeserializeObject <SCII.OrganisationRequest>(PayloadDetails);
                objCommon.tracingService.Trace("seriallised object working");
                var ValidationContext = new ValidationContext(AccountPayload, serviceProvider: null, items: null);
                ICollection <System.ComponentModel.DataAnnotations.ValidationResult> ValidationResults        = null;
                ICollection <System.ComponentModel.DataAnnotations.ValidationResult> ValidationResultsAddress = null;

                var     isValid        = objCommon.Validate(AccountPayload, out ValidationResults);
                Boolean isValidAddress = AccountPayload.address == null ? true :
                                         objCommon.Validate(AccountPayload.address, out ValidationResultsAddress);

                if (AccountPayload.address != null && AccountPayload.address.type != null)
                {
                    if (!Enum.IsDefined(typeof(SCII.AddressTypes), AccountPayload.address.type))
                    {
                        ErrorMessage.Append(String.Format("Option set value for address of type {0} not found;", AccountPayload.address.type));
                    }
                }

                if (isValid & isValidAddress && ErrorMessage.Length == 0)
                {
                    objCommon.tracingService.Trace("length{0}", AccountPayload.name.Length);

                    objCommon.tracingService.Trace("hierarchylevel level: {0}", AccountPayload.hierarchylevel);

                    if (AccountPayload.hierarchylevel == 0 || !String.IsNullOrEmpty(Enum.GetName(typeof(SCSE.defra_OrganisationHierarchyLevel), AccountPayload.hierarchylevel))
                        )
                    {
                        objCommon.tracingService.Trace("before assinging value");

                        if (AccountPayload.hierarchylevel != 0)
                        {
                            AccountObject[Defra.CustMaster.D365.Common.schema.AccountContants.HIERARCHYLEVEL] = new OptionSetValue(AccountPayload.hierarchylevel);
                        }
                        objCommon.tracingService.Trace("after assinging value");
                        if (!String.IsNullOrEmpty(Enum.GetName(typeof(SCSE.defra_OrganisationType), AccountPayload.type)))
                        {
                            //check if crn exists

                            OrganizationServiceContext orgSvcContext = new OrganizationServiceContext(objCommon.service);
                            if (AccountPayload.crn != null && AccountPayload.crn != string.Empty)
                            {
                                ExistingID = objCommon.CheckIfSameIdenfierExists(SCS.Identifers.COMPANYHOUSEIDENTIFIERNAME, AccountPayload.crn, null);
                                objCommon.tracingService.Trace("company housid from identifier:" + ExistingID);
                            }
                            //var checkCRNExistis = from c in orgSvcContext.CreateQuery("account")
                            //                      where (string)c[Defra.CustMaster.D365.Common.schema.AccountContants.COMPANY_HOUSE_ID] == AccountPayload.crn
                            //                      select new { organisationid = c.Id };


                            if (ExistingID == null)
                            {
                                objCommon.tracingService.Trace("After completing validation 12" + AccountPayload.type);
                                optionSetValue = AccountPayload.type;
                                objCommon.tracingService.Trace("before assigning type  " + AccountPayload.type);
                                objCommon.tracingService.Trace(optionSetValue.ToString());
                                objCommon.tracingService.Trace("after  setting up option set value");
                                OptionSetValueCollection BusinessTypes = new OptionSetValueCollection();
                                BusinessTypes.Add(new OptionSetValue(optionSetValue.Value));
                                AccountObject[Defra.CustMaster.D365.Common.schema.AccountContants.TYPE] = BusinessTypes;
                                AccountObject[Defra.CustMaster.D365.Common.schema.AccountContants.NAME] = AccountPayload.name == null ? string.Empty : AccountPayload.name;
                                //AccountObject[Defra.CustMaster.D365.Common.schema.AccountContants.COMPANY_HOUSE_ID] = AccountPayload.crn == string.Empty ? null : AccountPayload.crn;


                                AccountObject[Defra.CustMaster.D365.Common.schema.AccountContants.TELEPHONE1] = AccountPayload.telephone == null ? string.Empty : AccountPayload.telephone;
                                if (AccountPayload.validatedwithcompanieshouse != null)
                                {
                                    bool isValidCompaniesHouse = false;
                                    if (Boolean.TryParse(AccountPayload.validatedwithcompanieshouse.ToString(), out isValidCompaniesHouse))
                                    {
                                        AccountObject[SCS.AccountContants.VALIDATED_WITH_COMPANYHOUSE] = isValidCompaniesHouse;
                                    }
                                    else
                                    {
                                        ErrorMessage = ErrorMessage.Append(string.Format("Validated with companyhouse value {0} is not valid;",
                                                                                         AccountPayload.validatedwithcompanieshouse));
                                    }
                                }
                                objCommon.tracingService.Trace("after  setting other fields");

                                bool IsValidGuid;
                                Guid ParentAccountId;
                                if (AccountPayload.parentorganisation != null && !string.IsNullOrEmpty(AccountPayload.parentorganisation.parentorganisationcrmid))
                                {
                                    objCommon.tracingService.Trace("before checking value");
                                    IsValidGuid = Guid.TryParse(AccountPayload.parentorganisation.parentorganisationcrmid, out ParentAccountId);
                                    if (IsValidGuid)
                                    {
                                        var checkParentOrgExists = from c in orgSvcContext.CreateQuery("account")
                                                                   where (string)c[Defra.CustMaster.D365.Common.schema.AccountContants.ACCOUNTID] == AccountPayload.parentorganisation.parentorganisationcrmid
                                                                   select new
                                        {
                                            organisationid = c.Id
                                        };
                                        if (checkParentOrgExists.FirstOrDefault() != null)
                                        {
                                            AccountObject[Defra.CustMaster.D365.Common.schema.AccountContants.PARENTACCOUNTID]
                                                = new EntityReference(SCS.AccountContants.ENTITY_NAME, ParentAccountId);
                                            objCommon.tracingService.Trace("after assinging value");
                                        }
                                        else
                                        {
                                            objCommon.tracingService.Trace("throwing error becuase organisation does not exists.");
                                            throw new Exception("Parent account id does not exists.");
                                        }
                                    }
                                    else
                                    {
                                        objCommon.tracingService.Trace("invalid Guid.");
                                        throw new Exception("Invalid parent account Id.");
                                    }
                                }

                                AccountObject[Defra.CustMaster.D365.Common.schema.AccountContants.EMAILADDRESS1] = AccountPayload.email;
                                objCommon.tracingService.Trace("before createing guid:");
                                CrmGuid = objCommon.service.Create(AccountObject);

                                objCommon.CreateIdentifier(SCS.Identifers.COMPANYHOUSEIDENTIFIERNAME, AccountPayload.crn, new EntityReference(SCS.AccountContants.ENTITY_NAME, CrmGuid));
                                //create contactdetail record for primary contact details
                                if (AccountPayload.email != null)
                                {
                                    objCommon.tracingService.Trace("email id before upsert contact");
                                    objCommon.UpsertContactDetails((int)SCII.EmailTypes.PrincipalEmailAddress, AccountPayload.email, new EntityReference(SCS.AccountContants.ENTITY_NAME, CrmGuid), false, false);
                                    objCommon.tracingService.Trace("email id after upsert contact");
                                }
                                if (AccountPayload.telephone != null)
                                {
                                    objCommon.tracingService.Trace("telephone before upsert contact");

                                    objCommon.UpsertContactDetails((int)SCII.PhoneTypes.PrincipalPhoneNumber, AccountPayload.telephone, new EntityReference(SCS.AccountContants.ENTITY_NAME, CrmGuid), false, false);
                                    objCommon.tracingService.Trace("telephone after upsert contact");
                                }

                                objCommon.tracingService.Trace("after createing guid:{0}", CrmGuid.ToString());
                                Entity AccountRecord = objCommon.service.Retrieve("account", CrmGuid, new Microsoft.Xrm.Sdk.Query.ColumnSet(SCS.AccountContants.UNIQUEREFERENCE));
                                UniqueReference = (string)AccountRecord[SCS.AccountContants.UNIQUEREFERENCE];
                                if (AccountPayload.address != null)
                                {
                                    objCommon.CreateAddress(AccountPayload.address, new EntityReference(Defra.CustMaster.D365.Common.schema.AccountContants.ENTITY_NAME, CrmGuid));
                                }
                                ErrorCode = 200;
                            }
                            else
                            {
                                ErrorCode    = 412;
                                ErrorMessage = ErrorMessage.Append(string.Format("Company house id already exists.;"));
                            }
                        }
                        else
                        {
                            ErrorCode    = 400;
                            ErrorMessage = ErrorMessage.Append(string.Format("Option set value {0} for orgnisation type does not exists.",
                                                                             AccountPayload.type));
                        }
                    }
                    else
                    {
                        ErrorCode    = 400;
                        ErrorMessage = ErrorMessage.Append(string.Format("Option set value {0} for orgnisation hirarchy level not found.",
                                                                         AccountPayload.hierarchylevel));
                    }
                }
                else
                {
                    objCommon.tracingService.Trace("inside validation result");
                    //ErrorMessage = new StringBuilder();
                    //this will throw an error
                    foreach (System.ComponentModel.DataAnnotations.ValidationResult vr in ValidationResults)
                    {
                        ErrorMessage.Append(vr.ErrorMessage + " ");
                    }

                    if (ValidationResultsAddress != null)
                    {
                        foreach (System.ComponentModel.DataAnnotations.ValidationResult vr in ValidationResultsAddress)
                        {
                            ErrorMessage.Append(vr.ErrorMessage + " ");
                        }
                    }
                    ErrorCode = 400;
                }
            }
            catch (Exception ex)
            {
                objCommon.tracingService.Trace("inside exception");

                ErrorCode = 500;
                ErrorMessage.Append(ex.Message);
                _ErrorMessageDetail = ex.Message;
                ErrorCode           = 400;
                this.response.Set(executionContext, _ErrorMessageDetail);
                objCommon.tracingService.Trace(ex.Message);
            }
            finally
            {
                objCommon.tracingService.Trace("finally block start");
                SCIIR.AccountResponse responsePayload = new SCIIR.AccountResponse()
                {
                    code     = ErrorCode,
                    message  = ErrorMessage.ToString(),
                    datetime = DateTime.UtcNow,
                    version  = "1.0.0.2",

                    status = ErrorCode == 200 ? "success" : "failure",
                    data   = new SCIIR.AccountData()
                    {
                        accountid       = CrmGuid,
                        uniquereference = UniqueReference,
                        error           = new SCIIR.ResponseErrorBase()
                        {
                            details = _ErrorMessageDetail
                        }
                    }
                };
                objCommon.tracingService.Trace("attempting to serialise");

                string json = JsonConvert.SerializeObject(responsePayload);

                response.Set(executionContext, json);
                // OutputCode.Set(executionContext, _errorCode);

                objCommon.tracingService.Trace("json {0}", json);
                objCommon.tracingService.Trace("finally block end");
            }
        }