/// <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); }
/// <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()); } }
private Loan CallApiMethod(decimal loanAmount, decimal interestRate, int term) { using (HttpClient client = new HttpClient()) { client.BaseAddress = new Uri("https://spfapi.azurewebsites.net/api/cashflow/"); string fragment = $"calculate?loanAmount={loanAmount}&interestRate={interestRate}&term={term}"; TracingService.Trace(fragment); var response = client.GetAsync(fragment).Result; if (response.IsSuccessStatusCode) { string result = response.Content.ReadAsStringAsync().Result; Loan loan = ReadToObject(result); return(loan); } TracingService.Trace(response.RequestMessage.RequestUri.ToString()); TracingService.Trace(response.StatusCode.ToString()); TracingService.Trace(response.Content.ToString()); throw new InvalidPluginExecutionException("Error accessing API"); } }
/// <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()); } }
private void AddInsertFileParametersToRequest(DocumentRelayRequest request, Entity queryRecord) { TracingService.Trace("In AddInsertFileParametersToRequest()"); TracingService.Trace("Logical Name: {0}", queryRecord.LogicalName); var permitNo = GetPermitNumber(queryRecord); var applicationNo = GetApplicationNumber(queryRecord); var fileName = GetFileName(queryRecord); var body = GetBody(queryRecord); var subject = GetSubject(queryRecord); var crmId = GetCrmId(queryRecord); var caseNo = GetCaseFolderName(queryRecord); var regarding = GetRegarding(queryRecord); request.ApplicationContentType = Config[$"{SharePointSecureConfigurationKeys.ApplicationFolderContentType}"]; request.ApplicationNo = applicationNo; request.FileBody = body; request.FileDescription = subject; request.FileName = fileName; request.ListName = Config[$"{SharePointSecureConfigurationKeys.PermitListName}"]; request.PermitContentType = Config[$"{SharePointSecureConfigurationKeys.PermitFolderContentType}"]; request.PermitNo = permitNo; request.Customer = string.Empty; // Not currently set by Document relay, enhancement request.SiteDetails = string.Empty; // Not currently set by Document relay, enhancement request.PermitDetails = string.Empty; // Not currently set by Document relay, enhancement request.CrmId = crmId; request.CaseNo = caseNo; request.EmailRegarding = regarding; AddEmailParametersToRequest(request, queryRecord); TracingService.Trace(string.Format("Requests: {0}", request)); }
internal void ExecuteBase(CodeActivityContext executionContext, XrmWorkflowActivityRegistration xrmWorkflowActivityRegistration) { try { Activity = xrmWorkflowActivityRegistration; ExecutionContext = executionContext; TracingService.Trace( "Entered Workflow {0}\nActivity Instance Id: {1}\nWorkflow Instance Id: {2}\nCorrelation Id: {3}\nInitiating User: {4}", GetType().Name, ExecutionContext.ActivityInstanceId, ExecutionContext.WorkflowInstanceId, Context.CorrelationId, Context.InitiatingUserId); Execute(); } catch (InvalidPluginExecutionException ex) { LogController.LogLiteral(ex.XrmDisplayString()); throw; } catch (Exception ex) { LogController.LogLiteral(ex.XrmDisplayString()); throw new InvalidPluginExecutionException(ex.Message, ex); } }
public void Dispose() { if (TracingService != null) { TracingService.Dispose(); } }
/// <summary> /// Main code activity method /// </summary> /// <param name="executionContext">Standard execution context</param> /// <param name="crmWorkflowContext">Standard workflow context</param> public override void ExecuteCRMWorkFlowActivity(CodeActivityContext executionContext, LocalWorkflowContext crmWorkflowContext) { if (crmWorkflowContext == null) { throw new ArgumentNullException(nameof(crmWorkflowContext)); } TracingService = executionContext.GetExtension <ITracingService>(); Service = crmWorkflowContext.OrganizationService; // 1. Validation EntityReference applicatEntityReference = this.Application.Get(executionContext); if (applicatEntityReference == null) { TracingService.Trace("Application parameter not set."); return; } TracingService.Trace("Refreshing Answers for Application {0} ", applicatEntityReference.Id); // 2. Processing - add and remove application answers as dictated by the application lines DataAccessApplicationAnswers dal = new DataAccessApplicationAnswers(this.Service, this.TracingService); dal.RefreshApplicationAnswers(applicatEntityReference.Id); TracingService.Trace("Done refreshing Answers for Application {0} ", applicatEntityReference.Id); }
private XmlDocument RetrieveXmlWebResourceByName(string webresourceSchemaName) { TracingService.Trace("Begin:RetrieveXmlWebResourceByName, webresourceSchemaName={0}", webresourceSchemaName); QueryExpression webresourceQuery = new QueryExpression("webresource") { NoLock = true }; webresourceQuery.ColumnSet.AddColumn("content"); webresourceQuery.Criteria.AddCondition("name", ConditionOperator.Equal, webresourceSchemaName); EntityCollection webresources = OrganizationService.RetrieveMultiple(webresourceQuery); TracingService.Trace("Webresources Returned from server. Count={0}", webresources.Entities.Count); if (webresources.Entities.Count > 0) { byte[] bytes = Convert.FromBase64String((string)webresources.Entities[0]["content"]); // The bytes would contain the ByteOrderMask. Encoding.UTF8.GetString() does not remove the BOM. // Stream Reader auto detects the BOM and removes it on the text XmlDocument document = new XmlDocument(); document.XmlResolver = null; MemoryStream ms = new MemoryStream(bytes); using (StreamReader sr = new StreamReader(ms)) { document.Load(sr); } TracingService.Trace("End:RetrieveXmlWebResourceByName , webresourceSchemaName={0}", webresourceSchemaName); return(document); } else { TracingService.Trace("{0} Webresource missing. Reinstall the solution", webresourceSchemaName); throw new InvalidPluginExecutionException($"Unable to locate the web resource {webresourceSchemaName}."); } }
/// <summary> /// Associates the <see cref="Contact"/> record to the <see cref="EmailSend"/> record. /// </summary> /// <param name="context"></param> protected override void ExecuteActivity(CodeActivityContext context) { try { string emailAddress = EmailAddress.Get(context); var fetchXml = $@" <fetch top='1'> <entity name='contact'> <attribute name='contactid' /> <filter type='or'> <condition attribute='emailaddress1' operator='eq' value='{emailAddress}'/> <condition attribute='emailaddress2' operator='eq' value='{emailAddress}'/> <condition attribute='emailaddress3' operator='eq' value='{emailAddress}'/> </filter> </entity> </fetch>"; var results = Service.RetrieveMultiple(new FetchExpression(fetchXml)); if (results.Entities.Count > 0) { var contact = results.Entities[0].ToEntityReference(); Contact.Set(context, contact); } } catch (Exception e) { TracingService.Trace("Couldn't search for contact: {0}", e.Message); throw; } }
/// <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 Registered Address for application: {0}", application.Id.ToString()); string returnData = GetCompanyAddress(application); this.CompanyAddress.Set(executionContext, returnData); TracingService.Trace("Company Registered Address: {0}", returnData); }
internal void CreateFolder(EntityReference application) { TracingService.Trace($"In CreateFolder with Entity Type {application.LogicalName} and Entity Id {application.Id}"); var applicationEntity = Query.RetrieveDataForEntityRef(Service, new[] { defra_application.Fields.defra_name, defra_application.Fields.defra_permitnumber, defra_application.Fields.defra_applicationnumber }, application); TracingService.Trace($"Permit Number = {applicationEntity[defra_application.Fields.defra_permitnumber]}; Application Number = {applicationEntity[defra_application.Fields.defra_applicationnumber]}"); var request = new DocumentRelayRequest { ApplicationContentType = Config[$"{SharePointSecureConfigurationKeys.ApplicationFolderContentType}"], ApplicationNo = SharePointFilters.FilterPath(applicationEntity.GetAttributeValue <string>(defra_application.Fields.defra_applicationnumber)), FileBody = string.Empty, FileDescription = string.Empty, FileName = string.Empty, ListName = Config[$"{SharePointSecureConfigurationKeys.PermitListName}"], PermitContentType = Config[$"{SharePointSecureConfigurationKeys.PermitFolderContentType}"], PermitNo = SharePointFilters.FilterPath(applicationEntity.GetAttributeValue <string>(defra_application.Fields.defra_permitnumber)), Customer = string.Empty, SiteDetails = string.Empty, PermitDetails = string.Empty }; var stringContent = JsonConvert.SerializeObject(request); TracingService.Trace($"Data Sent to Logic App URL {Config[$"{SharePointSecureConfigurationKeys.DocumentRelayLogicAppUrl}"]}"); SendRequest(Config[$"{SharePointSecureConfigurationKeys.DocumentRelayLogicAppUrl}"], stringContent); }
/// <summary> /// The entry point of the Rule JS generator. This function constructs the If statement and wraps it with a documentready function. /// </summary> /// <param name="operand1"></param> /// <param name="operatorValue"></param> /// <param name="operand2"></param> /// <param name="operand1Type"></param> /// <param name="positiveJson"></param> /// <param name="negativeJson"></param> /// <returns></returns> public string GenerateJavacript(string ruleName, Guid ruleId, string operand1, int operatorValue, string operand2, string positiveJson, string negativeJson) { try { AttributeTypeCode operand1Type = GetAttributeType(Service, EntityName, operand1); string ifStatement = GenerateIfStatement(operand1, operatorValue, operand2, operand1Type); string ifTrueBody = GenerateIfElseBody(positiveJson, operand1Type); string ifFalseBody = GenerateIfElseBody(negativeJson, operand1Type); string finalOutput = ConstructFinalOutput(operand1, operand1Type, ifStatement, ifTrueBody, ifFalseBody); return(finalOutput); } catch (InvalidCastException castException) { castException.Data.Add("RuleName", ruleName); castException.Data.Add("RuleId", ruleId); TracingService.Trace("An invalid cast exception has been caught."); throw castException; } catch (Exception ex) { throw ex; } }
protected void Trace(string trace) { if (TracingService != null) { TracingService.Trace(trace); } }
/* * Checks if sum of all related agreement's paid invoices is bigger than it's own sum. * * invoice - lys_invoice. * * Returns true if sum of all related agreement's paid invoices <= agreement sum; false otherwise. */ private bool ValidateRelatedAgreementInvoicesSum(lys_invoice invoice) { lys_agreement relatedAgreement = new lys_agreement(); BaseRepository <lys_invoice> invoiceRepo = new BaseRepository <lys_invoice>(Service, lys_invoice.EntityLogicalName); // Checking if invoice contains related agreement ID. If not, obtaining it from CRM. if (invoice.lys_dogovorid != null) { relatedAgreement.Id = invoice.lys_dogovorid.Id; } else { relatedAgreement.Id = invoiceRepo.Get(invoice.Id, new ColumnSet(lys_invoice.Fields.lys_dogovorid)).lys_dogovorid.Id; } // Getting related agreement sum. BaseRepository <lys_agreement> agreementRepo = new BaseRepository <lys_agreement>(Service, lys_agreement.EntityLogicalName); relatedAgreement = agreementRepo.Get(relatedAgreement.Id, new ColumnSet(lys_agreement.Fields.lys_summ)); TracingService.Trace($"relatedAgreementId={relatedAgreement.Id}, invoiceId={invoice.Id}"); // Getting related paid invoices sum. Decimal totalPaidInvoiceSum = GetRelatedNavInvoicesSum(relatedAgreement.Id); return(totalPaidInvoiceSum <= relatedAgreement.lys_summ.Value); }
/// <summary> /// Logs a message to the trace log /// </summary> /// <param name="message">The message to log</param> protected void Trace(string message) { if (TracingService != null) { TracingService.Trace(message); } }
/* * Updates lys_fact and lys_factsum fields of invoice's related agreement based on all it's related paid invoices. * * invoice - lys_invoice; * invoicesToExclude - IDs of lys_invoices to exclude from the related invoices list. * * Returns true if updated, false otherwise. */ public bool UpdateRelatedAgreementFactData(lys_invoice invoice, params Guid[] invoicesToExclude) { Guid relatedAgreementId; BaseRepository <lys_invoice> invoiceRepo = new BaseRepository <lys_invoice>(Service, lys_invoice.EntityLogicalName); BaseRepository <lys_agreement> agreementRepo = new BaseRepository <lys_agreement>(Service, lys_agreement.EntityLogicalName); // Checking if invoice contains related agreement ID. If not, obtaining it from CRM.) if (invoice.lys_dogovorid != null) { relatedAgreementId = invoice.lys_dogovorid.Id; } else { relatedAgreementId = invoiceRepo.Get(invoice.Id, new ColumnSet(lys_invoice.Fields.lys_dogovorid)).lys_dogovorid.Id; } TracingService.Trace($"relatedAgreementId={relatedAgreementId}"); // Obtaining related agreement sum from CRM. lys_agreement relatedAgreement = agreementRepo.Get(relatedAgreementId, new ColumnSet(lys_agreement.Fields.lys_summ)); // Getting total paid invoices sum. Decimal totalPaidInvoiceSum = GetRelatedNavInvoicesSum(relatedAgreementId, invoicesToExclude); relatedAgreement.lys_factsumma = new Money(totalPaidInvoiceSum); relatedAgreement.lys_fact = relatedAgreement.lys_summ.Value == totalPaidInvoiceSum; // Updating related agreement. agreementRepo.Update(relatedAgreement); TracingService.Trace($"Updated agreement with ID={relatedAgreementId}, totalPaidInvoiceSum={totalPaidInvoiceSum}, lys_fact={relatedAgreement.lys_fact}."); return(true); }
/* * Retrieves sum of all agreement's related paid invoices. * * agreementId - GUID of lys_agreementl; * invoicesToExclude - IDs of lys_invoices to exclude from the related invoices list. * * returns sum of all agreement's related paid invoices lys_amounts. */ private Decimal GetRelatedNavInvoicesSum(Guid agreementId, params Guid[] invoicesToExclude) { QueryExpression query = new QueryExpression(); query.EntityName = lys_invoice.EntityLogicalName; query.Criteria.AddCondition(lys_invoice.Fields.lys_dogovorid, ConditionOperator.Equal, agreementId); query.Criteria.AddCondition(lys_invoice.Fields.lys_fact, ConditionOperator.Equal, true); foreach (Guid guid in invoicesToExclude) { query.Criteria.AddCondition(lys_invoice.Fields.lys_invoiceId, ConditionOperator.NotEqual, guid); } query.ColumnSet = new ColumnSet(lys_invoice.Fields.lys_amount); BaseRepository <Entity> entitiesRepo = new BaseRepository <Entity>(Service, lys_invoice.EntityLogicalName); EntityCollection ec = entitiesRepo.GetMultiple(query); TracingService.Trace($"Retrieved lys_invoices. ec={ec}, ec.Entities={ec.Entities}, ec.Entities.Count={ec.Entities.Count}"); decimal totalInvoiceAmount = 0M; foreach (Entity invoice in ec.Entities) { totalInvoiceAmount += invoice.GetAttributeValue <Money>(lys_invoice.Fields.lys_amount).Value; } return(totalInvoiceAmount); }
private IEnumerable <KeyValuePair <string, string> > EnumeratePostedFields(IOrganizationService service, Guid postedFormId) { TracingService.Trace("EnumberatePostedFields"); // Query posted fields referenced in Posted Form. string fetchXml = @" <fetch> <entity name='cdi_postedfield' > <attribute name='cdi_value' /> <filter> <condition attribute='cdi_postedformid' operator='eq' value='{0}' /> </filter> <link-entity name='cdi_formfield' from='cdi_formfieldid' to='cdi_formfieldid' alias='field' > <attribute name='cdi_fieldid' /> </link-entity> </entity> </fetch> "; fetchXml = string.Format(fetchXml, postedFormId); EntityCollection resultCollection = service.RetrieveMultiple(new FetchExpression(fetchXml)); foreach (var e in resultCollection.Entities) { if (e.Contains("cdi_value")) { var result = new KeyValuePair <string, string>( (string)e.GetAttributeValue <AliasedValue>("field.cdi_fieldid").Value, (string)e["cdi_value"]); TracingService.Trace("Enumerating posted field {0} ({1})", result.Key, result.Value); yield return(result); } } }
private Deal CallApiMethod(decimal acquisitionCosts, string loanType) { using (HttpClient client = new HttpClient()) { var builder = new UriBuilder("https://spfapi.azurewebsites.net/api/cashflow/calculatespf"); var query = HttpUtility.ParseQueryString(string.Empty); query["acquisitionCosts"] = acquisitionCosts.ToString(); query["loanType"] = loanType; builder.Query = query.ToString(); builder.Query = query.ToString(); string url = builder.ToString(); TracingService.Trace(url); var response = client.GetAsync(url).Result; if (response.IsSuccessStatusCode) { string result = response.Content.ReadAsStringAsync().Result; Deal deal = ReadToObject(result); return(deal); } TracingService.Trace(response.RequestMessage.RequestUri.ToString()); TracingService.Trace(response.StatusCode.ToString()); TracingService.Trace(response.Content.ToString()); throw new InvalidPluginExecutionException("Error accessing API"); } }
public void Trace(string message) { if (TracingService == null || string.IsNullOrWhiteSpace(message)) { return; } TracingService.Trace(message); }
private void SafeTrace(string message, params object[] o) { if (string.IsNullOrWhiteSpace(message) || TracingService == null) { return; } TracingService.Trace(message, o); }
/// <summary> /// Returns a list of task definitions that apply to an application /// </summary> /// <param name="applicationId">Application Guid</param> /// <param name="filterByTaskTypeIds">Task Types to filter by</param> /// <returns>List of defra_applicationtaskdefinition ids </returns> public List <ApplicationTaskAndDefinitionId> GetApplicationTaskIdsLinkedToApplication(Guid applicationId, params Guid[] filterByTaskTypeIds) { TracingService.Trace($"GetApplicationTaskIdsLinkedToApplication({applicationId}, {filterByTaskTypeIds}) Start..."); // Select defra_applicationtask records var query = new QueryExpression(defra_applicationtask.EntityLogicalName); query.ColumnSet.AddColumns(defra_applicationtask.Fields.defra_applicationtaskId, defra_applicationtask.Fields.defra_applicationtaskdefinitionid); query.Criteria.AddCondition(defra_applicationtask.Fields.StateCode, ConditionOperator.Equal, (int)defra_applicationtaskState.Active); query.Criteria.AddCondition(defra_applicationtask.Fields.defra_applicationid, ConditionOperator.Equal, applicationId); // Link to defra_applicationtaskdefinition var linkToTaskDefinition = query.AddLink( defra_applicationtaskdefinition.EntityLogicalName, defra_applicationtask.Fields.defra_applicationtaskdefinitionid, defra_applicationtaskdefinition.Fields.defra_applicationtaskdefinitionId); linkToTaskDefinition.LinkCriteria.AddCondition( defra_applicationtaskdefinition.Fields.StateCode, ConditionOperator.Equal, (int)defra_applicationtaskdefinitionState.Active); // Filter by specific Task Types (e.g. duly making checklist) if (filterByTaskTypeIds != null && filterByTaskTypeIds.Length > 0) { var filterByTaskType = new FilterExpression(); linkToTaskDefinition.LinkCriteria.AddFilter(filterByTaskType); filterByTaskType.FilterOperator = LogicalOperator.Or; foreach (Guid taskTypeId in filterByTaskTypeIds) { filterByTaskType.AddCondition(defra_tasktype.Fields.defra_tasktypeId, ConditionOperator.Equal, taskTypeId); } } // Query CRM EntityCollection entityCollectionResult = OrganisationService.RetrieveMultiple(query); List <ApplicationTaskAndDefinitionId> retVal = null; // Return a list of defra_applicationtaskdefinition ids if (entityCollectionResult?.Entities != null) { TracingService.Trace($"GetApplicationTaskIdsLinkedToApplication() Returning data"); retVal = entityCollectionResult.Entities .Select(e => new ApplicationTaskAndDefinitionId { ApplicationTaskId = e.GetAttributeIdOrDefault(defra_applicationtask.Fields.defra_applicationtaskId), ApplicationTaskDefinitionId = e.GetAttributeIdOrDefault(defra_applicationtask.Fields.defra_applicationtaskdefinitionid) }).ToList(); } retVal?.ForEach(t => TracingService.Trace($"GetApplicationTaskIdsLinkedToApplication - ApplicationTaskId={t.ApplicationTaskId}, ApplicationTaskDefinitionId={t.ApplicationTaskDefinitionId}")); TracingService.Trace("GetApplicationTaskIdsLinkedToApplication() Done"); return(retVal); }
private void UploadAttachment(Guid recordId) { var request = new DocumentRelayRequest(); // Email attachment has been created. Query CRM to get the email attachment data var attachmentData = ReturnAttachmentData(recordId); if (attachmentData == null) { throw new InvalidPluginExecutionException("No attachment data record returned from query"); } var regardingObjectId = GetRegardingObjectId(attachmentData); if (regardingObjectId != null && (regardingObjectId.LogicalName == Application.EntityLogicalName || regardingObjectId.LogicalName == Case.EntityLogicalName)) { var direction = (bool)(attachmentData.GetAttributeValue <AliasedValue>($"email.{Email.Fields.DirectionCode}")).Value; var statusCode = (OptionSetValue)(attachmentData.GetAttributeValue <AliasedValue>($"email.{Email.Fields.StatusCode}")).Value; if (direction && statusCode.Value != 3) { //Outgoing email, do not send the attachment on create TracingService.Trace("Aborted creating attachment for outgoing email attachment that is not sent"); return; } AddInsertFileParametersToRequest(request, attachmentData); // Check there is a file to upload if (request.HasBody()) { var resultBody = SendRequest(Config[SharePointSecureConfigurationKeys.DocumentRelayLogicAppUrl], JsonConvert.SerializeObject(request)); if (resultBody != null) { TracingService.Trace("Returned from LogicApp OK"); // Get the response object DocumentRelayResponse response = JsonConvert.DeserializeObject <DocumentRelayResponse>(resultBody); TracingService.Trace($"Returned from LogicApp OK, doc url is: {response.link}"); // Create document record CreateApplicationDocument(attachmentData, request.FileDescription, request.FileName, response.link); // Delete Attachment Service.Delete(attachmentData.LogicalName, attachmentData.Id); } } else { TracingService.Trace("No file body found for Attachment. Logic app not called."); } } else { TracingService.Trace("Only attachments for emails regarding Applications, RFIs or Schedule 5s are currently sent to SharePoint"); } }
private void ProcessAttachments() { var azureInterface = new AzureInterface(AdminService, Service, TracingService); var results = Service.GetEmailAndAttachmentsForId(Context.PrimaryEntityId); // Call the plugin to upload the email and all its attachments as files to SharePoint. if (results != null && results.Entities.Count > 0) { var emailUploaded = false; if (results.Entities[0].Contains(Email.Fields.defra_uploadedtosharepoint)) { // annotation and email emailUploaded = results.Entities[0].GetAttributeValue <bool>(Email.Fields.defra_uploadedtosharepoint); } if (!emailUploaded) { TracingService.Trace("Requesting action for Email upload."); azureInterface.SendFileToSharePointActionRequest(Context.PrimaryEntityName, Context.PrimaryEntityId); } else { TracingService.Trace("Email already uploaded to SharePoint"); } // Now process the attachments TracingService.Trace("Processing {0} attachments.", results.Entities.Count.ToString()); foreach (Entity attachment in results.Entities) { var filesize = 0; if (attachment.Contains("attachment.filesize")) { filesize = (int)((AliasedValue)attachment.Attributes["attachment.filesize"]).Value; } var filename = string.Empty; if (attachment.Contains("attachment.filename")) { filename = (string)((AliasedValue)attachment.Attributes["attachment.filename"]).Value; } TracingService.Trace("Attachment Id={0}, filename={1}, size={2}.", attachment.Id.ToString(), filename, filesize.ToString()); if (filesize > 0) { var attachmentId = (Guid)((AliasedValue)attachment.Attributes["attachment.activitymimeattachmentid"]).Value; // Using an action because we don't know how many attachments we'll have. Could take more than process // limit of 2 minutes so using action trigger async plugin. azureInterface.SendFileToSharePointActionRequest(ActivityMimeAttachment.EntityLogicalName, attachmentId); TracingService.Trace("{0} request sent", PluginMessages.SendFileToSharePoint); } else { TracingService.Trace("Attachment has zero filesize. Do not upload.", PluginMessages.SendFileToSharePoint, attachment.Id.ToString()); } } } }
public void Trace(string message) { if (TracingService == null || string.IsNullOrWhiteSpace(message)) { return; } var utcNow = DateTime.UtcNow; TracingService.Trace(message + utcNow.ToString(" | HHmmss.fff", CultureInfo.InvariantCulture)); }
public override void OnUpdate(IPluginExecutionContext context, Entity entity, Guid primaryEntityId) { var message = string.Format("Entity '{0}', Id = '{1}' updated", entity.LogicalName, primaryEntityId); var traceEntity = new Entity("rare_trace"); traceEntity["rare_tracemessage"] = message; SystemOrgService.Create(traceEntity); TracingService.Trace(message); }
public void StopInterfaceTracing() { EnableInterfaceTracingRequest request = new EnableInterfaceTracingRequest(); request.EnableTracingParams = new EnableInterfaceTracingParameters(); request.EnableTracingParams.IsTracingEnabled = false; request.EnableTracingParams.DurationInSeconds = 0; TracingService.EnableInterfaceTracing(request); }
public void StartInterfaceTracing(int duration) { EnableInterfaceTracingRequest request = new EnableInterfaceTracingRequest(); request.EnableTracingParams = new EnableInterfaceTracingParameters(); request.EnableTracingParams.IsTracingEnabled = true; request.EnableTracingParams.DurationInSeconds = duration; TracingService.EnableInterfaceTracing(request); }
internal void UpdateMetaData(EntityReference entity, string customer, string siteDetails, string permitDetails) { TracingService.Trace("In UpdateMetaData with Entity Type {0} and Entity Id {1}", entity.LogicalName, entity.Id.ToString()); var request = new MetaDataRequest(); if (entity.LogicalName == defra_application.EntityLogicalName) { var applicationEntity = Query.RetrieveDataForEntityRef(Service, new[] { Application.Name, Application.PermitNumber, Application.ApplicationNumber, defra_application.Fields.defra_eawmlnumber }, entity); if (applicationEntity != null) { TracingService.Trace($"Permit Number = {applicationEntity[Application.PermitNumber]}; Application Number = {applicationEntity[Application.ApplicationNumber]}"); request.ApplicationNo = SharePointFilters.FilterPath(applicationEntity.GetAttributeValue <string>(Application.ApplicationNumber)); request.ListName = Config[$"{SharePointSecureConfigurationKeys.PermitListName}"]; request.PermitNo = SharePointFilters.FilterPath(applicationEntity.GetAttributeValue <string>(Application.PermitNumber)); request.Customer = customer; request.SiteDetails = siteDetails; request.PermitDetails = permitDetails; request.UpdateType = AzureInterfaceConstants.MetaDataApplicationUpdateType; request.EawmlNo = applicationEntity.GetAttributeValue <string>(defra_application.Fields.defra_eawmlnumber); } else { throw new InvalidPluginExecutionException(string.Format("No Application exists for entity reference {0}", entity.Id.ToString())); } } else if (entity.LogicalName == defra_permit.EntityLogicalName) { var permitEntity = Query.RetrieveDataForEntityRef(Service, new[] { Permit.Name, Permit.PermitNumber, defra_permit.Fields.defra_eawmlnumber }, entity); if (permitEntity != null) { TracingService.Trace(string.Format("Permit Number = {0}", permitEntity[Permit.PermitNumber])); request.ApplicationNo = string.Empty; request.ListName = Config[$"{SharePointSecureConfigurationKeys.PermitListName}"]; request.PermitNo = permitEntity.GetAttributeValue <string>(Permit.PermitNumber); request.Customer = customer; request.SiteDetails = siteDetails; request.PermitDetails = permitDetails; request.UpdateType = AzureInterfaceConstants.MetaDataPermitUpdateType; request.EawmlNo = permitEntity.GetAttributeValue <string>(defra_permit.Fields.defra_eawmlnumber); } else { throw new InvalidPluginExecutionException(string.Format("No Permit exists for entity reference {0}", entity.Id.ToString())); } } var stringContent = JsonConvert.SerializeObject(request); TracingService.Trace($"Data Sent to Logic App URL {Config[$"{SharePointSecureConfigurationKeys.MetadataLogicAppUrl}"]}"); SendRequest(Config[$"{SharePointSecureConfigurationKeys.MetadataLogicAppUrl}"], stringContent); }