locked
How to Attach Annotation File to Email Attachment in Crm 2011 RRS feed

  • Question

  • Hi,

    I have a requirement to attach lead annotation content to email attachments. 

    i can able to retrieve annotation file , but while setting into activitymimeattachment itz not able to set. 

    using bellow link . 

    http://www.resultondemand.nl/support/sdk/4c27c9ae-c0e8-4de4-bba7-bf957a873ff5.htm

    here i am getting annotation id and setting in activitymime. 

    ActivityMimeAttachment _reuseAttachment = new ActivityMimeAttachment
    {
       ObjectId = new EntityReference("annotation", "GUID"),
       ObjectTypeCode = "annotation",
       Subject = "Sample Attachment,
       AttachmentId = retrievedAttachment.annotationID
    };

    Grateful for any help!!

    Monday, August 19, 2013 9:37 AM

Answers

  • By the way, I think the reason it's not working using the existing attachment is because you're going from Note to Email Attachment, rather than Email Attachment to Email Attachment.

    Here is a working example of copying the attributes (using late binding):

                Entity note = _sdk.Retrieve("annotation", leadNoteId, new ColumnSet(true));
    
                Entity attachment = new Entity("activitymimeattachment");
                attachment["subject"] = note["subject"];
                attachment["filename"] = note["filename"];
                attachment["body"] = note["documentbody"];
                attachment["mimetype"] = note["mimetype"];
                attachment["objectid"] = new EntityReference("email", emailId);
                attachment["objecttypecode"] = "email";
    
                service.Create(attachment);

    Hope that helps

    Paul


    If my response helped you find your answer please show your thanks by taking the time to "Mark As Answer" and "Vote As Helpful".

    Twitter LinkedIn Facebook Blog Magnetism

    • Marked as answer by kMAT1 Monday, August 19, 2013 11:16 AM
    Monday, August 19, 2013 11:05 AM

All replies

  • It looks like you're trying to reference the existing attachment, however you'll need to create a new attachment by copying across the values.

    Take a look at this article:

    http://rajeevpentyala.wordpress.com/2012/07/03/adding-file-as-attachment-to-entities-programmatically-in-plug-in/

    That'll give you the attributes you need to be setting. You shouldn't need to encode anything though since you're already getting the encoded attachment body.

    Make sure to specify the filename, body, and mimetype (you should be able to get all of these from the existing attachment object).

    Hope that helps

    Paul


    If my response helped you find your answer please show your thanks by taking the time to "Mark As Answer" and "Vote As Helpful".

    Twitter LinkedIn Facebook Blog Magnetism

    Monday, August 19, 2013 10:41 AM
  • By the way, I think the reason it's not working using the existing attachment is because you're going from Note to Email Attachment, rather than Email Attachment to Email Attachment.

    Here is a working example of copying the attributes (using late binding):

                Entity note = _sdk.Retrieve("annotation", leadNoteId, new ColumnSet(true));
    
                Entity attachment = new Entity("activitymimeattachment");
                attachment["subject"] = note["subject"];
                attachment["filename"] = note["filename"];
                attachment["body"] = note["documentbody"];
                attachment["mimetype"] = note["mimetype"];
                attachment["objectid"] = new EntityReference("email", emailId);
                attachment["objecttypecode"] = "email";
    
                service.Create(attachment);

    Hope that helps

    Paul


    If my response helped you find your answer please show your thanks by taking the time to "Mark As Answer" and "Vote As Helpful".

    Twitter LinkedIn Facebook Blog Magnetism

    • Marked as answer by kMAT1 Monday, August 19, 2013 11:16 AM
    Monday, August 19, 2013 11:05 AM
  • Following is the code for attaching the "n" no.of Annotation notes and attachments(Attached before sending),of a Contact record and sending via email using Workflow. If the Workflow needs to be triggered with a Custom button then please go through the following  for JS

    using System;
    using System.Activities;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using Microsoft.Crm.Sdk.Messages;
    using Microsoft.Xrm.Sdk;
    using Microsoft.Xrm.Sdk.Query;
    using Microsoft.Xrm.Sdk.Workflow;
    
    namespace WF_SendEmailWithAttachment
    {
        public class SendEmail : CodeActivity
        {
            //define variable
    	[Input("SourceEmail")]
            [ReferenceTarget("email")]
            public InArgument<EntityReference> SourceEmail { get; set; }
            private Guid RecordContactID;
            public Guid RecordContactID1
            {
                get { return RecordContactID; }
                set { RecordContactID = value; }
            }
    
            protected override void Execute(CodeActivityContext executionContext)
            {
                ITracingService tracingService = executionContext.GetExtension<ITracingService>();
                // Get workflow context
                IWorkflowContext context = executionContext.GetExtension<IWorkflowContext>();
                //Create service factory
                IOrganizationServiceFactory serviceFactory = executionContext.GetExtension<IOrganizationServiceFactory>();
                // Create Organization service
                IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);
                // Get the target entity from the context
                Entity ContactID = (Entity)service.Retrieve("contact", context.PrimaryEntityId, new ColumnSet(new string[] { "contactid" }));
                RecordContactID = ContactID.Id;
                AddAttachmentToEmailRecord(service, ContactID.Id, SourceEmail.Get<EntityReference>(executionContext));
                tracingService.Trace("SourceEmail", SourceEmail);
            }
    
            public void AddAttachmentToEmailRecord(IOrganizationService service, Guid SourceContactID, EntityReference SourceEmailID)
            {
                         //create email object    
                Entity _ResultEntity = service.Retrieve("email", SourceEmailID.Id, new ColumnSet(true));
                QueryExpression _QueryNotes = new QueryExpression("annotation");
                _QueryNotes.ColumnSet = new ColumnSet(new string[] { "subject", "mimetype", "filename", "documentbody"  });
                _QueryNotes.Criteria = new FilterExpression();
                _QueryNotes.Criteria.FilterOperator = LogicalOperator.And;
                _QueryNotes.Criteria.AddCondition(new ConditionExpression("objectid", ConditionOperator.Equal, RecordContactID));     
                EntityCollection _MimeCollection = service.RetrieveMultiple(_QueryNotes);
                if (_MimeCollection.Entities.Count > 0)
                {  
                    //Fetch all attachments
    
                    foreach (var item in _MimeCollection.Entities)
                    {
                        //Entity _NotesAttachment = _MimeCollection.Entities.First();     
                        //Create email attachment
                        Entity _EmailAttachment = new Entity("activitymimeattachment");
                        if (item.Contains("subject"))
                         _EmailAttachment["subject"] = item["subject"];
                        _EmailAttachment["objectid"] = new EntityReference("email", _ResultEntity.Id);
                        _EmailAttachment["objecttypecode"] = "email";
                        if (item.Contains("filename"))
                            _EmailAttachment["filename"] = item["filename"];
                        if (item.Contains("documentbody"))
                            _EmailAttachment["body"] = item["documentbody"];
                       if (item.Contains("mimetype"))
                            _EmailAttachment["mimetype"] = item["mimetype"];
                        service.Create(_EmailAttachment);
                    }
                }
           // Sending email
    
                SendEmailRequest SendEmail = new SendEmailRequest();
                SendEmail.EmailId = _ResultEntity.Id;
                SendEmail.TrackingToken = "";
                SendEmail.IssueSend = true;
                SendEmailResponse res = (SendEmailResponse)service.Execute(SendEmail);
            }
        }
    }

    JS To Trigger Workflow through Custom Button

    function TriggerWorkflow() 
    {
     // Get the Workflow ID
     var workflowId = GetProcessId();
     if (workflowId[0].results.length > 0) 
     {
      var xml = "" +
      "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
      "<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">" +
      GenerateAuthenticationHeader() +
      "<soap:Body>" +
      "<Execute xmlns=\"http://schemas.microsoft.com/crm/2007/WebServices\">" +
      "<Request xsi:type=\"ExecuteWorkflowRequest\">" +
      "<EntityId>" + Xrm.Page.data.entity.getId() + "</EntityId>" +
      "<WorkflowId>" + workflowId[0].results[0].WorkflowId + "</WorkflowId>" +
      "</Request>" +
      "</Execute>" +
      "  </soap:Body>" +
      "</soap:Envelope>" +
      "";
      var xmlHttpRequest = new ActiveXObject("Msxml2.XMLHTTP");
      xmlHttpRequest.Open("POST", "/mscrmservices/2007/CrmService.asmx", true);
      xmlHttpRequest.setRequestHeader("SOAPAction", "http://schemas.microsoft.com/crm/2007/WebServices/Execute");
      xmlHttpRequest.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
      xmlHttpRequest.setRequestHeader("Content-Length", xml.length);
      xmlHttpRequest.send(xml);
     }
    }
    
    function GetProcessId() {
     // Pass the workflow name manually to get the Id of the workflow
     var processName = "Name of the Workflow";
    
     // Get the server URL
     var serverUrl = Xrm.Page.context.getServerUrl();
     var oDataUri = serverUrl + "/xrmservices/2011/OrganizationData.svc/WorkflowSet?$select=WorkflowId&$filter=Name eq '" + processName + "' and ActiveWorkflowId/Id ne null";
     var jSonArray = new Array();
    
     jQuery.ajax({
      type: "GET",
      contentType: "application/json; charset=utf-8",
      datatype: "json",
      url: oDataUri,
      async: false,
      beforeSend: function (XMLHttpRequest) {
       XMLHttpRequest.setRequestHeader("Accept", "application/json");
      },
      success: function (data, textStatus, XmlHttpRequest) {
       if (data && data.d != null) {
        jSonArray.push(data.d);
       }
      },
      error: function (XmlHttpRequest, textStatus, errorThrown) {
       alert("Error :  has occured during retrieval of the workflowId");
      }
     });
     return jSonArray;
    }
    Forget not to download Jquery and upload to your solution to use the above Js snippet


    Friday, September 12, 2014 10:08 AM