Pergunta

No CRM 2011, quero anexar contatos para citar, sem problemas para isso.

Quando salvo a cotação, para cada contato, quero enviar um email para fins de lembrete. (Com um plug -in) Como é possível sinalizar isso e dar a capacidade de o usuário do CRM não fazer isso no formulário de cotação com uma caixa de seleção.

O objetivo final, é para dar a capacidade do usuário do CRM para enviar um novo lembrete de email para um ou vários contatos anexados na cotação.

Pode me ajudar ?

Foi útil?

Solução

Você precisará ter um botão de faixa de opções que chamará um método JavaScript em um dos recursos da web.

No CommandDefinition De você XML Ribbondiff, você precisará enviar um parâmetro para o método JS, que conterá todos os IDs dos registros selecionados na sub -grade.

<CommandDefinitions>
<CommandDefinition Id="xyz.Button.SendEmail.command">
<EnableRules>
</EnableRules>
<DisplayRules>
</DisplayRules>
<Actions>
    <JavaScriptFunction Library="$webresource:Test.Js" FunctionName="SendEmail">
        <CrmParameter Value="SelectedControlAllItemIds" />
    </JavaScriptFunction>
</Actions>
</CommandDefinition>

E então o método JS seria algo abaixo, onde você precisará analisar todos os IDs e depois processar sua lógica

function SendEmail(selectedIds) {
if (selectedIds != null && selectedIds != “”) {
    var strIds = selectedIds.toString();
    var arrIds = strIds.split(“, ”);
    for (var indxIds = 0; indxIds < arrIds.length; indxIds++) {
        //The logic that you want to process on each record will come here.
    }
} else {
    alert(“No records selected !! !”);
}
}

Outras dicas

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Crm;
using Microsoft.Xrm.Sdk;
using System.ServiceModel;
using Microsoft.Xrm.Sdk.Query;
using Microsoft.Crm.Sdk.Messages;
using System.Text.RegularExpressions;
using System.Xml.Linq;

namespace SendEmail
{
    public class Email : IPlugin
    {
        public void Execute(IServiceProvider serviceprovider)
        {

            IPluginExecutionContext context = (IPluginExecutionContext)serviceprovider.GetService(typeof(IPluginExecutionContext));
            if (!(context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity))
                return;

            //entity
            Entity ent = (Entity)context.InputParameters["Target"];
            if (ent.LogicalName != "entityName")//EntityName
                throw new InvalidPluginExecutionException("Not a Service Request record! ");

            //service
            IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceprovider.GetService(typeof(IOrganizationServiceFactory));
            IOrganizationService _service = serviceFactory.CreateOrganizationService(context.UserId);
             string Email="";

            if (ent.Contains("emailidfiled"))
               Email = (string)ent["emailidfiled"];



            #region email template
            QueryExpression query = new QueryExpression()
            {
                EntityName = "template",
                Criteria = new FilterExpression(LogicalOperator.And),
                ColumnSet = new ColumnSet(true)
            };
            query.Criteria.AddCondition("title", ConditionOperator.Equal, "templateName");

            EntityCollection _coll = _service.RetrieveMultiple(query);
            if (_coll.Entities.Count == 0)
                throw new InvalidPluginExecutionException("Unable to find the template!");
            if (_coll.Entities.Count > 1)
                throw new InvalidPluginExecutionException("More than one template found!");

            var subjectTemplate = "";
            if (_coll[0].Contains("subject"))
            {
                subjectTemplate = GetDataFromXml(_coll[0]["subject"].ToString(), "match");
            }
            var bodyTemplate = "";
            if (_coll[0].Contains("body"))
            {
                bodyTemplate = GetDataFromXml(_coll[0]["body"].ToString(), "match");
            }
            #endregion



            #region email prep
            Entity email = new Entity("email");
            Entity entTo = new Entity("activityparty");
            entTo["addressused"] =Email;
            Entity entFrom = new Entity("activityparty");
            entFrom["partyid"] = "admin@admin.com";
            email["to"] = new Entity[] { entTo };
            email["from"] = new Entity[] { entFrom };
            email["regardingobjectid"] = new EntityReference(ent.LogicalName, ent.Id);
            email["subject"] = subjectTemplate;
            email["description"] = bodyTemplate;
            #endregion

            #region email creation & sending
            try
            {
                var emailid = _service.Create(email);
                SendEmailRequest req = new SendEmailRequest();
                req.EmailId = emailid;
                req.IssueSend = true;
                GetTrackingTokenEmailRequest wod_GetTrackingTokenEmailRequest = new GetTrackingTokenEmailRequest();
                GetTrackingTokenEmailResponse wod_GetTrackingTokenEmailResponse = (GetTrackingTokenEmailResponse)
                                                                 _service.Execute(wod_GetTrackingTokenEmailRequest);
                req.TrackingToken = wod_GetTrackingTokenEmailResponse.TrackingToken;
                _service.Execute(req);
            }
            catch (Exception ex)
            {
                throw new InvalidPluginExecutionException("Email can't be saved / sent." + Environment.NewLine + "Details: " + ex.Message);
            }
            #endregion



        }


        private static string GetDataFromXml(string value, string attributeName)
        {
            if (string.IsNullOrEmpty(value))
            {
                return string.Empty;
            }

            XDocument document = XDocument.Parse(value);
            // get the Element with the attribute name specified
            XElement element = document.Descendants().Where(ele => ele.Attributes().Any(attr => attr.Name == attributeName)).FirstOrDefault();
            return element == null ? string.Empty : element.Value;
        }
    }
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top