Search

Download an Attachment

The following code example demonstrates how to download an attachment programmatically. This technique is demonstrated for a note (annotation), an e-mail attachment (activitymimeattachment), and for a sales literature item. You can use the same technique for downloading an e-mail template.


//CRM4.0: Download an Attachment
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.IO;
using Microsoft.Crm.Sdk.Utility;
using System.Web.Services.Protocols;

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

class DownloadAttachment
{
static void Main(string[] args)
{
bool success = false;
try
{
// TODO: Change the service URL and organization to match your Microsoft Dynamics
// CRM server installation. A value of String.Empty for the service URL indicates
// to use the default service URL defined in the WSDL.
success = DownloadAttachment.Run("http://localhost:5555", "CRM_Organization");
}
catch (SoapException ex)
{
Console.WriteLine("The application terminated with an error.");
Console.WriteLine(ex.Message);
Console.WriteLine(ex.Detail.InnerText);
}
catch (System.Exception ex)
{
Console.WriteLine("The application terminated with an error.");
Console.WriteLine(ex.Message);

// Display the details of the inner exception.
if (ex.InnerException != null)
{
Console.WriteLine(ex.InnerException.Message);

SoapException se = ex.InnerException as SoapException;
if (se != null)
Console.WriteLine(se.Detail.InnerText);
}
}
finally
{
Console.WriteLine("Completed successfully? {0}", success);
Console.WriteLine("Press to exit.");
Console.ReadLine();
}
}

public static bool Run(string crmServerUrl, string orgName)
{

bool success = false;

try
{
// Set up the CRM Service.
CrmService service = CrmServiceUtility.GetCrmService(crmServerUrl, orgName);
// Cache credentials so each request does not have to be authenticated again.
service.PreAuthenticate = true;

#region Setup Data Required for this Sample

// Create the root account.
Guid setupAnnotationId = Guid.Empty;
Guid setupEmailAttachmentId = Guid.Empty;
Guid setupEmailId = Guid.Empty;
Guid setupSalesLiteratureId = Guid.Empty;
Guid setupSalesLiteratureItemId = Guid.Empty;

// Create the annotation record.
annotation setupAnnotation = new annotation();
setupAnnotation.subject = "Example Annotation Attachment";
setupAnnotation.filename = "ExampleAnnotationAttachment.txt";
setupAnnotation.documentbody = "Sample Annotation Text";
setupAnnotationId = service.Create(setupAnnotation);

// Create the e-mail record.
email setupEmail = new email();
setupEmail.subject = "Example email";
setupEmail.torecipients = "unknown@example.com";
setupEmail.description = "This is an example email.";
setupEmailId = service.Create(setupEmail);

// Create the activitymimeattachment record for an e-mail attachment.
activitymimeattachment setupEmailAttachment = new activitymimeattachment();
setupEmailAttachment.subject = "Example Email Attachement";
setupEmailAttachment.filename = "ExampleEmailAttachment.txt";
setupEmailAttachment.body = "Some Text";
setupEmailAttachment.mimetype = "text/plain";
setupEmailAttachment.attachmentnumber = new CrmNumber();
setupEmailAttachment.attachmentnumber.Value = 1;
setupEmailAttachment.activityid = new Lookup();
setupEmailAttachment.activityid.type = EntityName.email.ToString();
setupEmailAttachment.activityid.Value = setupEmailId;
setupEmailAttachmentId = service.Create(setupEmailAttachment);

// Create the salesliterature record.
salesliterature attachment3 = new salesliterature();
attachment3.name = "Example SalesLiterature";
attachment3.hasattachments = new CrmBoolean();
attachment3.hasattachments.Value = true;
setupSalesLiteratureId = service.Create(attachment3);

// Create the salesliteratureitem record for an attachment to salesliterature.
salesliteratureitem attachementItem3 = new salesliteratureitem();
attachementItem3.title = "Example sales literature attachment";
attachementItem3.filename = "ExampleSalesLiteratureAttachment.txt";
attachementItem3.documentbody = "Example sales literature text.";
attachementItem3.mimetype = "text/plain";
attachementItem3.salesliteratureid = new Lookup();
attachementItem3.salesliteratureid.type = EntityName.salesliterature.ToString();
attachementItem3.salesliteratureid.Value = setupSalesLiteratureId;
setupSalesLiteratureItemId = service.Create(attachementItem3);

#endregion

#region How to download attachment from annotation record

// SDK: annotationId = new Guid("{bee08735-09d3-de11-9d71-00155da4c706}");
Guid annotationId = setupAnnotationId;

// Define the columns to retrieve from the annotation record.
ColumnSet cols1 = new ColumnSet();
cols1.Attributes = new string[] { "filename", "documentbody" };

// Retrieve the annotation record.
annotation annotationAttachment = (annotation)service.Retrieve(EntityName.annotation.ToString(), annotationId, cols1);

// Download the attachment in the current execution folder.
using (FileStream fileStream = new FileStream(annotationAttachment.filename, FileMode.OpenOrCreate))
{
byte[] fileContent = new UTF8Encoding(true).GetBytes(annotationAttachment.documentbody);
fileStream.Write(fileContent, 0, fileContent.Length);
}

#endregion

#region How to download attachment from activitymimeattachment record

// SDK: emailAttachmentId = new Guid("{c1e08735-09d3-de11-9d71-00155da4c706}");
Guid emailAttachmentId = setupEmailAttachmentId;

// Define the columns to retrieve from the activitymimeattachment record.
ColumnSet cols2 = new ColumnSet();
cols2.Attributes = new string[] { "filename", "body" };

// Retrieve the activitymimeattachment record.
activitymimeattachment emailAttachment = (activitymimeattachment)service.Retrieve(EntityName.activitymimeattachment.ToString(), emailAttachmentId, cols2);

// Download the attachment in the current execution folder.
using (FileStream fileStream = new FileStream(emailAttachment.filename, FileMode.OpenOrCreate))
{
// byte[] fileContent = Convert.FromBase64String(emailAttachment.body);
byte[] fileContent = new UTF8Encoding(true).GetBytes(emailAttachment.body);
fileStream.Write(fileContent, 0, fileContent.Length);
}

#endregion

#region How to download attachment from salesliterature record

// SDK: salesLiteratureId = new Guid("{a836993e-09d3-de11-9d71-00155da4c706}");
Guid salesLiteratureId = setupSalesLiteratureId;

// Search for all the salesliteratureitem records that belong
// to the specified salesliterature record.
BusinessEntityCollection entities = null;
salesliteratureitem entity = null;

// Create the query for search.
QueryExpression query = new QueryExpression();
query.EntityName = EntityName.salesliteratureitem.ToString();

// Define the columns to retrieve from the salesliteratureitem record.
ColumnSet cols3 = new ColumnSet();
cols3.Attributes = new string[] { "filename", "documentbody", "title" };

// Set the filter condition to query.
ConditionExpression condition = new ConditionExpression();
condition.AttributeName = "salesliteratureid";
condition.Values = new string[1] { salesLiteratureId.ToString() };
condition.Operator = ConditionOperator.Equal;
FilterExpression filter = new FilterExpression();
filter.Conditions = new ConditionExpression[] { condition };

query.ColumnSet = cols3;
query.Criteria = filter;

// Retrieve the salesliteratureitem records.
entities = service.RetrieveMultiple(query);

// Check for the retrieved salesliteratureitem count.
if (entities.BusinessEntities.Length != 0)
{
for (int i = 0; i < entities.BusinessEntities.Length; i++)
{
entity = (salesliteratureitem)entities.BusinessEntities[i];

// Download the attachment in the current execution folder.
using (FileStream fileStream = new FileStream(entity.filename, FileMode.OpenOrCreate))
{
byte[] fileContent = new UTF8Encoding(true).GetBytes(entity.documentbody);
fileStream.Write(fileContent, 0, fileContent.Length);
}
}
}

#endregion

#region check success

// Verify that there are attachments.
if (annotationAttachment.filename != null && emailAttachment.filename != null
&& entity.filename != null)
{
success = true;
Console.WriteLine(
"The following files were downloaded to the executable folder:\n {0}\n {1}\n {2}\n",
annotationAttachment.filename, emailAttachment.filename, entity.filename);
}
#endregion

#region Remove Data Required for this Sample

service.Delete(EntityName.annotation.ToString(), setupAnnotationId);
service.Delete(EntityName.activitymimeattachment.ToString(), setupEmailAttachmentId);
service.Delete(EntityName.email.ToString(), setupEmailId);
service.Delete(EntityName.salesliteratureitem.ToString(), setupSalesLiteratureItemId);
service.Delete(EntityName.salesliterature.ToString(), setupSalesLiteratureId);

#endregion

}
catch
{
// You can handle an exception here or pass it back to the calling method.
throw;
}

return success;
}

}
}