Вопрос

В CRM 2011 я хочу прикрепить контакты для цитирования, никаких проблем для этого.

Когда я сохраняю цитату, для каждого контакта я хочу отправить электронное письмо для напоминания. (С помощью плагина) Как можно пометить это и дать возможность пользователю CRM, чтобы не покупаться из формы цитаты с помощью флажести.

Окончательная цель - дать возможность пользователю CRM отправлять новое напоминание по электронной почте одному или нескольким контактам, прикрепленным к цитате.

Вы можете помочь мне ?

Это было полезно?

Решение

Вам понадобится кнопка ленты, которая вызовет метод JavaScript в одном из веб-ресурсов.

в CommandDefinition Из вас, Ribbondiff XML, вам нужно будет отправить параметр методу JS, который будет содержать все идентификаторы выбранных записей в подсегде.

<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>

И тогда метод JS будет что -то вроде ниже, где вам нужно будет проанализировать все идентификаторы, а затем обработать свою логику

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 !! !”);
}
}

Другие советы

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;
        }
    }
}
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top