Friday, 20 April 2012

Sending Email using Email Template in CRM 2011

Hi,
Here is the sample code to send an Email using Email template name.
Before start below are few keywords
  • Template Name   (i.e., Name of the Template)
  • Regarding Id        (i.e., GUID of the entity record which template associated with)
  • Regarding Type   (i.e., Logical name of the entity which template associated with)
  • ActivityParty[]     (i.e., Sender & Receivers Can be Users/Contacts/Accounts/Leads)
  • IOrganizationService crmService
 public void SendEmailUsingTemplate(IOrganizationService crmService,
ActivityParty[] fromParty,  ActivityParty[] toParty,
string templateName,
Guid regardingId, string regardingType)
{
try
{
// Create e-mail message.
var email = new Email
{
To = toParty,
From = fromParty,
DirectionCode = true
};
if (!string.IsNullOrEmpty(templateName))
{
Guid templateId = Guid.Empty;
// Get Template Id by Name
Entity template = GetTemplateByName(crmService, templateName);
if (template != null && template.Id != null)
{
var emailUsingTemplateReq = new SendEmailFromTemplateRequest
{
Target = email.ToEntity<Entity>(),
TemplateId = template.Id,
RegardingId = regardingId,
RegardingType = regardingType
};
var emailUsingTemplateResp = (SendEmailFromTemplateResponse)crmService.Execute(emailUsingTemplateReq);
}
else
{
// “****No email template exists with the given name ****”);
}
}
}
catch (Exception ex)
{
throw;
}
}
     private Entity GetTemplateByName(string title, IOrganizationService crmService)
{
var query = new QueryExpression();
query.EntityName = Template.EntityLogicalName;
var filter = new FilterExpression();
var condition1 = new ConditionExpression(“title”, ConditionOperator.Equal, new object[] { title });
filter.AddCondition(condition1);
query.Criteria = filter;
EntityCollection allTemplates = crmService.RetrieveMultiple(query);
Entity emailTemplate = new Template();
if (allTemplates.Entities.Count > 0)            {
emailTemplate = allTemplates.Entities[0];
}
return emailTemplate;
}
How Do I call this method -
  • Prepare From and To Users/Contacts/Accounts
  • Pass Service,Template Name,Regarding details
// Prepare “From” activity parties
var from = new ActivityParty
{
PartyId = new EntityReference(SystemUser.EntityLogicalName, {GUID of User})
};
var fromParty = new[] { from };
// Prepare “To” activity parties
var to = new ActivityParty
{
PartyId = new EntityReference(SystemUser.EntityLogicalName, {GUID of User})
};
var toParty = new[] { to };
var orgProxy = new OrganizationServiceProxy(organizationUri, homeRealmUri, credentials, null);
IOrganizationService orgnaizationService = orgProxy;
Guid regardingntityId={GUID of record} // Ex – Guid of contact
string regardingEntityName = “contact” // Logical name ‘contact’
SendEmailUsingTemplate(orgnaizationService , fromParty, toParty, “templateName”, regardingntityId, regardingEntityName);
Hope it helps :)

Saturday, 14 April 2012

Microsoft Dynamics CRM 2011 : How to send Email Notificaiton on Record Sharing?

Solution: Workflows are very useful in Microsoft Dynamics CRM 2011, can be used to send automated email messages, create, update, assign records etc.. but can only be triggered on record creation, status change, assignment, attribute change and deletion and what if it is required to trigger workflow on entity SDK message processing i.e. record sharing etc. For such requirements, i am taking an example of sending email notifications on lead record sharing, You can follow the steps below for sending email notification on lead record sharing.

1.    Create two new attributes in lead entity
    
     a. new_IsSharedRecord (Type = Bit/Two Options)
    
     b. new_LastSharedDateTime (Type = DateTime)

2.    Create plugin that will be triggered on “GrantAccess” message of lead entity and update “new_isSharedRecord”  attribute value to “True” and also store current system date time in “new_LastSharedDateTime”

3.    Create new workflow that will be triggered when “new_isSharedRecord” attribute value will be changed

4.    Check if attribute “new_isSharedRecord” = true then execute below steps

a.    Update attribute value “new_isSharedRecord” = false

b.    Send email message



[Plugin Code]



using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Metadata;
using Microsoft.Crm.Sdk;

namespace wod.Crm.LeadShareAlert
{
    public class wodPlugin : IPlugin
    {
        public void Execute(IServiceProvider serviceProvider)
        {
            // Obtain the execution context from the service provider.
            Microsoft.Xrm.Sdk.IPluginExecutionContext context = (Microsoft.Xrm.Sdk.IPluginExecutionContext)
                serviceProvider.GetService(typeof(Microsoft.Xrm.Sdk.IPluginExecutionContext));

            IOrganizationServiceFactory wod_serviceFactory = null;

            IOrganizationService wod_CrmService = null;

            try
            {
                wod_serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
                wod_CrmService = wod_serviceFactory.CreateOrganizationService(context.UserId);

                if (context.InputParameters.Contains("Target")
                && context.InputParameters["Target"] is EntityReference)
                {
                    switch (context.MessageName)
                    {
                        case "GrantAccess":

                            EntityReference wod_PluginEntity = (EntityReference)context.InputParameters["Target"];

                            if (wod_PluginEntity.LogicalName == "lead")
                            {
                                Entity wodLead = new Entity(wod_PluginEntity.LogicalName);

                                wodLead.Attributes.Add("leadid", wod_PluginEntity.Id);
                                wodLead.Attributes.Add("new_issharedrecord", true);
                                wodLead.Attributes.Add("new_lastshareddatetime", DateTime.Now);

                                wod_CrmService.Update(wodLead);
                            }

                            break;
                    }
                }

            }

            catch (System.Web.Services.Protocols.SoapException ex)
            {
                throw new InvalidPluginExecutionException(ex.Detail.InnerText);
            }
            catch (Exception ex)
            {
                throw new InvalidPluginExecutionException(ex.Message);
            }
        }
    }
}

Originaly posted on: http://worldofdynamics.blogspot.com/2011/05/scenario-on-record-sharing-sending.html



Friday, 13 April 2012

Get Picklist ,Status , State Lable Value

Get OptionSet Lable Value
function call :
GetOptionsSetTextOnValue(service, Opportunity.EntityLogicalName, “opportunityratingcode”, ((OptionSetValue)_entityOpp.Attributes["opportunityratingcode"]).Value);
 private string GetOptionsSetTextOnValue(IOrganizationService service, string entityName, string attributeName, int selectedValue)
        {

            RetrieveAttributeRequest retrieveAttributeRequest = new
            RetrieveAttributeRequest
            {

                EntityLogicalName = entityName,

                LogicalName = attributeName,

                RetrieveAsIfPublished = true

            };
            // Execute the request.
            RetrieveAttributeResponse retrieveAttributeResponse = (RetrieveAttributeResponse)service.Execute(retrieveAttributeRequest);
            // Access the retrieved attribute.

            Microsoft.Xrm.Sdk.Metadata.PicklistAttributeMetadata retrievedPicklistAttributeMetadata = (Microsoft.Xrm.Sdk.Metadata.PicklistAttributeMetadata)

            retrieveAttributeResponse.AttributeMetadata;// Get the current options list for the retrieved attribute.
            OptionMetadata[] optionList = retrievedPicklistAttributeMetadata.OptionSet.Options.ToArray();
            string selectedOptionLabel = string.Empty;
            foreach (OptionMetadata oMD in optionList)
            {
                if (oMD.Value == selectedValue)
                {
                    selectedOptionLabel = oMD.Label.UserLocalizedLabel.Label;

                }

            }
            return selectedOptionLabel;
        }
Get State Lable Value
private string GetStateTextOnValue(IOrganizationService service, string entityName, string attributeName, int selectedValue)
        {

            RetrieveAttributeRequest retrieveAttributeRequest = new
            RetrieveAttributeRequest
            {

                EntityLogicalName = entityName,

                LogicalName = attributeName,

                RetrieveAsIfPublished = true

            };
            // Execute the request.
            RetrieveAttributeResponse retrieveAttributeResponse = (RetrieveAttributeResponse)service.Execute(retrieveAttributeRequest);
            // Access the retrieved attribute.

            AttributeMetadata attrMetadata =
        (AttributeMetadata)retrieveAttributeResponse.AttributeMetadata;// Get the current options list for the retrieved attribute.

            // Cast the AttributeMetadata to StatusAttribute data
            StateAttributeMetadata statusAttrMetadata =
                (StateAttributeMetadata)attrMetadata;

            string selectedOptionLabel = string.Empty;
            foreach( StateOptionMetadata statusMeta in
    statusAttrMetadata.OptionSet.Options)
            {
                if (statusMeta.Value == selectedValue)
                {
                    selectedOptionLabel = statusMeta.Label.UserLocalizedLabel.Label;

                }

            }
            return selectedOptionLabel;
        }
Get Status Lable Value
private string GetStatusTextOnValue(IOrganizationService service, string entityName, string attributeName, int selectedValue)
        {

            RetrieveAttributeRequest retrieveAttributeRequest = new
            RetrieveAttributeRequest
            {

                EntityLogicalName = entityName,

                LogicalName = attributeName,

                RetrieveAsIfPublished = true

            };
            // Execute the request.
            RetrieveAttributeResponse retrieveAttributeResponse = (RetrieveAttributeResponse)service.Execute(retrieveAttributeRequest);
            // Access the retrieved attribute.

            AttributeMetadata attrMetadata =
        (AttributeMetadata)retrieveAttributeResponse.AttributeMetadata;// Get the current options list for the retrieved attribute.

            // Cast the AttributeMetadata to StatusAttribute data
            StatusAttributeMetadata statusAttrMetadata =
                (StatusAttributeMetadata)attrMetadata;

            string selectedOptionLabel = string.Empty;
            foreach (StatusOptionMetadata statusMeta in
    statusAttrMetadata.OptionSet.Options)
            {
                if (statusMeta.Value == selectedValue)
                {
                    selectedOptionLabel = statusMeta.Label.UserLocalizedLabel.Label;

                }

            }
            return selectedOptionLabel;
        }