#c# #plugins #dynamics-365
Вопрос:
Я пытаюсь заставить свой плагин работать и получаю исключение, которое я не уверен, как решить. Плагин должен отправлять электронное письмо при изменении статуса обращения (инцидента).
Я разместил трассировки в нескольких точках кода и выяснил, что исключение происходит в самом конце, когда я пытаюсь отправить электронное письмо с помощью функции выполнения службы OrganizationService.
Вот что я получаю от отслеживания:
Message Block
Get Guids
InstanciateTemplateRequest
Create email
Create email in D365
emailId: cd4204d0-a32d-ec11-b6e5-000d3add9e9a
Send email
Exception Details-Details of the exception.
System.ServiceModel.FaultException`1[Microsoft.Xrm.Sdk.OrganizationServiceFault]: An error occurred in CasePostUpdate Plugin. (Fault Detail is equal to Exception details:
ErrorCode: 0x80040265
Message: An error occurred in CasePostUpdate Plugin.
TimeStamp: 2021-10-15T10:36:57.6376945Z
OriginalException: PluginExecution
ExceptionSource: PluginExecution
--
).
Вот мой код плагина:
using Microsoft.Crm.Sdk.Messages;
using Microsoft.Xrm.Sdk;
using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using System.Text;
using System.Threading.Tasks;
namespace Crm.Plugins
{
public class CasePostUpdate : IPlugin
{
public void Execute(IServiceProvider serviceProvider)
{
// Obtain the tracing service
ITracingService tracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService));
// Obtain the execution context from the service provider.
IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
// The InputParameters collection contains all the data passed in the message request.
if (context.InputParameters.Contains("Target") amp;amp; context.InputParameters["Target"] is Entity)
{
// Obtain the target entity from the input parameters.
Incident target = ((Entity)context.InputParameters["Target"]).ToEntity<Incident>();
Incident postImage = ((Entity)context.PostEntityImages["PostImage"]).ToEntity<Incident>();
// Obtain the organization service reference which you will need for
// web service calls.
IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);
CrmServiceContext crmServiceContex = new CrmServiceContext(service);
try
{
if (context.MessageName.ToLower() != "update")
{
return;
}
tracingService.Trace("Get Guids");
Guid TemplateId = (from x in crmServiceContex.TemplateSet
where x.Title == "Case Status Change"
select x.Id)
.FirstOrDefault();
Guid SenderQueueId = (from x in crmServiceContex.QueueSet
where x.Name == "No-Reply-TrainingD365"
select x.Id)
.FirstOrDefault();
tracingService.Trace("InstanciateTemplateRequest");
// creates and execute request to create email instance from email template
InstantiateTemplateRequest instTemplateReq = new InstantiateTemplateRequest
{
TemplateId = TemplateId,
ObjectId = target.Id,
ObjectType = "incident",
};
InstantiateTemplateResponse instTemplateResp = (InstantiateTemplateResponse)service.Execute(instTemplateReq);
tracingService.Trace("Create email");
// response from above request is entity collection therefore use below syntas to access Email instance
Email email = instTemplateResp.EntityCollection.Entities.FirstOrDefault().ToEntity<Email>();
email.DirectionCode = true;
email.From = new List<Entity> { new Entity() { ["partyid"] = (new EntityReference("queue", SenderQueueId)), LogicalName = "activityparty" } };
email.To = new List<Entity> { new Entity() { ["partyid"] = postImage.OwnerId, LogicalName = "activityparty" } };
email.RegardingObjectId = new EntityReference("incident", postImage.Id);
tracingService.Trace("Create email in D365");
// create email into D365
Guid emailId = service.Create(email);
tracingService.Trace("emailId: " emailId.ToString());
// define and execute request to submit email for delivery
SendEmailRequest request = new SendEmailRequest
{
EmailId = emailId,
TrackingToken = string.Empty,
IssueSend = true,
};
tracingService.Trace("Send email");
SendEmailResponse response = (SendEmailResponse)service.Execute(request);
tracingService.Trace(response.ToString());
}
catch (FaultException<OrganizationServiceFault> ex)
{
throw new InvalidPluginExecutionException("An error occurred in CasePostUpdate Plugin.", ex);
}
catch (Exception ex)
{
tracingService.Trace("CasePostUpdate: {0}", ex.ToString());
throw;
}
}
}
}
}
Комментарии:
1. Это может иметь множество причин. Для эффективной отладки вам нужны два типа данных: сведения об исключении (сообщение, тип исключения и трассировка стека, включая внутренние исключения) и контекстная информация: этап/режим плагина и т. Д. И, предпочтительно, входные параметры, изображения объектов и т. Д. Подробные сведения можно записать с
ITracingService
помощью JSON-сериализации.