using System;
using System.Activities;
using System.Text;
using SendEmailPDFReport.ReportService; // Add Reporting Service as Web Reference
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Workflow;
using Microsoft.Xrm.Sdk.Messages;
using Microsoft.Crm.Sdk.Messages;
using Microsoft.Crm.Sdk;
using Microsoft.Xrm.Sdk.Query;
using Microsoft.Xrm.Sdk.Client;
using System.Collections.Generic;
namespace SendEmailPDFReport
{
public class SendEmailPDF : CodeActivity
{
#region Input Parameters
[Input("Report ID")]
[ReferenceTarget("report")]
public InArgument<EntityReference> ReportID { get; set; }
[RequiredArgument]
[Input("From")]
[ReferenceTarget("queue")]
public InArgument<EntityReference> From { get; set; }
[RequiredArgument]
[Input("To")]
[ReferenceTarget("contact")]
public InArgument<EntityReference> Recipient { get; set; }
[RequiredArgument]
[Input("Subject")]
public InArgument<string> Subject { get; set; }
[RequiredArgument]
[Input("Report Parameter")]
public InArgument<string> ReportParameter { get; set; }
[RequiredArgument]
[Input("Report URL")]
public InArgument<string> ReportURL { get; set; }
[RequiredArgument]
[Input("E-mail")]
[ReferenceTarget("email")]
public InArgument<EntityReference> Email { get; set; }
[RequiredArgument]
[Input("Report Name")]
public InArgument<string> ReportName { get; set; }
#endregion
protected override void Execute(CodeActivityContext context)
{
StringBuilder sb = new StringBuilder("Starting; ");
try
{
//Create the tracing service
ITracingService tracingService = context.GetExtension<ITracingService>();
//-----------------------------------
// Workflow Context & Service Objects
//-----------------------------------
IWorkflowContext workFlowContext = context.GetExtension<IWorkflowContext>();
IOrganizationServiceFactory serviceFactory = context.GetExtension<IOrganizationServiceFactory>();
IOrganizationService service = serviceFactory.CreateOrganizationService(workFlowContext.InitiatingUserId);
OrganizationServiceContext orgContext = new OrganizationServiceContext(service);
//--------------------------
// Obtain the Input Argument
// Report EntityReference
//--------------------------
Guid RptID = this.ReportID.Get(context).Id;
Guid fromUserID = this.From.Get(context).Id;
Guid sendto = this.Recipient.Get(context).Id;
string SubjectTitle = this.Subject.Get(context);
string rptParams = this.ReportParameter.Get(context);
string rptURL = this.ReportURL.Get(context);
Guid Emailent = this.Email.Get(context).Id;
string rptName = this.ReportName.Get(context);
tracingService.Trace("Retrieving Input Argument" + "ReportID: " + RptID + "fromUserID : " + fromUserID + "sendto: " + sendto + "Emailent " + Emailent);
sb.AppendFormat("Retrieving Input Argument" + "ReportID: " + RptID + "Queue : " + fromUserID + "contact: " + sendto + "Emailent " + Emailent);
// Credential to connect with CRM
ReportExecutionService rs = new ReportExecutionService();
rs.Credentials = System.Net.CredentialCache.DefaultCredentials;
rs.Url = this.ReportURL.Get(context);
byte[] result = null;
//--------------------------
// Specify the report path from the reporting server
// Note: To get the report name, report must be published for the external use.
// To do this edit the report from CRM and publish it for external use.
// After publishing it for external use report name will be visible in the reporting server instead of the report id.
//--------------------------
string reportPath = string.Format("/{0}_MSCRM/CustomReports/{1}", workFlowContext.OrganizationName, ((EntityReference)context.GetValue(this.ReportID)).Id.ToString("B"));
sb.AppendFormat("report path: {0}; ", reportPath);
string format = "PDF";
string historyID = null;
string devInfo = @"<DeviceInfo><Toolbar>False</Toolbar></DeviceInfo>";
ParameterValue[] parameters = new ParameterValue[1];
parameters[0] = new ParameterValue();
parameters[0].Name = "ClaimID";
parameters[0].Value = rptParams.ToString();
sb.AppendFormat("Parameter length: {0}; ", parameters.Length.ToString());
//string showHideToggle = null;
string encoding;
string mimeType;
string extension;
Warning[] warnings = null;
// ParameterValue[] reportHistoryParameters = null;
string[] streamIDs = null;
ExecutionInfo execInfo = new ExecutionInfo();
ExecutionHeader execHeader = new ExecutionHeader();
rs.ExecutionHeaderValue = execHeader;
execInfo = rs.LoadReport(reportPath, historyID);
if (execInfo.CredentialsRequired)
{
List<DataSourceCredentials> dsCredentials = new List<DataSourceCredentials>();
foreach (DataSourcePrompt dsp in execInfo.DataSourcePrompts)
{
DataSourceCredentials credentials1 = new DataSourceCredentials();
credentials1.DataSourceName = dsp.Name;
sb.Append("; DataSourceName: " + credentials1.DataSourceName);
credentials1.UserName = workFlowContext.InitiatingUserId.ToString();
sb.Append("; username: " + workFlowContext.InitiatingUserId.ToString());
credentials1.Password = workFlowContext.OrganizationId.ToString();
sb.Append("; pword: " + workFlowContext.OrganizationId.ToString());
dsCredentials.Add(credentials1);
}
execInfo = rs.SetExecutionCredentials(dsCredentials.ToArray());
}
rs.SetExecutionParameters(parameters, "en-us");
String SessionId = rs.ExecutionHeaderValue.ExecutionID;
sb.Append("Attempting the render; ");
try
{
result = rs.Render(format, devInfo, out extension, out encoding, out mimeType, out warnings, out streamIDs);
//Create email activity
Entity email = new Entity();
email.LogicalName = "email";
EntityReference regardingObject = new EntityReference("contact", sendto);
email.Attributes.Add("regardingobjectid", regardingObject);
//Creating EntityReference for from, to and cc. Need to be changed according to your requirement
EntityReference from = new EntityReference("queue", fromUserID);
EntityReference to = new EntityReference("contact", sendto);
//Creating party list
Entity fromParty = new Entity("activityparty");
fromParty.Attributes.Add("partyid", from);
Entity toParty = new Entity("activityparty");
toParty.Attributes.Add("partyid", to);
EntityCollection collFromParty = new EntityCollection();
collFromParty.EntityName = "queue";
collFromParty.Entities.Add(fromParty);
EntityCollection collToParty = new EntityCollection();
collToParty.EntityName = "contact";
collToParty.Entities.Add(toParty);
// Adding from & to to the email
email.Attributes.Add("from", collFromParty);
email.Attributes.Add("to", collToParty);
email.Attributes.Add("subject", "Test Report");
email.Attributes.Add("description", "Test description text..");
// Create the email
Guid emailID = service.Create(email);
// Attaching Pdf Report
//int NextActorID = new int();
RetrieveEntityRequest request = new RetrieveEntityRequest();
request.LogicalName = "email";
RetrieveEntityResponse response = (RetrieveEntityResponse)service.Execute(request);
int objecttypecode = response.EntityMetadata.ObjectTypeCode.Value;
Entity attachment = new Entity("activitymimeattachment");
attachment["subject"] = "Report";
attachment["filename"] = "Report.pdf";
attachment["body"] = Convert.ToBase64String(result);
attachment["filesize"] = result.Length;
attachment["mimetype"] = "text/plain";
attachment["attachmentnumber"] = 1;
attachment["objectid"] = new EntityReference("email", new Guid(email.Id.ToString()));
attachment["objecttypecode"] = objecttypecode;
service.Create(attachment);
// Sending email
SendEmailRequest SendEmail = new SendEmailRequest();
SendEmail.EmailId = emailID;
SendEmail.IssueSend = true;
SendEmail.TrackingToken = "";
SendEmailResponse res = (SendEmailResponse)service.Execute(SendEmail);
}
catch (Exception err)
{
throw new Exception(err.Message.ToString());
}
}
catch (Exception ex)
{
throw new InvalidPluginExecutionException("An error occurred attaching the pdf: " + ex.Message + ": " + sb.ToString());
}
}
}
}
using System.Activities;
using System.Text;
using SendEmailPDFReport.ReportService; // Add Reporting Service as Web Reference
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Workflow;
using Microsoft.Xrm.Sdk.Messages;
using Microsoft.Crm.Sdk.Messages;
using Microsoft.Crm.Sdk;
using Microsoft.Xrm.Sdk.Query;
using Microsoft.Xrm.Sdk.Client;
using System.Collections.Generic;
namespace SendEmailPDFReport
{
public class SendEmailPDF : CodeActivity
{
#region Input Parameters
[Input("Report ID")]
[ReferenceTarget("report")]
public InArgument<EntityReference> ReportID { get; set; }
[RequiredArgument]
[Input("From")]
[ReferenceTarget("queue")]
public InArgument<EntityReference> From { get; set; }
[RequiredArgument]
[Input("To")]
[ReferenceTarget("contact")]
public InArgument<EntityReference> Recipient { get; set; }
[RequiredArgument]
[Input("Subject")]
public InArgument<string> Subject { get; set; }
[RequiredArgument]
[Input("Report Parameter")]
public InArgument<string> ReportParameter { get; set; }
[RequiredArgument]
[Input("Report URL")]
public InArgument<string> ReportURL { get; set; }
[RequiredArgument]
[Input("E-mail")]
[ReferenceTarget("email")]
public InArgument<EntityReference> Email { get; set; }
[RequiredArgument]
[Input("Report Name")]
public InArgument<string> ReportName { get; set; }
#endregion
protected override void Execute(CodeActivityContext context)
{
StringBuilder sb = new StringBuilder("Starting; ");
try
{
//Create the tracing service
ITracingService tracingService = context.GetExtension<ITracingService>();
//-----------------------------------
// Workflow Context & Service Objects
//-----------------------------------
IWorkflowContext workFlowContext = context.GetExtension<IWorkflowContext>();
IOrganizationServiceFactory serviceFactory = context.GetExtension<IOrganizationServiceFactory>();
IOrganizationService service = serviceFactory.CreateOrganizationService(workFlowContext.InitiatingUserId);
OrganizationServiceContext orgContext = new OrganizationServiceContext(service);
//--------------------------
// Obtain the Input Argument
// Report EntityReference
//--------------------------
Guid RptID = this.ReportID.Get(context).Id;
Guid fromUserID = this.From.Get(context).Id;
Guid sendto = this.Recipient.Get(context).Id;
string SubjectTitle = this.Subject.Get(context);
string rptParams = this.ReportParameter.Get(context);
string rptURL = this.ReportURL.Get(context);
Guid Emailent = this.Email.Get(context).Id;
string rptName = this.ReportName.Get(context);
tracingService.Trace("Retrieving Input Argument" + "ReportID: " + RptID + "fromUserID : " + fromUserID + "sendto: " + sendto + "Emailent " + Emailent);
sb.AppendFormat("Retrieving Input Argument" + "ReportID: " + RptID + "Queue : " + fromUserID + "contact: " + sendto + "Emailent " + Emailent);
// Credential to connect with CRM
ReportExecutionService rs = new ReportExecutionService();
rs.Credentials = System.Net.CredentialCache.DefaultCredentials;
rs.Url = this.ReportURL.Get(context);
byte[] result = null;
//--------------------------
// Specify the report path from the reporting server
// Note: To get the report name, report must be published for the external use.
// To do this edit the report from CRM and publish it for external use.
// After publishing it for external use report name will be visible in the reporting server instead of the report id.
//--------------------------
string reportPath = string.Format("/{0}_MSCRM/CustomReports/{1}", workFlowContext.OrganizationName, ((EntityReference)context.GetValue(this.ReportID)).Id.ToString("B"));
sb.AppendFormat("report path: {0}; ", reportPath);
string format = "PDF";
string historyID = null;
string devInfo = @"<DeviceInfo><Toolbar>False</Toolbar></DeviceInfo>";
ParameterValue[] parameters = new ParameterValue[1];
parameters[0] = new ParameterValue();
parameters[0].Name = "ClaimID";
parameters[0].Value = rptParams.ToString();
sb.AppendFormat("Parameter length: {0}; ", parameters.Length.ToString());
//string showHideToggle = null;
string encoding;
string mimeType;
string extension;
Warning[] warnings = null;
// ParameterValue[] reportHistoryParameters = null;
string[] streamIDs = null;
ExecutionInfo execInfo = new ExecutionInfo();
ExecutionHeader execHeader = new ExecutionHeader();
rs.ExecutionHeaderValue = execHeader;
execInfo = rs.LoadReport(reportPath, historyID);
if (execInfo.CredentialsRequired)
{
List<DataSourceCredentials> dsCredentials = new List<DataSourceCredentials>();
foreach (DataSourcePrompt dsp in execInfo.DataSourcePrompts)
{
DataSourceCredentials credentials1 = new DataSourceCredentials();
credentials1.DataSourceName = dsp.Name;
sb.Append("; DataSourceName: " + credentials1.DataSourceName);
credentials1.UserName = workFlowContext.InitiatingUserId.ToString();
sb.Append("; username: " + workFlowContext.InitiatingUserId.ToString());
credentials1.Password = workFlowContext.OrganizationId.ToString();
sb.Append("; pword: " + workFlowContext.OrganizationId.ToString());
dsCredentials.Add(credentials1);
}
execInfo = rs.SetExecutionCredentials(dsCredentials.ToArray());
}
rs.SetExecutionParameters(parameters, "en-us");
String SessionId = rs.ExecutionHeaderValue.ExecutionID;
sb.Append("Attempting the render; ");
try
{
result = rs.Render(format, devInfo, out extension, out encoding, out mimeType, out warnings, out streamIDs);
//Create email activity
Entity email = new Entity();
email.LogicalName = "email";
EntityReference regardingObject = new EntityReference("contact", sendto);
email.Attributes.Add("regardingobjectid", regardingObject);
//Creating EntityReference for from, to and cc. Need to be changed according to your requirement
EntityReference from = new EntityReference("queue", fromUserID);
EntityReference to = new EntityReference("contact", sendto);
//Creating party list
Entity fromParty = new Entity("activityparty");
fromParty.Attributes.Add("partyid", from);
Entity toParty = new Entity("activityparty");
toParty.Attributes.Add("partyid", to);
EntityCollection collFromParty = new EntityCollection();
collFromParty.EntityName = "queue";
collFromParty.Entities.Add(fromParty);
EntityCollection collToParty = new EntityCollection();
collToParty.EntityName = "contact";
collToParty.Entities.Add(toParty);
// Adding from & to to the email
email.Attributes.Add("from", collFromParty);
email.Attributes.Add("to", collToParty);
email.Attributes.Add("subject", "Test Report");
email.Attributes.Add("description", "Test description text..");
// Create the email
Guid emailID = service.Create(email);
// Attaching Pdf Report
//int NextActorID = new int();
RetrieveEntityRequest request = new RetrieveEntityRequest();
request.LogicalName = "email";
RetrieveEntityResponse response = (RetrieveEntityResponse)service.Execute(request);
int objecttypecode = response.EntityMetadata.ObjectTypeCode.Value;
Entity attachment = new Entity("activitymimeattachment");
attachment["subject"] = "Report";
attachment["filename"] = "Report.pdf";
attachment["body"] = Convert.ToBase64String(result);
attachment["filesize"] = result.Length;
attachment["mimetype"] = "text/plain";
attachment["attachmentnumber"] = 1;
attachment["objectid"] = new EntityReference("email", new Guid(email.Id.ToString()));
attachment["objecttypecode"] = objecttypecode;
service.Create(attachment);
// Sending email
SendEmailRequest SendEmail = new SendEmailRequest();
SendEmail.EmailId = emailID;
SendEmail.IssueSend = true;
SendEmail.TrackingToken = "";
SendEmailResponse res = (SendEmailResponse)service.Execute(SendEmail);
}
catch (Exception err)
{
throw new Exception(err.Message.ToString());
}
}
catch (Exception ex)
{
throw new InvalidPluginExecutionException("An error occurred attaching the pdf: " + ex.Message + ": " + sb.ToString());
}
}
}
}
Hello..
ReplyDeleteCould you help me on this setp-How to Add Reporting Service as Web Reference..Actually i dont know what url to use for this..