Skip to main content

Notifications

Announcements

No record found.

Microsoft Dynamics 365 | Integration, Dataverse...
Unanswered

Cannot insert duplicate key plugin send email in dynamics 365 CRM

(0) ShareShare
ReportReport
Posted on by 2,745 User Group Leader

Hi Experts,

I am trying to send email to all required attendees and optional attendees of an appointment using plugin. It works fine on CREATE message but in update message its throwing error as Duplicate key cannot insert.

here is my code.

using Microsoft.Crm.Sdk.Messages;
using Microsoft.Xrm.Sdk;
using System;

namespace Send_Email_Plugin
{
// Importnant Note-------------------------------------------------------------------------------------------------------------------
// When you are sending emails you have to go to User profile in CRM from which the email gets triggered, and click on "APPROVE EMAIL"
// The Email Box should configured properly.
//-----------------------------------------------------------------------------------------------------------------------------------
public class SendEmail_Plugin : IPlugin
{
public void Execute(IServiceProvider serviceProvider)
{
//Tracing Object
ITracingService tracing = (ITracingService)serviceProvider.GetService(typeof(ITracingService));

//ExecutionContext Object
IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));

//OrganizationServiceFactory Object
IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));

//OrganizationService Object
IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);

string functionName = "Execute";

try
{
EntityCollection requiredAttendees;
EntityCollection optionalAttendees;
EntityReference RegardingEntRef;
Entity appointmentEn;

if (context.MessageName == "Update")
appointmentEn = context != null && context.InputParameters.Contains("Target") ? (Entity)context.PostEntityImages["PostImage"] : null;
else if (context.MessageName == "Create")
appointmentEn = context != null && context.InputParameters.Contains("Target") ? (Entity)context.InputParameters["Target"] : null;
else
return;

tracing.Trace("retrieved entity :" + appointmentEn.LogicalName + "Message:" + context.MessageName);

if (appointmentEn.LogicalName == "appointment")
{
tracing.Trace("validated entity..");
if (appointmentEn.Attributes.Contains("requiredattendees") && appointmentEn.Attributes.Contains("optionalattendees") && appointmentEn.Attributes.Contains("regardingobjectid"))
{
tracing.Trace("Validated attendees");

//read regarding field
RegardingEntRef = appointmentEn.GetAttributeValue<EntityReference>("regardingobjectid");
tracing.Trace("regarding : " + RegardingEntRef.Name);

//read required and optional attendees
requiredAttendees = appointmentEn.Attributes.Contains("requiredattendees") ? appointmentEn.GetAttributeValue<EntityCollection>("requiredattendees") : null;
optionalAttendees = appointmentEn.Attributes.Contains("optionalattendees") ? appointmentEn.GetAttributeValue<EntityCollection>("optionalattendees") : null;
var appointmentSubject = appointmentEn.Attributes.Contains("subject") ? appointmentEn.GetAttributeValue<String>("subject") : null;
var appointmentLocation = appointmentEn.Attributes.Contains("location") ? appointmentEn.GetAttributeValue<String>("location") : null;
var appointdescription = appointmentEn.Attributes.Contains("description") ? appointmentEn.GetAttributeValue<String>("description") : null;

//send email to required attendees
if (requiredAttendees != null && requiredAttendees.Entities.Count > 0)
{
SendEmail(requiredAttendees, appointmentSubject, appointdescription, service, tracing);
}

//send email to optional attendees
if (optionalAttendees != null && optionalAttendees.Entities.Count > 0)
{
SendEmail(requiredAttendees, appointmentSubject, appointdescription, service, tracing);
}
}
}
}
catch (Exception ex)
{
throw new InvalidPluginExecutionException(functionName + ": " + ex.Message);
}
}
public void SendEmail(EntityCollection ec, string subject, string desc, IOrganizationService svc,ITracingService trace)
{
trace.Trace("inside SendEmail EC");
// Create a new EntityCollection and add the all parties
EntityCollection to = new EntityCollection();
foreach (var attendees in ec.Entities)
{
to.Entities.Add(attendees);
}
trace.Trace("after EC");

// Create an email with the EntityCollection
Entity email = new Entity("email");
email["subject"] = subject;
email["to"] = to;
email["description"] = desc;
var eid = svc.Create(email);

trace.Trace("after email create");
SendEmailRequest sendEmailReq = new SendEmailRequest
{
EmailId = eid,
TrackingToken = "",
IssueSend = true
};
SendEmailResponse sendEmailResp = (SendEmailResponse)svc.Execute(sendEmailReq);
trace.Trace("after email sent");
}
}
}

  • Sanjaya Prakash Pradhan Profile Picture
    Sanjaya Prakash Pra... 2,745 User Group Leader on at
    RE: Cannot insert duplicate key plugin send email in dynamics 365 CRM

    As per the requirement I have achieved this using a workflow which is out of the box workflow so no coding is required.

  • erhan.keskin Profile Picture
    erhan.keskin 2,251 on at
    RE: Cannot insert duplicate key plugin send email in dynamics 365 CRM

    Hi Sanjaya,

    You shouldn't use entities from requiredAttendees directly, you need to create your new activity parties for the email, and get party ids from it. Does it make sense?

    regards,

    Erhan

Under review

Thank you for your reply! To ensure a great experience for everyone, your content is awaiting approval by our Community Managers. Please check back later.

Helpful resources

Quick Links

Congratulations 2024 Spotlight Honorees

Kudos to all of our 2024 community stars! 🎉

Meet the Top 10 leaders for December

Congratulations to our December super stars! 🥳

Start Your Super User Journey

Join the ranks of our community heros! 🦹

Leaderboard

#1
André Arnaud de Calavon Profile Picture

André Arnaud de Cal... 291,784 Super User 2024 Season 2

#2
Martin Dráb Profile Picture

Martin Dráb 230,476 Most Valuable Professional

#3
nmaenpaa Profile Picture

nmaenpaa 101,156

Leaderboard

Product updates

Dynamics 365 release plans