This documentation is archived and is not being maintained.

Upload an Attachment

Dynamics
banner art

[Applies to: Microsoft Dynamics CRM 4.0]

Find the latest SDK documentation: CRM 2015 SDK

The following code example demonstrates how to upload an attachment to a note programmatically.

This sample code can be found in the following files in the SDK download:

Server\HowTo\CS\Entities\UploadAttachment.cs
Server\HowTo\VB\Entities\ UploadAttachment.vb

For more information about the helper methods in the Microsoft.Crm.Sdk.Utility.CrmServiceUtility namespace, see Utility Sample Code.

Example

The following code example shows how to upload attachment to an annotation entity instance.

The code first creates an account entity instance, and then adds an attached note to it with a doc file as an attachment.

[C#]
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using Microsoft.Crm.Sdk.Utility;

namespace Microsoft.Crm.Sdk.HowTo
{
    // Use the following Microsoft Dynamics CRM namespaces in the sample.
    using CrmSdk;

    class UploadAttachment
    {
        static void Main(string[] args)
        {
            // TODO: Change the server URL and organization to match your 
            //  Microsoft Dynamics CRM Server and Microsoft Dynamics CRM Organization.
            UploadAttachment.Run("http://localhost:5555", "CRM_Organization");
        }

        public static bool Run(string crmServerUrl, string orgName)
        {
            #region Setup Data Required for this Sample

            bool success = false;
            
            #endregion

            try
            {
                // Set up the CRM Service.
                CrmService service = CrmServiceUtility.GetCrmService(crmServerUrl, orgName);
                service.PreAuthenticate = true;

                // Create an account object.
                account acct = new account();

                // Set the account properties.
                acct.accountnumber = "CRM102";
                acct.name = "Fourth Coffee";
                acct.address1_name = "Primary";
                acct.address1_line1 = "1234 Elm Street";
                acct.address1_city = "Redmond";
                acct.address1_stateorprovince = "WA";
                acct.address1_postalcode = "54199";

                // Creates an account in the Crm.
                Guid createdAccountId = service.Create(acct);

                // Now create the annotation object. 
                annotation note = new annotation();
                note.notetext = "This is a sample note";
                note.subject = "Test Subject";
                note.objectid = new Lookup();
                note.objectid.type = EntityName.account.ToString();
                
                // Sets the note's parent to the newly created account.
                note.objectid.Value = createdAccountId;
                note.objecttypecode = new EntityNameReference();
                note.objecttypecode.Value = EntityName.account.ToString();

                // Create the note.
                Guid createdNoteId = service.Create(note);

                #region Setup Additional Data Required for this Sample
                
                // Now convert the attachment to be uploaded to Base64 string.
                // This will create a doc file in the current folder of executable.
                string currentPath = System.Environment.CurrentDirectory.ToString();
                TextWriter tw = new StreamWriter(currentPath + "\\Crm" + createdNoteId.ToString() + ".doc");
                // Write a line of text to the file.
                tw.WriteLine("This document is for testing an attachment upload feature of CRM 4.0.");
                tw.Close();
                
                #endregion

                // Open a file and read the contents into a byte array.
                FileStream stream = File.OpenRead(currentPath + "\\Crm" + createdNoteId.ToString() + ".doc");
                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);

                // Now update the note.
                annotation updateNote = new annotation();
                updateNote.annotationid = new Key();
                // Set the Note ID that is being attached to.
                updateNote.annotationid.Value = createdNoteId;
                updateNote.documentbody = encodedData;
                updateNote.filename = "Crm" + createdNoteId.ToString() + ".doc";
                updateNote.mimetype = @"application\ms-word";
                service.Update(updateNote);

                #region check success

                if (createdNoteId != Guid.Empty)
                {
                    success = true;
                }

                #endregion

              
                #region Remove Data Required for this Sample

                if (createdNoteId != Guid.Empty)
                    service.Delete(EntityName.annotation.ToString(), createdNoteId);
                
                if(createdAccountId != Guid.Empty)
                    service.Delete(EntityName.account.ToString(), createdAccountId);

                if (File.Exists(currentPath + "\\Crm" + createdNoteId.ToString() + ".doc"))
                    File.Delete(currentPath+"\\Crm" + createdNoteId.ToString() + ".doc");

                #endregion
       
            }
            catch (System.Web.Services.Protocols.SoapException err)
            {
                string strError = String.Format("An error occurred. The message is {0}.  The detail is {1}.", err.Message, err.Detail.OuterXml.ToString());
            }
            
            
            return success;
        }
    }
}

[Visual Basic .NET]

Imports System
Imports System.Collections.Generic
Imports System.Text
Imports System.IO
Imports Microsoft.Crm.Sdk.Utility

Imports CrmSdk
Namespace Microsoft.Crm.Sdk.HowTo
    ' Use the following Microsoft Dynamics CRM namespaces in the sample.

    Friend Class UploadAttachment
        Shared Sub Main(ByVal args() As String)
            ' TODO: Change the server URL and organization to match your 
            '  Microsoft Dynamics CRM Server and Microsoft Dynamics CRM Organization.
            UploadAttachment.Run("http://localhost:5555", "CRM_Organization")
        End Sub

        Public Shared Function Run(ByVal crmServerUrl As String, ByVal orgName As String) As Boolean
            '         #Region "Setup Data Required for this Sample"

            Dim success As Boolean = False

            '         #End Region

            Try
                ' Set up the CRM Service.
                Dim service As CrmService = CrmServiceUtility.GetCrmService(crmServerUrl, orgName)
                service.PreAuthenticate = True

                ' Create an account object.
                Dim acct As New account()

                ' Set the account properties.
                acct.accountnumber = "CRM102"
                acct.name = "Fourth Coffee"
                acct.address1_name = "Primary"
                acct.address1_line1 = "1234 Elm Street"
                acct.address1_city = "Redmond"
                acct.address1_stateorprovince = "WA"
                acct.address1_postalcode = "54199"

                ' Creates an account in the Crm.
                Dim createdAccountId As Guid = service.Create(acct)

                ' Now create the annotation object. 
                Dim note As New annotation()
                note.notetext = "This is a sample note"
                note.subject = "Test Subject"
                note.objectid = New Lookup()
                note.objectid.type = EntityName.account.ToString()

                ' Sets the note's parent to the newly created account.
                note.objectid.Value = createdAccountId
                note.objecttypecode = New EntityNameReference()
                note.objecttypecode.Value = EntityName.account.ToString()

                ' Create the note.
                Dim createdNoteId As Guid = service.Create(note)

                '            #Region "Setup Additional Data Required for this Sample"

                ' Now convert the attachment to be uploaded to Base64 string.
                ' This will create a doc file in the current folder of executable.
                Dim currentPath As String = System.Environment.CurrentDirectory.ToString()
                Dim tw As TextWriter = New StreamWriter(currentPath & "\Crm" & createdNoteId.ToString() & ".doc")
                ' Write a line of text to the file.
                tw.WriteLine("This document is for testing an attachment upload feature of CRM 4.0.")
                tw.Close()

                '            #End Region

                ' Open a file and read the contents into a byte array.
                Dim stream As FileStream = File.OpenRead(currentPath & "\Crm" & createdNoteId.ToString() & ".doc")
                Dim byteData(CType(stream.Length, Integer) - 1) As Byte
                stream.Read(byteData, 0, byteData.Length)
                stream.Close()

                ' Encode the data using base64.
                Dim encodedData As String = System.Convert.ToBase64String(byteData)

                ' Now update the note.
                Dim updateNote As New annotation()
                updateNote.annotationid = New Key()
                ' Set the Note ID that is being attached to.
                updateNote.annotationid.Value = createdNoteId
                updateNote.documentbody = encodedData
                updateNote.filename = "Crm" & createdNoteId.ToString() & ".doc"
                updateNote.mimetype = "application\ms-word"
                service.Update(updateNote)

                '            #Region "check success"

                If createdNoteId <> Guid.Empty Then
                    success = True
                End If

                '            #End Region

                '            #Region "Remove Data Required for this Sample"

                If createdNoteId <> Guid.Empty Then
                    service.Delete(EntityName.annotation.ToString(), createdNoteId)
                End If

                If createdAccountId <> Guid.Empty Then
                    service.Delete(EntityName.account.ToString(), createdAccountId)
                End If

                If File.Exists(currentPath & "\Crm" & createdNoteId.ToString() & ".doc") Then
                    File.Delete(currentPath & "\Crm" & createdNoteId.ToString() & ".doc")
                End If

                '            #End Region

            Catch err As System.Web.Services.Protocols.SoapException
                Dim strError As String = String.Format("An error occurred. The message is {0}.  The detail is {1}.", _
                                                       err.Message, err.Detail.OuterXml.ToString())
            End Try


            Return success
        End Function
    End Class
End Namespace

See Also

Reference


© 2010 Microsoft Corporation. All rights reserved.


Show: