Exemplo n.º 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");
            }
        }
Exemplo n.º 2
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");
            }
        }