Esempio n. 1
0
        public static async Task<HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)] HttpRequestMessage req, TraceWriter log)
        {
            log.Info("C# HTTP trigger function processed a request- " + req.RequestUri.PathAndQuery);

            HttpClient httpClient = new HttpClient();
            string clientIPHeader = GetIpFromRequestHeaders(req);
            log.Info($"Request processed- {req.RequestUri.PathAndQuery} and clientip is {clientIPHeader}.");

            var content = req.Content.ReadAsStringAsync().GetAwaiter().GetResult();

            ReqPayload payload = JsonConvert.DeserializeObject<ReqPayload>(content);

            byte[] bKey = Convert.FromBase64String(payload.Payload.stringkey);
            byte[] signatureBytes = Encoding.UTF8.GetBytes(payload.Payload.stringtosign);


            HMACSHA256 hmac = new HMACSHA256(bKey);
            byte[] signatureHash = hmac.ComputeHash(signatureBytes);

            string base64Signature = Convert.ToBase64String(signatureHash);


            return new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StringContent(base64Signature, Encoding.UTF8, "application/json")
            };
        }
Esempio n. 2
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");
            }
        }
Esempio n. 3
0
        public override void ExecuteCRMWorkFlowActivity(CodeActivityContext executionContext, LocalWorkflowContext crmWorkflowContext)
        {
            string orgPayload = ReqPayload.Get(executionContext);

            DataContractJsonSerializer deserializer = new DataContractJsonSerializer(typeof(Organisation));
            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;
            Entity        AccountObject = new Entity(CommonSchema.AccountContants.ENTITY_NAME);

            try
            {
                objCommon = new Helper(executionContext);
                objCommon.tracingService.Trace("Load CRM Service from context --- OK");

                objCommon.tracingService.Trace("attempt to seriallised");

                string       jsonPayload    = ReqPayload.Get(executionContext);
                Organisation accountPayload = JsonConvert.DeserializeObject <Organisation>(jsonPayload);
                objCommon.tracingService.Trace("seriallised object working");

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

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


                if (isValid)
                {
                    //check organisation id exists
                    if (!string.IsNullOrEmpty(accountPayload.organisationid) && !string.IsNullOrWhiteSpace(accountPayload.organisationid))
                    {
                        if (Guid.TryParse(accountPayload.organisationid, out orgId))
                        {
                            existingAccountRecord = objCommon.service.Retrieve("account", orgId, new Microsoft.Xrm.Sdk.Query.ColumnSet(CommonSchema.AccountContants.UNIQUEREFERENCE, CommonSchema.AccountContants.COMPANY_HOUSE_ID, CommonSchema.AccountContants.PARENTACCOUNTID));
                            if (existingAccountRecord != null && existingAccountRecord.Id != null)
                            {
                                AccountObject.Id = existingAccountRecord.Id;
                                _uniqueReference = (string)existingAccountRecord[CommonSchema.AccountContants.UNIQUEREFERENCE];
                                _crn             = (string)existingAccountRecord[CommonSchema.AccountContants.COMPANY_HOUSE_ID];
                                isOrgExists      = true;
                            }
                        }
                    }
                    // if org exists then go on to update the organisation
                    if (isOrgExists)
                    {
                        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[CommonSchema.AccountContants.HIERARCHYLEVEL] = new OptionSetValue(accountPayload.hierarchylevel);
                                objCommon.tracingService.Trace("after assinging value");
                            }
                            else
                            {
                                ErrorMessage = ErrorMessage.Append(String.Format("Option set value {0} for orgnisation hirarchy level not found.",
                                                                                 accountPayload.hierarchylevel));
                            }
                        }

                        if (!String.IsNullOrEmpty(Enum.GetName(typeof(defra_OrganisationType), accountPayload.type)))
                        {
                            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[CommonSchema.AccountContants.TYPE] = BusinessTypes;
                        }
                        else
                        {
                            ErrorMessage = ErrorMessage.Append(String.Format("Option set value {0} for orgnisation type does not exists.",
                                                                             accountPayload.type));
                        }

                        //check if crn exists
                        if (accountPayload.crn != null && _crn != accountPayload.crn)
                        {
                            objCommon.tracingService.Trace("account crn:" + _crn + "request crn:" + accountPayload.crn);
                            OrganizationServiceContext orgSvcContext = new OrganizationServiceContext(objCommon.service);
                            var checkCRNExistis = from c in orgSvcContext.CreateQuery("account")
                                                  where (string)c[CommonSchema.AccountContants.COMPANY_HOUSE_ID] == accountPayload.crn
                                                  select new { organisationid = c.Id };


                            if (checkCRNExistis.FirstOrDefault() == null)
                            {
                                AccountObject[CommonSchema.AccountContants.COMPANY_HOUSE_ID] = accountPayload.crn;
                            }
                            else
                            {
                                _errorCode   = 412;
                                ErrorMessage = ErrorMessage.Append(String.Format("Company house id already exists."));
                            }
                        }
                        if (accountPayload.name != null)
                        {
                            AccountObject[CommonSchema.AccountContants.NAME] = accountPayload.name;
                        }
                        if (accountPayload.telephone != null)
                        {
                            AccountObject[CommonSchema.AccountContants.TELEPHONE1] = accountPayload.telephone;
                        }
                        objCommon.tracingService.Trace("after  setting other fields");

                        bool isValidGuid;
                        Guid parentAccountId;
                        if (accountPayload.parentorganisation != null && !String.IsNullOrEmpty(accountPayload.parentorganisation.parentorganisationcrmid))
                        {
                            if (((EntityReference)existingAccountRecord[CommonSchema.AccountContants.PARENTACCOUNTID]).Id.ToString() != accountPayload.parentorganisation.parentorganisationcrmid)
                            {
                                isValidGuid = Guid.TryParse(accountPayload.parentorganisation.parentorganisationcrmid, out parentAccountId);
                                if (isValidGuid)
                                {
                                    AccountObject[CommonSchema.AccountContants.PARENTACCOUNTID] = new EntityReference("account", parentAccountId);
                                }
                                else
                                {
                                    ErrorMessage = ErrorMessage.Append(String.Format("parentorganisationcrmid: {0} is not valid guid",
                                                                                     accountPayload.parentorganisation.parentorganisationcrmid));
                                }
                            }
                        }
                        if (accountPayload.email != null)
                        {
                            AccountObject[CommonSchema.AccountContants.EMAILADDRESS1] = accountPayload.email;
                        }
                        objCommon.tracingService.Trace("before updating guid:" + AccountObject.Id.ToString());
                        objCommon.service.Update(AccountObject);
                        objCommon.tracingService.Trace("after updating guid:{0}", AccountObject.Id.ToString());

                        _errorCode = 200;
                    }
                    //if the organisation does not exists
                    else
                    {
                        _errorCode   = 417;
                        ErrorMessage = ErrorMessage.Append(String.Format("Oranisation with id {0} does not exists.",
                                                                         accountPayload.organisationid));
                    }
                }
                else
                {
                    objCommon.tracingService.Trace("inside validation result");
                    ErrorMessage = new StringBuilder();
                    //this will throw an error
                    foreach (ValidationResult vr in ValidationResults)
                    {
                        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;

                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    = AccountObject.Id,
                        uniquerefere = _uniqueReference,
                        error        = new ResponseErrorBase()
                        {
                            details = _errorMessageDetail
                        }
                    }
                };

                string resPayload = JsonConvert.SerializeObject(responsePayload);
                ResPayload.Set(executionContext, resPayload);
                objCommon.tracingService.Trace("finally block end");
            }
        }
Esempio n. 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");
            }
        }