protected override void Execute(CodeActivityContext context) { if (context == null) { throw new ArgumentNullException("serviceProvider"); } //IWorkflowContext workflowContext = context.GetExtension<IWorkflowContext>(); //workflowContext.BusinessUnitId //workflowContext.InitiatingUserId // Construct the Local plug-in context. var localContext = new LocalWorkflowContext(context); localContext.Log(string.Format("Entered {0}.Execute()", ChildClassName)); try { if (ActivityAction != null) { localContext.Log(string.Format( "{0} is firing for Entity: {1}, Message: {2}, Mode: {3}", ChildClassName, localContext.WorkflowContext.PrimaryEntityName, localContext.WorkflowContext.MessageName, localContext.WorkflowContext.Mode)); localContext.DumpInputParameters(); localContext.DumpSharedVariables(); DumpInputArguments(localContext, context); localContext.Log(ActivityAction.Name, "Start"); Invoke(ActivityAction, localContext); localContext.Log(ActivityAction.Name, "End"); DumpOutputArguments(localContext, context); // now exit - if the derived plug-in has incorrectly registered overlapping event registrations, // guard against multiple executions. } } catch (FaultException<OrganizationServiceFault> e) { localContext.Log(string.Format("Exception: {0}", e)); // Handle the exception. throw; } catch (TargetInvocationException e) { localContext.Log(string.Format("Exception: {0}", e.InnerException)); throw e.InnerException; } finally { localContext.Log(string.Format("Exiting {0}.Execute()", ChildClassName)); } }
/// <summary> /// Executes the WorkFlow. /// </summary> /// <param name="crmWorkflowContext">The <see cref="WorkFlowActivityBase.LocalWorkflowContext"/> which contains the /// <param name="executionContext" > <see cref="CodeActivityContext"/> /// </param> /// <remarks> /// For improved performance, Microsoft Dynamics 365 caches WorkFlow instances. /// The WorkFlow's Execute method should be written to be stateless as the constructor /// is not called for every invocation of the WorkFlow. Also, multiple system threads /// could execute the WorkFlow at the same time. All per invocation state information /// is stored in the context. This means that you should not use global variables in WorkFlows. /// </remarks> public override void ExecuteCRMWorkFlowActivity(CodeActivityContext executionContext, LocalWorkflowContext crmWorkflowContext) { if (crmWorkflowContext == null) { throw new ArgumentNullException("crmWorkflowContext"); } TracingService = executionContext.GetExtension <ITracingService>(); Service = crmWorkflowContext.OrganizationService; Context = crmWorkflowContext.WorkflowExecutionContext; var application = Application.Get(executionContext); var permit = Permit.Get(executionContext); if (application == null && permit == null) { return; } string returnData; if (application != null) { TracingService.Trace("Getting Standard Rules for application: {0}", application.Id.ToString()); returnData = Service.GetStandardRules(application); } else { TracingService.Trace("Getting Standard Rules for permit: {0}", permit.Id.ToString()); returnData = Service.GetStandardRules(permit, defra_permit.EntityLogicalName, defra_permit.Fields.defra_permitId, defra_permit_lines.EntityLogicalName); } ReturnData.Set(executionContext, returnData); TracingService.Trace("Returning data: {0}", returnData); }
protected override void ExecuteCrmWorkFlowActivity(CodeActivityContext context, LocalWorkflowContext localContext) { if (context == null) { throw new ArgumentNullException(nameof(context)); } if (localContext == null) { throw new ArgumentNullException(nameof(localContext)); } string aiSetupJson = AiSetupJson.Get(context); AiLogger aiLogger = new AiLogger(aiSetupJson, localContext.OrganizationService, localContext.TracingService, localContext.WorkflowExecutionContext, null, localContext.WorkflowExecutionContext.WorkflowCategory); string message = Message.Get(context); string severity = Severity.Get(context); string severityValidationResult = AiTrace.ValidateSeverityValue(severity); if (!string.IsNullOrEmpty(severityValidationResult)) { localContext.TracingService.Trace(severityValidationResult); LogSuccess.Set(context, false); return; } Enum.TryParse(severity, out AiTraceSeverity traceSeverity); bool logSuccess = aiLogger.WriteTrace(message, traceSeverity); LogSuccess.Set(context, logSuccess); }
protected override void ExecuteCrmWorkFlowActivity(CodeActivityContext context, LocalWorkflowContext localContext) { if (context == null) { throw new ArgumentNullException(nameof(context)); } if (localContext == null) { throw new ArgumentNullException(nameof(localContext)); } EntityReference emailToSend = EmailToSend.Get(context); EntityReference recipientQueue = RecipientQueue.Get(context); bool sendEmail = SendEmail.Get(context); bool includeOwner = IncludeOwner.Get(context); List <Entity> ccList = new List <Entity>(); Entity email = RetrieveEmail(localContext.OrganizationService, emailToSend.Id); if (email == null) { UsersAdded.Set(context, 0); return; } //Add any pre-defined recipients specified to the array foreach (Entity activityParty in email.GetAttributeValue <EntityCollection>("cc").Entities) { ccList.Add(activityParty); } bool is2011 = Is2011(localContext.OrganizationService); EntityCollection users = is2011 ? GetQueueOwner(localContext.OrganizationService, recipientQueue.Id) : GetQueueMembers(localContext.OrganizationService, recipientQueue.Id); if (!is2011) { if (includeOwner) { users.Entities.AddRange(GetQueueOwner(localContext.OrganizationService, recipientQueue.Id).Entities); } } ccList = ProcessUsers(users, ccList); //Update the email email["cc"] = ccList.ToArray(); localContext.OrganizationService.Update(email); //Send if (sendEmail) { SendEmailRequest request = new SendEmailRequest { EmailId = emailToSend.Id, TrackingToken = string.Empty, IssueSend = true }; localContext.OrganizationService.Execute(request); } UsersAdded.Set(context, ccList.Count); }
protected override void ExecuteCrmWorkFlowActivity(CodeActivityContext context, LocalWorkflowContext localContext) { if (context == null) { throw new ArgumentNullException(nameof(context)); } if (localContext == null) { throw new ArgumentNullException(nameof(localContext)); } DateTime startTimeInput = StartTime.Get(context); localContext.TracingService.Trace("Input: " + startTimeInput.ToString("yyyy-MM-dd HH:mm:ss.fff")); DateTime startTime = startTimeInput == DateTime.MinValue ? localContext.WorkflowExecutionContext.OperationCreatedOn : startTimeInput; localContext.TracingService.Trace("StartTime: " + startTime.ToString("yyyy-MM-dd HH:mm:ss.fff")); DateTime endTime = TimeProvider.UtcNow; localContext.TracingService.Trace("EndTime: " + endTime.ToString("yyyy-MM-dd HH:mm:ss.fff")); TimeSpan difference = endTime - startTime; DurationMs.Set(context, Convert.ToInt32(difference.TotalMilliseconds)); }
/// <summary> /// Executes the WorkFlow. /// </summary> /// <param name="crmWorkflowContext">The <see cref="LocalWorkflowContext"/> which contains the /// <param name="executionContext" > <see cref="CodeActivityContext"/> /// </param> /// <remarks> /// For improved performance, Microsoft Dynamics 365 caches WorkFlow instances. /// The WorkFlow's Execute method should be written to be stateless as the constructor /// is not called for every invocation of the WorkFlow. Also, multiple system threads /// could execute the WorkFlow at the same time. All per invocation state information /// is stored in the context. This means that you should not use global variables in WorkFlows. /// </remarks> public override void ExecuteCRMWorkFlowActivity(CodeActivityContext executionContext, LocalWorkflowContext crmWorkflowContext) { if (crmWorkflowContext == null) { throw new ArgumentNullException("crmWorkflowContext"); } if (executionContext == null) { throw new ArgumentNullException(nameof(executionContext)); } TracingService = executionContext.GetExtension <ITracingService>(); Service = crmWorkflowContext.OrganizationService; Context = crmWorkflowContext.WorkflowExecutionContext; var saveAndReturnId = SaveAndReturnId.Get(executionContext); if (string.IsNullOrWhiteSpace(saveAndReturnId)) { return; } TracingService.Trace("Getting application for Save and Return Id {0}", saveAndReturnId); var application = GetApplicationForSaveAndReturnId(saveAndReturnId); if (application != null) { Application.Set(executionContext, application); TracingService.Trace("Returning entity ref for Application: {0}", application.Id.ToString()); } }
protected override void ExecuteCrmWorkFlowActivity(CodeActivityContext context, LocalWorkflowContext localContext) { if (context == null) { throw new ArgumentNullException(nameof(context)); } if (localContext == null) { throw new ArgumentNullException(nameof(localContext)); } EntityReference noteToMove = NoteToMove.Get(context); string recordUrl = RecordUrl.Get <string>(context); var dup = new DynamicUrlParser(recordUrl); string newEntityLogical = dup.GetEntityLogicalName(localContext.OrganizationService); Entity note = GetNote(localContext.OrganizationService, noteToMove.Id); if (note.GetAttributeValue <EntityReference>("objectid").Id == dup.Id && note.GetAttributeValue <EntityReference>("objectid").LogicalName == newEntityLogical) { WasNoteMoved.Set(context, false); return; } Entity updateNote = new Entity("annotation") { Id = noteToMove.Id, ["objectid"] = new EntityReference(newEntityLogical, dup.Id) }; localContext.OrganizationService.Update(updateNote); WasNoteMoved.Set(context, true); }
protected override void ExecuteCrmWorkFlowActivity(CodeActivityContext context, LocalWorkflowContext localContext) { if (context == null) { throw new ArgumentNullException(nameof(context)); } if (localContext == null) { throw new ArgumentNullException(nameof(localContext)); } EntityReference noteToCopy = NoteToCopy.Get(context); string recordUrl = RecordUrl.Get <string>(context); bool copyAttachment = CopyAttachment.Get(context); var dup = new DynamicUrlParser(recordUrl); string newEntityLogical = dup.GetEntityLogicalName(localContext.OrganizationService); Entity note = GetNote(localContext.OrganizationService, noteToCopy.Id); if (note.GetAttributeValue <EntityReference>("objectid").Id == dup.Id && note.GetAttributeValue <EntityReference>("objectid").LogicalName == newEntityLogical) { WasNoteCopied.Set(context, false); return; } Entity newNote = new Entity("annotation") { ["objectid"] = new EntityReference(newEntityLogical, dup.Id), ["notetext"] = note.GetAttributeValue <string>("notetext"), ["subject"] = note.GetAttributeValue <string>("subject") }; if (copyAttachment) { newNote["isdocument"] = note.GetAttributeValue <bool>("isdocument"); newNote["filename"] = note.GetAttributeValue <string>("filename"); newNote["filesize"] = note.GetAttributeValue <int>("filesize"); newNote["documentbody"] = note.GetAttributeValue <string>("documentbody"); } else { newNote["isdocument"] = false; } localContext.OrganizationService.Create(newNote); WasNoteCopied.Set(context, true); }
protected override void ExecuteCrmWorkFlowActivity(CodeActivityContext context, LocalWorkflowContext localContext) { if (context == null) { throw new ArgumentNullException(nameof(context)); } if (localContext == null) { throw new ArgumentNullException(nameof(localContext)); } DateTime startingDate = StartingDate.Get(context); DateTime endingDate = EndingDate.Get(context); DateTime fromDate; DateTime toDate; int increment = 0; int[] monthDay = { 31, -1, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; int month; int day; if (startingDate > endingDate) { fromDate = endingDate; toDate = startingDate; } else { fromDate = startingDate; toDate = endingDate; } if (fromDate.Day > toDate.Day) { increment = monthDay[fromDate.Month - 1]; } if (increment == -1) { increment = DateTime.IsLeapYear(fromDate.Year) ? 29 : 28; } if (increment != 0) { day = toDate.Day + increment - fromDate.Day; increment = 1; } else { day = toDate.Day - fromDate.Day; } if (fromDate.Month + increment > toDate.Month) { month = toDate.Month + 12 - (fromDate.Month + increment); increment = 1; } else { month = toDate.Month - (fromDate.Month + increment); increment = 0; } int year = toDate.Year - (fromDate.Year + increment); int yearsDifference = year; YearsDifference.Set(context, yearsDifference); }
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"); } }
protected override void ExecuteCrmWorkFlowActivity(CodeActivityContext context, LocalWorkflowContext localContext) { if (context == null) { throw new ArgumentNullException(nameof(context)); } if (localContext == null) { throw new ArgumentNullException(nameof(localContext)); } DateTime dateToUse = DateToUse.Get(context); bool evaluateAsUserLocal = EvaluateAsUserLocal.Get(context); if (evaluateAsUserLocal) { int?timeZoneCode = GetLocalTime.RetrieveTimeZoneCode(localContext.OrganizationService); dateToUse = GetLocalTime.RetrieveLocalTimeFromUtcTime(dateToUse, timeZoneCode, localContext.OrganizationService); } int quarterNumberOfYear = (dateToUse.Month - 1) / 3 + 1; QuarterNumberOfYear.Set(context, quarterNumberOfYear); }
public override void ExecuteCRMWorkFlowActivity(CodeActivityContext executionContext, LocalWorkflowContext crmWorkflowContext) { crmWorkflowContext.Trace("Started: Defra.CustMaster.Identity.WfActivities.SearchRecords"); string advancedFindXml; string replaceString; const string BREAK_CHAR = "{SEP}"; // Separator string for the values input string[] replaceValues; advancedFindXml = InFetchXmlQuery.Get(executionContext); if (string.IsNullOrEmpty(advancedFindXml)) { throw new InvalidPluginExecutionException("Please provide valid Email Address in the Email."); } replaceString = InValues.Get(executionContext); crmWorkflowContext.Trace("SearchRecords: Value Replacement started..."); if (!string.IsNullOrEmpty(replaceString)) { //replaceValues = replaceString.Split(BREAK_CHAR.ToCharArray()); replaceValues = replaceString.Split(new string[] { BREAK_CHAR }, StringSplitOptions.RemoveEmptyEntries); if (replaceValues.Length <= 0) { throw new InvalidPluginExecutionException("Please provide a valid replace string in the format {value0}{SEP}{value1}{SEP}{value2}."); } int iLoop = 0; foreach (string replaceValue in replaceValues) { crmWorkflowContext.Trace(string.Format("SearchRecords: Value{0} = {1}", iLoop, replaceValue)); advancedFindXml = advancedFindXml.Replace("{" + iLoop++ + "}", replaceValue.Trim()); } } crmWorkflowContext.Trace("SearchRecords: Replaced query = " + advancedFindXml); crmWorkflowContext.Trace("SearchRecords: Value Replacement finished!"); crmWorkflowContext.Trace("SearchRecords: Calling Retrieve Multiple..."); EntityCollection results = crmWorkflowContext.OrganizationService.RetrieveMultiple(new FetchExpression(advancedFindXml)); crmWorkflowContext.Trace("count from entity collection count" + results.Entities.Count); crmWorkflowContext.Trace("count from entity collection total record count" + results.TotalRecordCount); int recourdCount = 0; if (results != null) { recourdCount = results.TotalRecordCount; //recourdCount = results.Entities.Count; } crmWorkflowContext.TracingService.Trace(string.Format("SearchRecords: Found {0} records.", recourdCount)); OutRecordCount.Set(executionContext, recourdCount); crmWorkflowContext.Trace("Finished: Defra.CustMaster.Identity.WfActivities.ExecuteCRMWorkFlowActivity"); }
protected override void ExecuteCrmWorkFlowActivity(CodeActivityContext context, LocalWorkflowContext localContext) { if (context == null) { throw new ArgumentNullException(nameof(context)); } if (localContext == null) { throw new ArgumentNullException(nameof(localContext)); } string stringToMeasure = StringToMeasure.Get(context); if (string.IsNullOrEmpty(stringToMeasure)) { StringLength.Set(context, 0); return; } int stringLength = stringToMeasure.Length; StringLength.Set(context, stringLength); }
protected override void ExecuteCrmWorkFlowActivity(CodeActivityContext context, LocalWorkflowContext localContext) { if (context == null) { throw new ArgumentNullException(nameof(context)); } if (localContext == null) { throw new ArgumentNullException(nameof(localContext)); } EntityReference emailToSend = EmailToSend.Get(context); EntityReference recipientTeam = RecipientTeam.Get(context); bool sendEmail = SendEmail.Get(context); List <Entity> toList = new List <Entity>(); Entity email = RetrieveEmail(localContext.OrganizationService, emailToSend.Id); if (email == null) { UsersAdded.Set(context, 0); return; } //Add any pre-defined recipients specified to the array foreach (Entity activityParty in email.GetAttributeValue <EntityCollection>("to").Entities) { toList.Add(activityParty); } EntityCollection teamMembers = GetTeamMembers(localContext.OrganizationService, recipientTeam.Id); toList = ProcessUsers(localContext.OrganizationService, teamMembers, toList); //Update the email email["to"] = toList.ToArray(); localContext.OrganizationService.Update(email); //Send if (sendEmail) { SendEmailRequest request = new SendEmailRequest { EmailId = emailToSend.Id, TrackingToken = string.Empty, IssueSend = true }; localContext.OrganizationService.Execute(request); } UsersAdded.Set(context, toList.Count); }
private void Invoke(MethodInfo entityAction, LocalWorkflowContext localContext) { var listParamValues = new List<object>(); foreach (var param in entityAction.GetParameters()) { if (typeof(ICustomWorkflowContext).IsAssignableFrom(param.ParameterType)) { listParamValues.Add(localContext); } else if (typeof(IService).IsAssignableFrom(param.ParameterType)) { var obj = localContext.GetService(param.ParameterType); listParamValues.Add(obj); } } entityAction.Invoke(this, listParamValues.ToArray()); }
protected override void ExecuteCrmWorkFlowActivity(CodeActivityContext context, LocalWorkflowContext localContext) { if (context == null) { throw new ArgumentNullException(nameof(context)); } if (localContext == null) { throw new ArgumentNullException(nameof(localContext)); } DateTime x = TimeProvider.UtcNow; CurrentTimeUtc.Set(context, TimeProvider.UtcNow); }
public override void ExecuteCRMWorkFlowActivity(CodeActivityContext executionContext, LocalWorkflowContext crmWorkflowContext) { crmWorkflowContext.Trace("Started: Defra.CustMaster.Identity.WfActivities.ContactDetailType"); HierarchyType.Set(executionContext, new OptionSetValue(HierarchyTypeValue.Get(executionContext))); crmWorkflowContext.Trace("Finished: Defra.CustMaster.Identity.WfActivities.ContactDetailType"); }
protected override void ExecuteCrmWorkFlowActivity(CodeActivityContext context, LocalWorkflowContext localContext) { if (context == null) { throw new ArgumentNullException(nameof(context)); } if (localContext == null) { throw new ArgumentNullException(nameof(localContext)); } DateTime originalDate = OriginalDate.Get(context); int businessDaysToAdd = BusinessDaysToAdd.Get(context); EntityReference holidaySchedule = HolidayClosureCalendar.Get(context); DateTime tempDate = originalDate; if (businessDaysToAdd > 0) { while (businessDaysToAdd > 0) { tempDate = tempDate.AddDays(1); if (tempDate.IsBusinessDay(localContext.OrganizationService, holidaySchedule)) { // Only decrease the days to add if the day we've just added counts as a business day businessDaysToAdd--; } } } else if (businessDaysToAdd < 0) { while (businessDaysToAdd < 0) { tempDate = tempDate.AddDays(-1); if (tempDate.IsBusinessDay(localContext.OrganizationService, holidaySchedule)) { // Only increase the days to add if the day we've just added counts as a business day businessDaysToAdd++; } } } DateTime updatedDate = tempDate; UpdatedDate.Set(context, updatedDate); }
/// <summary> /// Executes the WorkFlow. /// </summary> public override void ExecuteCRMWorkFlowActivity(CodeActivityContext executionContext, LocalWorkflowContext crmWorkflowContext) { if (crmWorkflowContext == null) { throw new ArgumentNullException("crmWorkflowContext"); } ContextWrapper contextWrapper = new ContextWrapper ( crmWorkflowContext.TracingService, crmWorkflowContext.OrganizationService ); try { // get the input parameters EntityReference saProdRef = SaProductParam.Get(executionContext); EntityReference woRef = WorkOrderParam.Get(executionContext); // crmWorkflowContext.Trace("instantiated workflow parameters woRef, saProdRef"); if (saProdRef != null) { // get the related SA product records //crmWorkflowContext.Trace("saRef and woRef instantiated, now run fetch/retrievemultiple"); //Get all of the SA products var fetchXml = @" <fetch version='1.0' no-lock='true'> <entity name='fsip_serviceactivityproduct'> <attribute name='fsip_quantity' /> <attribute name='fsip_unitofmeasure' /> <attribute name='fsip_product' /> <attribute name='fsip_productname' /> <attribute name='fsip_serviceactivity' /> <attribute name='fsip_comment' /> <attribute name='clima_pocostperunit' /> <attribute name='clima_vendor' /> <filter> <condition attribute='fsip_serviceactivityproductid' operator='eq' value='" + saProdRef.Id + @"' /> <condition attribute='statecode' operator='eq' value='0' /> </filter> </entity> </fetch>"; EntityCollection saProducts = contextWrapper.service.RetrieveMultiple(new FetchExpression(fetchXml)); //crmWorkflowContext.Trace(String.Format("retrievemultiple complete, with a count of {0}", saProducts.Entities.Count.ToString())); if (saProducts.Entities.Count > 0) { //crmWorkflowContext.Trace("records found, about to enter for each"); foreach (Entity saProduct in saProducts.Entities) { Entity workOrderDetail = new Entity("salesorderdetail"); workOrderDetail["salesorderid"] = woRef; FBCommon.mapValuesToEntity(workOrderDetail, "quantity", saProduct, "fsip_quantity"); FBCommon.mapValuesToEntity(workOrderDetail, "productid", saProduct, "fsip_product"); FBCommon.mapValuesToEntity(workOrderDetail, "uomid", saProduct, "fsip_unitofmeasure"); FBCommon.mapValuesToEntity(workOrderDetail, "fsip_committedcostperunit", saProduct, "clima_pocostperunit"); if (saProduct.Contains("fsip_comment")) { FBCommon.mapValuesToEntity(workOrderDetail, "fsip_podescription", saProduct, "fsip_comment"); } FBCommon.mapValuesToEntity(workOrderDetail, "fsip_vendorcode", saProduct, "clima_vendor"); workOrderDetail["fsip_autocreateponumber"] = true; //Set local time for the PO Date int? userTimeZoneCode = FBCommon.getUserTimeZoneCode(contextWrapper); DateTime dateTimeLocal = FBCommon.UTCToLocalTime(DateTime.Now, userTimeZoneCode, contextWrapper); workOrderDetail["fsip_purchaseorderdate"] = dateTimeLocal; contextWrapper.service.Create(workOrderDetail); //Submit the PO Entity wo = new Entity("salesorder", "salesorderid", woRef.Id); wo["fsip_submittoerp"] = true; contextWrapper.service.Update(wo); } } //crmWorkflowContext.Trace("complete, leaving CreateWorkOrderProductFromSaProduct class"); } } catch (FaultException <OrganizationServiceFault> e) { // Handle the exception. throw e; } }
protected override void ExecuteCrmWorkFlowActivity(CodeActivityContext context, LocalWorkflowContext localContext) { if (context == null) { throw new ArgumentNullException(nameof(context)); } if (localContext == null) { throw new ArgumentNullException(nameof(localContext)); } DateTime originalDate = OriginalDate.Get(context); int daysToAdd = DaysToAdd.Get(context); DateTime updatedDate = originalDate.AddDays(daysToAdd); UpdatedDate.Set(context, updatedDate); }
/// <summary> /// Executes the WorkFlow. /// </summary> /// <param name="crmWorkflowContext">The <see cref="LocalWorkflowContext"/> which contains the /// <param name="executionContext" > <see cref="CodeActivityContext"/> /// </param> /// <remarks> /// For improved performance, Microsoft Dynamics 365 caches WorkFlow instances. /// The WorkFlow's Execute method should be written to be stateless as the constructor /// is not called for every invocation of the WorkFlow. Also, multiple system threads /// could execute the WorkFlow at the same time. All per invocation state information /// is stored in the context. This means that you should not use global variables in WorkFlows. /// </remarks> public override void ExecuteCRMWorkFlowActivity(CodeActivityContext executionContext, LocalWorkflowContext crmWorkflowContext) { var tracingService = executionContext.GetExtension <ITracingService>(); tracingService.Trace("Inside GetAddressBasedOnOperatorType CWA"); // defra_addressdetails if (crmWorkflowContext == null) { throw new ArgumentNullException("crmWorkflowContext"); } EntityReference addressResult = new EntityReference(defra_address.EntityLogicalName, Guid.NewGuid()); EntityReference contactAddressResult = new EntityReference(defra_addressdetails.EntityLogicalName, Guid.NewGuid()); var service = crmWorkflowContext.OrganizationService; var context = crmWorkflowContext.WorkflowExecutionContext; var appId = crmWorkflowContext.WorkflowExecutionContext.PrimaryEntityId; var appEnt = service.Retrieve(defra_application.EntityLogicalName, appId, new Microsoft.Xrm.Sdk.Query.ColumnSet(defra_application.Fields.defra_customerid, defra_application.Fields.defra_applicant_organisation_type)); OptionSetValue opType = null; if (appEnt.Contains(defra_application.Fields.defra_applicant_organisation_type)) { opType = (OptionSetValue)appEnt[defra_application.Fields.defra_applicant_organisation_type]; } var ltdAddressFetch = @"<fetch > <entity name='defra_address'> <attribute name='defra_addressid' /> <link-entity name='defra_addressdetails' from='defra_address' to='defra_addressid' link-type='inner' alias='am'> <filter type='and'> <condition attribute='defra_addresstype' operator='eq' value='" + (int)defra_organisation_type.Limitedliabilitypartnership + @"' /> </filter> <link-entity name='account' from='accountid' to='defra_customer' link-type='inner' alias='an'> <link-entity name='defra_application' from='defra_customerid' to='accountid' link-type='inner' alias='ao'> <filter type='and'> <condition attribute='defra_applicationid' operator='eq' uitype='defra_application' value='{" + appId.ToString() + @"}' /> </filter> </link-entity> </link-entity> </link-entity> </entity> </fetch>"; if (opType != null) { tracingService.Trace("Operator Type is {0}", (defra_organisation_type)opType.Value); switch (opType.Value) { case (int)defra_organisation_type.Limitedcompany: { var addressOp = service.RetrieveMultiple(new FetchExpression(ltdAddressFetch)).Entities.FirstOrDefault(); contactAddressResult = GetContactDetailGivenAppAndType(appId, (int)defra_AddressType.Companysecretaryordirector, service) ?? contactAddressResult; if (addressOp != null) { addressResult = new EntityReference(defra_address.EntityLogicalName, addressOp.Id); } break; } case (int)defra_organisation_type.Limitedliabilitypartnership: { var addressOp = service.RetrieveMultiple(new FetchExpression(ltdAddressFetch)).Entities.FirstOrDefault(); if (addressOp != null) { addressResult = new EntityReference(defra_address.EntityLogicalName, addressOp.Id); } contactAddressResult = GetContactDetailGivenAppAndType(appId, (int)defra_AddressType.LLPdesignatedmember, service) ?? contactAddressResult; break; } case (int)defra_organisation_type.Localauthorityorpublicbody: { contactAddressResult = GetContactDetailGivenAppAndType(appId, (int)defra_AddressType.Responsibleofficer, service) ?? contactAddressResult; var addRef = GetAddressGivenAppAndType(appId, (int)defra_AddressType.Publicbodyaddress, service); if (addRef != null) { addressResult = new EntityReference(defra_address.EntityLogicalName, addRef.Id); } break; } case (int)defra_organisation_type.Otherorganisationforexampleacluborassociation: { var addRef = GetAddressAndEmailGivenAppAndType(appId, (int)defra_AddressType.Postholder, service); if (addRef != null) { addressResult = new EntityReference(defra_address.EntityLogicalName, addRef.Id); } contactAddressResult = GetContactDetailGivenAppAndType(appId, (int)defra_AddressType.Postholder, service) ?? contactAddressResult; break; } case (int)defra_organisation_type.Partnership: { var addRef = GetAddressAndEmailGivenAppAndType(appId, (int)defra_AddressType.Partner, service); if (addRef != null) { addressResult = new EntityReference(defra_address.EntityLogicalName, addRef.Id); } contactAddressResult = GetContactDetailGivenAppAndType(appId, (int)defra_AddressType.Partner, service) ?? contactAddressResult; break; } case (int)defra_organisation_type.Registeredcharity: { contactAddressResult = GetContactDetailGivenAppAndType(appId, (int)defra_AddressType.Responsibleofficer, service) ?? contactAddressResult; var addRef = GetAddressAndEmailGivenAppAndType(appId, (int)defra_AddressType.Publicbodyaddress, service); if (addRef != null) { addressResult = new EntityReference(defra_address.EntityLogicalName, addRef.Id); } break; } case (int)defra_organisation_type.Soletrader: { var addRef = GetAddressAndEmailGivenAppAndType(appId, (int)defra_AddressType.Individualorsoletrader, service); if (addRef != null) { addressResult = new EntityReference(defra_address.EntityLogicalName, addRef.Id); } contactAddressResult = GetContactDetailGivenAppAndType(appId, (int)defra_AddressType.Individualorsoletrader, service) ?? contactAddressResult; break; } } } else { tracingService.Trace("Operator Type is NULL"); var addRef = GetAddressAndEmailGivenAppAndType(appId, (int)defra_AddressType.Individualorsoletrader, service); if (addRef != null) { addressResult = new EntityReference(defra_address.EntityLogicalName, addRef.Id); } contactAddressResult = GetContactDetailGivenAppAndType(appId, (int)defra_AddressType.Individualorsoletrader, service) ?? contactAddressResult; } tracingService.Trace("Try to set the output parameters"); GetPermitHolderAddress.Set(executionContext, addressResult); GetPermitHolderAddressDetail.Set(executionContext, contactAddressResult); tracingService.Trace("Done"); }
/// <summary> /// Executes the WorkFlow. /// </summary> /// <param name="crmWorkflowContext">The <see cref="LocalWorkflowContext"/> which contains the /// <param name="executionContext" > <see cref="CodeActivityContext"/> /// </param> /// <remarks> /// For improved performance, Microsoft Dynamics 365 caches WorkFlow instances. /// The WorkFlow's Execute method should be written to be stateless as the constructor /// is not called for every invocation of the WorkFlow. Also, multiple system threads /// could execute the WorkFlow at the same time. All per invocation state information /// is stored in the context. This means that you should not use global variables in WorkFlows. /// </remarks> public override void ExecuteCRMWorkFlowActivity(CodeActivityContext executionContext, LocalWorkflowContext crmWorkflowContext) { if (crmWorkflowContext == null) { throw new ArgumentNullException("crmWorkflowContext"); } TracingService = executionContext.GetExtension <ITracingService>(); Service = crmWorkflowContext.OrganizationService; Context = crmWorkflowContext.WorkflowExecutionContext; var application = this.Application.Get(executionContext); if (application == null) { return; } TracingService.Trace("Getting Company Secretary Email contact details for application: {0}", application.Id.ToString()); var contactDetail = GetContactDetailsForApplication(application, "910400006"); if (contactDetail != null) { CompanySecretaryContactDetail.Set(executionContext, contactDetail); TracingService.Trace("Returning entity ref for Company Secretary Email contact detail: {0}", contactDetail.Id.ToString()); } }
protected override void ExecuteCrmWorkFlowActivity(CodeActivityContext context, LocalWorkflowContext localContext) { if (context == null) { throw new ArgumentNullException(nameof(context)); } if (localContext == null) { throw new ArgumentNullException(nameof(localContext)); } string stringToEncode = StringToEncode.Get(context); var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(stringToEncode); string b64EncodedString = Convert.ToBase64String(plainTextBytes); B64EncodedString.Set(context, b64EncodedString); }
protected override void ExecuteCrmWorkFlowActivity(CodeActivityContext context, LocalWorkflowContext localContext) { if (context == null) { throw new ArgumentNullException(nameof(context)); } if (localContext == null) { throw new ArgumentNullException(nameof(localContext)); } DateTime dateToUse = DateToUse.Get(context); bool evaluateAsUserLocal = EvaluateAsUserLocal.Get(context); if (evaluateAsUserLocal) { int?timeZoneCode = GetLocalTime.RetrieveTimeZoneCode(localContext.OrganizationService); dateToUse = GetLocalTime.RetrieveLocalTimeFromUtcTime(dateToUse, timeZoneCode, localContext.OrganizationService); } DateTime yearStartDate = new DateTime(dateToUse.Year, 1, 1, 0, 0, 0); DateTime yearEndDate = yearStartDate.AddYears(1).AddDays(-1).AddHours(23).AddMinutes(59).AddSeconds(59).AddMilliseconds(999); YearStartDate.Set(context, yearStartDate); YearEndDate.Set(context, yearEndDate); }
protected override void ExecuteCrmWorkFlowActivity(CodeActivityContext context, LocalWorkflowContext localContext) { if (context == null) { throw new ArgumentNullException(nameof(context)); } if (localContext == null) { throw new ArgumentNullException(nameof(localContext)); } string stringToSearch = StringToSearch.Get(context); string replacementValue = ReplacementValue.Get(context); string pattern = Pattern.Get(context); if (string.IsNullOrEmpty(replacementValue)) { replacementValue = ""; } Regex regex = new Regex(pattern, RegexOptions.IgnoreCase); string replacedString = regex.Replace(stringToSearch, replacementValue); ReplacedString.Set(context, replacedString); }
/// <summary> /// Executes the WorkFlow. /// </summary> /// <param name="crmWorkflowContext">The <see cref="LocalWorkflowContext"/> which contains the /// <param name="executionContext" > <see cref="CodeActivityContext"/> /// </param> /// <remarks> /// For improved performance, Microsoft Dynamics 365 caches WorkFlow instances. /// The WorkFlow's Execute method should be written to be stateless as the constructor /// is not called for every invocation of the WorkFlow. Also, multiple system threads /// could execute the WorkFlow at the same time. All per invocation state information /// is stored in the context. This means that you should not use global variables in WorkFlows. /// </remarks> public override void ExecuteCRMWorkFlowActivity(CodeActivityContext executionContext, LocalWorkflowContext crmWorkflowContext) { if (crmWorkflowContext == null) { throw new ArgumentNullException("crmWorkflowContext"); } try { #region Create the services var tracingService = executionContext.GetExtension <ITracingService>(); if (tracingService == null) { throw new InvalidPluginExecutionException("Failed to retrieve tracing service."); } tracingService.Trace($"Entered UnshareRecordWithTeam.ExecuteCRMWorkFlowActivity(), Activity Instance Id: {executionContext.ActivityInstanceId}, Workflow Instance Id: {executionContext.WorkflowInstanceId}"); var serviceFactory = executionContext.GetExtension <IOrganizationServiceFactory>(); var service = serviceFactory.CreateOrganizationService(null); #endregion #region Get Parameters string sharingRecordUrl = SharingRecordUrl.Get(executionContext); if (string.IsNullOrEmpty(sharingRecordUrl)) { return; } var refObject = DataAccessMetaData.GetEntityReferenceFromRecordUrl(service, sharingRecordUrl); // // Why do we need an List of principals? // List <EntityReference> principals = new List <EntityReference>(); EntityReference teamReference = Team.Get(executionContext); principals.Clear(); if (teamReference != null) { principals.Add(teamReference); } #endregion #region Revoke Access service.RevokeAccess(refObject, principals); tracingService.Trace("Revoked Permissions--- OK"); #endregion } catch (FaultException <OrganizationServiceFault> e) { // Handle the exception. throw e; } }
/// <summary> /// Main code activity methoid /// </summary> /// <param name="executionContext">Standard CRM execution context</param> /// <param name="crmWorkflowContext">Standard CRM workflow context</param> public override void ExecuteCRMWorkFlowActivity(CodeActivityContext executionContext, LocalWorkflowContext crmWorkflowContext) { // 1. SETUP ITracingService tracingService = executionContext.GetExtension <ITracingService>(); IOrganizationService organisationService = crmWorkflowContext.OrganizationService; tracingService.Trace("Started dsd"); // Validation EntityReference application = Application.Get(executionContext); if (application == null || application.Id == Guid.Empty) { throw new ArgumentException("Application parameter is invalid", nameof(application)); } // Read the task type ids to filter application tasks by List <Guid> taskTypeIds = new List <Guid>(); AddIdToList(TaskType1.Get(executionContext), taskTypeIds); AddIdToList(TaskType2.Get(executionContext), taskTypeIds); AddIdToList(TaskType3.Get(executionContext), taskTypeIds); AddIdToList(TaskType4.Get(executionContext), taskTypeIds); AddIdToList(TaskType5.Get(executionContext), taskTypeIds); AddIdToList(TaskType6.Get(executionContext), taskTypeIds); AddIdToList(TaskType7.Get(executionContext), taskTypeIds); AddIdToList(TaskType8.Get(executionContext), taskTypeIds); AddIdToList(TaskType9.Get(executionContext), taskTypeIds); AddIdToList(TaskType10.Get(executionContext), taskTypeIds); Guid[] taskTypeIdArray = taskTypeIds.ToArray(); // Prepare the DALs DataAccessApplicationTask dalAppTask = new DataAccessApplicationTask(organisationService, tracingService); DataAccessApplication dalApp = new DataAccessApplication(organisationService, tracingService); // 2. PROCESSING // Get Application Type, SubType and owners ApplicationTypesAndOwners applicationDetails = dalApp.GetApplicationTypeAndOwner(application.Id); // Which tasks should be linked to the application? List <Guid> applicableTasks = dalAppTask.GetTaskDefinitionIdsThatApplyToApplication(application.Id, applicationDetails.ApplicationType, applicationDetails.ApplicationSubType, taskTypeIdArray) ?? new List <Guid>(); // Which tasks are already linked? List <ApplicationTaskAndDefinitionId> existingTasks = dalAppTask.GetApplicationTaskIdsLinkedToApplication(application.Id, taskTypeIdArray) ?? new List <ApplicationTaskAndDefinitionId>(); // Deactivate application tasks that no longer apply List <Guid> tasksToRemove = existingTasks.Where(existingTask => !applicableTasks.Contains(existingTask.ApplicationTaskDefinitionId)) .Select(t => t.ApplicationTaskId) .ToList(); tasksToRemove.ForEach(dalAppTask.DeactivateApplicationTask); // Create application tasks that apply List <Guid> tasksToAdd = applicableTasks.Where(applicableTask => existingTasks.All(t => t.ApplicationTaskDefinitionId != applicableTask)).ToList(); tasksToAdd.ForEach(newtask => dalAppTask.CreateApplicationTask(application.Id, applicationDetails.OwningUser, applicationDetails.OwningTeam, newtask)); tracingService.Trace("Done"); }
public virtual void ExecuteCRMWorkFlowActivity(CodeActivityContext context, LocalWorkflowContext crmWorkflowContext) { // Do nothing. }
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"); } }
private void DumpOutputArguments(LocalWorkflowContext localContext, CodeActivityContext context) { foreach (var propertyInfo in this.GetType().GetProperties()) { if (typeof(OutArgument).IsAssignableFrom(propertyInfo.PropertyType)) { var argument = propertyInfo.GetValue(this, null) as OutArgument; localContext.DumpObject(propertyInfo.Name, argument.Get(context)); } } }
protected override void ExecuteCrmWorkFlowActivity(CodeActivityContext context, LocalWorkflowContext localContext) { if (context == null) { throw new ArgumentNullException(nameof(context)); } if (localContext == null) { throw new ArgumentNullException(nameof(localContext)); } var dateToRound = DateToRound.Get(context); var roundDown = RoundDown.Get(context); dateToRound = dateToRound.AddSeconds(-dateToRound.Second); var roundedDate = dateToRound; var minute = dateToRound.Minute; if (minute > 0 && minute < 30) { roundedDate = roundDown ? dateToRound.AddMinutes(-minute) // 0 : dateToRound.AddMinutes(30 - minute); // 30 } else if (minute > 30 && minute < 60) { roundedDate = roundDown ? dateToRound.AddMinutes(-(minute - 30)) // 60 : dateToRound.AddMinutes(60 - minute); // Next hour } RoundedDate.Set(context, roundedDate); }
public override void ExecuteCRMWorkFlowActivity(CodeActivityContext executionContext, LocalWorkflowContext crmWorkflowContext) { localcontext = crmWorkflowContext; String PayloadDetails = request.Get(executionContext); int ErrorCode = 400; //400 -- bad request int RoleCountToCheck = 0; String _ErrorMessage = string.Empty; String _ErrorMessageDetail = string.Empty; Guid ContactId = Guid.Empty; Guid AccountId = Guid.Empty; StringBuilder ErrorMessage = new StringBuilder(); String UniqueReference = string.Empty; Guid? ToConnectId = Guid.Empty; Guid? ConnectionDetailsId = Guid.Empty; SCII.Helper objCommon = new SCII.Helper(executionContext); try { localcontext.Trace("before seriallising1"); SCII.CreateRelationshipRequest ConnectContact = JsonConvert.DeserializeObject <SCII.CreateRelationshipRequest>(PayloadDetails); localcontext.Trace("after seriallising"); EntityReference FromEntityContact = null; EntityReference ToEntityAccount; var ValidationContext = new ValidationContext(ConnectContact, serviceProvider: null, items: null); ICollection <ValidationResult> ValidationResultsConnectContact = null; ICollection <ValidationResult> ValidationResultsRoles = null; localcontext.Trace("before validating"); Boolean isValid = objCommon.Validate(ConnectContact, out ValidationResultsConnectContact); Boolean isValidRoles = objCommon.Validate(ConnectContact.relations, out ValidationResultsRoles); string FromEntityName = ConnectContact.fromrecordtype == SCII.RecordTypeName.contact ? SCS.Contact.ENTITY : SCS.AccountContants.ENTITY_NAME; string ToEntityName = ConnectContact.torecordtype == SCII.RecordTypeName.contact ? SCS.Contact.ENTITY : SCS.AccountContants.ENTITY_NAME; if (isValid && isValidRoles) { //get role ids localcontext.Trace("inside valid schema"); localcontext.Trace(string.Format("contact id {0} org id {1}.", ConnectContact.fromrecordid, ConnectContact.torecordid)); #region Validate record exists //check if account record exists Boolean ContactExists = false; if (!String.IsNullOrEmpty(ConnectContact.fromrecordid)) { FromEntityContact = new EntityReference(FromEntityName, Guid.Parse(ConnectContact.fromrecordid)); ContactExists = CheckIfRecordExists(FromEntityContact); } ToEntityAccount = new EntityReference(ToEntityName, Guid.Parse(ConnectContact.torecordid)); localcontext.Trace("before validating details new"); Boolean AccountExists = CheckIfRecordExists(ToEntityAccount); localcontext.Trace("after validating"); if (ContactExists && AccountExists) { #region Getting connection role IDs List <String> RoleNames = new List <string>(); if (ConnectContact.relations.fromrole != null) { RoleNames.Add(ConnectContact.relations.fromrole); RoleCountToCheck = RoleCountToCheck + 1; } if (ConnectContact.relations.torole != null) { RoleNames.Add(ConnectContact.relations.torole); RoleCountToCheck = RoleCountToCheck + 1; } RoleNames.Add(SCS.Connection.PRIMARYUSERROLENAME); localcontext.Trace("before getting role name"); List <Entity> RolesList = GetRoles(RoleNames); localcontext.Trace("after getting role name"); EntityReference FromEntityRole = null; EntityReference ToEntityRole = null; EntityReference PrimaryUserRole = null; foreach (Entity ConnectionRoles in RolesList) { if (ConnectContact.relations.fromrole == (string)ConnectionRoles[SCS.Connection.NAME]) { localcontext.Trace("received from role id"); FromEntityRole = new EntityReference(ConnectionRoles.LogicalName, ConnectionRoles.Id); } if (ConnectContact.relations.torole == (string)ConnectionRoles[SCS.Connection.NAME]) { localcontext.Trace("received to role id"); ToEntityRole = new EntityReference(ConnectionRoles.LogicalName, ConnectionRoles.Id); } if (SCS.Connection.PRIMARYUSERROLENAME == (string)ConnectionRoles[SCS.Connection.NAME]) { localcontext.Trace("received to primary role id"); PrimaryUserRole = new EntityReference(ConnectionRoles.LogicalName, ConnectionRoles.Id); } } if (!String.IsNullOrEmpty(ConnectContact.relations.fromrole) && FromEntityRole == null) { //from role not found ErrorCode = 404; _ErrorMessage = String.Format("From role {0} not found.", ConnectContact.relations.fromrole); } if (ToEntityRole == null) { //to role not found ErrorCode = 404; _ErrorMessage = String.Format("To role {0} not found.", ConnectContact.relations.torole); } if (PrimaryUserRole == null) { //primary role not found ErrorCode = 404; _ErrorMessage = String.Format("Primary rolenot found."); } #endregion localcontext.Trace("after performing common chencks"); localcontext.Trace("error" + _ErrorMessage); localcontext.Trace("roles count" + RoleCountToCheck); Guid?ToEntityRoleID = ToEntityRole == null ? Guid.Empty : ToEntityRole.Id; if (_ErrorMessage == string.Empty) { if (FromEntityRole != null && ToEntityRole != null) { localcontext.Trace("case when both role ids present"); // check if reverse connection exists if (CheckIfReverseConnectionRoleExists(FromEntityRole, ToEntityRole)) { localcontext.Trace("checking for reverse connection"); if (IsSameConnectionExists(FromEntityContact, ToEntityAccount, FromEntityRole.Id , ToEntityRole.Id)) { //connection already exists ErrorCode = 412; _ErrorMessage = "Connection already exists"; } else { //check if there is any other contact as a primary user for the same account localcontext.Trace("before primary check"); if (!CheckifSingleRoleAlreadyExists(ToEntityAccount, PrimaryUserRole.Id)) { //create primary connection localcontext.Trace("before creating primary connection"); CreateSingleConnection(FromEntityContact, ToEntityAccount, PrimaryUserRole.Id); } if (FromEntityRole != null && ToEntityRoleID != null) { ToConnectId = CreateDoubleConnection(FromEntityContact, ToEntityAccount, FromEntityRole.Id, ToEntityRole.Id); } else if (FromEntityRole == null && ToEntityRole != null) { ToConnectId = CreateSingleConnection(FromEntityContact, ToEntityAccount, ToEntityRole.Id); } else if (FromEntityRole != null && ToEntityRole == null) { ToConnectId = CreateSingleConnection(FromEntityContact, ToEntityAccount, FromEntityRole.Id); } ErrorCode = 200; } } else { _ErrorMessage = String.Format("From role {0} and reverse role {1} combination doesn't exists.", ConnectContact.relations.fromrole, ConnectContact.relations.torole); } } else { //single conneciton localcontext.Trace("checking if single connection exists"); if (CheckifSingleRoleAlreadyExists(ToEntityAccount, ToEntityRole.Id)) { //connection already ErrorCode = 412; _ErrorMessage = "Connection already exists"; } else { //check if there are any other contact as a primary user for the same account if (!CheckifSingleRoleAlreadyExists(ToEntityAccount, PrimaryUserRole.Id)) { //create primary connection CreateSingleConnection(FromEntityContact, ToEntityAccount, PrimaryUserRole.Id); } ToConnectId = CreateSingleConnection(FromEntityContact, ToEntityAccount, ToEntityRole.Id); ErrorCode = 200; } } } #endregion } { if (!ContactExists & !AccountExists) { ErrorCode = 404; _ErrorMessage = String.Format(@"Contact id {0} does not exists and Account id{1} does not exists", ConnectContact.fromrecordid, ConnectContact.torecordid); } else if (!ContactExists) { ErrorCode = 404; _ErrorMessage = String.Format("Contact id {0} does not exists", ConnectContact.fromrecordid); } else if (!AccountExists) { ErrorCode = 404; _ErrorMessage = String.Format("Account id {0} does not exists", ConnectContact.torecordid); } } } else { localcontext.Trace("inside validation result"); //this will throw an error foreach (ValidationResult vr in ValidationResultsConnectContact) { ErrorMessage.Append(vr.ErrorMessage + " "); } if (ConnectContact.relations != null) { foreach (ValidationResult vr in ValidationResultsRoles) { ErrorMessage.Append(vr.ErrorMessage + " "); } } ErrorCode = 400; _ErrorMessage = ErrorMessage.ToString(); } } #region Catch Exception catch (Exception ex) { crmWorkflowContext.Trace("inside catch"); crmWorkflowContext.Trace("exception message: " + ex.Message); ErrorCode = 500; _ErrorMessage = ex.Message; _ErrorMessageDetail = ex.Message; // crmWorkflowContext.Trace(String.Format("message details {0}", ex.Message)); //_ErrorMessageDetail = ex.Message ; ErrorCode = 400; this.response.Set(executionContext, _ErrorMessageDetail); //throw ex; } #endregion #region Finally Block finally { if (ToConnectId.HasValue && !ToConnectId.Value.Equals(Guid.Empty)) { localcontext.Trace("started retreiving connection detailsid"); Entity connectionEntity = localcontext.OrganizationService.Retrieve(SCS.Connection.CONNECTIONENTITY, new Guid(ToConnectId.ToString()), new ColumnSet("defra_connectiondetailsid")); EntityReference connectionDetails = (EntityReference)connectionEntity.Attributes["defra_connectiondetailsid"]; ConnectionDetailsId = connectionDetails.Id; localcontext.Trace("started retreiving connection detailsid:" + ConnectionDetailsId); } SCIIR.ConnectContactResponse responsePayload = new SCIIR.ConnectContactResponse() { code = ErrorCode, message = _ErrorMessage, datetime = DateTime.UtcNow, version = "1.0.0.2", program = "Create relatioship", status = ErrorCode == 200 || ErrorCode == 412 ? "success" : "failure", data = new SCIIR.ConnectContactData() { connectionid = ToConnectId.HasValue ? ToConnectId.Value.ToString() : string.Empty, connectiondetailsid = ConnectionDetailsId.HasValue ? ConnectionDetailsId.Value.ToString() : string.Empty } }; string resPayload = JsonConvert.SerializeObject(responsePayload); response.Set(executionContext, resPayload); localcontext.Trace("finally block end"); } #endregion }
/// <summary> /// Executes the WorkFlow. /// </summary> /// <param name="crmWorkflowContext">The <see cref="LocalWorkflowContext"/> which contains the /// <param name="executionContext" > <see cref="CodeActivityContext"/> /// </param> /// <remarks> /// For improved performance, Microsoft Dynamics 365 caches WorkFlow instances. /// The WorkFlow's Execute method should be written to be stateless as the constructor /// is not called for every invocation of the WorkFlow. Also, multiple system threads /// could execute the WorkFlow at the same time. All per invocation state information /// is stored in the context. This means that you should not use global variables in WorkFlows. /// </remarks> public override void ExecuteCRMWorkFlowActivity(CodeActivityContext executionContext, LocalWorkflowContext crmWorkflowContext) { if (executionContext == null) { throw new ArgumentNullException(nameof(executionContext)); } var tracingService = executionContext.GetExtension <ITracingService>(); var returnString = Guid.NewGuid().ToString("N"); tracingService.Trace("SaveAndReturnId = '{0}'", returnString); SaveAndReturnId.Set(executionContext, returnString); }