Esempio n. 1
0
        public void SaveCycle()
        {
            using (Transaction tr = new Transaction())
                using (OperationLogic.AllowSave <ArtistEntity>())
                {
                    ArtistEntity m = new ArtistEntity()
                    {
                        Name = "Michael"
                    };
                    ArtistEntity f = new ArtistEntity()
                    {
                        Name = "Frank"
                    };
                    m.Friends.Add(f.ToLiteFat());
                    f.Friends.Add(m.ToLiteFat());

                    Database.SaveParams(m, f);

                    var list = Database.Query <ArtistEntity>().Where(a => a == m || a == f).ToList();

                    Assert.IsTrue(list[0].Friends.Contains(list[1].ToLite()));
                    Assert.IsTrue(list[1].Friends.Contains(list[0].ToLite()));

                    //tr.Commit();
                }
        }
Esempio n. 2
0
        public void SaveMany()
        {
            using (Transaction tr = new Transaction())
                using (OperationLogic.AllowSave <ArtistEntity>())
                {
                    var prev = Database.Query <ArtistEntity>().Count();

                    Type[] types = typeof(int).Assembly.GetTypes().Where(a => a.Name.Length > 3 && a.Name.StartsWith("A")).ToArray();

                    var list = types.Select(t => new ArtistEntity()
                    {
                        Name = t.Name
                    }).ToList();

                    list.SaveList();

                    Assert.AreEqual(prev + types.Length, Database.Query <ArtistEntity>().Count());

                    list.ForEach(a => a.Name += "Updated");

                    list.SaveList();

                    //tr.Commit();
                }
        }
Esempio n. 3
0
 private static void SendOneMessage(SMSMessageEntity message)
 {
     using (OperationLogic.AllowSave <SMSMessageEntity>())
     {
         try
         {
             message.MessageID = GetProvider().SMSSendAndGetTicket(message);
             message.SendDate  = TimeZoneManager.Now.TrimToSeconds();
             message.State     = SMSMessageState.Sent;
             message.Save();
         }
         catch (Exception e)
         {
             var ex = e.LogException();
             using (Transaction tr = Transaction.ForceNew())
             {
                 message.Exception = ex.ToLite();
                 message.State     = SMSMessageState.SendFailed;
                 message.Save();
                 tr.Commit();
             }
             throw;
         }
     }
 }
Esempio n. 4
0
        public string SetCurrentCulture([Required, FromBody] Lite <CultureInfoEntity> culture)
        {
            var ci = ExecutionMode.Global().Using(_ => culture.RetrieveAndRemember().ToCultureInfo());

            if (UserEntity.Current != null && !UserEntity.Current.Is(AuthLogic.AnonymousUser)) //Won't be used till next refresh
            {
                using (AuthLogic.Disable())
                    using (OperationLogic.AllowSave <UserEntity>())
                    {
                        var user = UserEntity.Current.ToLite().RetrieveAndRemember();
                        user.CultureInfo   = culture.RetrieveAndRemember();
                        UserEntity.Current = user;
                        user.Save();
                    }
            }

            ControllerContext.HttpContext.Response.Cookies.Append("language", ci.Name, new CookieOptions
            {
                Expires     = DateTimeOffset.Now.AddYears(10),
                Path        = "/",
                IsEssential = true,
                Domain      = Request.Host.Host
            });
            return(ci.Name);
        }
Esempio n. 5
0
        public static WordTemplateEntity GetDefaultTemplate(SystemWordTemplateEntity systemWordTemplate, Entity entity)
        {
            var templates = SystemWordTemplateToWordTemplates.Value.TryGetC(systemWordTemplate.ToLite()).EmptyIfNull().Select(a => WordTemplateLogic.WordTemplatesLazy.Value.GetOrThrow(a));

            if (templates.IsNullOrEmpty() && HasDefaultTemplateConstructor(systemWordTemplate))
            {
                using (ExecutionMode.Global())
                    using (OperationLogic.AllowSave <WordTemplateEntity>())
                        using (Transaction tr = Transaction.ForceNew())
                        {
                            var template = CreateDefaultTemplate(systemWordTemplate);

                            template.Save();

                            return(tr.Commit(template));
                        }
            }

            var isAllowed  = Schema.Current.GetInMemoryFilter <WordTemplateEntity>(userInterface: false);
            var candidates = templates.Where(isAllowed).Where(t => t.IsApplicable(entity));

            return(GetTemplate(candidates, systemWordTemplate, CultureInfo.CurrentCulture) ??
                   GetTemplate(candidates, systemWordTemplate, CultureInfo.CurrentCulture.Parent) ??
                   candidates.Only() ??
                   throw new InvalidProgramException($"No active template found for {systemWordReports} in {CultureInfo.CurrentCulture} or {CultureInfo.CurrentCulture.Parent}"));
        }
Esempio n. 6
0
 public static void SendMailAsync(this EmailMessageEntity email)
 {
     using (OperationLogic.AllowSave <EmailMessageEntity>())
     {
         email.State = EmailMessageState.ReadyToSend;
         email.Save();
     }
 }
Esempio n. 7
0
        public static void LoadOrders()
        {
            using (NorthwindDataContext db = new NorthwindDataContext())
            {
                var northwind = db.Customers.Select(a => new { a.CustomerID, a.ContactName }).ToList();

                var companies = Database.Query <CompanyEntity>().Select(c => new
                {
                    Lite = c.ToLite <CustomerEntity>(),
                    c.ContactName
                }).ToList();

                var persons = Database.Query <PersonEntity>().Select(p => new
                {
                    Lite        = p.ToLite <CustomerEntity>(),
                    ContactName = p.FirstName + " " + p.LastName
                }).ToList();

                Dictionary <string, Lite <CustomerEntity> > customerMapping =
                    (from n in northwind
                     join s in companies.Concat(persons) on n.ContactName equals s.ContactName
                     select new KeyValuePair <string, Lite <CustomerEntity> >(n.CustomerID, s.Lite)).ToDictionary();

                db.Orders.GroupsOf(10).ProgressForeachDisableIdentity(typeof(OrderEntity), l => l.ToInterval(a => a.OrderID).ToString(), null, (orders, writer) =>
                {
                    using (OperationLogic.AllowSave <OrderEntity>())
                        orders.Select(o => new OrderEntity
                        {
                            Employee     = Lite.Create <EmployeeEntity>(o.EmployeeID.Value),
                            OrderDate    = o.OrderDate.Value,
                            RequiredDate = o.RequiredDate.Value,
                            ShippedDate  = o.ShippedDate,
                            State        = o.ShippedDate.HasValue ? OrderState.Shipped : OrderState.Ordered,
                            ShipVia      = Lite.Create <ShipperEntity>(o.ShipVia.Value),
                            ShipName     = o.ShipName,
                            ShipAddress  = new AddressEntity
                            {
                                Address    = o.ShipAddress,
                                City       = o.ShipCity,
                                Region     = o.ShipRegion,
                                PostalCode = o.ShipPostalCode,
                                Country    = o.ShipCountry,
                            },
                            Freight = o.Freight.Value,
                            Details = o.Order_Details.Select(od => new OrderDetailsEntity
                            {
                                Discount  = (decimal)od.Discount,
                                Product   = Lite.Create <ProductEntity>(od.ProductID),
                                Quantity  = od.Quantity,
                                UnitPrice = od.UnitPrice,
                            }).ToMList(),
                            Customer = customerMapping[o.CustomerID].RetrieveAndForget(),
                            IsLegacy = true,
                        }.SetId(o.OrderID)).SaveList();
                });
            }
        }
Esempio n. 8
0
        public static void Start(SchemaBuilder sb, FileTypeSymbol?testFileType = null)
        {
            if (sb.NotDefined(MethodInfo.GetCurrentMethod()))
            {
                TestFileType = testFileType;

                sb.Include <PrintLineEntity>()
                .WithQuery(() => p => new
                {
                    Entity = p,
                    p.CreationDate,
                    p.File,
                    p.State,
                    p.Package,
                    p.PrintedOn,
                    p.Referred,
                });

                sb.Include <PrintPackageEntity>()
                .WithQuery(() => e => new
                {
                    Entity = e,
                    e.Id,
                    e.Name
                });

                ProcessLogic.AssertStarted(sb);
                ProcessLogic.Register(PrintPackageProcess.PrintPackage, new PrintPackageAlgorithm());
                PermissionAuthLogic.RegisterPermissions(PrintPermission.ViewPrintPanel);
                PrintLineGraph.Register();

                SimpleTaskLogic.Register(PrintTask.RemoveOldFiles, (ScheduledTaskContext ctx) =>
                {
                    var lines = Database.Query <PrintLineEntity>().Where(a => a.State == PrintLineState.Printed).Where(b => b.CreationDate <= DateTime.Now.AddMinutes(-DeleteFilesAfter));
                    foreach (var line in lines)
                    {
                        try
                        {
                            using (Transaction tr = new Transaction())
                            {
                                line.File.DeleteFileOnCommit();
                                line.State = PrintLineState.PrintedAndDeleted;
                                using (OperationLogic.AllowSave <PackageLineEntity>())
                                    line.Save();

                                tr.Commit();
                            }
                        }
                        catch (Exception e)
                        {
                            e.LogException();
                        }
                    }
                    return(null);
                });
            }
        }
Esempio n. 9
0
        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();
        }
Esempio n. 10
0
        public void Execute()
        {
            var user = ExecutionMode.Global().Using(_ => CurrentProcess.User.RetrieveAndRemember());

            using (UserHolder.UserSession(user))
            {
                using (ProcessLogic.OnApplySession(CurrentProcess))
                {
                    if (UserEntity.Current == null)
                    {
                        UserEntity.Current = AuthLogic.SystemUser !;
                    }
                    try
                    {
                        Algorithm.Execute(this);

                        CurrentProcess.ExecutionEnd = TimeZoneManager.Now;
                        CurrentProcess.State        = ProcessState.Finished;
                        CurrentProcess.Progress     = null;
                        CurrentProcess.User.ClearEntity();
                        using (OperationLogic.AllowSave <ProcessEntity>())
                            CurrentProcess.Save();
                    }
                    catch (OperationCanceledException e)
                    {
                        if (!e.CancellationToken.Equals(this.CancellationToken))
                        {
                            throw;
                        }

                        CurrentProcess.SuspendDate = TimeZoneManager.Now;
                        CurrentProcess.State       = ProcessState.Suspended;
                        using (OperationLogic.AllowSave <ProcessEntity>())
                            CurrentProcess.Save();
                    }
                    catch (Exception e)
                    {
                        if (Transaction.InTestTransaction)
                        {
                            throw;
                        }

                        CurrentProcess.State         = ProcessState.Error;
                        CurrentProcess.ExceptionDate = TimeZoneManager.Now;
                        CurrentProcess.Exception     = e.LogException(el => el.ActionName = CurrentProcess.Algorithm.ToString()).ToLite();
                        using (OperationLogic.AllowSave <ProcessEntity>())
                            CurrentProcess.Save();
                    }
                    finally
                    {
                        ProcessRunnerLogic.OnFinally?.Invoke(this);
                    }
                }
            }
        }
Esempio n. 11
0
        public static bool LoginAzureADAuthentication(ActionContext ac, string jwt)
        {
            using (AuthLogic.Disable())
            {
                try
                {
                    var ada = (ActiveDirectoryAuthorizer)AuthLogic.Authorizer !;

                    if (!ada.GetConfig().LoginWithAzureAD)
                    {
                        return(false);
                    }

                    var principal = ValidateToken(jwt, out var jwtSecurityToken);
                    var ctx       = new AzureClaimsAutoCreateUserContext(principal);

                    UserEntity?user =
                        Database.Query <UserEntity>().SingleOrDefault(a => a.Mixin <UserOIDMixin>().OID == ctx.OID);

                    if (user == null)
                    {
                        user = Database.Query <UserEntity>().SingleOrDefault(a => a.UserName == ctx.UserName) ??
                               (ctx.UserName.Contains("@") && ada.GetConfig().AllowSimpleUserNames ? Database.Query <UserEntity>().SingleOrDefault(a => a.UserName == ctx.UserName.Before("@")) : null);

                        if (user != null && user.Mixin <UserOIDMixin>().OID == null)
                        {
                            user.Mixin <UserOIDMixin>().OID = ctx.OID;
                            using (AuthLogic.Disable())
                                using (OperationLogic.AllowSave <UserEntity>())
                                {
                                    user.Save();
                                }
                        }
                    }

                    if (user == null)
                    {
                        user = ada.OnAutoCreateUser(ctx);

                        if (user == null)
                        {
                            return(false);
                        }
                    }

                    AuthServer.OnUserPreLogin(ac, user);
                    AuthServer.AddUserSession(ac, user);
                    return(true);
                }
                catch
                {
                    return(false);
                }
            }
        }
Esempio n. 12
0
        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();
        }
Esempio n. 13
0
        public static void SendAllAsync <T>(List <T> emails)
            where T : IEmailModel
        {
            var list = emails.SelectMany(a => a.CreateEmailMessage()).ToList();

            list.ForEach(a => a.State = EmailMessageState.ReadyToSend);

            using (OperationLogic.AllowSave <EmailMessageEntity>())
            {
                list.SaveList();
            }
        }
Esempio n. 14
0
    static void DoTraining(PredictorTrainingContext ctx)
    {
        using (HeavyProfiler.Log("DoTraining"))
        {
            try
            {
                if (ctx.Predictor.ResultSaver != null)
                {
                    var saver = ResultSavers.GetOrThrow(ctx.Predictor.ResultSaver);
                    saver.AssertValid(ctx.Predictor);
                }

                PredictorLogicQuery.RetrieveData(ctx);
                PredictorCodificationLogic.CreatePredictorCodifications(ctx);

                var algorithm = Algorithms.GetOrThrow(ctx.Predictor.Algorithm);
                using (HeavyProfiler.Log("Train"))
                    algorithm.Train(ctx);

                if (ctx.Predictor.ResultSaver != null)
                {
                    using (HeavyProfiler.Log("ResultSaver"))
                    {
                        var saver = ResultSavers.GetOrThrow(ctx.Predictor.ResultSaver);
                        saver.SavePredictions(ctx);
                    }
                }

                ctx.Predictor.State = PredictorState.Trained;
                using (OperationLogic.AllowSave <PredictorEntity>())
                    ctx.Predictor.Save();
            }
            catch (OperationCanceledException)
            {
                var p = ctx.Predictor.ToLite().Retrieve();
                CleanTrained(p);
                p.State = PredictorState.Draft;
                using (OperationLogic.AllowSave <PredictorEntity>())
                    p.Save();
            }
            catch (Exception ex)
            {
                ex.Data["entity"] = ctx.Predictor;
                var e = ex.LogException();
                var p = ctx.Predictor.ToLite().Retrieve();
                p.State             = PredictorState.Error;
                p.TrainingException = e.ToLite();
                using (OperationLogic.AllowSave <PredictorEntity>())
                    p.Save();
            }
        }
    }
Esempio n. 15
0
        public void SaveManyMList()
        {
            using (var tr = new Transaction())
                using (OperationLogic.AllowSave <LabelEntity>())
                    using (OperationLogic.AllowSave <CountryEntity>())
                        using (OperationLogic.AllowSave <AlbumEntity>())
                            using (OperationLogic.AllowSave <ArtistEntity>())
                            {
                                var prev = Database.MListQuery((AlbumEntity a) => a.Songs).Count();

                                var authors =
                                    Database.Query <BandEntity>().Take(6).ToList().Concat <IAuthorEntity>(
                                        Database.Query <ArtistEntity>().Take(8).ToList()).ToList();

                                var label = new LabelEntity {
                                    Name = "Four Music", Country = new CountryEntity {
                                        Name = "Germany"
                                    }, Node = MusicLoader.NextLabelNode()
                                };

                                List <AlbumEntity> albums = 0.To(16).Select(i => new AlbumEntity()
                                {
                                    Name   = "System Greatest hits {0}".FormatWith(i),
                                    Author = i < authors.Count ? authors[i] : new ArtistEntity {
                                        Name = ".Net Framework"
                                    },
                                    Year  = 2001,
                                    Songs = { new SongEmbedded {
                                                  Name = "Compilation {0}".FormatWith(i)
                                              } },
                                    State = AlbumState.Saved,
                                    Label = label,
                                }).ToList();

                                albums.SaveList();

                                Assert.All(GraphExplorer.FromRoots(albums), a => Assert.False(a.IsGraphModified));

                                Assert.Equal(prev + 16, Database.MListQuery((AlbumEntity a) => a.Songs).Count());

                                albums.ForEach(a => a.Name += "Updated");

                                albums.SaveList();

                                albums.ForEach(a => a.Songs.ForEach(s => s.Name = "Updated"));

                                albums.SaveList();

                                //tr.Commit();
                            }
        }
Esempio n. 16
0
        public virtual void Execute(ExecutingProcess executingProcess)
        {
            PackageEntity package = (PackageEntity)executingProcess.Data;

            var args = package.OperationArgs;

            using (OperationLogic.AllowSave <T>())
                executingProcess.ForEachLine(package.Lines().Where(a => a.FinishTime == null), line =>
                {
                    ((T)(object)line.Target).Save();
                    line.FinishTime = TimeZoneManager.Now;
                    line.Save();
                });
        }
Esempio n. 17
0
    public static ImportAction Save(Entity entity)
    {
        if (!GraphExplorer.HasChanges(entity))
        {
            return(ImportAction.NoChanges);
        }

        var result = entity.IsNew ? ImportAction.Inserted : ImportAction.Updated;

        using (OperationLogic.AllowSave(entity.GetType()))
            entity.Save();

        return(result);
    }
Esempio n. 18
0
        internal static void CreateSystemUser()
        {
            using (OperationLogic.AllowSave <UserEntity>())
                using (Transaction tr = new Transaction())
                {
                    UserEntity system = new UserEntity
                    {
                        UserName     = "******",
                        PasswordHash = Security.EncodePassword("System"),
                        Role         = Database.Query <RoleEntity>().Where(r => r.Name == "Super user").SingleEx().ToLite(),
                        State        = UserState.Saved,
                    }.Save();

                    tr.Commit();
                }
        } //CreateSystemUser
Esempio n. 19
0
        public void SaveMList()
        {
            using (var tr = new Transaction())
                using (OperationLogic.AllowSave <LabelEntity>())
                    using (OperationLogic.AllowSave <CountryEntity>())
                        using (OperationLogic.AllowSave <AlbumEntity>())
                            using (OperationLogic.AllowSave <ArtistEntity>())
                            {
                                var prev = Database.MListQuery((AlbumEntity a) => a.Songs).Count();

                                Type[] types = typeof(int).Assembly.GetTypes().Where(a => a.Name.Length > 3 && a.Name.StartsWith("A")).ToArray();

                                AlbumEntity album = new AlbumEntity()
                                {
                                    Name   = "System Greatest hits",
                                    Author = new ArtistEntity {
                                        Name = ".Net Framework"
                                    },
                                    Year  = 2001,
                                    Songs = types.Select(t => new SongEmbedded()
                                    {
                                        Name = t.Name
                                    }).ToMList(),
                                    State = AlbumState.Saved,
                                    Label = new LabelEntity {
                                        Name = "Four Music", Country = new CountryEntity {
                                            Name = "Germany"
                                        }, Node = MusicLoader.NextLabelNode()
                                    },
                                }.Save();

                                Assert.All(GraphExplorer.FromRoot(album), a => Assert.False(a.IsGraphModified));

                                Assert.Equal(prev + types.Length, Database.MListQuery((AlbumEntity a) => a.Songs).Count());

                                album.Name += "Updated";

                                album.Save();

                                album.Songs.ForEach(a => a.Name = "Updated");

                                album.Save();

                                //tr.Commit();
                            }
        }
Esempio n. 20
0
        public virtual void Send(EmailMessageEntity email)
        {
            using (OperationLogic.AllowSave <EmailMessageEntity>())
            {
                if (!EmailLogic.Configuration.SendEmails)
                {
                    email.State = EmailMessageState.Sent;
                    email.Sent  = TimeZoneManager.Now;
                    email.Save();
                    return;
                }

                try
                {
                    SendInternal(email);

                    email.State = EmailMessageState.Sent;
                    email.Sent  = TimeZoneManager.Now;
                    email.Save();
                }
                catch (Exception ex)
                {
                    if (Transaction.InTestTransaction) //Transaction.IsTestTransaction
                    {
                        throw;
                    }

                    var exLog = ex.LogException().ToLite();

                    try
                    {
                        using (Transaction tr = Transaction.ForceNew())
                        {
                            email.Exception = exLog;
                            email.State     = EmailMessageState.SentException;
                            email.Save();
                            tr.Commit();
                        }
                    }
                    catch { } //error updating state for email

                    throw;
                }
            }
        }
        public virtual void UpdateUser(UserEntity user, IAutoCreateUserContext ctx)
        {
            if (this.GetConfig().AutoUpdateUsers == false)
            {
                return;
            }

            UpdateUserInternal(user, ctx);

            if (GraphExplorer.IsGraphModified(user))
            {
                using (AuthLogic.Disable())
                    using (OperationLogic.AllowSave <UserEntity>())
                    {
                        user.Save();
                    }
            }
        }
Esempio n. 22
0
        public HttpResponseMessage SetCurrentCulture(Lite <CultureInfoEntity> culture)
        {
            var ci = ExecutionMode.Global().Using(_ => culture.Retrieve().ToCultureInfo());

            if (UserEntity.Current != null) //Won't be used till next refresh
            {
                var user = UserEntity.Current.ToLite().Retrieve();

                user.CultureInfo = culture.Retrieve();
                using (AuthLogic.Disable())
                    using (OperationLogic.AllowSave <UserEntity>())
                        user.Save();
            }

            var resp = Request.CreateResponse(ci.Name);

            TranslationServer.AddLanguageCookie(resp, Request, ci);
            return(resp);
        }
Esempio n. 23
0
        public static void GenerateAllTemplates()
        {
            foreach (var emailModelType in registeredModels.Keys)
            {
                var emailModelEntity = ToEmailModelEntity(emailModelType);

                var template = Database.Query <EmailTemplateEntity>().SingleOrDefaultEx(t =>
                                                                                        t.Model == emailModelEntity);

                if (template == null)
                {
                    template = CreateDefaultTemplate(emailModelEntity);

                    using (ExecutionMode.Global())
                        using (OperationLogic.AllowSave <EmailTemplateEntity>())
                            template.Save();
                }
            }
        }
Esempio n. 24
0
        public static Lite <EmailMasterTemplateEntity> GetDefaultMasterTemplate()
        {
            var result = Database.Query <EmailMasterTemplateEntity>().Select(emt => emt.ToLite()).FirstOrDefault();

            if (result != null)
            {
                return(result);
            }

            if (CreateDefaultMasterTemplate == null)
            {
                return(null);
            }

            var newTemplate = CreateDefaultMasterTemplate();

            using (OperationLogic.AllowSave <EmailMasterTemplateEntity>())
                return(newTemplate.Save().ToLite());
        }
Esempio n. 25
0
        public static void GenerateAllTemplates()
        {
            foreach (var systemEmail in systemEmails.Keys)
            {
                var systemEmailEntity = ToSystemEmailEntity(systemEmail);

                var template = Database.Query <EmailTemplateEntity>().SingleOrDefaultEx(t =>
                                                                                        t.SystemEmail == systemEmailEntity);

                if (template == null)
                {
                    template = CreateDefaultTemplate(systemEmailEntity);

                    using (ExecutionMode.Global())
                        using (OperationLogic.AllowSave <EmailTemplateEntity>())
                            template.Save();
                }
            }
        }
Esempio n. 26
0
        public static UserEntity CreateUserFromAD(ActiveDirectoryUser adUser)
        {
            ClientCredentialProvider authProvider = GetClientCredentialProvider();
            GraphServiceClient       graphClient  = new GraphServiceClient(authProvider);
            var msGraphUser = graphClient.Users[adUser.ObjectID.ToString()].Request().GetAsync().Result;

            using (ExecutionMode.Global())
            {
                var user = Database.Query <UserEntity>().SingleOrDefaultEx(a => a.Mixin <UserOIDMixin>().OID == Guid.Parse(msGraphUser.Id));
                if (user != null)
                {
                    return(user);
                }

                var config = ((ActiveDirectoryAuthorizer)AuthLogic.Authorizer !).GetConfig();

                user = Database.Query <UserEntity>().SingleOrDefault(a => a.UserName == msGraphUser.UserPrincipalName) ??
                       (msGraphUser.UserPrincipalName.Contains("@") && config.AllowMatchUsersBySimpleUserName ? Database.Query <UserEntity>().SingleOrDefault(a => a.Email == msGraphUser.UserPrincipalName || a.UserName == msGraphUser.UserPrincipalName.Before("@")) : null);

                if (user != null)
                {
                    using (AuthLogic.Disable())
                        using (OperationLogic.AllowSave <UserEntity>())
                        {
                            user.Mixin <UserOIDMixin>().OID = Guid.Parse(msGraphUser.Id);
                            user.UserName = msGraphUser.UserPrincipalName;
                            user.Email    = msGraphUser.UserPrincipalName;
                            if (!UserOIDMixin.AllowUsersWithPassswordAndOID)
                            {
                                user.PasswordHash = null;
                            }
                            user.Save();
                        }

                    return(user);
                }
            }

            var result = ((ActiveDirectoryAuthorizer)AuthLogic.Authorizer !).OnAutoCreateUser(new MicrosoftGraphCreateUserContext(msGraphUser));

            return(result ?? throw new InvalidOperationException(ReflectionTools.GetPropertyInfo((ActiveDirectoryConfigurationEmbedded e) => e.AutoCreateUsers).NiceName() + " is not activated"));
        }
Esempio n. 27
0
        public void SaveManyMList()
        {
            using (Transaction tr = new Transaction())
                using (OperationLogic.AllowSave <AlbumEntity>())
                    using (OperationLogic.AllowSave <ArtistEntity>())
                    {
                        var prev = Database.MListQuery((AlbumEntity a) => a.Songs).Count();

                        var authors =
                            Database.Query <BandEntity>().Take(6).ToList().Concat <IAuthorEntity>(
                                Database.Query <ArtistEntity>().Take(8).ToList()).ToList();

                        List <AlbumEntity> albums = 0.To(16).Select(i => new AlbumEntity()
                        {
                            Name   = "System Greatest hits {0}".FormatWith(i),
                            Author = i < authors.Count ? authors[i] : new ArtistEntity {
                                Name = ".Net Framework"
                            },
                            Year  = 2001,
                            Songs = { new SongEntity {
                                          Name = "Compilation {0}".FormatWith(i)
                                      } },
                            State = AlbumState.Saved
                        }).ToList();

                        albums.SaveList();

                        Assert2.AssertAll(GraphExplorer.FromRoots(albums), a => !a.IsGraphModified);

                        Assert.AreEqual(prev + 16, Database.MListQuery((AlbumEntity a) => a.Songs).Count());

                        albums.ForEach(a => a.Name += "Updated");

                        albums.SaveList();

                        albums.ForEach(a => a.Songs.ForEach(s => s.Name = "Updated"));

                        albums.SaveList();

                        //tr.Commit();
                    }
        }
Esempio n. 28
0
        public ActionResult <LoginResponse> ChangePassword([Required, FromBody] ChangePasswordRequest request)
        {
            if (string.IsNullOrEmpty(request.newPassword))
            {
                return(ModelError("newPassword", LoginAuthMessage.PasswordMustHaveAValue.NiceToString()));
            }

            var error = UserEntity.OnValidatePassword(request.newPassword);

            if (error.HasText())
            {
                return(ModelError("newPassword", error));
            }

            var user = UserEntity.Current;

            if (string.IsNullOrEmpty(request.oldPassword))
            {
                if (user.PasswordHash != null)
                {
                    return(ModelError("oldPassword", LoginAuthMessage.PasswordMustHaveAValue.NiceToString()));
                }
            }
            else
            {
                if (user.PasswordHash == null || !user.PasswordHash.SequenceEqual(Security.EncodePassword(request.oldPassword)))
                {
                    return(ModelError("oldPassword", LoginAuthMessage.InvalidPassword.NiceToString()));
                }
            }

            user.PasswordHash = Security.EncodePassword(request.newPassword);
            using (AuthLogic.Disable())
                using (OperationLogic.AllowSave <UserEntity>())
                {
                    user.Save();
                }

            return(new LoginResponse {
                userEntity = user, token = AuthTokenServer.CreateToken(UserEntity.Current), authenticationType = "changePassword"
            });
        }
Esempio n. 29
0
            public IUserAssetEntity GetEntity(Guid guid)
            {
                return(entities.GetOrCreate(guid, () =>
                {
                    var element = elements.GetOrThrow(guid);

                    Type type = UserAssetNames.GetOrThrow(element.Name.ToString());

                    var entity = giRetrieveOrCreate.GetInvoker(type)(guid);

                    if (entity.IsNew || overrideEntity.ContainsKey(guid))
                    {
                        entity.FromXml(element, this);
                        using (OperationLogic.AllowSave(entity.GetType()))
                            entity.Save();
                    }

                    return entity;
                }));
            }
Esempio n. 30
0
        public void SaveSelfCycle()
        {
            using (Transaction tr = new Transaction())
                using (OperationLogic.AllowSave <ArtistEntity>())
                {
                    ArtistEntity m = new ArtistEntity()
                    {
                        Name = "Michael"
                    };
                    m.Friends.Add(m.ToLiteFat());

                    m.Save();

                    var m2 = m.ToLite().RetrieveAndForget();

                    Assert.IsTrue(m2.Friends.Contains(m2.ToLite()));

                    //tr.Commit();
                }
        }