Send Template Email
The Send Template Email custom workflow activity
will search for Template Records where the Lead Source and Lead Sub-Source are
match the Source and Sub-Source from the designated lead, or are null. Using
the email template specified on the Template Record, the custom workflow
activity will create an email from the template and send it to the leadusing System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Activities;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Workflow;
using Microsoft.Xrm.Sdk.Messages;
using Microsoft.Xrm.Sdk.Query;
using Microsoft.Crm.Sdk.Messages;
using Microsoft.Xrm.Sdk.Metadata;
namespace LeadTemplate_WF
{
public class LeadTemplate_WF : CodeActivity
{
#region Set the input mandatory parameters.
//Input Value of Template Record
[RequiredArgument]
[Input("new_leadorigin")]
[ReferenceTarget("sbi_leadorigin")]
public InArgument<EntityReference> LeadOrgin { get; set; }
[RequiredArgument]
[Input("new_leadsuborigin")]
[ReferenceTarget("sbi_leadsuborigin")]
public InArgument<EntityReference> LeadSubOrgin { get; set; }
[Output("Notes")]
public OutArgument<String> Notes { get; set; }
[Output("Success")]
public OutArgument<bool> Success { get; set; }
[Output("From Address")]
public OutArgument<String> FromAddress { get; set; }
[Output("ClickDimensions Email Template")]
[ReferenceTarget("cdi_emailtemplate")]
public OutArgument<EntityReference> ClickDimensionsEmailTemplate { get; set; }
#endregion
protected override void Execute(CodeActivityContext context)
{
//Create the tracing service
ITracingService tracingService = context.GetExtension<ITracingService>();
//Create the context
IWorkflowContext workFlowContext = context.GetExtension<IWorkflowContext>();
IOrganizationServiceFactory serviceFactory = context.GetExtension<IOrganizationServiceFactory>();
IOrganizationService service = serviceFactory.CreateOrganizationService(workFlowContext.UserId);
string strLeadOrgin = this.LeadOrgin.Get(context) == null ? Guid.Empty.ToString() : this.LeadOrgin.Get(context).Id.ToString();
string strLeadSubOrgin = this.LeadSubOrgin.Get(context) == null ? Guid.Empty.ToString() : this.LeadSubOrgin.Get(context).Id.ToString();
const String FetchTemplateRecord = @"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>
<entity name='new_templaterecord'>
<attribute name='new_templaterecordid' />
<attribute name='new_name' />
<attribute name='new_leadsuborigin' />
<attribute name='new_leadorigin' />
<attribute name='new_template' />
<attribute name='new_templatesource' />
<order attribute='new_leadorigin' descending='true' />
<order attribute='new_leadsuborigin' descending='true' />
<filter type='and'>
<condition attribute='new_templatetype' operator='eq' value='100000000' />
<condition attribute='new_template' operator='not-null' />
<filter type='or'>
<filter type='and'>
<condition attribute='new_leadorigin' operator='eq' uitype='sbi_leadorigin' value='{0}' />
<filter type='or'>
<condition attribute='new_leadsuborigin' operator='eq' uitype='sbi_leadsuborigin' value='{1}' />
<condition attribute='new_leadsuborigin' operator='null' />
</filter>
</filter>
<condition attribute='new_leadorigin' operator='null' />
</filter>
</filter>
</entity>
</fetch>";
// Team Query
const String FetchTeam = @"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='true'>
<entity name='team'>
<attribute name='name' />
<attribute name='businessunitid' />
<attribute name='teamid' />
<attribute name='teamtype' />
<attribute name='queueid' />
<attribute name='emailaddress' />
<order attribute='name' descending='false' />
<filter type='and'>
<condition attribute='teamtype' operator='eq' value='0' />
</filter>
<link-entity name='businessunit' from='businessunitid' to='businessunitid' alias='ae'>
<link-entity name='lead' from='owningbusinessunit' to='businessunitid' alias='af'>
<filter type='and'>
<condition attribute='leadid' operator='eq' uitype='lead' value='{0}' />
</filter>
</link-entity>
</link-entity>
</entity>
</fetch>";
try
{
tracingService.Trace("Retrieving the Template Record");
FetchExpression fetchQuerytoRetrieveTemplateRecord = new FetchExpression(String.Format(FetchTemplateRecord, strLeadOrgin, strLeadSubOrgin));
//tracingService.Trace("Retrieving " + fetchQuerytoRetrieveTemplateRecord);
// Retrive Business Unit’s Team
FetchExpression fetchQuerytoRetrieveTeam = new FetchExpression(String.Format(FetchTeam, strLeadOrgin));
var aa = service.RetrieveMultiple(fetchQuerytoRetrieveTemplateRecord);
var bb = service.RetrieveMultiple(fetchQuerytoRetrieveTeam);
if (aa.Entities.Count > 0)
{
// tracingService.Trace("Entity count " + aa.Entities.Count);
Entity TemplateRecordObj = aa.Entities[0];
string strtitle = TemplateRecordObj.Attributes.Contains("new_name") ? TemplateRecordObj.Attributes["new_name"].ToString() : "No Name found";
//tracingService.Trace("strtitle " + strtitle.ToString());
Guid TempalteID = Guid.Empty;
string TempID = TemplateRecordObj.Attributes.Contains("new_template") ? TemplateRecordObj.Attributes["new_template"].ToString() : "Test Guid";
//tracingService.Trace("strTempID " + TempID.ToString());
if (Guid.TryParse(TemplateRecordObj.Attributes["new_template"].ToString(), out TempalteID) && TemplateRecordObj.Contains("new_templatesource"))
{
switch (((OptionSetValue)TemplateRecordObj["new_templatesource"]).Value)
{
case 100000001://CRM Email Template
tracingService.Trace("Sending emails");
InstantiateTemplateRequest req = new InstantiateTemplateRequest();
req.ObjectId = workFlowContext.PrimaryEntityId;
req.ObjectType = workFlowContext.PrimaryEntityName;
req.TemplateId = TempalteID;
InstantiateTemplateResponse resp = (InstantiateTemplateResponse)service.Execute(req);
Entity tmpEmail = new Entity("email");
if (resp.EntityCollection != null && resp.EntityCollection.Entities.Count > 0)
{
tmpEmail = resp.EntityCollection.Entities[0];
}
List<Entity> toParty = new List<Entity>();
Entity tempParty = new Entity("activityparty");
tempParty["partyid"] = new EntityReference(workFlowContext.PrimaryEntityName, workFlowContext.PrimaryEntityId);
toParty.Add(tempParty);
tmpEmail.Attributes["to"] = toParty.ToArray();
tmpEmail.Attributes["regardingobjectid"] = new EntityReference(workFlowContext.PrimaryEntityName, workFlowContext.PrimaryEntityId);
service.Create(tmpEmail);
SendEmailRequest sendReq = new SendEmailRequest();
sendReq.EmailId = tmpEmail.Id;
sendReq.TrackingToken = "";
sendReq.IssueSend = true;
SendEmailResponse res = (SendEmailResponse)service.Execute(sendReq);
// Set the Output Parameters
this.Success.Set(context, true);
this.Notes.Set(context, strtitle);
this.ClickDimensionsEmailTemplate.Set(context, null);
this.FromAddress.Set(context, null);
break;
case 100000000://ClickD Email Template
this.ClickDimensionsEmailTemplate.Set(context, new EntityReference("cdi_emailtemplate", TempalteID));
if (bb.Entities.Count > 0)
{
Entity TeamObj = bb.Entities[0];
// string str_queuename = TeamObj.Attributes.Contains("name") ? TeamObj.Attributes["name"].ToString() : "No Queue Name Found";
string str_emailaddress = TeamObj.Attributes.Contains("emailaddress") ? TeamObj.Attributes["emailaddress"].ToString() : "No Email Address Found";
this.FromAddress.Set(context, str_emailaddress);
}
break;
}
}
}
}
catch (Exception ex)
{
//throw new Exception(ex.Message.ToString());
//tracingService.Trace("Exception" + ex.Message.ToString());
this.Notes.Set(context, ex.Message.ToString());
//return;
}
}
}
}
No comments:
Post a Comment