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