serving the solutions day and night


Tuesday, May 13, 2014

MS Dynamics CRM - Attach SSRS Report in Email Attachments

This blog will explain to call SSRS report, convert SSRS report content to HTML and place it in the body of the email, same SSRS report will convert to PDF and attached to the email.

It contains 2 class, one is email and call EmailAttachment() function to generate email. Second class name is ReportServerCredentials, it extends IReportServerCredentials, code at the end of blog.

using System.ServiceModel.Description;
using System.Security.Principal;
using System.Net;
using Microsoft.Reporting.WebForms;
using Microsoft.Xrm.Sdk;
using Microsoft.Crm.Sdk.Messages;
using Microsoft.Xrm.Sdk.Client;

     //Email Class      //Email Attachment
     //Body of the email content will be pdf attached in the email

     public  void EmailAttachment()
    System.Text.UTF8Encoding reportInHtml = new UTF8Encoding();
    Guid orgid, userid;

    //Display body content in the HTML format
    byte[] report = RenderReport("HTML4.0");
    string body = reportInHtml.GetString(report);

    WhoAmIResponse(out orgid, out userid);

    ActivityParty fromParty = new ActivityParty
        PartyId = new EntityReference(SystemUser.EntityLogicalName, userid)

    Email email = new Email();
    email.From = new ActivityParty[] { fromParty };
    email.Subject = "test email subject";
    email.Description = body;
    Guid emailID = CRMServiceProxy.Create(email);

    //Convert HTML content to PDF and attached to email
    report = RenderReport("PDF");
    AttachFileToEmail(report, emailID, "PDF" , "Inline Email", "Attachment Name.PDF");

        //CRM OrganizationServiceProxy connection code
        //var serviceProxy = new OrganizationServiceProxy(uri, null, cntcre, null);

        //private OrganizationServiceProxy CRMServiceProxy
        //Get Calling UserID and Organizaiton ID
        private void WhoAmIResponse(out Guid orgid, out Guid userid)
            WhoAmIRequest req = new WhoAmIRequest();
            WhoAmIResponse resp = (WhoAmIResponse)CRMServiceProxy.Execute(req);
            orgid = resp.OrganizationId;
            userid = resp.UserId;

        //Attach File to Email
        private void AttachFileToEmail(byte[] bodyContent, Guid emailID, string mimeType, string subject, string fileName)

            string aMimeType = string.Empty;
            if (mimeType=="PDF")
                aMimeType = "Application/pdf";
            else if (mimeType == "Excel")
                //.xlsx format
                //.xls format
                aMimeType = "application/";
            else if (mimeType == "Image")
                aMimeType = "image/gif";
            else if (mimeType == "Text")
                aMimeType = "text/plain";
            else if (mimeType == "HTML")
                aMimeType = "text/html";
            var Attachment = new ActivityMimeAttachment
                ObjectId = new EntityReference(Email.EntityLogicalName, emailID),
                ObjectTypeCode = Email.EntityLogicalName,
                Subject = subject,
                Body = Convert.ToBase64String(bodyContent),
                MimeType = aMimeType,
                FileName = fileName


        //Render report
        private byte[] RenderReport(string reportOutPutFormat)
            string usernmae = "username";
            string pwd = "pwd";
            string domain = "domain";
            string url = "http://<SERVER_NAME>/ReportServer";
            string path = "/DNS_MSCRM/CustomReports/{1234a5b67-a123-e123-a1bc-1234567a8bc9}";
            string parameterNames = "contactid";
            string parameterValues = "1234a5b67-a123-e123-a1bc-0050568c2ee0";

            //Get organization id and calling user id
            Guid orgid, userid;
            WhoAmIResponse(out orgid, out userid);
            ReportViewer rViewer = new ReportViewer();
            rViewer.ServerReport.ReportServerCredentials = new ReportServerCredentials(usernmae, pwd, domain);
            rViewer.ProcessingMode = ProcessingMode.Remote;
            rViewer.ShowPrintButton = true;
            rViewer.ServerReport.ReportServerUrl = new Uri(url);
            rViewer.ServerReport.ReportPath = path;

            //CRM Report
            DataSourceCredentials dsc = new DataSourceCredentials();
            dsc.UserId = userid.ToString();
            dsc.Password = orgid.ToString();
            dsc.Name = "CRMDataSource";//"MSCRM_DataSource"; //
            List<DataSourceCredentials> dscs = new List<DataSourceCredentials>();

            ReportParameterCollection rpc = new ReportParameterCollection();
            List<string> lpNames = new List<string>();
            List<string> lpValues = new List<string>();

            if (!string.IsNullOrEmpty(parameterNames) && !string.IsNullOrEmpty(parameterValues))
                lpNames = parameterNames.Split('#').ToList();

                lpValues = parameterValues.Split('#').ToList();
                int index = 0;
                foreach (string parValue in lpValues)
                    rpc.Add(new ReportParameter(lpNames[index], parValue));


            Warning[] warnings;
            string[] streamids;
            string mimeType;
            string encoding;
            string extension;

            return rViewer.ServerReport.Render(reportOutPutFormat, null, out mimeType, out encoding, out extension, out streamids, out warnings);

     //ReportServerCredentials Class starts here
public class ReportServerCredentials : IReportServerCredentials

    private string _userName;
    private string _password;
    private string _domain;

    public ReportServerCredentials(string userName, string password, string domain)
        _userName = userName;
        _password = password;
        _domain = domain;
    public WindowsIdentity ImpersonationUser
            return null;

    public ICredentials NetworkCredentials
            return new NetworkCredential(_userName, _password, _domain);

    public bool GetFormsCredentials(out System.Net.Cookie authCookie, out string userName, out string Password, out string Authority)
        userName = null;
        Password = null;
        Authority = null;
        authCookie = null;
        return false;


Anonymous said...

do u know if that is possible for CRM online, how it work?, how can i pass the auth information?

Unknown said...

How to do same in MS CRM Online Version?

Anonymous said...

Ditto! Need this in CRM Online! Anyone?

Unknown said...

Did anyone find a solution for CRM online?