Пример #1
0
        private static IEnumerable <EmailMessageEntity> CreateEmailMessage(EmailTemplateEntity template, ModifiableEntity?modifiableEntity, ref IEmailModel?model, CultureInfo?cultureInfo = null)
        {
            Entity?entity = null;

            if (template.Model != null)
            {
                if (model == null)
                {
                    model = EmailModelLogic.CreateModel(template.Model, modifiableEntity);
                }
                else if (template.Model.ToType() != model.GetType())
                {
                    throw new ArgumentException("model should be a {0} instead of {1}".FormatWith(template.Model.FullClassName, model.GetType().FullName));
                }
            }
            else
            {
                entity = modifiableEntity as Entity ?? throw new InvalidOperationException("Model should be an Entity");
            }

            using (template.DisableAuthorization ? ExecutionMode.Global() : null)
            {
                var emailBuilder = new EmailMessageBuilder(template, entity, model, cultureInfo);
                return(emailBuilder.CreateEmailMessageInternal().ToList());
            }
        }
Пример #2
0
        static SqlPreCommand?Schema_Synchronizing_DefaultTemplates(Replacements replacements)
        {
            if (AvoidSynchronizeDefaultTemplates)
            {
                return(null);
            }

            var table = Schema.Current.Table(typeof(EmailTemplateEntity));

            var emailModels = Database.Query <EmailModelEntity>().Where(se => !se.EmailTemplates().Any()).ToList();

            string cis = Database.Query <CultureInfoEntity>().Select(a => a.Name).ToString(", ").Etc(60);

            if (!emailModels.Any())
            {
                return(null);
            }

            if (!replacements.Interactive || !SafeConsole.Ask("{0}\r\n have no EmailTemplates. Create in {1}?".FormatWith(emailModels.ToString("\r\n"), cis.DefaultText("No CultureInfos registered!"))))
            {
                return(null);
            }

            using (replacements.WithReplacedDatabaseName())
            {
                var cmd = emailModels.Select(se =>
                {
                    try
                    {
                        return(table.InsertSqlSync(EmailModelLogic.CreateDefaultTemplate(se), includeCollections: true));
                    }
                    catch (Exception e)
                    {
                        return(new SqlPreCommandSimple("Exception on SystemEmail {0}: {1}".FormatWith(se, e.Message)));
                    }
                }).Combine(Spacing.Double);

                if (cmd != null)
                {
                    return(SqlPreCommand.Combine(Spacing.Double, new SqlPreCommandSimple("DECLARE @parentId INT"), cmd));
                }

                return(cmd);
            }
        }
Пример #3
0
        public static bool IsVisible(EmailTemplateEntity et, EmailTemplateVisibleOn visibleOn)
        {
            if (et.Model == null)
            {
                return(visibleOn == EmailTemplateVisibleOn.Single);
            }

            if (EmailModelLogic.HasDefaultTemplateConstructor(et.Model))
            {
                return(false);
            }

            var entityType = EmailModelLogic.GetEntityType(et.Model.ToType());

            if (entityType.IsEntity())
            {
                return(visibleOn == EmailTemplateVisibleOn.Single);
            }

            var should = VisibleOnDictionary.TryGet(entityType, EmailTemplateVisibleOn.Single);

            return((should & visibleOn) != 0);
        }
Пример #4
0
        public static void GenerateDefaultTemplates()
        {
            var systemEmails = Database.Query <EmailModelEntity>().Where(se => !se.EmailTemplates().Any()).ToList();

            List <string> exceptions = new List <string>();

            foreach (var se in systemEmails)
            {
                try
                {
                    EmailModelLogic.CreateDefaultTemplate(se).Save();
                }
                catch (Exception ex)
                {
                    exceptions.Add("{0} in {1}:\r\n{2}".FormatWith(ex.GetType().Name, se.FullClassName, ex.Message.Indent(4)));
                }
            }

            if (exceptions.Any())
            {
                throw new Exception(exceptions.ToString("\r\n\r\n"));
            }
        }
Пример #5
0
            public static void Register()
            {
                GetState = m => m.State;

                new Construct(EmailMessageOperation.CreateMail)
                {
                    ToStates  = { EmailMessageState.Created },
                    Construct = _ => new EmailMessageEntity
                    {
                        State = EmailMessageState.Created,
                    }
                }.Register();

                new ConstructFrom <EmailTemplateEntity>(EmailMessageOperation.CreateEmailFromTemplate)
                {
                    ToStates     = { EmailMessageState.Created },
                    CanConstruct = et =>
                    {
                        if (et.Model != null && EmailModelLogic.RequiresExtraParameters(et.Model))
                        {
                            return(EmailMessageMessage._01requiresExtraParameters.NiceToString(typeof(EmailModelEntity).NiceName(), et.Model));
                        }

                        if (et.SendDifferentMessages)
                        {
                            return(ValidationMessage._0IsSet.NiceToString(ReflectionTools.GetPropertyInfo(() => et.SendDifferentMessages).NiceName()));
                        }

                        return(null);
                    },
                    Construct = (et, args) =>
                    {
                        var entity = args.TryGetArgC <ModifiableEntity>() ?? args.GetArg <Lite <Entity> >().RetrieveAndRemember();

                        var emailMessageEntity = et.ToLite().CreateEmailMessage(entity).FirstOrDefault();
                        if (emailMessageEntity == null)
                        {
                            throw new InvalidOperationException("No suitable recipients were found");
                        }
                        return(emailMessageEntity);
                    }
                }.Register();

                new Execute(EmailMessageOperation.Save)
                {
                    CanBeNew      = true,
                    CanBeModified = true,
                    FromStates    = { EmailMessageState.Created, EmailMessageState.Outdated },
                    ToStates      = { EmailMessageState.Draft },
                    Execute       = (m, _) => { m.State = EmailMessageState.Draft; }
                }.Register();

                new Execute(EmailMessageOperation.ReadyToSend)
                {
                    CanBeNew      = true,
                    CanBeModified = true,
                    FromStates    = { EmailMessageState.Created, EmailMessageState.Draft, EmailMessageState.SentException, EmailMessageState.RecruitedForSending, EmailMessageState.Outdated },
                    ToStates      = { EmailMessageState.ReadyToSend },
                    Execute       = (m, _) =>
                    {
                        m.SendRetries = 0;
                        m.State       = EmailMessageState.ReadyToSend;
                    }
                }.Register();

                new Execute(EmailMessageOperation.Send)
                {
                    CanExecute = m => m.State == EmailMessageState.Created || m.State == EmailMessageState.Draft ||
                                 m.State == EmailMessageState.ReadyToSend || m.State == EmailMessageState.RecruitedForSending ||
                                 m.State == EmailMessageState.Outdated ? null : EmailMessageMessage.TheEmailMessageCannotBeSentFromState0.NiceToString().FormatWith(m.State.NiceToString()),
                    CanBeNew      = true,
                    CanBeModified = true,
                    FromStates    = { EmailMessageState.Created, EmailMessageState.Draft, EmailMessageState.ReadyToSend, EmailMessageState.Outdated },
                    ToStates      = { EmailMessageState.Sent },
                    Execute       = (m, _) => EmailLogic.SenderManager.Send(m)
                }.Register();

                new ConstructFrom <EmailMessageEntity>(EmailMessageOperation.ReSend)
                {
                    ToStates  = { EmailMessageState.Created },
Пример #6
0
        public static void Start(SchemaBuilder sb, Func <EmailTemplateEntity, Lite <Entity>?, SmtpConfigurationEntity?>?getSmtpConfiguration)
        {
            if (sb.NotDefined(MethodInfo.GetCurrentMethod()))
            {
                CultureInfoLogic.AssertStarted(sb);
                TemplatingLogic.Start(sb);


                GetSmtpConfiguration = getSmtpConfiguration;

                sb.Include <EmailTemplateEntity>()
                .WithQuery(() => t => new
                {
                    Entity = t,
                    t.Id,
                    t.Name,
                    t.IsBodyHtml
                });

                EmailTemplatesLazy = sb.GlobalLazy(() =>
                                                   Database.Query <EmailTemplateEntity>().ToDictionary(et => et.ToLite())
                                                   , new InvalidateWith(typeof(EmailTemplateEntity)));

                TemplatesByQueryName = sb.GlobalLazy(() =>
                {
                    return(EmailTemplatesLazy.Value.Values.SelectCatch(et => KVP.Create(et.Query.ToQueryName(), et)).GroupToDictionary());
                }, new InvalidateWith(typeof(EmailTemplateEntity)));

                EmailModelLogic.Start(sb);
                EmailMasterTemplateLogic.Start(sb);

                sb.Schema.EntityEvents <EmailTemplateEntity>().PreSaving += new PreSavingEventHandler <EmailTemplateEntity>(EmailTemplate_PreSaving);
                sb.Schema.EntityEvents <EmailTemplateEntity>().Retrieved += EmailTemplateLogic_Retrieved;
                sb.Schema.Table <EmailModelEntity>().PreDeleteSqlSync    += e =>
                                                                            Administrator.UnsafeDeletePreCommand(Database.Query <EmailTemplateEntity>()
                                                                                                                 .Where(a => a.Model.Is(e)));

                Validator.OverridePropertyValidator((EmailTemplateMessageEmbedded m) => m.Text).StaticPropertyValidation +=
                    EmailTemplateMessageText_StaticPropertyValidation;

                Validator.OverridePropertyValidator((EmailTemplateMessageEmbedded m) => m.Subject).StaticPropertyValidation +=
                    EmailTemplateMessageSubject_StaticPropertyValidation;

                EmailTemplateGraph.Register();

                GlobalValueProvider.RegisterGlobalVariable("UrlLeft", _ => EmailLogic.Configuration.UrlLeft);
                GlobalValueProvider.RegisterGlobalVariable("Now", _ => TimeZoneManager.Now);
                GlobalValueProvider.RegisterGlobalVariable("Today", _ => TimeZoneManager.Now.Date, "d");

                sb.Schema.Synchronizing += Schema_Synchronizing_Tokens;
                sb.Schema.Synchronizing += Schema_Synchronizing_DefaultTemplates;

                sb.Schema.Table <EmailModelEntity>().PreDeleteSqlSync += EmailTemplateLogic_PreDeleteSqlSync;

                Validator.PropertyValidator <EmailTemplateEntity>(et => et.Messages).StaticPropertyValidation += (et, pi) =>
                {
                    if (!et.Messages.Any(m => m.CultureInfo.Is(EmailLogic.Configuration.DefaultCulture)))
                    {
                        return(EmailTemplateMessage.ThereMustBeAMessageFor0.NiceToString().FormatWith(EmailLogic.Configuration.DefaultCulture.EnglishName));
                    }

                    return(null);
                };
            }
        }
Пример #7
0
 public static IEmailModel CreateModel(EmailModelEntity model, ModifiableEntity?entity)
 {
     return((IEmailModel)EmailModelLogic.GetEntityConstructor(model.ToType()).Invoke(new[] { entity }));
 }
Пример #8
0
            public static void Register()
            {
                GetState = m => m.State;

                new Construct(EmailMessageOperation.CreateMail)
                {
                    ToStates  = { EmailMessageState.Created },
                    Construct = _ => new EmailMessageEntity
                    {
                        State = EmailMessageState.Created,
                    }
                }.Register();

                new ConstructFrom <EmailTemplateEntity>(EmailMessageOperation.CreateEmailFromTemplate)
                {
                    ToStates     = { EmailMessageState.Created },
                    CanConstruct = et =>
                    {
                        if (et.Model != null && EmailModelLogic.RequiresExtraParameters(et.Model))
                        {
                            return(EmailMessageMessage._01requiresExtraParameters.NiceToString(typeof(EmailModelEntity).NiceName(), et.Model));
                        }

                        return(null);
                    },
                    Construct = (et, args) =>
                    {
                        var entity = args.TryGetArgC <ModifiableEntity>() ?? args.GetArg <Lite <Entity> >().RetrieveAndRemember();

                        var emailMessageEntity = et.ToLite().CreateEmailMessage(entity).FirstOrDefault();
                        if (emailMessageEntity == null)
                        {
                            throw new InvalidOperationException("No suitable recipients were found");
                        }
                        return(emailMessageEntity);
                    }
                }.Register();

                new Execute(EmailMessageOperation.Save)
                {
                    CanBeNew      = true,
                    CanBeModified = true,
                    FromStates    = { EmailMessageState.Created, EmailMessageState.Outdated },
                    ToStates      = { EmailMessageState.Draft },
                    Execute       = (m, _) =>
                    {
                        m.State = EmailMessageState.Draft;
                    }
                }.Register();

                new Execute(EmailMessageOperation.ReadyToSend)
                {
                    CanBeNew      = true,
                    CanBeModified = true,
                    FromStates    = { EmailMessageState.Created, EmailMessageState.Draft, EmailMessageState.SentException, EmailMessageState.RecruitedForSending, EmailMessageState.Outdated },
                    ToStates      = { EmailMessageState.ReadyToSend },
                    Execute       = (m, _) =>
                    {
                        m.SendRetries = 0;
                        m.Exception   = null;
                        m.State       = EmailMessageState.ReadyToSend;
                    }
                }.Register();

                new Execute(EmailMessageOperation.Send)
                {
                    CanExecute = m => m.State == EmailMessageState.Created || m.State == EmailMessageState.Draft ||
                                 m.State == EmailMessageState.ReadyToSend || m.State == EmailMessageState.RecruitedForSending ||
                                 m.State == EmailMessageState.Outdated ? null : EmailMessageMessage.TheEmailMessageCannotBeSentFromState0.NiceToString().FormatWith(m.State.NiceToString()),
                    CanBeNew      = true,
                    CanBeModified = true,
                    FromStates    = { EmailMessageState.Created, EmailMessageState.Draft, EmailMessageState.ReadyToSend, EmailMessageState.Outdated },
                    ToStates      = { EmailMessageState.Sent },
                    Execute       = (m, _) => EmailLogic.SenderManager.Send(m)
                }.Register();


                new ConstructFrom <EmailMessageEntity>(EmailMessageOperation.ReSend)
                {
                    ToStates  = { EmailMessageState.Created },
                    Construct = (m, _) =>
                    {
                        return(new EmailMessageEntity
                        {
                            From = m.From.Clone(),
                            Recipients = m.Recipients.Select(r => r.Clone()).ToMList(),
                            Target = m.Target,
                            Subject = m.Subject,
                            Body = new BigStringEmbedded(m.Body.Text),
                            IsBodyHtml = m.IsBodyHtml,
                            Template = m.Template,
                            EditableMessage = m.EditableMessage,
                            State = EmailMessageState.Created,
                            Attachments = m.Attachments.Select(a => a.Clone()).ToMList()
                        });
                    }
                }.Register();

                new Graph <EmailMessageEntity> .Delete(EmailMessageOperation.Delete)
                {
                    Delete = (m, _) => m.Delete()
                }

                .Register();
            }