Add Attachments to Entity

ath

Attaching file in MS CRM through coding ,

Many times we needs to add different documents as an attachments to note, thus thought to share it ..

I explored, PDF, Word, Excel, Text file only, but i belive same code can be useful for other types of documents as well. Thus only Text file and PDF file complete function ahs been provided as an example and for rest only change of that document. That change belongs to  “mimetype”   only, rest part is same.

Word file : only change mimetype in below PDF code

// Set the type of attachment
note.MimeType = @"application\ms-word";

Excel

note.MimeType = @"application\ms-excel";

Text File

private void AttachFileinNote(string entityLogicalName, Guid entityId, string strMessage, string file, string subject, string notetext)
 { 
 byte[] filename = Encoding.ASCII.GetBytes(strMessage);
 string encodedData = System.Convert.ToBase64String(filename);
 Entity Annotation = new Entity("annotation");
 Annotation.Attributes["objectid"] = new EntityReference(entityLogicalName, entityId);
 Annotation.Attributes["objecttypecode"] = entityLogicalName; //"quote";
 Annotation.Attributes["subject"] = subject;
 Annotation.Attributes["documentbody"] = encodedData;
 Annotation.Attributes["mimetype"] = @"text/plain";
 Annotation.Attributes["notetext"] = notetext;
 Annotation.Attributes["filename"] = file + ".txt";
 service.Create(Annotation);
 }

PDF file

/// <summary>
 /// genarate and attach PDF to quote
///var fileData = Convert.FromBase64String(FileByteStream.Value);
 /// </summary> 
 private void PDFattachment(string entityLogicalName, Guid entiyId, string fileName, byte[] fileData)
 { 
 string encodedData = System.Convert.ToBase64String(fileData);
 Entity Annotation = new Entity("annotation");
 Annotation.Attributes["objectid"] = new EntityReference(entityLogicalName, entiyId);//"quote", quoteId);
 Annotation.Attributes["objecttypecode"] = "quote";
 Annotation.Attributes["subject"] = "Print Quote for Services: " + System.DateTime.Now;
 Annotation.Attributes["documentbody"] = encodedData;
 Annotation.Attributes["mimetype"] = @"application\pdf";
 Annotation.Attributes["notetext"] = "File generated on " + System.DateTime.Now;
 Annotation.Attributes["filename"] = fileName;
 Guid AnnotationID = service.Create(Annotation);

 }
Advertisements

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