locked
Copying e-mail attachment to task attachment using jScript RRS feed

  • Question

  • Hi there,

    We have implemented a function to copy an email to a task for a client.

    Since the newly created task should be opened right away, we have implemented this using jScript.

    The client has now requested that any attachments should be copied with the email, and I have tried to implement this using the REST endpoint (utilizing the CrmRestKit)

    However, I get a Bad Request error when calling the Create method for the new annotation.

    My code:

     

    if (typeof (Sog) == "undefined")
    { Sog= { __namespace: true }; }
    
    // Create Namespace container for functions in this library;
    Sog.Activities = {    
        CopyToTask: function () {
            if (Xrm.Page.data.entity.getIsDirty()) {
                alert(LOCID_CONV_ACT_SAVE_WARNING);
                return false
            }
            if (crmForm.IsValid()) {
                //get info from email
                var subject = Xrm.Page.getAttribute("subject").getValue();
                var description = Xrm.Page.data.entity.attributes.get("description").getValue();
                if (description != null) {
                    if (Xrm.Page.data.entity.getEntityName() == "email" && $(description).text() != "") {
                        description = $(description).text();
                    }
                    var descriptionTrunc = description.substring(0, Math.min(2000, description.length));
                }
                var regardingAtt = Xrm.Page.getAttribute("regardingobjectid").getValue();
                var regardingRef = null;
                if (!IsNull(regardingAtt)) {
                    regardingRef = { Id: regardingAtt[0].id, Name: regardingAtt[0].name, LogicalName: regardingAtt[0].entityType };
                }
    
                var task = { Subject: subject, Description: descriptionTrunc, RegardingObjectId: regardingRef };
                task = CrmRestKit.Create('Task', task);
                //retrieve/copy attachments/notes from email            
                if (Xrm.Page.data.entity.getEntityName() == "email") {
                    var emailActivityId = Xrm.Page.data.entity.getId();
                    Sog.Activities.CopyEmailAttachmentsToTask(task.ActivityId, emailActivityId);
                }
    
                var serverUrl = Xrm.Page.context.getServerUrl();
                if (serverUrl.match(/\/$/)) {
                    serverUrl = serverUrl.substring(0, serverUrl.length - 1);
                }
    
                var URL = serverUrl + "/main.aspx?etn=task&pagetype=entityrecord&id=" + task.ActivityId.toString();
    
                window.open(URL, 'Task', 'width=900, height=1200');
                Xrm.Page.ui.close();
    
            }
    
        },
        CopyEmailAttachmentsToTask: function (taskActivityId, emailActivityId) {
            var columns = ['Subject', 'FileName', 'Body', 'MimeType', 'FileSize'];
            var filter = "ActivityId/Id eq (guid'" + emailActivityId + "')";
            var collection = CrmRestKit.RetrieveMultiple('ActivityMimeAttachment', columns, filter);
            if (collection != null && collection.results != null) {
                for (var i = 0; i < collection.results.length; i++) {
    
                    var subject = "";
                    if (collection.results[i].Subject != null) {
                        subject = collection.results[i].Subject;
                    }
                    // Create new Annotation
                    var annotation = {
                        ObjectTypeCode: 'Task',
                        ObjectId: taskActivityId,
                        NoteText: "Attachment copied from email",
                        Subject: subject,
                        IsDocument: true,
                        MimeType: collection.results[i].MimeType,
                        FileName: collection.results[i].FileName,
                        DocumentBody: collection.results[i].Body
                    };
                    annotation = CrmRestKit.Create('Annotation', annotation);
                }
            }
        }
    }
    

     

    Any suggestions on why the Create request fails?

     

    System spec:

    - Dynamics CRM 2011 On-premise

    - Base language: English

    - Language pack installed: Swedish

    - Update Rollup 2

     

    Thank you!

    /Frida


    Friday, January 13, 2012 3:52 PM

Answers

  • I found the cause myself - I made a mistake in referencing when creating the annotation object - both ObjectTypeCode and ObjectId. The below works correctly:

        CopyEmailAttachmentsToTask: function (task, emailActivityId) {
            var columns = ['Subject', 'FileName', 'Body', 'MimeType', 'FileSize'];
            var filter = "ActivityId/Id eq (guid'" + emailActivityId + "')";
            var collection = CrmRestKit.RetrieveMultiple('ActivityMimeAttachment', columns, filter);
            if (collection != null && collection.results != null) {
                for (var i = 0; i < collection.results.length; i++) {
                    // Create new Annotation
                    var subject = "";
                    if (collection.results[i].Subject != null) {
                        subject = collection.results[i].Subject;
                    }
                    var annotation = {
                        ObjectTypeCode: "task",
                        ObjectId: { Id: task.ActivityId, Name: task.Subject, LogicalName: "task" },
                        NoteText: "Attachment copied from email",
                        Subject: subject,
                        IsDocument: true,
                        MimeType: collection.results[i].MimeType,
                        FileName: collection.results[i].FileName,
                        DocumentBody: collection.results[i].Body
                    };
                    annotation = CrmRestKit.Create('Annotation', annotation);
                }
            }
        },
    

    Monday, January 16, 2012 11:22 AM
  • Hi,

    I modified my original code to copy an appointment to an email, including any attachments. The below seems to work.

    if (typeof (Sog) == "undefined")
    { Sog = { __namespace: true }; }
    
    // Create Namespace container for functions in this library;
    Sog.Activities = {
        CopyToEmail: function () {
            if (Xrm.Page.data.entity.getIsDirty()) {
                alert(LOCID_CONV_ACT_SAVE_WARNING);
                return false
            }
            if (crmForm.IsValid()) {
                //get info from email
                var subject = Xrm.Page.getAttribute("subject").getValue();
                var description = Xrm.Page.data.entity.attributes.get("description").getValue();
                var regardingAtt = Xrm.Page.getAttribute("regardingobjectid").getValue();
                var regardingRef = null;
                if (!IsNull(regardingAtt)) {
                    regardingRef = { Id: regardingAtt[0].id, Name: regardingAtt[0].name, LogicalName: regardingAtt[0].entityType };
                }
    
                var email = { Subject: subject, Description: description, RegardingObjectId: regardingRef };
                email = CrmRestKit.Create('Email', email);
                //retrieve/copy attachments/notes from appointment            
                if (Xrm.Page.data.entity.getEntityName() == "appointment") {
                    var appointmentActivityId = Xrm.Page.data.entity.getId();
                    Sog.Activities.CopyAppointmentAttachmentsToEmail(email, appointmentActivityId);
                }
    
                var serverUrl = Xrm.Page.context.getServerUrl();
                if (serverUrl.match(/\/$/)) {
                    serverUrl = serverUrl.substring(0, serverUrl.length - 1);
                }
    
                var URL = serverUrl + "/main.aspx?etn=email&pagetype=entityrecord&id=" + email.ActivityId.toString();
    
                window.open(URL, 'Email', 'width=900, height=1200');
                Xrm.Page.ui.close();
    
            }
    
        },
        CopyAppointmentAttachmentsToEmail: function (email, appointmentActivityId) {
            var columns = ['Subject', 'FileName', 'DocumentBody', 'MimeType', 'FileSize'];
            var filter = "ObjectId/Id eq (guid'" + appointmentActivityId + "') and IsDocument eq true";
            var collection = CrmRestKit.RetrieveMultiple('Annotation', columns, filter);
            if (collection != null && collection.results != null) {
                for (var i = 0; i < collection.results.length; i++) {
                    // Create new Annotation
                    var subject = "";
                    if (collection.results[i].Subject != null) {
                        subject = collection.results[i].Subject;
                    }
                    var activityMimeAttachment = {
                        ObjectTypeCode: "email",
                        ObjectId: { Id: email.ActivityId, Name: email.Subject, LogicalName: "email" },
                        Subject: subject,
                        MimeType: collection.results[i].MimeType,
                        FileName: collection.results[i].FileName,
                        Body: collection.results[i].DocumentBody
                    };
                    activityMimeAttachment = CrmRestKit.Create('ActivityMimeAttachment', activityMimeAttachment);
                }
            }
        }
    }
    


    I have not tried to correct your code, since I don't have the rest of your solution it was easier to work with what I had already.

    However, the differences I've seen are:

    - You are using DocumentBody.value rather than DocumentBody

    - Incorrect case "CRmRestKit.Create" instead of "CrmRestKit.Create"

    - The parameters for CrmRestKit.Create should be entityName, entityObject (plus callback if async)

    - The parameter entityName should be ActivityMimeAttachment, not ActivityMimeAttachmentSet since the CrmRestKit adds the "Set"-part.

     

    Hope this helps!

    /Frida

    Wednesday, February 1, 2012 2:36 PM

All replies

  • I found the cause myself - I made a mistake in referencing when creating the annotation object - both ObjectTypeCode and ObjectId. The below works correctly:

        CopyEmailAttachmentsToTask: function (task, emailActivityId) {
            var columns = ['Subject', 'FileName', 'Body', 'MimeType', 'FileSize'];
            var filter = "ActivityId/Id eq (guid'" + emailActivityId + "')";
            var collection = CrmRestKit.RetrieveMultiple('ActivityMimeAttachment', columns, filter);
            if (collection != null && collection.results != null) {
                for (var i = 0; i < collection.results.length; i++) {
                    // Create new Annotation
                    var subject = "";
                    if (collection.results[i].Subject != null) {
                        subject = collection.results[i].Subject;
                    }
                    var annotation = {
                        ObjectTypeCode: "task",
                        ObjectId: { Id: task.ActivityId, Name: task.Subject, LogicalName: "task" },
                        NoteText: "Attachment copied from email",
                        Subject: subject,
                        IsDocument: true,
                        MimeType: collection.results[i].MimeType,
                        FileName: collection.results[i].FileName,
                        DocumentBody: collection.results[i].Body
                    };
                    annotation = CrmRestKit.Create('Annotation', annotation);
                }
            }
        },
    

    Monday, January 16, 2012 11:22 AM
  • Hi Frida,

     

    I am trying to copy Appointment attachment to Email Attachment using rest end point (CRmRestKit.Create function)  but getting issue as "Unexpected Error Occured". Can you please share me the working code. I got scratched my head for last two days but didn't get solution. Can you please help me in this regard.

    Thanks a lot!

    Tuesday, January 31, 2012 1:43 PM
  • Hi!

    The code in my reply above works for a task attachment which is stored in the Annotation entity. An email attachment however is stored in the ActivityMimeAttachment entity, i.e. you would have to call the create method for an ActivityMimeAttachment object. I have no example code at the moment but can take a look over the weekend if you still need help.

    Cheers

    /Frida

    Tuesday, January 31, 2012 1:54 PM
  • Hi Frida,

     

    Kindly look. I tried to create attachment by two ways( refer uncommented part and commented Bold). But it is Giving error as Unexpected error. can you please elt me know what I am doing wrong

    //Email ID to which Email attahcment needs to be executed

    var gsNewEmailGuid = "75A33686-024C-E111-A2CB-005056000958"

    ;

     

    function

    onLoad()

    {debugger

    ;

    var loEmailAttachment = null

    ;

    var lsFetchXml = null

    ;

    var lsTaskId = Xrm.Page.data.entity.getId().replace("{", "").replace("}", ""

    );

    try

     

    {

    //var lstest = "hdsfkjhbgk";

     

    var loEmailAttachmentEntity = new

    Object();

    var loAttachment = new

    Object();

    var lsFetchXml = "<fetch mapping='logical'><entity name='annotation'><attribute name='annotationid'/><attribute name='filename'/><attribute name='mimetype'/><attribute name='documentbody'/><filter type='and'> <condition attribute='isdocument' operator='eq' value='1'/> <condition attribute='objectid' operator='eq' value='" + lsTaskId + "'/></filter></entity></fetch>"

    ;

    //Executing Fetch Command

    //_FetchXML is library to exeute fetchxml request

    loFetchXML = new

    _FetchXML();

    loEmailAttachment = loFetchXML.Fetch(lsFetchXml);

    for (var

    liCounter = 0; liCounter < loEmailAttachment.length; liCounter++)

    {

    // loAttachment =

    // {

    // Subject: lstest,

    // //Body: loEmailAttachment[liCounter].attributes.documentbody.value,

    // MimeType: lstest,

    // FileName: lstest

    // };

    // loEmailAttachmentEntity =

    // {

    // ObjectId: { LogicalName: "email", Id: gsNewEmailGuid },

    // ObjectTypeCode: { Value: 4202 },

    // attachment_activity_mime_attachments: loAttachment  ////attachment_activity_mime_attachments is relationship name

    ////b/w email attachment and attachment entity

     

     

    // };

     

    var

    a = Object();

    a.ObjectTypeCode = { Value: 4202 };

    a.FileName =

    "CCR.pdf"

    ;

    a.Body = loEmailAttachment[liCounter].attributes.documentbody.value;

    a.Subject =

    "Report Attachment"

    ;

    a.MimeType =

    "application/pdf"

    ;

    a.ObjectId = { LogicalName:

    "email"

    , Id: gsNewEmailGuid };

    // a.ObjectId.LogicalName = "activitymimeattachment";

    // a.ObjectId.Id = id.ActivityId;

    // var attachId = rest.CreateRecord(a, "ActivityMimeAttachmentSet", null, null);

     

     

    CRmRestKit.Create(a,

    "ActivityMimeAttachmentSet", null, null, false

    );

    }

    }

     

    catch

    (voCatchMessage)

    {

    }

    }

     

     

     

     

     

     

     

    Tuesday, January 31, 2012 2:11 PM
  • Hi,

    I modified my original code to copy an appointment to an email, including any attachments. The below seems to work.

    if (typeof (Sog) == "undefined")
    { Sog = { __namespace: true }; }
    
    // Create Namespace container for functions in this library;
    Sog.Activities = {
        CopyToEmail: function () {
            if (Xrm.Page.data.entity.getIsDirty()) {
                alert(LOCID_CONV_ACT_SAVE_WARNING);
                return false
            }
            if (crmForm.IsValid()) {
                //get info from email
                var subject = Xrm.Page.getAttribute("subject").getValue();
                var description = Xrm.Page.data.entity.attributes.get("description").getValue();
                var regardingAtt = Xrm.Page.getAttribute("regardingobjectid").getValue();
                var regardingRef = null;
                if (!IsNull(regardingAtt)) {
                    regardingRef = { Id: regardingAtt[0].id, Name: regardingAtt[0].name, LogicalName: regardingAtt[0].entityType };
                }
    
                var email = { Subject: subject, Description: description, RegardingObjectId: regardingRef };
                email = CrmRestKit.Create('Email', email);
                //retrieve/copy attachments/notes from appointment            
                if (Xrm.Page.data.entity.getEntityName() == "appointment") {
                    var appointmentActivityId = Xrm.Page.data.entity.getId();
                    Sog.Activities.CopyAppointmentAttachmentsToEmail(email, appointmentActivityId);
                }
    
                var serverUrl = Xrm.Page.context.getServerUrl();
                if (serverUrl.match(/\/$/)) {
                    serverUrl = serverUrl.substring(0, serverUrl.length - 1);
                }
    
                var URL = serverUrl + "/main.aspx?etn=email&pagetype=entityrecord&id=" + email.ActivityId.toString();
    
                window.open(URL, 'Email', 'width=900, height=1200');
                Xrm.Page.ui.close();
    
            }
    
        },
        CopyAppointmentAttachmentsToEmail: function (email, appointmentActivityId) {
            var columns = ['Subject', 'FileName', 'DocumentBody', 'MimeType', 'FileSize'];
            var filter = "ObjectId/Id eq (guid'" + appointmentActivityId + "') and IsDocument eq true";
            var collection = CrmRestKit.RetrieveMultiple('Annotation', columns, filter);
            if (collection != null && collection.results != null) {
                for (var i = 0; i < collection.results.length; i++) {
                    // Create new Annotation
                    var subject = "";
                    if (collection.results[i].Subject != null) {
                        subject = collection.results[i].Subject;
                    }
                    var activityMimeAttachment = {
                        ObjectTypeCode: "email",
                        ObjectId: { Id: email.ActivityId, Name: email.Subject, LogicalName: "email" },
                        Subject: subject,
                        MimeType: collection.results[i].MimeType,
                        FileName: collection.results[i].FileName,
                        Body: collection.results[i].DocumentBody
                    };
                    activityMimeAttachment = CrmRestKit.Create('ActivityMimeAttachment', activityMimeAttachment);
                }
            }
        }
    }
    


    I have not tried to correct your code, since I don't have the rest of your solution it was easier to work with what I had already.

    However, the differences I've seen are:

    - You are using DocumentBody.value rather than DocumentBody

    - Incorrect case "CRmRestKit.Create" instead of "CrmRestKit.Create"

    - The parameters for CrmRestKit.Create should be entityName, entityObject (plus callback if async)

    - The parameter entityName should be ActivityMimeAttachment, not ActivityMimeAttachmentSet since the CrmRestKit adds the "Set"-part.

     

    Hope this helps!

    /Frida

    Wednesday, February 1, 2012 2:36 PM
  • Hi Frida,

     

    Thanks a lot. It is working like a charm

    That made my day.


    Friday, February 3, 2012 4:30 AM