Send Email using Custom Entity in Ms crm 2011
using 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;
namespace DealerAnnouncementWorkflow
{
public class DealerAnnouncementWorkflow : CodeActivity
{
#region Set the input mandatory parameters.
//Input Value of Email Template
[RequiredArgument]
[Input("Email Template")]
[ReferenceTarget("template")]
public InArgument<EntityReference> EmailTemplate { get; set; }
//Input Value From Email
[RequiredArgument]
[Input("Select FROM user")]
[ReferenceTarget("systemuser")]
public InArgument<EntityReference> FromUser { get; set; }
// Add by Rajeev on Dated 05/09/2014 - Additional
//Input Value From URL
[RequiredArgument]
[Input("URL")]
[Default("http://mal-crm-dev:81/announcements/")]
public InArgument<string> url { 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);
Guid fromUserID = FromUser.Get(context).Id;
const String FetchAccouncementCategory = @"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>
<entity name='col_announcement'>
<attribute name='col_announcementid' />
<attribute name='col_announcementcategoryid' />
<attribute name='col_name' />
<attribute name='col_body' />
<filter type='and'>
<condition attribute='col_announcementid' operator='eq' value='{0}' />
</filter>
</entity>
</fetch>";
//<value uiname='Malibu Boats' uitype='col_announcementcategory'>{E9A110DB-24A9-E311-B928-005056881341}</value>
const String FetchAnnouncementCategoryAssociatedContacts = @"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='true'>
<entity name='contact'>
<attribute name='contactid' />
<filter type='and'>
<condition attribute='col_subscribetoannouncements' operator='eq' value='1' />
</filter>
<link-entity name='col_col_announcementcategory_contact' from='contactid' to='contactid' visible='false' intersect='true'>
<link-entity name='col_announcementcategory' from='col_announcementcategoryid' to='col_announcementcategoryid' alias='ah'>
<filter type='and'>
<condition attribute='col_announcementcategoryid' operator='eq' value='{0}' />
</filter>
</link-entity>
</link-entity>
</entity>
</fetch>";
try
{
EntityCollection AssociatedContactsEntityCol = new EntityCollection();
tracingService.Trace("Retrieving the Announcement Category Records");
FetchExpression fetchQuerytoRetrieveAnnouncementCategory = new FetchExpression(String.Format(FetchAccouncementCategory, workFlowContext.PrimaryEntityId.ToString()));
EntityCollection AnnouncementCategoryEntityCol = service.RetrieveMultiple(fetchQuerytoRetrieveAnnouncementCategory);
// Add by Rajeev on 05/09/2014
string strtitle = "";
string strbody = "";
if (AnnouncementCategoryEntityCol != null && AnnouncementCategoryEntityCol.Entities.Count > 0)
{
foreach (Entity announcementCategoryObj in AnnouncementCategoryEntityCol.Entities)
{
// Add by Rajeev on 05/09/2014
if (announcementCategoryObj.Attributes.Contains("col_name") && announcementCategoryObj.GetAttributeValue<String>("col_name") != null)
{
strtitle = announcementCategoryObj.Attributes.Contains("col_name").ToString();
}
//// Add by Rajeev on 05/09/2014
if (announcementCategoryObj.Attributes.Contains("col_body") && announcementCategoryObj.GetAttributeValue<String>("col_body") != null)
{
strbody = announcementCategoryObj.Attributes.Contains("col_body").ToString();
}
if (announcementCategoryObj.Attributes.Contains("col_announcementcategoryid") && announcementCategoryObj.GetAttributeValue<EntityReference>("col_announcementcategoryid") != null)
{
tracingService.Trace("Retrieving the associated contacts");
FetchExpression fetchQuerytoRetrieveAssocaitedContacts = new FetchExpression(String.Format(FetchAnnouncementCategoryAssociatedContacts, announcementCategoryObj.GetAttributeValue<EntityReference>("col_announcementcategoryid").Id.ToString()));
AssociatedContactsEntityCol = service.RetrieveMultiple(fetchQuerytoRetrieveAssocaitedContacts);
if (AssociatedContactsEntityCol != null && AssociatedContactsEntityCol.Entities.Count > 0)
{
foreach (Entity contactObj in AssociatedContactsEntityCol.Entities)
{
try
{
tracingService.Trace("Sending emails to Contacts");
// Add by Rajeev
string urlToReplace = string.Format("<a href='{0}'>View the Announcement</a>", this.url.Get(context));
String newBody = GetGlobalTemplate("Announcement Notification", service, contactObj.Id, contactObj.LogicalName);
newBody = newBody.Replace("[URL]", urlToReplace);
newBody = newBody.Replace("[Title]", strtitle);
newBody = newBody.Replace("[Body]", strbody);
Entity email = new Entity();
email.LogicalName = "email";
email["description"] = newBody;
List<Entity> toParty = new List<Entity>();
Entity tempParty = new Entity("activityparty");
tempParty["partyid"] = new EntityReference(contactObj.LogicalName, contactObj.Id);
toParty.Add(tempParty);
email.Attributes["to"] = toParty.ToArray();
email.Attributes["regardingobjectid"] = new EntityReference("contact", contactObj.Id);
Guid emailCreated = service.Create(email);
SendEmailRequest req = new SendEmailRequest();
req.EmailId = emailCreated;
req.TrackingToken = "";
req.IssueSend = true;
SendEmailResponse res = (SendEmailResponse)service.Execute(req);
// ******************************************** Comment by Rajeev ******************************************************************
// Create the request
//SendEmailFromTemplateRequest emailUsingTemplateReq = new SendEmailFromTemplateRequest
//{
// Target = emailObj,
// // Use a built-in Email Template of type "contact".
// TemplateId = EmailTempalteID,
// // The regarding Id is required, and must be of the same type as the Email Template.
// RegardingId = contactObj.Id,
// RegardingType = "contact"
//};
//SendEmailFromTemplateResponse emailUsingTemplateResp = (SendEmailFromTemplateResponse)ServiceObj.Execute(emailUsingTemplateReq);
// *********************************************************************************************************************************
}
catch (Exception ex)
{
tracingService.Trace("Exception" + ex.Message + " while sending out the Email for Contact:" + contactObj.Id.ToString());
}
}
}
}
}
}
}
catch (Exception ex)
{
throw new InvalidPluginExecutionException("Exception occured while executing the workflow logic of Email notificaiton. Detailed exception is:" + ex.Message);
}
}
public static String GetGlobalTemplate(string title, IOrganizationService orgService, Guid recId, String recType)
{
String retBody = null;
try
{
QueryExpression query = new QueryExpression();
// Setup the query for the template entity
query.EntityName = "template";
// Return all columns
query.ColumnSet.AllColumns = true;
query.Criteria = new FilterExpression();
query.Criteria.FilterOperator = LogicalOperator.And;
// Create the title condition
ConditionExpression condition1 = new ConditionExpression();
condition1.AttributeName = "title";
condition1.Operator = ConditionOperator.Equal;
condition1.Values.Add(title);
query.Criteria.Conditions.Add(condition1);
// Execute the query and return the result
EntityCollection entityColl = orgService.RetrieveMultiple(query);
if (entityColl.Entities.Count > 0)
{
InstantiateTemplateRequest req = new InstantiateTemplateRequest();
req.ObjectId = recId;
req.ObjectType = recType;
req.TemplateId = entityColl.Entities[0].Id;
InstantiateTemplateResponse resp = (InstantiateTemplateResponse)orgService.Execute(req);
if (resp.EntityCollection != null && resp.EntityCollection.Entities.Count > 0)
{
retBody = resp.EntityCollection.Entities[0]["description"].ToString();
}
}
}
catch
{
throw;
}
return retBody;
}
}
}
using 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;
namespace DealerAnnouncementWorkflow
{
public class DealerAnnouncementWorkflow : CodeActivity
{
#region Set the input mandatory parameters.
//Input Value of Email Template
[RequiredArgument]
[Input("Email Template")]
[ReferenceTarget("template")]
public InArgument<EntityReference> EmailTemplate { get; set; }
//Input Value From Email
[RequiredArgument]
[Input("Select FROM user")]
[ReferenceTarget("systemuser")]
public InArgument<EntityReference> FromUser { get; set; }
// Add by Rajeev on Dated 05/09/2014 - Additional
//Input Value From URL
[RequiredArgument]
[Input("URL")]
[Default("http://mal-crm-dev:81/announcements/")]
public InArgument<string> url { 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);
Guid fromUserID = FromUser.Get(context).Id;
const String FetchAccouncementCategory = @"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>
<entity name='col_announcement'>
<attribute name='col_announcementid' />
<attribute name='col_announcementcategoryid' />
<attribute name='col_name' />
<attribute name='col_body' />
<filter type='and'>
<condition attribute='col_announcementid' operator='eq' value='{0}' />
</filter>
</entity>
</fetch>";
//<value uiname='Malibu Boats' uitype='col_announcementcategory'>{E9A110DB-24A9-E311-B928-005056881341}</value>
const String FetchAnnouncementCategoryAssociatedContacts = @"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='true'>
<entity name='contact'>
<attribute name='contactid' />
<filter type='and'>
<condition attribute='col_subscribetoannouncements' operator='eq' value='1' />
</filter>
<link-entity name='col_col_announcementcategory_contact' from='contactid' to='contactid' visible='false' intersect='true'>
<link-entity name='col_announcementcategory' from='col_announcementcategoryid' to='col_announcementcategoryid' alias='ah'>
<filter type='and'>
<condition attribute='col_announcementcategoryid' operator='eq' value='{0}' />
</filter>
</link-entity>
</link-entity>
</entity>
</fetch>";
try
{
EntityCollection AssociatedContactsEntityCol = new EntityCollection();
tracingService.Trace("Retrieving the Announcement Category Records");
FetchExpression fetchQuerytoRetrieveAnnouncementCategory = new FetchExpression(String.Format(FetchAccouncementCategory, workFlowContext.PrimaryEntityId.ToString()));
EntityCollection AnnouncementCategoryEntityCol = service.RetrieveMultiple(fetchQuerytoRetrieveAnnouncementCategory);
// Add by Rajeev on 05/09/2014
string strtitle = "";
string strbody = "";
if (AnnouncementCategoryEntityCol != null && AnnouncementCategoryEntityCol.Entities.Count > 0)
{
foreach (Entity announcementCategoryObj in AnnouncementCategoryEntityCol.Entities)
{
// Add by Rajeev on 05/09/2014
if (announcementCategoryObj.Attributes.Contains("col_name") && announcementCategoryObj.GetAttributeValue<String>("col_name") != null)
{
strtitle = announcementCategoryObj.Attributes.Contains("col_name").ToString();
}
//// Add by Rajeev on 05/09/2014
if (announcementCategoryObj.Attributes.Contains("col_body") && announcementCategoryObj.GetAttributeValue<String>("col_body") != null)
{
strbody = announcementCategoryObj.Attributes.Contains("col_body").ToString();
}
if (announcementCategoryObj.Attributes.Contains("col_announcementcategoryid") && announcementCategoryObj.GetAttributeValue<EntityReference>("col_announcementcategoryid") != null)
{
tracingService.Trace("Retrieving the associated contacts");
FetchExpression fetchQuerytoRetrieveAssocaitedContacts = new FetchExpression(String.Format(FetchAnnouncementCategoryAssociatedContacts, announcementCategoryObj.GetAttributeValue<EntityReference>("col_announcementcategoryid").Id.ToString()));
AssociatedContactsEntityCol = service.RetrieveMultiple(fetchQuerytoRetrieveAssocaitedContacts);
if (AssociatedContactsEntityCol != null && AssociatedContactsEntityCol.Entities.Count > 0)
{
foreach (Entity contactObj in AssociatedContactsEntityCol.Entities)
{
try
{
tracingService.Trace("Sending emails to Contacts");
// Add by Rajeev
string urlToReplace = string.Format("<a href='{0}'>View the Announcement</a>", this.url.Get(context));
String newBody = GetGlobalTemplate("Announcement Notification", service, contactObj.Id, contactObj.LogicalName);
newBody = newBody.Replace("[URL]", urlToReplace);
newBody = newBody.Replace("[Title]", strtitle);
newBody = newBody.Replace("[Body]", strbody);
Entity email = new Entity();
email.LogicalName = "email";
email["description"] = newBody;
List<Entity> toParty = new List<Entity>();
Entity tempParty = new Entity("activityparty");
tempParty["partyid"] = new EntityReference(contactObj.LogicalName, contactObj.Id);
toParty.Add(tempParty);
email.Attributes["to"] = toParty.ToArray();
email.Attributes["regardingobjectid"] = new EntityReference("contact", contactObj.Id);
Guid emailCreated = service.Create(email);
SendEmailRequest req = new SendEmailRequest();
req.EmailId = emailCreated;
req.TrackingToken = "";
req.IssueSend = true;
SendEmailResponse res = (SendEmailResponse)service.Execute(req);
// ******************************************** Comment by Rajeev ******************************************************************
// Create the request
//SendEmailFromTemplateRequest emailUsingTemplateReq = new SendEmailFromTemplateRequest
//{
// Target = emailObj,
// // Use a built-in Email Template of type "contact".
// TemplateId = EmailTempalteID,
// // The regarding Id is required, and must be of the same type as the Email Template.
// RegardingId = contactObj.Id,
// RegardingType = "contact"
//};
//SendEmailFromTemplateResponse emailUsingTemplateResp = (SendEmailFromTemplateResponse)ServiceObj.Execute(emailUsingTemplateReq);
// *********************************************************************************************************************************
}
catch (Exception ex)
{
tracingService.Trace("Exception" + ex.Message + " while sending out the Email for Contact:" + contactObj.Id.ToString());
}
}
}
}
}
}
}
catch (Exception ex)
{
throw new InvalidPluginExecutionException("Exception occured while executing the workflow logic of Email notificaiton. Detailed exception is:" + ex.Message);
}
}
public static String GetGlobalTemplate(string title, IOrganizationService orgService, Guid recId, String recType)
{
String retBody = null;
try
{
QueryExpression query = new QueryExpression();
// Setup the query for the template entity
query.EntityName = "template";
// Return all columns
query.ColumnSet.AllColumns = true;
query.Criteria = new FilterExpression();
query.Criteria.FilterOperator = LogicalOperator.And;
// Create the title condition
ConditionExpression condition1 = new ConditionExpression();
condition1.AttributeName = "title";
condition1.Operator = ConditionOperator.Equal;
condition1.Values.Add(title);
query.Criteria.Conditions.Add(condition1);
// Execute the query and return the result
EntityCollection entityColl = orgService.RetrieveMultiple(query);
if (entityColl.Entities.Count > 0)
{
InstantiateTemplateRequest req = new InstantiateTemplateRequest();
req.ObjectId = recId;
req.ObjectType = recType;
req.TemplateId = entityColl.Entities[0].Id;
InstantiateTemplateResponse resp = (InstantiateTemplateResponse)orgService.Execute(req);
if (resp.EntityCollection != null && resp.EntityCollection.Entities.Count > 0)
{
retBody = resp.EntityCollection.Entities[0]["description"].ToString();
}
}
}
catch
{
throw;
}
return retBody;
}
}
}
No comments:
Post a Comment