Skip to main content

Notifications

Announcements

No record found.

Microsoft Dynamics CRM (Archived)

Exception while trying to send email with a plugin

Posted on by Microsoft Employee
Hello guys

I just started witht programming plugins for our crm and I am trying to create a plugin which should send an Email when a record is beeing updated.
I dont rly know how to add an activity id. Please help me

This is my code:
namespace Hardware_Email_On_Update
{
    public class Hardware_Email_on_Update_Pre_OP : IPlugin
    {
        #region Secure/Unsecure Configuration Setup
        private string _secureConfig = null;
        private string _unsecureConfig = null;

        public Hardware_Email_on_Update_Pre_OP(string unsecureConfig, string secureConfig)
        {
            _secureConfig = secureConfig;
            _unsecureConfig = unsecureConfig;
        }
        #endregion
        public void Execute(IServiceProvider serviceProvider)
        {
            ITracingService tracer = (ITracingService)serviceProvider.GetService(typeof(ITracingService));
            IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
            IOrganizationServiceFactory factory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
            IOrganizationService service = factory.CreateOrganizationService(context.UserId);

            try
            {
                //Die Hardware Entity ansprechen
                Entity entity = (Entity)context.InputParameters["Target"];
                //Alle Attribute holen
                ColumnSet gesuchteAttribute = new ColumnSet(new string[] { "nov_f_aktuelleruser", "nov_name", "nov_f_hardware_os" });
                //Die Guid von Hardware
                Guid entity_Guid = entity.Id;
                //Entity mit Informationen füllen
                entity = service.Retrieve(entity.LogicalName,entity_Guid,gesuchteAttribute);

                string ausgabe = entity["nov_f_aktuelleruser"].ToString();

                updateEmailversenden(service,context,entity);

            
                


                
            }
            catch (Exception e)
            {
                throw new InvalidPluginExecutionException("=(");
            }
        }
        /// <summary>
        /// Diese Methode erstellt eine Email Entity und versendet sie mittels EmailRequest
        /// </summary>
        /// <param name="service"></param>
        /// <param name="context"></param>
        /// <param name="entity"></param>
        public void updateEmailversenden(IOrganizationService service, IPluginExecutionContext context, Entity entity)
        {
            Entity email = new Entity("email"); //Das Email Obcekt
            Entity fromParty = new Entity("activityparty"); //Der Absender
            Entity toParty = new Entity("activityparty"); //Der Empfänger

            toParty["partyid"] = new EntityReference("systemuser", context.UserId); //Hier kann man einen beliebigen CRM User einfügen mittels GUID
            fromParty["partyid"] = new EntityReference("systemuser", context.UserId);
            email["from"] = new Entity[] { fromParty }; //Referenz der Email übergeben (Absender)
            email["to"] = new Entity[] { toParty };//Referenz der Email übergeben (Empfänger)

            email["subject"] = "email subject - " + DateTime.Now.ToString();//Email Betreff
            email["description"] = "email description"; //Vermute hier der Emailtext
            email["regardingobjectid"] = new EntityReference("hardware", entity.Id);// Email mit GUID versehen

            Guid emailId = service.Create(email); <------------ THE EXCEPTION FIRES HERE since it doesnt generate a GUID (look in the Exception)
            SendEmailRequest sendEmailreq = new SendEmailRequest
            {
                EmailId = emailId,
                TrackingToken = "",
                IssueSend = true
            };

            SendEmailResponse sendEmailresp = (SendEmailResponse)service.Execute(sendEmailreq);
        }
    }
}
this is the exception I get after I debugged my code:
Unhandled Exception: System.ServiceModel.FaultException`1[[Microsoft.Xrm.Sdk.OrganizationServiceFault, Microsoft.Xrm.Sdk, Version=8.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35]]: Klappt nicht
Detail: <OrganizationServiceFault xmlns="schemas.microsoft.com/.../Contracts" xmlns:i="www.w3.org/.../XMLSchema-instance">
  <ActivityId>00000000-0000-0000-0000-000000000000</ActivityId>
  <ErrorCode>-2147220970</ErrorCode>
  <ErrorDetails xmlns:a="schemas.datacontract.org/.../System.Collections.Generic">
    <KeyValuePairOfstringanyType>
      <a:key>CallStack</a:key>
      <a:value i:type="b:string" xmlns:b="www.w3.org/.../XMLSchema">   bei Hardware_Email_On_Update.Hardware_Email_on_Update_Pre_OP.Execute(IServiceProvider serviceProvider)
   bei PluginProfiler.Library.PluginAppDomainProxy.ExecuteCore(Stopwatch watch, ProfilerExecutionReport report, Object instance, Object executionParameter)
   bei PluginProfiler.Library.AppDomainProxy.Execute(ProfilerExecutionConfiguration configuration, ProfilerExecutionReport report)</a:value>
    </KeyValuePairOfstringanyType>
  </ErrorDetails>
  <Message>Klappt nicht</Message>
  <Timestamp>2018-04-11T09:14:55.9198986Z</Timestamp>
  <ExceptionSource i:nil="true" />
  <InnerFault i:nil="true" />
  <OriginalException i:nil="true" />
  <TraceText i:nil="true" />
</OrganizationServiceFault>

*This post is locked for comments

  • Verified answer
    Community Member Profile Picture
    Community Member Microsoft Employee on at
    RE: Exception while trying to send email with a plugin

    hmm now I have a new issue:

    It is delivering 4 emails insteed of 1.

    EDIT:

    Ok I fixed it by comparing the context.Depth>3 ... since it fired 4 times =)

  • Community Member Profile Picture
    Community Member Microsoft Employee on at
    RE: Exception while trying to send email with a plugin

    yep this was my mistake. I solved it with the following solution:

    email["regardingobjectid"] = new EntityReference(entity.LogicalName, entity.Id);

    Thank you very much, you just saved my day :D

    kind regards

    Artur

  • Verified answer
    Mahendar Pal Profile Picture
    Mahendar Pal 45,095 on at
    RE: Exception while trying to send email with a plugin

    In addition to that you should first capture FaultException exception in your code

    try{

    //code

    }

    catch (FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault> ex)

    {

    }

    catch (Exception e)

               {

    }

    you can find more details here:msdn.microsoft.com/.../gg327884.aspx

  • Verified answer
    Arpit Shrivastava Profile Picture
    Arpit Shrivastava 7,518 User Group Leader on at
    RE: Exception while trying to send email with a plugin

    Seems you have not specified the correct entity logical  name in below line:

    email["regardingobjectid"] = new EntityReference("hardware", entity.Id);// Email mit GUID versehen

    Please correct the name run the code again.

    Hope it will work.


    If found useful, please mark the answer as verified.


    Cheers
    Arpit
    https://arpitmscrmhunt.blogspot.com

     

  • Community Member Profile Picture
    Community Member Microsoft Employee on at
    RE: Exception while trying to send email with a plugin

    Hi ,

    email["regardingobjectid"] = new EntityReference("hardware", entity.Id);//  

    What's this entity : "hardware" ?? is it a custom one ? i would expect a custom entity to have prefix like "nov_hardware" .  i guess the prefix you are using is nov.

    Can you check the name of the entity and check if it was enabled for Activities in the entity definition .

    you can try  : email["regardingobjectid"] = new EntityReference("nov_hardware", entity.Id);//  or

     email["regardingobjectid"] = new EntityReference( entity.LogicalName, entity.Id);//  

    or directly :  email["regardingobjectid"] = entity.ToEntityReference(); 

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

December Spotlight Star - Muhammad Affan

Congratulations to a top community star!

Top 10 leaders for November!

Congratulations to our November super stars!

Tips for Writing Effective Suggested Answers

Best practices for providing successful forum answers ✍️

Leaderboard

#1
André Arnaud de Calavon Profile Picture

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

#2
Martin Dráb Profile Picture

Martin Dráb 230,188 Most Valuable Professional

#3
nmaenpaa Profile Picture

nmaenpaa 101,156

Leaderboard

Featured topics

Product updates

Dynamics 365 release plans