目标:
Dynamics CRM 365 online中使用Plugin的PostOperation开发,创建完account后自动创建note
内容:
使用Visual studio 2019开发Plugin dll, 直接贴上如下代码
using Microsoft.Xrm.Sdk;
using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using System.Text;
using System.Threading.Tasks;
namespace Fei_Crm_Plugin
{
public class AccountNoteCreate :IPlugin
{
public void Execute(IServiceProvider serviceProvider)
{
ITracingService tracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService));
IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);
if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)
{
Entity entity = (Entity)context.InputParameters["Target"];
try
{
var welcomeText = entity.Attributes["accountnumber"].ToString();
Entity NoteEntity = new Entity("annotation");
if (NoteEntity != null)
{
NoteEntity.Attributes.Add("subject", $"created on {DateTime.UtcNow.ToString()}");
NoteEntity.Attributes.Add("notetext", $"This is auto note for {welcomeText}");
NoteEntity.Attributes.Add("objectid", entity.ToEntityReference());
Guid note_guid = service.Create(NoteEntity);
}
}
catch (FaultException<OrganizationServiceFault> ex)
{
throw new InvalidPluginExecutionException($"An error occurred in Plug-in {ex.Message.ToString()}", ex);
}
catch (Exception ex)
{
tracingService.Trace($"Fei_Plugin:{ex.ToString()}");
throw;
}
}
}
}
}