Skip to main content

Notifications

Announcements

No record found.

Microsoft Dynamics CRM (Archived)

Adding an attachment to a note via console application

Posted on by 156

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

  • Shyam D Profile Picture
    Shyam D 15 on at
    RE: Adding an attachment to a note via console application

    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?

  • Pratima Profile Picture
    Pratima on at
    RE: Adding an attachment to a note via console application

    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.

  • Suggested answer
    Emre GULCAN Profile Picture
    Emre GULCAN 2,379 on at
    RE: Adding an attachment to a note via console application

    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
                 */
  • Verified answer
    jestuder Profile Picture
    jestuder 156 on at
    RE: Adding an attachment to a note via console application

    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.

  • Verified answer
    jestuder Profile Picture
    jestuder 156 on at
    RE: Adding an attachment to a note via console application

    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
    M.Azwar Alam Profile Picture
    M.Azwar Alam on at
    RE: Adding an attachment to a note via console application

    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

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

December Spotlight Star - Muhammad Affan

Congratulations to a top community star!

Top 10 leaders for November!

Congratulations to our November super stars!

Tips for Writing Effective Suggested Answers

Best practices for providing successful forum answers ✍️

Leaderboard

#1
André Arnaud de Calavon Profile Picture

André Arnaud de Cal... 291,280 Super User 2024 Season 2

#2
Martin Dráb Profile Picture

Martin Dráb 230,235 Most Valuable Professional

#3
nmaenpaa Profile Picture

nmaenpaa 101,156

Leaderboard

Featured topics

Product updates

Dynamics 365 release plans