Hi VENKY, I have it as a custom CRM step as below (you framework must be > 4.6.2)
using ITWORX.Reliance.Reliable.Common.Helper;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Workflow;
using System;
using System.Activities;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Threading.Tasks;
namespace CustomSteps
{
[DataContract]
public class ApiTokenResponse
{
[DataMember]
public string access_token { get; set; }
}
public class ReportObject
{
public string id { get; set; }
public string iscustomreport { get; set; }
public string reporttypecode { get; set; }
public string isScheduledReport { get; set; }
public string EntitySchemaName { get; set; }
public string CRM_Filter { get; set; }
public string reportName { get; set; }
public string EntityRecordID { get; set; }
}
public class ConvertReportToPDF : CodeActivity
{
#region params
[Output("ReportPDF")]
public OutArgument<string> ReportPDF { get; set; }
[Input("ReportID")]
[RequiredArgument]
public InArgument<string> ReportID { get; set; }
[Input("ReportName")]
[RequiredArgument]
public InArgument<string> ReportName { get; set; }
[Input("EntitySchemaName")]
public InArgument<string> EntitySchemaName { get; set; }
[Input("EntityRecordID")]
public InArgument<string> EntityRecordID { get; set; }
[Input("CRMFilter")]
public InArgument<string> CRMFilter { get; set; }
#endregion
protected override void Execute(CodeActivityContext context)
{
// Create the context
IWorkflowContext WFContext = context.GetExtension<IWorkflowContext>();
if (WFContext == null)
{
throw new InvalidPluginExecutionException("Failed to retrieve workflow context.");
}
IOrganizationServiceFactory serviceFactory = context.GetExtension<IOrganizationServiceFactory>();
IOrganizationService service = serviceFactory.CreateOrganizationService(WFContext.UserId);
ReportObject reportParams = new ReportObject()
{
id = ReportID.Get<string>(context),
reportName = ReportName.Get<string>(context),
EntitySchemaName = EntitySchemaName.Get<string>(context),
EntityRecordID = EntityRecordID.Get<string>(context),
CRM_Filter = CRMFilter.Get<string>(context)
};
formatReportParams(reportParams);
CallIntermediate(service, context, ReportPDF, reportParams);
}
private void formatReportParams(ReportObject reportParams)
{
reportParams.id = formatIDBrackets(reportParams.id);
reportParams.EntityRecordID = formatIDBrackets(reportParams.EntityRecordID);
reportParams.iscustomreport = "true";
reportParams.reporttypecode = "1";
reportParams.isScheduledReport = "false";
if (string.IsNullOrEmpty(reportParams.CRM_Filter)
&& !string.IsNullOrEmpty(reportParams.EntitySchemaName)
&& !string.IsNullOrEmpty(reportParams.EntityRecordID))
{
if (reportParams.EntitySchemaName == "salesorder")
{
reportParams.CRM_Filter = "<ReportFilter><ReportEntity paramname=\"CRM_FilteredSalesOrder\" donotconvert=\"1\"><fetch version=\"1.0\" output-format=\"xml-platform\" mapping=\"logical\" distinct=\"false\"><entity name=\"salesorder\"><all-attributes/><filter type=\"and\"><condition attribute=\"salesorderid\" operator=\"eq\" value=\"" + reportParams.EntityRecordID + "\"/></filter></entity></fetch></ReportEntity></ReportFilter>";
}
}
}
private string formatIDBrackets(string id)
{
if (!string.IsNullOrEmpty(id))
{
id = id.Replace("{", "").Replace("}", "");
return "{" + id + "}";
}
return null;
}
private static async void CallIntermediate(IOrganizationService service, CodeActivityContext context, OutArgument<string> ReportPDF, ReportObject reportParams)
{
await GenerateResportAsPDF_Async(service, context, ReportPDF, reportParams);
}
public static async Task<string> GenerateResportAsPDF_Async(IOrganizationService service, CodeActivityContext context, OutArgument<string> ReportPDF, ReportObject reportParams)
{
try
{
string organizationUrl = "yourenv.crm.dynamics.com";
string tenantID = "a1a5384f-f0fc-4df9-9f37-000000000000";
string clientId_applicationId = "2e4ee484-8654-4fdf-a629-000000000000";
string OAuth2_0Token_Endpoint = "login.microsoftonline.com/" + tenantID + "/oauth2/token";
string username = "user@domain.com";
string password = "pwd";
string clientSecret = "scrt";
string accessToken = CRMAuthentication.GetAuthToken(organizationUrl, tenantID, clientId_applicationId, OAuth2_0Token_Endpoint, username, password, clientSecret);
//********** Request 2 to run the resport**********//
HttpClient _httpClient2 = new HttpClient();
_httpClient2.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
_httpClient2.Timeout = new TimeSpan(0, 2, 0);
_httpClient2.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("*/*"));
//Account Distribution OOB report sample
HttpRequestMessage request2 = new HttpRequestMessage(HttpMethod.Post, organizationUrl + "/CRMReports/rsviewer/reportviewer.aspx");
var lst = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("id",reportParams.id),
new KeyValuePair<string, string>("iscustomreport",reportParams.iscustomreport),
new KeyValuePair<string, string>("reporttypecode",reportParams.reporttypecode),
new KeyValuePair<string, string>("reportName",reportParams.reportName),
new KeyValuePair<string, string>("isScheduledReport",reportParams.isScheduledReport),
new KeyValuePair<string, string>("CRM_Filter",reportParams.CRM_Filter)
};
var formUrlEncodedContent = new FormUrlEncodedContent(lst);
request2.Content = formUrlEncodedContent;
using (Task<HttpResponseMessage> response = _httpClient2.SendAsync(request2))
{
string resultValue = await response.Result.Content.ReadAsStringAsync();
var x = resultValue.LastIndexOf("ReportSession=");
var y = resultValue.LastIndexOf("ControlID=");
string ReportSession = resultValue.Substring(x + 14, 24);
string ControlID = resultValue.Substring(y + 10, 32);
//********** Request 3 to save the generated report as PDF**********//
var pth = organizationUrl + "/Reserved.ReportViewerWebControl.axd?ReportSession=" + ReportSession + "&Culture=1033&CultureOverrides=True&UICulture=1033&UICultureOverrides=True&ReportStack=1&ControlID=" + ControlID + "&OpType=Export&FileName=Public&ContentDisposition=OnlyHtmlInline&Format=PDF";
HttpClient _httpClient3 = new HttpClient();
_httpClient3.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
_httpClient3.Timeout = new TimeSpan(0, 2, 0);
_httpClient3.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("*/*"));
HttpRequestMessage request3 = new HttpRequestMessage(HttpMethod.Get, pth);
using (Task<HttpResponseMessage> response3 = _httpClient2.SendAsync(request3))
{
//System.IO.Stream resultValue3 = await response3.Result.Content.ReadAsStreamAsync();
var resultValue3 = await response3.Result.Content.ReadAsByteArrayAsync();
string encodedData = Convert.ToBase64String(resultValue3);
ReportPDF.Set(context, encodedData);
}
}
}
catch (Exception ex)
{
throw ex;
}
return "";
}
}
}