web
You’re offline. This is a read only version of the page.
close
Skip to main content

Notifications

Announcements

No record found.

Community site session details

Community site session details

Session Id :
Microsoft Dynamics CRM (Archived)

Adding an attachment to a note via console application

(0) ShareShare
ReportReport
Posted on by 158

I have a folder that contains attachments I need to attach to notes that already exist in CRM.  Everything is working up to the point of attaching the file via C# console application.  Here is my code:

try
                {
                    string fullFilePath = noteGuid.attachmentLocation + "\\" + noteGuid.attachmentName;
                    byte[] convertedFile = Encoding.Unicode.GetBytes(fullFilePath);
                    ColumnSet attributes = new ColumnSet(new string[] { "annotationid", "filename", "documentbody", "isdocument", "mimetype" });
                    Entity annotation = new Entity("annotation");
                    annotation = orgService.Retrieve(annotation.LogicalName, noteGuid.RecordGuid, attributes);
                    if (annotation != null)
                    {
                        Console.WriteLine("Retrieved: " + annotation.Id);
                        annotation["annotationid"] = annotation.Id;
                        annotation["filename"] = noteGuid.attachmentName;
                        //annotation["documentbody"] = Convert.ToBase64String(new UnicodeEncoding().GetBytes(fullFilePath));
                        annotation["documentbody"] = Convert.ToBase64String(convertedFile);
                        annotation["mimetype"] = noteGuid.mimeType;
                        annotation["isdocument"] = 1;
                        orgService.Update(annotation);
                        Console.WriteLine("Note with GUID " + annotation.Id + " updated successfully!");
                    }
                    else
                    {
                        throw new Exception("Record Not Retrieved");
                    }


As you can see I did what the SDK and Microsoft article tell me to do, but I keep getting a cast error when the update step is hit.

*This post is locked for comments

I have the same question (0)
  • Verified answer
    M.Azwar Alam Profile Picture
    on at

    Hi you can try following method. It will attach pdf file in notes

    private void AttachUpdatedDocumentToCase(ref IOrganizationService service, byte[] filebytes, EntityReference _CaseReference, string FileName)
    {
    string encodedData = System.Convert.ToBase64String(filebytes);
    Entity AnnotationEntityObject = new Entity(_AnnotationEntityName);
    AnnotationEntityObject.Attributes[_ObjectIdFieldName] = _CaseReference;
    AnnotationEntityObject.Attributes[_SubjectFieldName] = FileName;
    AnnotationEntityObject.Attributes[_DocumentBodyFieldName] = encodedData;
    // Set the type of attachment
    AnnotationEntityObject.Attributes[_MimeTypeFieldName] = @"application\pdf";
    // Set the File Name
    AnnotationEntityObject.Attributes[_FileNameFieldName] = FileName;
    service.Create(AnnotationEntityObject);
    }

    Mark as verified, if it works for you

  • Verified answer
    jestuder Profile Picture
    158 on at

    So I ended up switching to Early Bound and generated a filtered xrm file.  I then used this code:

                        string fullFilePath = noteGuid.attachmentLocation + "\\" + noteGuid.attachmentName;
                        XrmServiceContext context = new XrmServiceContext(orgService);
                        var note = (from n in context.AnnotationSet where n.Id == noteGuid.RecordGuid select n).Single();
                        if(note != null)
                        {
                            note.FileName = noteGuid.attachmentName;
                            note.DocumentBody = Convert.ToBase64String(new UnicodeEncoding().GetBytes(fullFilePath));
                            note.MimeType = noteGuid.mimeType;
                            note.IsDocument = true;
                            if (!context.IsAttached(note)) { context.Attach(note); }
                            context.UpdateObject(note);
                            context.SaveChanges();
                            Console.WriteLine("Note with GUID " + note.Id + " updated successfully!");
                        }

    The attachment does attach now, but if I open the note up and click on the attachment it downloads the attachment and when I try to open it I get a decoding error in Adobe Acrobat.

  • Verified answer
    jestuder Profile Picture
    158 on at

    It was the way I was encoding the file.  This is my first go around with encoding file and converting to base64.  Here is the code to encode it correctly.  I was just encoding the file path and not the actual file:

    byte[] convertedFile = File.ReadAllBytes(fullFilePath);

    string encodedFile = Convert.ToBase64String(convertedFile);

    I then pass encodedFile to the documentbody.

  • Suggested answer
    Emre GULCAN Profile Picture
    2,379 on at

    Hi,

    You can also do it easly with XrmLibrary with 3 lines code below;

    AnnotationHelper helper = new AnnotationHelper(_organizationService);
    var attachment1 = AttachmentHelper.CreateFromPath(@"C:\your file path", "");
    helper.AddAttachment(Guid.Parse("Annotation (note) record Id"), attachment1);
    
                /*
                 * or you can also use 
                 * AttachmentHelper.CreateFromBase64
                 * AttachmentHelper.CreateFromByte
                 * AttachmentHelper.CreateFromStream
                 */
  • Pratima Profile Picture
    on at

    Hi James,

    I am facing problem in getting the filepath of my attachment. Please let me know how you have fetched the filepath from a note attachment. Thanks.

  • Shyam D Profile Picture
    15 on at

    Hi James, here what we need to specify the MIME type....if we don't specify the MIME type, CRM is taking it as OCTET STREAM type.  What if I had different type of file as well?

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

Responsible AI policies

As AI tools become more common, we’re introducing a Responsible AI Use…

Neeraj Kumar – Community Spotlight

We are honored to recognize Neeraj Kumar as our Community Spotlight honoree for…

Leaderboard > 🔒一 Microsoft Dynamics CRM (Archived)

#1
SA-08121319-0 Profile Picture

SA-08121319-0 4

#1
Calum MacFarlane Profile Picture

Calum MacFarlane 4

#3
Alex Fun Wei Jie Profile Picture

Alex Fun Wei Jie 2

Last 30 days Overall leaderboard

Featured topics

Product updates

Dynamics 365 release plans