Upload an Attachment

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.



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;
}
}
}