public static void Start(SchemaBuilder sb) { if (sb.NotDefined(MethodInfo.GetCurrentMethod())) { sb.Include <OrderEntity>() .WithQuery(() => o => new { Entity = o, o.Id, o.State, o.Customer, o.Employee, o.OrderDate, o.RequiredDate, o.ShipAddress, o.ShipVia, }); QueryLogic.Queries.Register(OrderQuery.OrderLines, () => from o in Database.Query <OrderEntity>() from od in o.Details select new { Entity = o, o.Id, od.Product, od.Quantity, od.UnitPrice, od.Discount, od.SubTotalPrice, }); OrderGraph.Register(); ProcessLogic.Register(OrderProcess.CancelOrders, new CancelOrderAlgorithm()); SimpleTaskLogic.Register(OrderTask.CancelOldOrdersWithProcess, ctx => { var package = new PackageEntity().CreateLines(Database.Query <OrderEntity>().Where(a => a.OrderDate < DateTime.Now.AddDays(-7) && a.State != OrderState.Canceled)); var process = ProcessLogic.Create(OrderProcess.CancelOrders, package); process.Execute(ProcessOperation.Execute); return(process.ToLite()); }); SimpleTaskLogic.Register(OrderTask.CancelOldOrders, ctx => { Database.Query <OrderEntity>() .Where(a => a.OrderDate < DateTime.Now.AddDays(-7)) .UnsafeUpdate() .Set(o => o.CancelationDate, o => DateTime.Now) .Set(o => o.State, o => OrderState.Canceled) .Execute(); return(null); });//CancelOldOrdersProcess } }
public static void Start(SchemaBuilder sb) { if (sb.NotDefined(MethodInfo.GetCurrentMethod())) { sb.Schema.Settings.AssertImplementedBy((ProcessEntity p) => p.Data, typeof(EmailPackageEntity)); sb.Include <EmailPackageEntity>() .WithQuery(() => e => new { Entity = e, e.Id, e.Name, }); QueryLogic.Expressions.Register((EmailPackageEntity ep) => ep.Messages(), () => EmailMessageMessage.Messages.NiceToString()); QueryLogic.Expressions.Register((EmailPackageEntity ep) => ep.RemainingMessages(), () => EmailMessageMessage.RemainingMessages.NiceToString()); QueryLogic.Expressions.Register((EmailPackageEntity ep) => ep.ExceptionMessages(), () => EmailMessageMessage.ExceptionMessages.NiceToString()); ProcessLogic.AssertStarted(sb); ProcessLogic.Register(EmailMessageProcess.CreateEmailsSendAsync, new CreateEmailsSendAsyncProcessAlgorithm()); ProcessLogic.Register(EmailMessageProcess.SendEmails, new SendEmailProcessAlgorithm()); new Graph <ProcessEntity> .ConstructFromMany <EmailMessageEntity>(EmailMessageOperation.ReSendEmails) { Construct = (messages, args) => { if (!messages.Any()) { return(null); } EmailPackageEntity emailPackage = new EmailPackageEntity() { Name = args.TryGetArgC <string>() }.Save(); foreach (var m in messages.Select(m => m.RetrieveAndForget())) { new EmailMessageEntity() { Package = emailPackage.ToLite(), From = m.From, Recipients = m.Recipients.ToMList(), Target = m.Target, Body = new BigStringEmbedded(m.Body.Text), IsBodyHtml = m.IsBodyHtml, Subject = m.Subject, Template = m.Template, EditableMessage = m.EditableMessage, State = EmailMessageState.RecruitedForSending, Attachments = m.Attachments.Select(a => a.Clone()).ToMList() }.Save(); } return(ProcessLogic.Create(EmailMessageProcess.SendEmails, emailPackage)); } } .Register(); } }
private static ProcessEntity?UpdateMessages(List <SMSMessageEntity> messages) { if (!messages.Any()) { return(null); } SMSUpdatePackageEntity package = new SMSUpdatePackageEntity().Save(); var packLite = package.ToLite(); if (messages.Any(m => m.State != SMSMessageState.Sent)) { throw new ApplicationException("SMS messages must be sent prior to update the status"); } messages.ForEach(ms => ms.UpdatePackage = packLite); messages.SaveList(); var process = ProcessLogic.Create(SMSMessageProcess.UpdateStatus, package); process.Execute(ProcessOperation.Execute); return(process); }
public static ProcessEntity SendMultipleEmailsAsync(Lite <EmailTemplateEntity> template, List <Lite <Entity> > targets, ModelConverterSymbol?converter) { if (converter == null) { return(ProcessLogic.Create(EmailMessageProcess.CreateEmailsSendAsync, new PackageEntity().SetOperationArgs(new object[] { template }).CreateLines(targets))); } return(ProcessLogic.Create(EmailMessageProcess.CreateEmailsSendAsync, new PackageEntity().SetOperationArgs(new object[] { template, converter }).CreateLines(targets))); }
public static void RegisterSMSOwnerData <T>(Expression <Func <T, SMSOwnerData> > phoneExpression) where T : Entity { new Graph <ProcessEntity> .ConstructFromMany <T>(SMSMessageOperation.SendMultipleSMSMessages) { Construct = (providers, args) => { var sMSOwnerDatas = Database.Query <T>().Where(p => providers.Contains(p.ToLite())) .Select(pr => phoneExpression.Evaluate(pr)) .AsEnumerable().NotNull().Distinct().ToList(); MultipleSMSModel model = args.GetArg <MultipleSMSModel>(); IntegrityCheck?ic = model.IntegrityCheck(); if (!model.Message.HasText()) { throw new ApplicationException("The text for the SMS message has not been set"); } var owners = (from od in sMSOwnerDatas from n in od.TelephoneNumber.SplitNoEmpty(",") select new { TelephoneNumber = n, SMSOwnerData = od }); if (!owners.Any()) { return(null); } SMSSendPackageEntity package = new SMSSendPackageEntity().Save(); var packLite = package.ToLite(); using (OperationLogic.AllowSave <SMSMessageEntity>()) { owners.Select(o => new SMSMessageEntity { DestinationNumber = o.TelephoneNumber, SendPackage = packLite, Referred = o.SMSOwnerData.Owner, Message = model.Message, From = model.From, Certified = model.Certified, State = SMSMessageState.Created, }).SaveList(); } var process = ProcessLogic.Create(SMSMessageProcess.Send, package); process.Execute(ProcessOperation.Execute); return(process); } } .Register(); }
public static void RegisterPhoneNumberProvider <T>(Expression <Func <T, string> > phoneExpression, Expression <Func <T, CultureInfo> > cultureExpression) where T : Entity { phoneNumberProviders[typeof(T)] = phoneExpression; cultureProviders[typeof(T)] = cultureExpression; new Graph <ProcessEntity> .ConstructFromMany <T>(SMSMessageOperation.SendSMSMessages) { Construct = (providers, args) => { var numbers = Database.Query <T>().Where(p => providers.Contains(p.ToLite())) .Select(pr => new { Exp = phoneExpression.Evaluate(pr), Referred = pr.ToLite() }).AsEnumerable().NotNull().Distinct().ToList(); var splitNumbers = (from p in numbers.Where(p => p.Exp.Contains(',')) from n in p.Exp.Split('n') select new { Exp = n.Trim(), p.Referred }).Concat(numbers.Where(p => !p.Exp.Contains(','))).Distinct().ToList(); numbers = splitNumbers; MultipleSMSModel model = args.GetArg <MultipleSMSModel>(); IntegrityCheck ic = model.IntegrityCheck(); if (!model.Message.HasText()) { throw new ApplicationException("The text for the SMS message has not been set"); } SMSSendPackageEntity package = new SMSSendPackageEntity().Save(); var packLite = package.ToLite(); using (OperationLogic.AllowSave <SMSMessageEntity>()) numbers.Select(n => new SMSMessageEntity { DestinationNumber = n.Exp, SendPackage = packLite, Referred = n.Referred, Message = model.Message, From = model.From, Certified = model.Certified, State = SMSMessageState.Created, }).SaveList(); var process = ProcessLogic.Create(SMSMessageProcess.Send, package); process.Execute(ProcessOperation.Execute); return(process); } } .Register(); }
public static void Start(SchemaBuilder sb, DynamicQueryManager dqm) { if (sb.NotDefined(MethodInfo.GetCurrentMethod())) { sb.Include <EmailPackageEntity>() .WithQuery(dqm, () => e => new { Entity = e, e.Id, e.Name, }); dqm.RegisterExpression((EmailPackageEntity ep) => ep.Messages(), () => EmailMessageMessage.Messages.NiceToString()); dqm.RegisterExpression((EmailPackageEntity ep) => ep.RemainingMessages(), () => EmailMessageMessage.RemainingMessages.NiceToString()); dqm.RegisterExpression((EmailPackageEntity ep) => ep.ExceptionMessages(), () => EmailMessageMessage.ExceptionMessages.NiceToString()); ProcessLogic.AssertStarted(sb); ProcessLogic.Register(EmailMessageProcess.CreateEmailsSendAsync, new CreateEmailsSendAsyncProcessAlgorithm()); ProcessLogic.Register(EmailMessageProcess.SendEmails, new SendEmailProcessAlgorithm()); new Graph <ProcessEntity> .ConstructFromMany <EmailMessageEntity>(EmailMessageOperation.ReSendEmails) { Construct = (messages, args) => { EmailPackageEntity emailPackage = new EmailPackageEntity() { Name = args.TryGetArgC <string>() }.Save(); foreach (var m in messages.Select(m => m.RetrieveAndForget())) { new EmailMessageEntity() { Package = emailPackage.ToLite(), From = m.From, Recipients = m.Recipients.ToMList(), Target = m.Target, Body = m.Body, IsBodyHtml = m.IsBodyHtml, Subject = m.Subject, Template = m.Template, EditableMessage = m.EditableMessage, State = EmailMessageState.RecruitedForSending }.Save(); } return(ProcessLogic.Create(EmailMessageProcess.SendEmails, emailPackage)); } } .Register(); } }
public static void Register() { GetState = n => n.State; new ConstructFrom <NewsletterEntity>(NewsletterOperation.Clone) { ToStates = { NewsletterState.Created }, Construct = (n, _) => new NewsletterEntity { Name = n.Name, From = n.From, DisplayFrom = n.DisplayFrom, Query = n.Query, Subject = n.Subject, Text = n.Text, } }.Register(); new Execute(NewsletterOperation.Save) { CanBeNew = true, CanBeModified = true, FromStates = { NewsletterState.Created, NewsletterState.Saved }, ToStates = { NewsletterState.Saved }, Execute = (n, _) => n.State = NewsletterState.Saved }.Register(); new Execute(NewsletterOperation.AddRecipients) { FromStates = { NewsletterState.Saved }, ToStates = { NewsletterState.Saved }, Execute = (n, args) => { var p = args.GetArg <List <Lite <IEmailOwnerEntity> > >(); var existent = Database.Query <NewsletterDeliveryEntity>().Where(d => d.Newsletter.Is(n)).Select(d => d.Recipient).ToList(); p.Except(existent).Select(ie => new NewsletterDeliveryEntity { Recipient = ie, Newsletter = n.ToLite() }).ToList().SaveList(); n.State = NewsletterState.Saved; } }.Register(); new Execute(NewsletterOperation.RemoveRecipients) { FromStates = { NewsletterState.Saved }, ToStates = { NewsletterState.Saved }, Execute = (n, args) => { var p = args.GetArg <List <Lite <NewsletterDeliveryEntity> > >(); foreach (var nd in p.GroupsOf(20)) { Database.DeleteList(nd); } n.State = NewsletterState.Saved; } }.Register(); new Graph <ProcessEntity> .ConstructFrom <NewsletterEntity>(NewsletterOperation.Send) { CanConstruct = n => { if (n.Subject.IsNullOrEmpty()) { return("Subject must be set"); } if (n.Text.IsNullOrEmpty()) { return("Text must be set"); } if (!Database.Query <NewsletterDeliveryEntity>().Any(d => d.Newsletter.Is(n))) { return("There is not any delivery for this newsletter"); } return(null); }, Construct = (n, _) => ProcessLogic.Create(NewsletterProcess.SendNewsletter, n) } .Register(); }
public static void RegisterDataObjectProvider <T, A>(Expression <Func <T, A> > func) where T : Entity { dataObjectProviders[typeof(T)] = func; new Graph <ProcessEntity> .ConstructFromMany <T>(SMSMessageOperation.SendSMSMessagesFromTemplate) { Construct = (providers, args) => { var template = args.GetArg <SMSTemplateEntity>(); if (TypeLogic.EntityToType[template.AssociatedType] != typeof(T)) { throw new ArgumentException("The SMS template is associated with the type {0} instead of {1}" .FormatWith(template.AssociatedType.FullClassName, typeof(T).FullName)); } var phoneFunc = (Expression <Func <T, string> >)phoneNumberProviders .GetOrThrow(typeof(T), "{0} is not registered as PhoneNumberProvider".FormatWith(typeof(T).NiceName())); var cultureFunc = (Expression <Func <T, CultureInfo> >)cultureProviders .GetOrThrow(typeof(T), "{0} is not registered as CultureProvider".FormatWith(typeof(T).NiceName())); var numbers = Database.Query <T>().Where(p => providers.Contains(p.ToLite())) .Select(p => new { Phone = phoneFunc.Evaluate(p), Data = func.Evaluate(p), Referred = p.ToLite(), Culture = cultureFunc.Evaluate(p) }).Where(n => n.Phone.HasText()).AsEnumerable().ToList(); var splitdNumbers = (from p in numbers.Where(p => p.Phone.Contains(',')) from n in p.Phone.Split(',') select new { Phone = n.Trim(), p.Data, p.Referred, p.Culture }).Concat(numbers.Where(p => !p.Phone.Contains(','))).Distinct().ToList(); numbers = splitdNumbers; SMSSendPackageEntity package = new SMSSendPackageEntity().Save(); var packLite = package.ToLite(); using (OperationLogic.AllowSave <SMSMessageEntity>()) { numbers.Select(n => new SMSMessageEntity { Message = template.ComposeMessage(n.Data, n.Culture), EditableMessage = template.EditableMessage, From = template.From, DestinationNumber = n.Phone, SendPackage = packLite, State = SMSMessageState.Created, Referred = n.Referred }).SaveList(); } var process = ProcessLogic.Create(SMSMessageProcess.Send, package); process.Execute(ProcessOperation.Execute); return(process); } } .Register(); new Graph <SMSMessageEntity> .ConstructFrom <T>(SMSMessageOperation.CreateSMSWithTemplateFromEntity) { Construct = (provider, args) => { var template = args.GetArg <SMSTemplateEntity>(); if (template.AssociatedType != null && TypeLogic.EntityToType[template.AssociatedType] != typeof(T)) { throw new ArgumentException("The SMS template is associated with the type {0} instead of {1}" .FormatWith(template.AssociatedType.FullClassName, typeof(T).FullName)); } return(new SMSMessageEntity { Message = template.ComposeMessage(func.Evaluate(provider), GetCulture(provider)), EditableMessage = template.EditableMessage, From = template.From, DestinationNumber = GetPhoneNumber(provider), State = SMSMessageState.Created, Referred = provider.ToLite(), Certified = template.Certified }); } } .Register(); }
public static void Register() { GetState = o => o.State; new Construct(OrderOperation.Create) { ToStates = { OrderState.New }, Construct = (args) => { var customer = args.TryGetArgC <Lite <CustomerEntity> >()?.Retrieve(); return(new OrderEntity { Customer = customer, ShipAddress = customer?.Address.Clone(), State = OrderState.New, Employee = EmployeeEntity.Current, RequiredDate = DateTime.Now.AddDays(3), }); } }.Register(); new ConstructFrom <CustomerEntity>(OrderOperation.CreateOrderFromCustomer) { ToStates = { OrderState.New }, Construct = (c, _) => new OrderEntity { State = OrderState.New, Customer = c, Employee = EmployeeEntity.Current, ShipAddress = c.Address, RequiredDate = DateTime.Now.AddDays(3), } }.Register(); new ConstructFromMany <ProductEntity>(OrderOperation.CreateOrderFromProducts) { ToStates = { OrderState.New }, Construct = (prods, args) => { var dic = Database.Query <ProductEntity>() .Where(p => prods.Contains(p.ToLite())) .Select(p => new KeyValuePair <Lite <ProductEntity>, decimal>(p.ToLite(), p.UnitPrice)).ToDictionary(); var customer = args.TryGetArgC <Lite <CustomerEntity> >()?.Retrieve(); return(new OrderEntity { Customer = customer, ShipAddress = customer?.Address.Clone(), State = OrderState.New, Employee = EmployeeEntity.Current, RequiredDate = DateTime.Now.AddDays(3), Details = prods.Select(p => new OrderDetailEmbedded { Product = p, UnitPrice = dic[p], Quantity = 1, }).ToMList() }); } }.Register(); new Graph <ProcessEntity> .ConstructFromMany <OrderEntity>(OrderOperation.CancelWithProcess) { Construct = (orders, _) => { return(ProcessLogic.Create(OrderProcess.CancelOrders, new PackageEntity().CreateLines(orders))); } } .Register(); new Execute(OrderOperation.SaveNew) { FromStates = { OrderState.New }, ToStates = { OrderState.Ordered }, CanBeNew = true, CanBeModified = true, Execute = (o, args) => { o.OrderDate = DateTime.Now; o.State = OrderState.Ordered; } }.Register(); new Execute(OrderOperation.Save) { FromStates = { OrderState.Ordered }, ToStates = { OrderState.Ordered }, CanBeModified = true, Execute = (o, _) => { } }.Register(); new Execute(OrderOperation.Ship) { CanExecute = o => o.Details.IsEmpty() ? "No order lines" : null, FromStates = { OrderState.Ordered }, ToStates = { OrderState.Shipped }, CanBeModified = true, Execute = (o, args) => { o.ShippedDate = args.TryGetArgS <DateTime>() ?? DateTime.Now; o.State = OrderState.Shipped; } }.Register(); new Execute(OrderOperation.Cancel) { FromStates = { OrderState.Ordered, OrderState.Shipped }, ToStates = { OrderState.Canceled }, Execute = (o, args) => { o.CancelationDate = DateTime.Now; o.State = OrderState.Canceled; } }.Register(); new Delete(OrderOperation.Delete) { FromStates = { OrderState.Ordered }, Delete = (o, args) => { o.Delete(); } }.Register(); }
public static void Start(SchemaBuilder sb, IFileTypeAlgorithm predictorFileAlgorithm) { if (sb.NotDefined(MethodInfo.GetCurrentMethod())) { sb.Settings.AssertIgnored((PredictorEntity p) => p.MainQuery.Filters.Single().Pinned, "use PredictorLogic", "by calling PredictorLogic.IgnorePinned in Starter.OverrideAttributes"); sb.Settings.AssertIgnored((PredictorSubQueryEntity p) => p.Filters.Single().Pinned, "use PredictorLogic", "by calling PredictorLogic.IgnorePinned in Starter.OverrideAttributes"); sb.Include <PredictorEntity>() .WithVirtualMList(p => p.SubQueries, mc => mc.Predictor) .WithQuery(() => e => new { Entity = e, e.Id, e.Name, e.MainQuery.Query, e.Algorithm, e.State, e.TrainingException, }); PredictorGraph.Register(); sb.Include <PredictorSubQueryEntity>() .WithQuery(() => e => new { Entity = e, e.Id, e.Name, e.Query, e.Predictor }); sb.Include <PredictorCodificationEntity>() .WithUniqueIndex(pc => new { pc.Predictor, pc.Index, pc.Usage }) .WithExpressionFrom((PredictorEntity e) => e.Codifications()) .WithQuery(() => e => new { Entity = e, e.Id, e.Predictor, e.Index, e.Usage, e.OriginalColumnIndex, e.SubQueryIndex, e.SplitKey0, e.SplitKey1, e.SplitKey2, e.IsValue, e.Min, e.Max, e.Average, e.StdDev, }); sb.Include <PredictorEpochProgressEntity>() .WithExpressionFrom((PredictorEntity e) => e.EpochProgresses()) .WithQuery(() => e => new { Entity = e, e.Predictor, e.Id, e.Epoch, e.Ellapsed, e.LossTraining, e.AccuracyTraining, e.LossValidation, e.AccuracyValidation, }); FileTypeLogic.Register(PredictorFileType.PredictorFile, predictorFileAlgorithm); SymbolLogic <PredictorAlgorithmSymbol> .Start(sb, () => Algorithms.Keys); SymbolLogic <PredictorColumnEncodingSymbol> .Start(sb, () => Algorithms.Values.SelectMany(a => a.GetRegisteredEncodingSymbols()).Distinct()); SymbolLogic <PredictorResultSaverSymbol> .Start(sb, () => ResultSavers.Keys); SymbolLogic <PredictorPublicationSymbol> .Start(sb, () => Publications.Keys); sb.Schema.EntityEvents <PredictorEntity>().Retrieved += PredictorEntity_Retrieved; sb.Schema.EntityEvents <PredictorSubQueryEntity>().Retrieved += PredictorMultiColumnEntity_Retrieved; Validator.PropertyValidator((PredictorColumnEmbedded c) => c.Encoding).StaticPropertyValidation += Column_StaticPropertyValidation; Validator.PropertyValidator((PredictorSubQueryColumnEmbedded c) => c.Token).StaticPropertyValidation += GroupKey_StaticPropertyValidation; Validator.PropertyValidator((PredictorSubQueryEntity c) => c.Columns).StaticPropertyValidation += SubQueryColumns_StaticPropertyValidation; sb.Include <PredictSimpleResultEntity>() .WithQuery(() => e => new { Entity = e, e.Id, e.Predictor, e.Target, e.Type, e.OriginalValue, e.PredictedValue, e.OriginalCategory, e.PredictedCategory, }); RegisterResultSaver(PredictorSimpleResultSaver.StatisticsOnly, new PredictorSimpleSaver { SaveAllResults = false }); RegisterResultSaver(PredictorSimpleResultSaver.Full, new PredictorSimpleSaver { SaveAllResults = true }); sb.Schema.EntityEvents <PredictorEntity>().PreUnsafeDelete += query => { Database.Query <PredictSimpleResultEntity>().Where(a => query.Contains(a.Predictor.Entity)).UnsafeDelete(); return(null); }; sb.Schema.WhenIncluded <ProcessEntity>(() => { sb.Schema.Settings.AssertImplementedBy((ProcessEntity p) => p.Data, typeof(PredictorEntity)); sb.Schema.Settings.AssertImplementedBy((ProcessEntity p) => p.Data, typeof(AutoconfigureNeuralNetworkEntity)); ProcessLogic.Register(PredictorProcessAlgorithm.AutoconfigureNeuralNetwork, new AutoconfigureNeuralNetworkAlgorithm()); new Graph <ProcessEntity> .ConstructFrom <PredictorEntity>(PredictorOperation.AutoconfigureNetwork) { CanConstruct = p => p.AlgorithmSettings is NeuralNetworkSettingsEntity ? null : ValidationMessage._0ShouldBeOfType1.NiceToString(p.NicePropertyName(_ => _.AlgorithmSettings), typeof(NeuralNetworkSettingsEntity).NiceName()), Construct = (p, _) => { return(ProcessLogic.Create(PredictorProcessAlgorithm.AutoconfigureNeuralNetwork, new AutoconfigureNeuralNetworkEntity { InitialPredictor = p.ToLite() })); } }.Register(); }); } }