Add html Tables while sending emails through custom workflow

I have created a custom workflow send email with table format dynamically in Dynamics CRM.

Email
My requirement is to create a html table and attach data dynamically.


Step1: First, I approached by query expression to get the data and total count.

           QueryExpression queryAccounts = new QueryExpression("entity");
            queryAccounts.ColumnSet = new ColumnSet(true);
            queryAccounts.ColumnSet = new ColumnSet(new String[] { "createdon", "subject", "statecode", "scheduledend", "createdby", "description" });
            queryAccounts.Criteria.AddCondition("subject", ConditionOperator.NotNull);
            queryAccounts.Criteria.AddCondition("statecode", ConditionOperator.Equal, 0);
            queryAccounts.Criteria.AddCondition(new ConditionExpression("createdby", ConditionOperator.In, values));

            EntityCollection collAccounts = service.RetrieveMultiple(queryAccounts);
            int count = collAccounts.Entities.Count();

Step2: Based on count, I started using stringbuilder format, To create html table in email body section.

                StringBuilder stringBuilder = new StringBuilder();
                stringBuilder.Append("<HTML><Head>");
                stringBuilder.Append("</head><body style='font-family:verdana'>");
                stringBuilder.Append("Dear Owner");
                stringBuilder.Append("<br/> Below are the list of this week.<br/><br/>");
                stringBuilder.Append("<Table border='1' cellspacing='0' cellpadding='3' style='width:100%; font-family:Segoe UI'>");
                stringBuilder.Append("<tr><th>Task Subject</th><th>Description</th><th>Due Date</th> </tr>");

                foreach (Entity entity in collAccounts.Entities)
                {
                //Based on your reqirements
                }

                stringBuilder.Append("</table>");
                stringBuilder.Append("</body>");
                stringBuilder.Append("</html>");

Step3: To send email without creating from and to emils dynamics by customworkflow. I have approached by using "activityparty" and "partyid" in my custom workflow and attached the strinbuilder in description


                Entity Fromparty = new Entity("activityparty");
                Fromparty.Attributes.Add("partyid", new EntityReference("systemuser", workflowContext.UserId));
                Entity Toparty = new Entity("activityparty");
                Toparty.Attributes.Add("partyid", new EntityReference("systemuser", erfUser.Id));

                Entity entity6 = new Entity("email");
                entity6["from"] = new Entity[] { Fromparty };
                entity6["to"] = new Entity[] { Toparty };
                entity6["subject"] = "Open task till today";
                entity6["description"] = Convert.ToString(stringBuilder); //stringBuilder.ToString();

                Guid guid = service.Create(entity6);

To send email by token,emailId. We used SendEmailRequest() and SendEmailResponse.
                SendEmailRequest req = new SendEmailRequest();
                req.EmailId = guid;
                req.TrackingToken = "";
                req.IssueSend = true;
                SendEmailResponse sendEmailResponse = (SendEmailResponse)service.Execute(req);

Change label format in Charts

In Dynamics CRM 365, We change the Label formats by using some logic.

Here, I have created a little cheat sheets, so i can find the change with different cheats.

I have used LabelFormat and Format . I have used for values displyed in charts.

Before:                                                             After:
 

We have downloaded the xml file and made changes in label format.

Attach SSRS report Pdf and Attach to Notes in CRM form

In Dynamics CRM 365 online, We have a requirement to attach create dynamics ssrs report through javascript and attach to notes.

I have a create custom ssrs report and attached to CRM.

Step1: Get the name and id of custom report and also fetchxml to create a custom reports. Like name.rdl, ID.

var reportName = "LeadReports.rdl";  //Name.rdl
var reportGuid = "664741B6-D356-E911-A822-000D3A315BF6"; //Id of your lead report

Step2: Based on your requirements, create a path with custom report and ID.


var number = Xrm.Page.getAttribute("subject").getValue();
if(number != null)
{
var params = getReportingSession(); 
var newPth = Xrm.Page.context.getClientUrl() + "/Reserved.ReportViewerWebControl.axd?ReportSession=" + params[0] + "&Culture=1033&CultureOverrides=True&UICulture=1033&UICultureOverrides=True&ReportStack=1&ControlID=" + params[1] + "&OpType=Export&FileName=" + number+ "&ContentDisposition=OnlyHtmlInline&Format=PDF";
window.open(newPth, "_self");
encodePdf(params);
}
else
{
alert("Lead ID is Missing");
}


Step3:  Change your fetchxml as per your requirement along with ID, logical name of entity. In below logic we get url of ssrs reports, reportguid, reportname and along with parameters of fetchxml will be retrieved. We convert  responseText into array.

        var recordId = Xrm.Page.data.entity.getId();
recordId = recordId.replace('{', '').replace('}', '');

var strParameterXML = "<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'><entity name='lead'><all-attributes /><filter type='and'><condition attribute='leadid' operator='eq' value='" + recordId + "' /> </filter></entity></fetch>";

   
var pth = Xrm.Page.context.getClientUrl() + "/CRMReports/rsviewer/QuirksReportViewer.aspx";
var retrieveEntityReq = new XMLHttpRequest();
retrieveEntityReq.open("POST", pth, false);
retrieveEntityReq.setRequestHeader("Accept", "*/*");
retrieveEntityReq.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
retrieveEntityReq.send("id=%7B" + reportGuid + "%7D&uniquename=" + Xrm.Page.context.getOrgUniqueName() + "&iscustomreport=true&reportnameonsrs=&reportName=" + reportName + "&isScheduledReport=false&p:CRM_lead=" + strParameterXML);

var x = retrieveEntityReq.responseText.lastIndexOf("ReportSession=");
var y = retrieveEntityReq.responseText.lastIndexOf("ControlID=");

var ret = new Array();
ret[0] = retrieveEntityReq.responseText.substr(x + 14, 24);
ret[1] = retrieveEntityReq.responseText.substr(x + 10, 32);
return ret;

Step4:
In below, we convert the ssrs report into PDF conversion by using bytes by passing the above parameters

var retrieveEntityReq = new XMLHttpRequest();
var pth = Xrm.Page.context.getClientUrl() + "/Reserved.ReportViewerWebControl.axd?ReportSession=" + responseSession[0] + "&Culture=1033&CultureOverrides=True&UICulture=1033&UICultureOverrides=True&ReportStack=1&ControlID=" + responseSession[1] + "&OpType=Export&FileName=Public&ContentDisposition=OnlyHtmlInline&Format=PDF";

retrieveEntityReq.open("GET", pth, true);
retrieveEntityReq.setRequestHeader("Accept","*/*");
retrieveEntityReq.responseType = "arraybuffer";
retrieveEntityReq.onreadystatechange = function ()
{

if (retrieveEntityReq.readyState == 4 && retrieveEntityReq.status == 200)
{
var binary = "";
var bytes = new Uint8Array(this.response);
for (var i = 0; i < bytes.byteLength; i++)
{
binary += String.fromCharCode(bytes[i]);
}
var bdy = btoa(binary);
createNote(bdy);
}
};
retrieveEntityReq.send();


Step5: Based on my requirement, I want to add pdf into notes in the CRM Form.
I have created pdf and and named it by "subject.pdf" and attached to "Annotation" "Notes" by using SDK.Create();

var note = {};
var recordId = Xrm.Page.data.entity.getId();
recordId = recordId.replace('{', '').replace('}', '');
var inumber= Xrm.Page.getAttribute("subject").getValue();


var refInvoice = new Object();
refInvoice.LogicalName = "lead";
refInvoice.Id = recordId;
note.ObjectId = refInvoice;
note.ObjectTypeCode = refInvoice.LogicalName;

note.Subject = "lead: " + inumber;
note.MimeType = "application/pdf";
note.DocumentBody = data;
note.FileName = invoicenumber + ".pdf";

SDK.REST.createRecord(note,"Annotation",function (result) {
alert("Note Created");
Xrm.Page.data.refresh(false);
},
function (error) {
alert(error.message);
},true);