Ejemplo n.º 1
0
        static void Newsletter_PreSaving(NewsletterEntity newsletter, ref bool graphModified)
        {
            var queryname       = QueryLogic.ToQueryName(newsletter.Query.Key);
            QueryDescription qd = DynamicQueryManager.Current.QueryDescription(queryname);

            newsletter.Subject = EmailTemplateParser.Parse(newsletter.Subject, qd, null).ToString();
            newsletter.Text    = EmailTemplateParser.Parse(newsletter.Text, qd, null).ToString();
        }
Ejemplo n.º 2
0
        EmailTemplateParser.BlockNode SubjectNode(EmailTemplateMessageEmbedded message)
        {
            if (message.SubjectParsedNode == null)
            {
                message.SubjectParsedNode = EmailTemplateParser.Parse(message.Subject, qd, template.SystemEmail.ToType());
            }

            return((EmailTemplateParser.BlockNode)message.SubjectParsedNode);
        }
Ejemplo n.º 3
0
        private static string GetTemplateString(string title, ref object titleNode, EmailTemplateLogic.GenerateAttachmentContext ctx)
        {
            var block = titleNode != null ? (EmailTemplateParser.BlockNode)titleNode :
                        (EmailTemplateParser.BlockNode)(titleNode = EmailTemplateParser.Parse(title, ctx.QueryDescription, ctx.ModelType));

            return(block.Print(new EmailTemplateParameters(ctx.Entity, ctx.Culture, ctx.ResultColumns, ctx.CurrentRows)
            {
                SystemEmail = ctx.SystemEmail
            }));
        }
Ejemplo n.º 4
0
        public static void Start(SchemaBuilder sb, DynamicQueryManager dqm)
        {
            sb.Settings.AssertImplementedBy((EmailTemplateEntity e) => e.Attachments.First(), typeof(ImageAttachmentEntity));

            sb.Include <ImageAttachmentEntity>()
            .WithQuery(dqm, () => s => new
            {
                Entity = s,
                s.Id,
                s.FileName,
                s.ContentId
            });

            Validator.PropertyValidator((ImageAttachmentEntity e) => e.FileName).StaticPropertyValidation = ImageAttachmentFileName_StaticPropertyValidation;

            EmailTemplateLogic.FillAttachmentTokens.Register((ImageAttachmentEntity wa, EmailTemplateLogic.FillAttachmentTokenContext ctx) =>
            {
                if (wa.FileName != null)
                {
                    EmailTemplateParser.Parse(wa.FileName, ctx.QueryDescription, ctx.ModelType).FillQueryTokens(ctx.QueryTokens);
                }
            });

            EmailTemplateLogic.GenerateAttachment.Register((ImageAttachmentEntity a, EmailTemplateLogic.GenerateAttachmentContext ctx) =>
            {
                using (CultureInfoUtils.ChangeBothCultures(ctx.Culture))
                {
                    var fileName = a.FileName.IsEmpty() ? a.File.FileName : GetTemplateString(a.FileName, ref a.FileNameNode, ctx);

                    return(new List <EmailAttachmentEmbedded>
                    {
                        new EmailAttachmentEmbedded
                        {
                            File = new FilePathEmbedded(EmailFileType.Attachment, fileName, a.File.BinaryFile),
                            Type = a.Type,
                            ContentId = a.ContentId,
                        }
                    });
                }
            });
        }
Ejemplo n.º 5
0
        EmailTemplateParser.BlockNode TextNode(EmailTemplateMessageEmbedded message)
        {
            if (message.TextParsedNode == null)
            {
                string body = message.Text;

                if (template.MasterTemplate != null)
                {
                    var emt  = template.MasterTemplate.Retrieve();
                    var emtm = emt.GetCultureMessage(message.CultureInfo.ToCultureInfo()) ??
                               emt.GetCultureMessage(EmailLogic.Configuration.DefaultCulture.ToCultureInfo());

                    if (emtm != null)
                    {
                        body = EmailMasterTemplateEntity.MasterTemplateContentRegex.Replace(emtm.Text, m => body);
                    }
                }

                message.TextParsedNode = EmailTemplateParser.Parse(body, qd, template.SystemEmail.ToType());
            }

            return((EmailTemplateParser.BlockNode)message.TextParsedNode);
        }
Ejemplo n.º 6
0
        public void Execute(ExecutingProcess executingProcess)
        {
            NewsletterEntity newsletter = (NewsletterEntity)executingProcess.Data;

            var queryName = QueryLogic.ToQueryName(newsletter.Query.Key);

            QueryDescription qd = DynamicQueryManager.Current.QueryDescription(queryName);

            List <QueryToken> list = new List <QueryToken>();

            using (ExecutionMode.Global())
            {
                list.Add(QueryUtils.Parse("Entity", qd, 0));
                list.Add(QueryUtils.Parse(".".Combine("Entity", "NewsletterDeliveries", "Element"), qd, SubTokensOptions.CanElement));
                list.Add(QueryUtils.Parse(".".Combine("Entity", "EmailOwnerData"), qd, 0));

                EmailTemplateParser.Parse(newsletter.Subject, qd, null).FillQueryTokens(list);
                EmailTemplateParser.Parse(newsletter.Text, qd, null).FillQueryTokens(list);

                list = list.Distinct().ToList();
            }

            var columns = list.Select(qt => new Column(qt, null)).ToList();

            //var columns = new List<QueryToken>();
            //columns.Add(QueryUtils.Parse("Entity.NewsletterDeliveries.Element", qd, canAggregate: false));
            //columns.Add(QueryUtils.Parse("Entity.Email", qd, canAggregate: false));
            //columns.AddRange(NewsletterLogic.GetTokens(queryName, newsletter.Subject));
            //columns.AddRange(NewsletterLogic.GetTokens(queryName, newsletter.Text));

            columns = columns.Distinct().ToList();

            var resultTable = DynamicQueryManager.Current.ExecuteQuery(new QueryRequest
            {
                QueryName = queryName,
                Filters   = new List <Filter>
                {
                    new Filter(QueryUtils.Parse("Entity.NewsletterDeliveries.Element.Newsletter", qd, SubTokensOptions.CanElement), FilterOperation.EqualTo, newsletter.ToLite()),
                    new Filter(QueryUtils.Parse("Entity.NewsletterDeliveries.Element.Sent", qd, SubTokensOptions.CanElement), FilterOperation.EqualTo, false),
                },
                Orders     = new List <Order>(),
                Columns    = columns,
                Pagination = new Pagination.All(),
            });

            var dicTokenColumn = resultTable.Columns.ToDictionary(rc => rc.Column.Token);

            var entityColumn     = resultTable.Columns.SingleEx(c => c.Column.Token.FullKey() == "Entity");
            var deliveryColumn   = resultTable.Columns.SingleEx(c => c.Column.Token.FullKey() == "Entity.NewsletterDeliveries.Element");
            var emailOwnerColumn = resultTable.Columns.SingleEx(c => c.Column.Token.FullKey() == "Entity.EmailOwnerData");

            var lines = resultTable.Rows.GroupBy(r => (Lite <Entity>)r[entityColumn]).Select(g => new SendLine
            {
                NewsletterDelivery = (Lite <NewsletterDeliveryEntity>)g.DistinctSingle(deliveryColumn),
                Email = (EmailOwnerData)g.DistinctSingle(emailOwnerColumn),
                Rows  = g,
            }).ToList();

            if (newsletter.SubjectParsedNode == null)
            {
                newsletter.SubjectParsedNode = EmailTemplateParser.Parse(newsletter.Subject, qd, null);
            }

            if (newsletter.TextParsedNode == null)
            {
                newsletter.TextParsedNode = EmailTemplateParser.Parse(newsletter.Text, qd, null);
            }

            var conf = EmailLogic.Configuration;

            int processed = 0;

            foreach (var group in lines.GroupsOf(20))
            {
                processed += group.Count;

                executingProcess.CancellationToken.ThrowIfCancellationRequested();

                if (conf.SendEmails)
                {
                    Parallel.ForEach(group, s =>
                    {
                        try
                        {
                            var smtpConfig = NewsletterLogic.GetStmpConfiguration(newsletter);

                            var client  = smtpConfig.GenerateSmtpClient();
                            var message = new MailMessage();

                            if (newsletter.From.HasText())
                            {
                                message.From = new MailAddress(newsletter.From, newsletter.DisplayFrom);
                            }
                            else
                            {
                                message.From = smtpConfig.DefaultFrom.ToMailAddress();
                            }

                            message.To.Add(conf.OverrideEmailAddress.DefaultText(s.Email.Email));

                            message.Subject = ((EmailTemplateParser.BlockNode)newsletter.SubjectParsedNode).Print(
                                new EmailTemplateParameters(null, null, dicTokenColumn, s.Rows)
                            {
                                IsHtml = false,
                            });

                            message.Body = ((EmailTemplateParser.BlockNode)newsletter.TextParsedNode).Print(
                                new EmailTemplateParameters(null, null, dicTokenColumn, s.Rows)
                            {
                                IsHtml = true,
                            });

                            message.IsBodyHtml = true;

                            client.Send(message);
                        }
                        catch (Exception ex)
                        {
                            s.Exception = ex;
                        }
                    });
                }

                var failed = group.Extract(sl => sl.Exception != null);
                foreach (var f in failed)
                {
                    new ProcessExceptionLineEntity
                    {
                        Exception = f.Exception.LogException().ToLite(),
                        Line      = f.NewsletterDelivery,
                        Process   = executingProcess.CurrentProcess.ToLite(),
                    }.Save();
                }


                var sent = group.Select(sl => sl.NewsletterDelivery).ToList();
                if (sent.Any())
                {
                    Database.Query <NewsletterDeliveryEntity>()
                    .Where(nd => sent.Contains(nd.ToLite()))
                    .UnsafeUpdate()
                    .Set(nd => nd.Sent, nd => true)
                    .Set(nd => nd.SendDate, nd => TimeZoneManager.Now.TrimToSeconds())
                    .Execute();
                }

                executingProcess.ProgressChanged(processed, lines.Count);
            }

            newsletter.State = NewsletterState.Sent;

            using (OperationLogic.AllowSave <NewsletterEntity>())
                newsletter.Save();
        }