Attachments in Microsoft Dynamics CRM 2011

Posted: November 1, 2012 in Code Snippets, CRM 2011

Here i’m going to attach and detach files from Note and Email entities in crm programmatically.

I’m using early bound entities in my code to attach and detach files. Add the Autogenerated cs file in your solution by generating it using crmsvcutil in the sdk bin folder.

Attach Word document to Note

public static void AttachWordDocToNote(EntityReference account, IOrganizationService service)
        {
            // Open a file and read the contents into a byte array
            FileStream stream = File.OpenRead(@"C:\Lakshman\TDD.docx");
            byte[] byteData = new byte[stream.Length];
            stream.Read(byteData, 0, byteData.Length);
            stream.Close();

            // Encode the data using base64.
            string encodedData = System.Convert.ToBase64String(byteData);

            // Add the Note
            Annotation note = new Annotation();

            // Im going to add Note to Account entity
            note.ObjectId = account;
            note.Subject = "Note Added with attachment";

            // Set EncodedData to Document Body
            note.DocumentBody = encodedData;

            // Set the type of attachment
            note.MimeType = @"application\ms-word";
            note.NoteText = "Note Added with Document attached.";

            // Set the File Name
            note.FileName = "TDD.doc";
            service.Create(note);
        }

Attach Pdf file to Note

public static void AttachPDFToNote(EntityReference account, IOrganizationService service)
        {
            // Open a file and read the contents into a byte array
            FileStream stream = File.OpenRead(@"C:\Lakshman\TDD1.pdf");
            byte[] byteData = new byte[stream.Length];
            stream.Read(byteData, 0, byteData.Length);
            stream.Close();

            // Encode the data using base64.
            string encodedData = System.Convert.ToBase64String(byteData);

            // Add the Note
            Annotation note = new Annotation();

            // Im going to add Note to Account entity
            note.ObjectId = account;
            note.Subject = "Note Added with attachment";

            // Set EncodedData to Document Body
            note.DocumentBody = encodedData;

            // Set the type of attachment
            note.MimeType = @"application\pdf";
            note.NoteText = "Note Added with pdf attached.";

            // Set the File Name
            note.FileName = "TDD1.pdf";
            service.Create(note);
        }

Attach Excel file to Note

public static void AttachExcelToNote(EntityReference account, IOrganizationService service)
        {
            // Open a file and read the contents into a byte array
            FileStream stream = File.OpenRead(@"C:\Lakshman\ActiveRecords.xls");
            byte[] byteData = new byte[stream.Length];
            stream.Read(byteData, 0, byteData.Length);
            stream.Close();

            // Encode the data using base64.
            string encodedData = System.Convert.ToBase64String(byteData);

            // Add the Note
            Annotation note = new Annotation();

            // Im going to add Note to Account entity
            note.ObjectId = account;
            note.Subject = "Note Added with attachment";

            // Set EncodedData to Document Body
            note.DocumentBody = encodedData;

            // Set the type of attachment
            note.MimeType = @"application\ms-excel";
            note.NoteText = "Note Added with Excel attached.";

            // Set the File Name
            note.FileName = "ActiveRecords.xls";
            service.Create(note);
        }

Attach Text file to Note

public static void AttachTextToNote(EntityReference account, IOrganizationService service)
        {
            // Open a file and read the contents into a byte array
            FileStream stream = File.OpenRead(@"C:\Lakshman\sample.txt");
            byte[] byteData = new byte[stream.Length];
            stream.Read(byteData, 0, byteData.Length);
            stream.Close();

            // Encode the data using base64.
            string encodedData = System.Convert.ToBase64String(byteData);

            // Add the Note
            Annotation note = new Annotation();

            // Im going to add Note to Account entity
            note.ObjectId = account;
            note.Subject = "Note Added with attachment";

            // Set EncodedData to Document Body
            note.DocumentBody = encodedData;

            // Set the type of attachment
            note.MimeType = @"text/plain";
            note.NoteText = "Note Added with Text attached.";

            // Set the File Name
            note.FileName = "Sample.txt";
            service.Create(note);
        }

Delete attachment from Note

public static void DeleteAttachmentFromNote(Guid noteId, IOrganizationService service)
        {
            Annotation note = new Annotation();
            note.Id = noteId;

            // Set the Documentbody and other fields to null to remove the attachment
            note.DocumentBody = null;

            note.FileName = null;
            note.IsDocument = false;
            service.Update(note);
        }

Add attachment to Email

public static void AddAttachmentToEmail(EntityReference email, IOrganizationService service)
        {
            // Open a file and read the contents into a byte array
            FileStream stream = File.OpenRead(@"C:\Lakshman\sample.txt");
            byte[] byteData = new byte[stream.Length];
            stream.Read(byteData, 0, byteData.Length);
            stream.Close();

            // Encode the data using base64.
            string encodedData = System.Convert.ToBase64String(byteData);
            
            // Add attachment
            ActivityMimeAttachment attachment = new ActivityMimeAttachment();

            // Set the body
            attachment.Body = encodedData;

            // Set the attachment Type
            attachment.MimeType = @"text/plain";
            attachment.FileName = "Sample.txt";

            // Set the regarding object. In my case it is Email entity
            attachment.ObjectId = email;
            attachment.ObjectTypeCode = email.LogicalName;

            // Create the attachment
            service.Create(attachment);
        }

Delete attachments from Email

public static void DeleteAttachmentFromEmail(Guid emailId, IOrganizationService service, XrmDataContext context)
        {
            // Get all the attachments by passing the email guid
            List<ActivityMimeAttachment> attachments = (from at in context.ActivityMimeAttachmentSet
                                                        where at.ObjectId.Id.Equals(emailId)
                                                        select at).ToList();
            foreach (ActivityMimeAttachment attachment in attachments)
            {
                // Delete attachments
                service.Delete(ActivityMimeAttachment.EntityLogicalName, attachment.Id);    
            }
        }
Advertisements
Comments
  1. Paul Ostregich says:

    This helped me alot. Thanks!

  2. Piyush says:

    how do i do the same with SCRIPT??? any idea???… i tried with the text file and working fine… but while reading the PDF… the content not the same as orignal… 😦

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s