Пример #1
0
        public static string GenerateEmailContent(this XrmService xrmService, string emailTemplateResourceName, string emailTemplateTargetType, Guid emailTemplateTargetId, string crmurl = null, string appendAppIdToCrmUrl = null)
        {
            string activityDescription = null;
            var    targetTokens        = new List <string>();
            var    staticTokens        = new Dictionary <string, List <string> >();
            var    ifTokens            = new List <string>();
            var    staticIdentifier    = "STATIC|";
            var    ifIdentifier        = "IF|";
            var    endifIdentifier     = "ENDIF";

            if (emailTemplateResourceName != null)
            {
                var resource = xrmService.GetFirst(Entities.webresource, Fields.webresource_.name, emailTemplateResourceName);
                if (resource == null)
                {
                    throw new NullReferenceException(string.Format("Could Not Find {0} With {1} '{2}'", xrmService.GetEntityLabel(Entities.webresource), xrmService.GetFieldLabel(Fields.webresource_.name, Entities.webresource), emailTemplateResourceName));
                }
                var    encoded = resource.GetStringField(Fields.webresource_.content);
                byte[] binary  = Convert.FromBase64String(encoded);
                activityDescription = UnicodeEncoding.UTF8.GetString(binary);

                if (appendAppIdToCrmUrl != null)
                {
                    var baseUrlPart = "crminstanceurl]/main.aspx?";
                    activityDescription = activityDescription.Replace(baseUrlPart, baseUrlPart + "appid=" + appendAppIdToCrmUrl + "&");
                }

                //parse out all tokens inside [] chars to replace in the email

                var i = 0;
                while (i < activityDescription.Length)
                {
                    if (activityDescription[i] == '[')
                    {
                        var startIndex = i;
                        while (i < activityDescription.Length)
                        {
                            if (activityDescription[i] == ']')
                            {
                                var endIndex = i;
                                var token    = activityDescription.Substring(startIndex + 1, endIndex - startIndex - 1);

                                if (token.ToUpper().StartsWith(ifIdentifier) || token.ToUpper().StartsWith(endifIdentifier))
                                {
                                    ifTokens.Add(token);
                                }
                                else if (token.ToUpper().StartsWith(staticIdentifier))
                                {
                                    token = token.Substring(staticIdentifier.Length);
                                    var split = token.Split('.');
                                    if (split.Count() != 2)
                                    {
                                        throw new Exception(string.Format("The static token {0} is not formatted as expected. It should be of the form type.field", token));
                                    }
                                    var staticType  = split.First();
                                    var staticField = split.ElementAt(1);
                                    if (!staticTokens.ContainsKey(staticType))
                                    {
                                        staticTokens.Add(staticType, new List <string>());
                                    }
                                    staticTokens[staticType].Add(staticField);
                                }

                                else
                                {
                                    targetTokens.Add(token);
                                }
                                break;
                            }
                            i++;
                        }
                    }
                    else
                    {
                        i++;
                    }
                }
            }

            //query to get all the fields for replacing tokens
            var query = xrmService.BuildSourceQuery(emailTemplateTargetType, targetTokens);

            query.Criteria.AddCondition(new ConditionExpression(xrmService.GetPrimaryKeyField(emailTemplateTargetType), ConditionOperator.Equal, emailTemplateTargetId));
            var targetObject = xrmService.RetrieveFirst(query);

            //process all the ifs (clear where not)
            while (ifTokens.Any())
            {
                var endIfTokenStackCount = 0;
                var removeAll            = false;
                var token = ifTokens.First();
                if (token.ToUpper() != endifIdentifier)
                {
                    var tokenIndex = activityDescription.IndexOf(token);
                    var indexOf    = token.IndexOf("|");
                    if (indexOf > -1)
                    {
                        var field           = token.Substring(indexOf + 1);
                        var fieldValue      = targetObject.GetFieldValue(field);
                        var endIfTokenStack = 1;
                        var remainingTokens = ifTokens.Skip(1).ToList();
                        while (true && remainingTokens.Any())
                        {
                            if (remainingTokens.First().ToUpper() == endifIdentifier)
                            {
                                endIfTokenStack--;
                                endIfTokenStackCount++;
                            }
                            else
                            {
                                endIfTokenStack++;
                            }
                            remainingTokens.RemoveAt(0);
                            if (endIfTokenStack == 0)
                            {
                                break;
                            }
                        }
                        //okay so starting at the current index need to find the end if
                        //and remove the content or the tokens
                        var currentStack = endIfTokenStackCount;
                        var currentIndex = activityDescription.IndexOf(token);
                        while (currentStack > 0)
                        {
                            var endIfIndex = activityDescription.IndexOf(endifIdentifier, currentIndex, StringComparison.OrdinalIgnoreCase);
                            if (endIfIndex > -1)
                            {
                                currentIndex = endIfIndex;
                                currentStack--;
                            }
                            else
                            {
                                break;
                            }
                        }
                        removeAll = fieldValue == null;
                        if (removeAll)
                        {
                            var startRemove = tokenIndex - 1;
                            var endRemove   = currentIndex + endifIdentifier.Length + 1;
                            activityDescription = activityDescription.Substring(0, startRemove) + activityDescription.Substring(endRemove);
                        }
                        else
                        {
                            var startRemove = tokenIndex - 1;
                            var endRemove   = currentIndex - 1;
                            activityDescription = activityDescription.Substring(0, startRemove)
                                                  + activityDescription.Substring(startRemove + token.Length + 2, endRemove - startRemove - token.Length - 2)
                                                  + activityDescription.Substring(endRemove + endifIdentifier.Length + 2);
                        }
                    }
                }
                ifTokens.RemoveRange(0, endIfTokenStackCount > 0 ? endIfTokenStackCount * 2 : 1);
            }

            //replace all the tokens
            foreach (var token in targetTokens)
            {
                var    sourceType    = emailTemplateTargetType;
                string displayString = xrmService.GetDisplayString(targetObject, token, isHtml: true);
                activityDescription = activityDescription.Replace("[" + token + "]", displayString);
            }

            foreach (var staticTargetTokens in staticTokens)
            {
                var staticType   = staticTargetTokens.Key;
                var staticFields = staticTargetTokens.Value;

                //query to get all the fields for replacing tokens
                var staticQuery  = xrmService.BuildSourceQuery(staticType, staticFields);
                var staticTarget = xrmService.RetrieveFirst(staticQuery);

                //replace all the tokens
                foreach (var staticField in staticFields)
                {
                    string staticFunc = null;
                    activityDescription = activityDescription.Replace("[STATIC|" + string.Format("{0}.{1}", staticType, staticField) + "]", xrmService.GetFieldAsDisplayString(staticType, staticField, staticTarget.GetFieldValue(staticField), isHtml: true, func: staticFunc));
                }
            }
            return(activityDescription);
        }