Ejemplo n.º 1
0
 public static void Start(SchemaBuilder sb)
 {
     if (sb.NotDefined(MethodBase.GetCurrentMethod()))
     {
         PermissionAuthLogic.RegisterTypes(typeof(OmniboxPermission));
     }
 }
Ejemplo n.º 2
0
    /// <summary>
    /// If you have invalidation problems look at exceptions in: select * from sys.transmission_queue
    /// If there are exceptions like: 'Could not obtain information about Windows NT group/user'
    ///    Change login to a SqlServer authentication (i.e.: sa)
    ///    Change Server Authentication mode and enable SA: http://msdn.microsoft.com/en-us/library/ms188670.aspx
    ///    Change Database ownership to sa: ALTER AUTHORIZATION ON DATABASE::yourDatabase TO sa
    /// </summary>
    public static void Start(SchemaBuilder sb, bool?withSqlDependency = null, IServerBroadcast?serverBroadcast = null)
    {
        if (sb.NotDefined(MethodInfo.GetCurrentMethod()))
        {
            PermissionAuthLogic.RegisterTypes(typeof(CachePermission));

            sb.SwitchGlobalLazyManager(new CacheGlobalLazyManager());

            if (withSqlDependency == true && !Connector.Current.SupportsSqlDependency)
            {
                throw new InvalidOperationException("Sql Dependency is not supported by the current connection");
            }

            WithSqlDependency = withSqlDependency ?? Connector.Current.SupportsSqlDependency;

            if (serverBroadcast != null && WithSqlDependency)
            {
                throw new InvalidOperationException("cacheInvalidator is only necessary if SqlDependency is not enabled");
            }

            ServerBroadcast = serverBroadcast;
            if (ServerBroadcast != null)
            {
                ServerBroadcast !.Receive      += ServerBroadcast_Receive;
                sb.Schema.BeforeDatabaseAccess += () => ServerBroadcast !.Start();
            }

            sb.Schema.SchemaCompleted      += () => Schema_SchemaCompleted(sb);
            sb.Schema.BeforeDatabaseAccess += StartSqlDependencyAndEnableBrocker;
            sb.Schema.InvalidateCache      += CacheLogic.ForceReset;
        }
    }
Ejemplo n.º 3
0
 public static void Start(SchemaBuilder sb)
 {
     if (sb.NotDefined(MethodInfo.GetCurrentMethod()))
     {
         PermissionAuthLogic.RegisterPermissions(MapPermission.ViewMap);
     }
 }
Ejemplo n.º 4
0
        /// <summary>
        /// If you have invalidation problems look at exceptions in: select * from sys.transmission_queue
        /// If there are exceptions like: 'Could not obtain information about Windows NT group/user'
        ///    Change login to a SqlServer authentication (i.e.: sa)
        ///    Change Server Authentication mode and enable SA: http://msdn.microsoft.com/en-us/library/ms188670.aspx
        ///    Change Database ownership to sa: ALTER AUTHORIZATION ON DATABASE::yourDatabase TO sa
        /// </summary>
        public static void Start(SchemaBuilder sb, bool?withSqlDependency = null, ICacheMultiServerInvalidator cacheInvalidator = null)
        {
            if (sb.NotDefined(MethodInfo.GetCurrentMethod()))
            {
                PermissionAuthLogic.RegisterTypes(typeof(CachePermission));

                sb.SwitchGlobalLazyManager(new CacheGlobalLazyManager());

                if (withSqlDependency == true && !Connector.Current.SupportsSqlDependency)
                {
                    throw new InvalidOperationException("Sql Dependency is not supported by the current connection");
                }

                WithSqlDependency = withSqlDependency ?? Connector.Current.SupportsSqlDependency;

                if (cacheInvalidator != null && WithSqlDependency)
                {
                    throw new InvalidOperationException("cacheInvalidator is only necessary if SqlDependency is not enabled");
                }

                CacheInvalidator = cacheInvalidator;
                if (CacheInvalidator != null)
                {
                    CacheInvalidator.ReceiveInvalidation += CacheInvalidator_ReceiveInvalidation;
                }

                sb.Schema.SchemaCompleted      += Schema_SchemaCompleted;
                sb.Schema.BeforeDatabaseAccess += StartSqlDependencyAndEnableBrocker;
            }
        }
Ejemplo n.º 5
0
        public PermissionRulePack GetPermissionRules(string roleId)
        {
            BasicPermission.AdminRules.AssertAuthorized();
            var rules = PermissionAuthLogic.GetPermissionRules(Lite.ParsePrimaryKey <RoleEntity>(roleId).FillToString());

            CleanChanges(rules);
            return(rules);
        }
Ejemplo n.º 6
0
 public static void Start(SchemaBuilder sb)
 {
     if (sb.NotDefined(MethodInfo.GetCurrentMethod()))
     {
         PermissionAuthLogic.RegisterTypes(typeof(DynamicPanelPermission));
         DynamicLogic.GetCodeFiles += GetCodeGenStarter;
         AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(AssemblyResolveHandler);
     }
 }
Ejemplo n.º 7
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);
                });
            }
        }
Ejemplo n.º 8
0
        public ActionResult Permissions(FormCollection form)
        {
            Lite <RoleEntity> role = this.ExtractLite <RoleEntity>("Role");

            var prp = PermissionAuthLogic.GetPermissionRules(role).ApplyChanges(this, "");;

            PermissionAuthLogic.SetPermissionRules(prp.Value);

            return(RedirectToAction("Permissions", new { role = role.Id }));
        }
Ejemplo n.º 9
0
        public static void Start(SchemaBuilder sb, DynamicQueryManager dqm)
        {
            if (sb.NotDefined(MethodInfo.GetCurrentMethod()))
            {
                QueryLogic.Start(sb, dqm);

                PermissionAuthLogic.RegisterTypes(typeof(ChartPermission));

                ChartColorLogic.Start(sb, dqm);
                ChartScriptLogic.Start(sb, dqm);
                UserChartLogic.Start(sb, dqm);
            }
        }
Ejemplo n.º 10
0
    public static void StartAllModules(SchemaBuilder sb, bool activeDirectoryIntegration = false)
    {
        TypeAuthLogic.Start(sb);
        PropertyAuthLogic.Start(sb);
        QueryAuthLogic.Start(sb);
        OperationAuthLogic.Start(sb);
        PermissionAuthLogic.Start(sb);

        if (activeDirectoryIntegration)
        {
            PermissionAuthLogic.RegisterTypes(typeof(ActiveDirectoryPermission));
        }
    }
Ejemplo n.º 11
0
 public static void Start(SchemaBuilder sb, bool withCodeGen)
 {
     if (sb.NotDefined(MethodInfo.GetCurrentMethod()))
     {
         PermissionAuthLogic.RegisterPermissions(DynamicPanelPermission.ViewDynamicPanel);
         if (withCodeGen)
         {
             PermissionAuthLogic.RegisterPermissions(DynamicPanelPermission.RestartApplication);
             DynamicLogic.GetCodeFiles += GetCodeGenStarter;
             AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(AssemblyResolveHandler);
         }
     }
 }
Ejemplo n.º 12
0
        public static void Start(SchemaBuilder sb, bool googleMapsChartScripts)
        {
            if (sb.NotDefined(MethodInfo.GetCurrentMethod()))
            {
                QueryLogic.Start(sb);

                PermissionAuthLogic.RegisterTypes(typeof(ChartPermission));

                ChartColorLogic.Start(sb);
                ChartScriptLogic.Start(sb, googleMapsChartScripts);
                UserChartLogic.Start(sb);
            }
        }
Ejemplo n.º 13
0
        public static void Start(SchemaBuilder sb, bool countLocalizationHits)
        {
            if (sb.NotDefined(MethodInfo.GetCurrentMethod()))
            {
                CultureInfoLogic.AssertStarted(sb);

                PermissionAuthLogic.RegisterTypes(typeof(TranslationPermission));

                if (countLocalizationHits)
                {
                    DescriptionManager.NotLocalizedMember += DescriptionManager_NotLocalizedMemeber;
                }
            }
        }
Ejemplo n.º 14
0
        public static void Start(SchemaBuilder sb, bool registerAll)
        {
            if (sb.NotDefined(MethodInfo.GetCurrentMethod()))
            {
                MixinDeclarations.AssertDeclared(typeof(OperationLogEntity), typeof(DiffLogMixin));

                PermissionAuthLogic.RegisterTypes(typeof(TimeMachinePermission));

                OperationLogic.SurroundOperation += OperationLogic_SurroundOperation;

                if (registerAll)
                {
                    RegisterShouldLog <Entity>((entity, oper) => true);
                }
            }
        }
Ejemplo n.º 15
0
        public static void Start(
            SchemaBuilder sb,
            Func <EmailConfigurationEmbedded> getConfiguration,
            Func <EmailTemplateEntity?, Lite <Entity>?, SmtpConfigurationEntity> getSmtpConfiguration,
            Func <EmailMessageEntity, SmtpClient>?getSmtpClient = null,
            IFileTypeAlgorithm?attachment = null)
        {
            if (sb.NotDefined(MethodInfo.GetCurrentMethod()))
            {
                if (getSmtpClient == null && getSmtpConfiguration != null)
                {
                    getSmtpClient = message => getSmtpConfiguration(message.Template?.Let(a => EmailTemplateLogic.EmailTemplatesLazy.Value.GetOrThrow(a)), message.Target).GenerateSmtpClient();
                }

                FilePathEmbeddedLogic.AssertStarted(sb);
                CultureInfoLogic.AssertStarted(sb);
                EmailLogic.getConfiguration = getConfiguration;
                EmailLogic.GetSmtpClient    = getSmtpClient ?? throw new ArgumentNullException(nameof(getSmtpClient));
                EmailTemplateLogic.Start(sb, getSmtpConfiguration);
                if (attachment != null)
                {
                    FileTypeLogic.Register(EmailFileType.Attachment, attachment);
                }

                Schema.Current.WhenIncluded <ProcessEntity>(() => EmailPackageLogic.Start(sb));

                sb.Include <EmailMessageEntity>()
                .WithQuery(() => e => new
                {
                    Entity = e,
                    e.Id,
                    e.State,
                    e.Subject,
                    e.Template,
                    e.Sent,
                    e.Target,
                    e.Package,
                    e.Exception,
                });

                PermissionAuthLogic.RegisterPermissions(AsyncEmailSenderPermission.ViewAsyncEmailSenderPanel);

                SenderManager = new EmailSenderManager();

                EmailGraph.Register();
            }
        }
Ejemplo n.º 16
0
        public static void Start(
            SchemaBuilder sb,
            Func <EmailConfigurationEmbedded> getConfiguration,
            Func <EmailTemplateEntity?, Lite <Entity>?, EmailMessageEntity?, EmailSenderConfigurationEntity> getEmailSenderConfiguration,
            IFileTypeAlgorithm?attachment = null)
        {
            if (sb.NotDefined(MethodInfo.GetCurrentMethod()))
            {
                FilePathEmbeddedLogic.AssertStarted(sb);
                CultureInfoLogic.AssertStarted(sb);
                EmailLogic.getConfiguration = getConfiguration;
                EmailTemplateLogic.Start(sb, getEmailSenderConfiguration);
                EmailSenderConfigurationLogic.Start(sb);
                if (attachment != null)
                {
                    FileTypeLogic.Register(EmailFileType.Attachment, attachment);
                }

                Schema.Current.WhenIncluded <ProcessEntity>(() => EmailPackageLogic.Start(sb));

                sb.Include <EmailMessageEntity>()
                .WithQuery(() => e => new
                {
                    Entity = e,
                    e.Id,
                    e.State,
                    e.Subject,
                    e.Template,
                    e.Sent,
                    e.Target,
                    e.Package,
                    e.Exception,
                });

                PermissionAuthLogic.RegisterPermissions(AsyncEmailSenderPermission.ViewAsyncEmailSenderPanel);

                SenderManager = new EmailSenderManager(getEmailSenderConfiguration);

                EmailGraph.Register();

                QueryLogic.Expressions.Register((EmailPackageEntity a) => a.EmailMessages(), () => typeof(EmailMessageEntity).NicePluralName());

                ExceptionLogic.DeleteLogs += ExceptionLogic_DeleteLogs;
                ExceptionLogic.DeleteLogs += ExceptionLogic_DeletePackages;
            }
        }
Ejemplo n.º 17
0
        public static void Start(SchemaBuilder sb, DynamicQueryManager dqm, bool timeTracker, bool heavyProfiler, bool overrideSessionTimeout)
        {
            if (sb.NotDefined(MethodInfo.GetCurrentMethod()))
            {
                if (timeTracker)
                {
                    PermissionAuthLogic.RegisterPermissions(ProfilerPermission.ViewTimeTracker);
                }

                if (heavyProfiler)
                {
                    PermissionAuthLogic.RegisterPermissions(ProfilerPermission.ViewHeavyProfiler);
                }

                if (overrideSessionTimeout)
                {
                    PermissionAuthLogic.RegisterPermissions(ProfilerPermission.OverrideSessionTimeout);
                }
            }
        }
Ejemplo n.º 18
0
        public static void Start(SchemaBuilder sb)
        {
            if (sb.NotDefined(MethodInfo.GetCurrentMethod()))
            {
                QueryLogic.Start(sb);

                PermissionAuthLogic.RegisterPermissions(UserQueryPermission.ViewUserQuery);

                UserAssetsImporter.Register <UserQueryEntity>("UserQuery", UserQueryOperation.Save);

                sb.Schema.Synchronizing += Schema_Synchronizing;
                sb.Schema.Table <QueryEntity>().PreDeleteSqlSync += e =>
                                                                    Administrator.UnsafeDeletePreCommand(Database.Query <UserQueryEntity>().Where(a => a.Query == e));

                sb.Include <UserQueryEntity>()
                .WithSave(UserQueryOperation.Save)
                .WithDelete(UserQueryOperation.Delete)
                .WithQuery(() => uq => new
                {
                    Entity = uq,
                    uq.Id,
                    uq.DisplayName,
                    uq.Query,
                    uq.EntityType,
                    uq.Owner,
                });

                sb.Schema.EntityEvents <UserQueryEntity>().Retrieved += UserQueryLogic_Retrieved;

                UserQueries = sb.GlobalLazy(() => Database.Query <UserQueryEntity>().ToDictionary(a => a.ToLite()),
                                            new InvalidateWith(typeof(UserQueryEntity)));

                UserQueriesByQuery = sb.GlobalLazy(() => UserQueries.Value.Values.Where(a => a.EntityType == null).SelectCatch(uq => KeyValuePair.Create(uq.Query.ToQueryName(), uq.ToLite())).GroupToDictionary(),
                                                   new InvalidateWith(typeof(UserQueryEntity)));

                UserQueriesByTypeForQuickLinks = sb.GlobalLazy(() => UserQueries.Value.Values.Where(a => a.EntityType != null && !a.HideQuickLink).SelectCatch(uq => KeyValuePair.Create(TypeLogic.IdToType.GetOrThrow(uq.EntityType !.Id), uq.ToLite())).GroupToDictionary(),
                                                               new InvalidateWith(typeof(UserQueryEntity)));
            }
        }
Ejemplo n.º 19
0
    public static void Start(SchemaBuilder sb)
    {
        if (sb.NotDefined(MethodInfo.GetCurrentMethod()))
        {
            AuthLogic.AssertStarted(sb);

            sb.Include <SessionLogEntity>()
            .WithQuery(() => sl => new
            {
                Entity = sl,
                sl.Id,
                sl.User,
                sl.SessionStart,
                sl.SessionEnd,
                sl.SessionTimeOut
            });

            PermissionAuthLogic.RegisterPermissions(SessionLogPermission.TrackSession);

            ExceptionLogic.DeleteLogs += ExceptionLogic_DeleteLogs;

            IsStarted = true;
        }
    }
Ejemplo n.º 20
0
        public static void Start(SchemaBuilder sb, bool excelReport)
        {
            if (sb.NotDefined(MethodInfo.GetCurrentMethod()))
            {
                PermissionAuthLogic.RegisterTypes(typeof(ExcelPermission));

                if (excelReport)
                {
                    QueryLogic.Start(sb);

                    sb.Include <ExcelReportEntity>()
                    .WithSave(ExcelReportOperation.Save)
                    .WithDelete(ExcelReportOperation.Delete)
                    .WithQuery(() => s => new
                    {
                        Entity = s,
                        s.Id,
                        s.Query,
                        s.File.FileName,
                        s.DisplayName,
                    });
                }
            }
        }
Ejemplo n.º 21
0
        public static void Start(SchemaBuilder sb, DynamicQueryManager dqm)
        {
            if (sb.NotDefined(MethodInfo.GetCurrentMethod()))
            {
                GetDashboard = GetDashboardDefault;

                PermissionAuthLogic.RegisterPermissions(DashboardPermission.ViewDashboard);

                UserAssetsImporter.RegisterName <DashboardEntity>("Dashboard");

                UserAssetsImporter.PartNames.AddRange(new Dictionary <string, Type>
                {
                    { "UserChartPart", typeof(UserChartPartEntity) },
                    { "UserQueryPart", typeof(UserQueryPartEntity) },
                    { "LinkListPart", typeof(LinkListPartEntity) },
                    { "ValueUserQueryListPart", typeof(ValueUserQueryListPartEntity) },
                });

                sb.Include <DashboardEntity>()
                .WithQuery(dqm, () => cp => new
                {
                    Entity = cp,
                    cp.Id,
                    cp.DisplayName,
                    cp.EntityType,
                    cp.Owner,
                    cp.DashboardPriority,
                });

                sb.Include <LinkListPartEntity>()
                .WithQuery(dqm, () => cp => new
                {
                    Entity = cp,
                    ToStr  = cp.ToString(),
                    Links  = cp.Links.Count
                });

                sb.Include <ValueUserQueryListPartEntity>()
                .WithQuery(dqm, () => cp => new
                {
                    Entity = cp,
                    ToStr  = cp.ToString(),
                    Links  = cp.UserQueries.Count
                });

                if (sb.Settings.ImplementedBy((DashboardEntity cp) => cp.Parts.First().Content, typeof(UserQueryPartEntity)))
                {
                    sb.Schema.EntityEvents <UserQueryEntity>().PreUnsafeDelete += query =>
                    {
                        Database.MListQuery((DashboardEntity cp) => cp.Parts).Where(mle => query.Contains(((UserQueryPartEntity)mle.Element.Content).UserQuery)).UnsafeDeleteMList();
                        Database.Query <UserQueryPartEntity>().Where(uqp => query.Contains(uqp.UserQuery)).UnsafeDelete();
                    };

                    sb.Schema.Table <UserQueryEntity>().PreDeleteSqlSync += arg =>
                    {
                        var uq = (UserQueryEntity)arg;

                        var parts = Administrator.UnsafeDeletePreCommand((DashboardEntity cp) => cp.Parts, Database.MListQuery((DashboardEntity cp) => cp.Parts)
                                                                         .Where(mle => ((UserQueryPartEntity)mle.Element.Content).UserQuery == uq));

                        var parts2 = Administrator.UnsafeDeletePreCommand(Database.Query <UserQueryPartEntity>()
                                                                          .Where(mle => mle.UserQuery == uq));

                        return(SqlPreCommand.Combine(Spacing.Simple, parts, parts2));
                    };
                }

                if (sb.Settings.ImplementedBy((DashboardEntity cp) => cp.Parts.First().Content, typeof(UserChartPartEntity)))
                {
                    sb.Schema.EntityEvents <UserChartEntity>().PreUnsafeDelete += query =>
                    {
                        Database.MListQuery((DashboardEntity cp) => cp.Parts).Where(mle => query.Contains(((UserChartPartEntity)mle.Element.Content).UserChart)).UnsafeDeleteMList();
                        Database.Query <UserChartPartEntity>().Where(uqp => query.Contains(uqp.UserChart)).UnsafeDelete();
                    };

                    sb.Schema.Table <UserChartEntity>().PreDeleteSqlSync += arg =>
                    {
                        var uc = (UserChartEntity)arg;

                        var parts = Administrator.UnsafeDeletePreCommand((DashboardEntity cp) => cp.Parts, Database.MListQuery((DashboardEntity cp) => cp.Parts)
                                                                         .Where(mle => ((UserChartPartEntity)mle.Element.Content).UserChart == uc));

                        var parts2 = Administrator.UnsafeDeletePreCommand(Database.Query <UserChartPartEntity>()
                                                                          .Where(mle => mle.UserChart == uc));

                        return(SqlPreCommand.Combine(Spacing.Simple, parts, parts2));
                    };
                }

                DashboardGraph.Register();


                Dashboards = sb.GlobalLazy(() => Database.Query <DashboardEntity>().ToDictionary(a => a.ToLite()),
                                           new InvalidateWith(typeof(DashboardEntity)));

                DashboardsByType = sb.GlobalLazy(() => Dashboards.Value.Values.Where(a => a.EntityType != null)
                                                 .GroupToDictionary(a => TypeLogic.IdToType.GetOrThrow(a.EntityType.Id), a => a.ToLite()),
                                                 new InvalidateWith(typeof(DashboardEntity)));
            }
        }
Ejemplo n.º 22
0
        public static void Start(SchemaBuilder sb, Func <WorkflowConfigurationEmbedded> getConfiguration)
        {
            if (sb.NotDefined(MethodInfo.GetCurrentMethod()))
            {
                PermissionAuthLogic.RegisterPermissions(WorkflowPermission.ViewWorkflowPanel);
                PermissionAuthLogic.RegisterPermissions(WorkflowPermission.ViewCaseFlow);

                WorkflowLogic.getConfiguration = getConfiguration;

                sb.Include <WorkflowEntity>()
                .WithQuery(() => DynamicQueryCore.Auto(
                               from e in Database.Query <WorkflowEntity>()
                               select new
                {
                    Entity = e,
                    e.Id,
                    e.Name,
                    e.MainEntityType,
                    HasExpired = e.HasExpired(),
                    e.ExpirationDate,
                })
                           .ColumnDisplayName(a => a.HasExpired, () => WorkflowMessage.HasExpired.NiceToString()))
                .WithExpressionFrom((CaseActivityEntity ca) => ca.Workflow());

                WorkflowGraph.Register();
                QueryLogic.Expressions.Register((WorkflowEntity wf) => wf.WorkflowStartEvent());
                QueryLogic.Expressions.Register((WorkflowEntity wf) => wf.HasExpired(), () => WorkflowMessage.HasExpired.NiceToString());
                sb.AddIndex((WorkflowEntity wf) => wf.ExpirationDate);

                DynamicCode.GetCustomErrors += GetCustomErrors;


                sb.Include <WorkflowPoolEntity>()
                .WithUniqueIndex(wp => new { wp.Workflow, wp.Name })
                .WithSave(WorkflowPoolOperation.Save)
                .WithDelete(WorkflowPoolOperation.Delete)
                .WithExpressionFrom((WorkflowEntity p) => p.WorkflowPools())
                .WithQuery(() => e => new
                {
                    Entity = e,
                    e.Id,
                    e.Name,
                    e.BpmnElementId,
                    e.Workflow,
                });

                sb.Include <WorkflowLaneEntity>()
                .WithUniqueIndex(wp => new { wp.Pool, wp.Name })
                .WithSave(WorkflowLaneOperation.Save)
                .WithDelete(WorkflowLaneOperation.Delete)
                .WithExpressionFrom((WorkflowPoolEntity p) => p.WorkflowLanes())
                .WithQuery(() => e => new
                {
                    Entity = e,
                    e.Id,
                    e.Name,
                    e.BpmnElementId,
                    e.Pool,
                    e.Pool.Workflow,
                });

                sb.Include <WorkflowActivityEntity>()
                .WithUniqueIndex(w => new { w.Lane, w.Name })
                .WithSave(WorkflowActivityOperation.Save)
                .WithDelete(WorkflowActivityOperation.Delete)
                .WithExpressionFrom((WorkflowEntity p) => p.WorkflowActivities())
                .WithExpressionFrom((WorkflowLaneEntity p) => p.WorkflowActivities())
                .WithVirtualMList(wa => wa.BoundaryTimers, e => e.BoundaryOf, WorkflowEventOperation.Save, WorkflowEventOperation.Delete)
                .WithQuery(() => e => new
                {
                    Entity = e,
                    e.Id,
                    e.Name,
                    e.BpmnElementId,
                    e.Comments,
                    e.Lane,
                    e.Lane.Pool.Workflow,
                });

                sb.Include <WorkflowEventEntity>()
                .WithExpressionFrom((WorkflowEntity p) => p.WorkflowEvents())
                .WithExpressionFrom((WorkflowLaneEntity p) => p.WorkflowEvents())
                .WithQuery(() => e => new
                {
                    Entity = e,
                    e.Id,
                    e.Type,
                    e.Name,
                    e.BpmnElementId,
                    e.Lane,
                    e.Lane.Pool.Workflow,
                });


                new Graph <WorkflowEventEntity> .Execute(WorkflowEventOperation.Save)
                {
                    CanBeNew      = true,
                    CanBeModified = true,
                    Execute       = (e, _) => {
                        if (e.Timer == null && e.Type.IsTimer())
                        {
                            throw new InvalidOperationException(ValidationMessage._0IsMandatoryWhen1IsSetTo2.NiceToString(e.NicePropertyName(a => a.Timer), e.NicePropertyName(a => a.Type), e.Type.NiceToString()));
                        }

                        if (e.Timer != null && !e.Type.IsTimer())
                        {
                            throw new InvalidOperationException(ValidationMessage._0ShouldBeNullWhen1IsSetTo2.NiceToString(e.NicePropertyName(a => a.Timer), e.NicePropertyName(a => a.Type), e.Type.NiceToString()));
                        }

                        if (e.BoundaryOf == null && e.Type.IsBoundaryTimer())
                        {
                            throw new InvalidOperationException(ValidationMessage._0IsMandatoryWhen1IsSetTo2.NiceToString(e.NicePropertyName(a => a.BoundaryOf), e.NicePropertyName(a => a.Type), e.Type.NiceToString()));
                        }

                        if (e.BoundaryOf != null && !e.Type.IsBoundaryTimer())
                        {
                            throw new InvalidOperationException(ValidationMessage._0ShouldBeNullWhen1IsSetTo2.NiceToString(e.NicePropertyName(a => a.BoundaryOf), e.NicePropertyName(a => a.Type), e.Type.NiceToString()));
                        }

                        e.Save();
                    },
                }

                .Register();

                new Graph <WorkflowEventEntity> .Delete(WorkflowEventOperation.Delete)
                {
                    Delete = (e, _) =>
                    {
                        if (e.Type.IsScheduledStart())
                        {
                            var scheduled = e.ScheduledTask();
                            if (scheduled != null)
                            {
                                WorkflowEventTaskLogic.DeleteWorkflowEventScheduledTask(scheduled);
                            }
                        }

                        e.Delete();
                    },
                }

                .Register();

                sb.Include <WorkflowGatewayEntity>()
                .WithSave(WorkflowGatewayOperation.Save)
                .WithDelete(WorkflowGatewayOperation.Delete)
                .WithExpressionFrom((WorkflowEntity p) => p.WorkflowGateways())
                .WithExpressionFrom((WorkflowLaneEntity p) => p.WorkflowGateways())
                .WithQuery(() => e => new
                {
                    Entity = e,
                    e.Id,
                    e.Type,
                    e.Name,
                    e.BpmnElementId,
                    e.Lane,
                    e.Lane.Pool.Workflow,
                });

                sb.Include <WorkflowConnectionEntity>()
                .WithSave(WorkflowConnectionOperation.Save)
                .WithDelete(WorkflowConnectionOperation.Delete)
                .WithExpressionFrom((WorkflowEntity p) => p.WorkflowConnections())
                .WithExpressionFrom((WorkflowEntity p) => p.WorkflowMessageConnections(), null !)
                .WithExpressionFrom((WorkflowPoolEntity p) => p.WorkflowConnections())
                .WithExpressionFrom((IWorkflowNodeEntity p) => p.NextConnections(), null !)
                .WithExpressionFrom((IWorkflowNodeEntity p) => p.PreviousConnections(), null !)
                .WithQuery(() => e => new
                {
                    Entity = e,
                    e.Id,
                    e.Name,
                    e.BpmnElementId,
                    e.From,
                    e.To,
                });

                WorkflowEventTaskEntity.GetWorkflowEntity = lite => WorkflowGraphLazy.Value.GetOrThrow(lite).Workflow;

                WorkflowGraphLazy = sb.GlobalLazy(() =>
                {
                    using (new EntityCache())
                    {
                        var events      = Database.RetrieveAll <WorkflowEventEntity>().GroupToDictionary(a => a.Lane.Pool.Workflow.ToLite());
                        var gateways    = Database.RetrieveAll <WorkflowGatewayEntity>().GroupToDictionary(a => a.Lane.Pool.Workflow.ToLite());
                        var activities  = Database.RetrieveAll <WorkflowActivityEntity>().GroupToDictionary(a => a.Lane.Pool.Workflow.ToLite());
                        var connections = Database.RetrieveAll <WorkflowConnectionEntity>().GroupToDictionary(a => a.From.Lane.Pool.Workflow.ToLite());

                        var result = Database.RetrieveAll <WorkflowEntity>().ToDictionary(workflow => workflow.ToLite(), workflow =>
                        {
                            var w         = workflow.ToLite();
                            var nodeGraph = new WorkflowNodeGraph
                            {
                                Workflow    = workflow,
                                Events      = events.TryGetC(w).EmptyIfNull().ToDictionary(e => e.ToLite()),
                                Gateways    = gateways.TryGetC(w).EmptyIfNull().ToDictionary(g => g.ToLite()),
                                Activities  = activities.TryGetC(w).EmptyIfNull().ToDictionary(a => a.ToLite()),
                                Connections = connections.TryGetC(w).EmptyIfNull().ToDictionary(c => c.ToLite()),
                            };

                            nodeGraph.FillGraphs();
                            return(nodeGraph);
                        });

                        return(result);
                    }
                }, new InvalidateWith(typeof(WorkflowConnectionEntity)));
                WorkflowGraphLazy.OnReset += (e, args) => DynamicCode.OnInvalidated?.Invoke();

                Validator.PropertyValidator((WorkflowConnectionEntity c) => c.Condition).StaticPropertyValidation = (e, pi) =>
                {
                    if (e.Condition != null && e.From != null)
                    {
                        var conditionType = Conditions.Value.GetOrThrow(e.Condition).MainEntityType;
                        var workflowType  = e.From.Lane.Pool.Workflow.MainEntityType;

                        if (!conditionType.Is(workflowType))
                        {
                            return(WorkflowMessage.Condition0IsDefinedFor1Not2.NiceToString(conditionType, workflowType));
                        }
                    }

                    return(null);
                };

                StartWorkflowConditions(sb);

                StartWorkflowTimerConditions(sb);

                StartWorkflowActions(sb);

                StartWorkflowScript(sb);
            }
        }
Ejemplo n.º 23
0
        public static void Start(SchemaBuilder sb, DynamicQueryManager dqm)
        {
            if (sb.NotDefined(MethodInfo.GetCurrentMethod()))
            {
                sb.Include <WordTemplateEntity>()
                .WithSave(WordTemplateOperation.Save)
                .WithDelete(WordTemplateOperation.Delete)
                .WithQuery(dqm, () => e => new
                {
                    Entity = e,
                    e.Id,
                    e.Name,
                    e.Query,
                    e.Culture,
                    e.Template.Entity.FileName
                });

                PermissionAuthLogic.RegisterPermissions(WordTemplatePermission.GenerateReport);

                SystemWordTemplateLogic.Start(sb, dqm);

                SymbolLogic <WordTransformerSymbol> .Start(sb, dqm, () => Transformers.Keys.ToHashSet());

                SymbolLogic <WordConverterSymbol> .Start(sb, dqm, () => Converters.Keys.ToHashSet());

                sb.Include <WordTransformerSymbol>()
                .WithQuery(dqm, () => f => new
                {
                    Entity = f,
                    f.Key
                });

                sb.Include <WordConverterSymbol>()
                .WithQuery(dqm, () => f => new
                {
                    Entity = f,
                    f.Key
                });


                ToDataTableProviders.Add("Model", new ModelDataTableProvider());
                ToDataTableProviders.Add("UserQuery", new UserQueryDataTableProvider());
                ToDataTableProviders.Add("UserChart", new UserChartDataTableProvider());

                dqm.RegisterExpression((SystemWordTemplateEntity e) => e.WordTemplates(), () => typeof(WordTemplateEntity).NiceName());


                new Graph <WordTemplateEntity> .Execute(WordTemplateOperation.CreateWordReport)
                {
                    CanExecute = et =>
                    {
                        if (et.SystemWordTemplate != null && SystemWordTemplateLogic.RequiresExtraParameters(et.SystemWordTemplate))
                        {
                            return(WordTemplateMessage._01RequiresExtraParameters.NiceToString(typeof(SystemWordTemplateEntity).NiceName(), et.SystemWordTemplate));
                        }

                        return(null);
                    },
                    Execute = (et, args) =>
                    {
                        throw new InvalidOperationException("UI-only operation");
                    }
                }

                .Register();

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

                TemplatesByQueryName = sb.GlobalLazy(() =>
                {
                    return(WordTemplatesLazy.Value.Values.GroupToDictionary(a => a.Query.ToQueryName()));
                }, new InvalidateWith(typeof(WordTemplateEntity)));

                TemplatesByEntityType = sb.GlobalLazy(() =>
                {
                    return((from wr in WordTemplatesLazy.Value.Values
                            let imp = DynamicQueryManager.Current.GetEntityImplementations(wr.Query.ToQueryName())
                                      where !imp.IsByAll
                                      from t in imp.Types
                                      select KVP.Create(t, wr))
                           .GroupToDictionary(a => a.Key, a => a.Value));
                }, new InvalidateWith(typeof(WordTemplateEntity)));

                Schema.Current.Synchronizing += Schema_Synchronize_Tokens;

                Validator.PropertyValidator((WordTemplateEntity e) => e.Template).StaticPropertyValidation += ValidateTemplate;
            }
        }
Ejemplo n.º 24
0
        public static void Start(SchemaBuilder sb)
        {
            if (sb.NotDefined(MethodInfo.GetCurrentMethod()))
            {
                sb.Include <TypeHelpEntity>()
                .WithUniqueIndex(e => new { e.Type, e.Culture })
                .WithUniqueIndexMList(e => e.Properties, mle => new { mle.Parent, mle.Element.Property })
                .WithUniqueIndexMList(e => e.Operations, mle => new { mle.Parent, mle.Element.Operation })
                .WithSave(TypeHelpOperation.Save)
                .WithDelete(TypeHelpOperation.Delete)
                .WithQuery(() => e => new
                {
                    Entity = e,
                    e.Id,
                    e.Type,
                    Description = e.Description.Try(d => d.Etc(100))
                });

                sb.Include <NamespaceHelpEntity>()
                .WithUniqueIndex(e => new { e.Name, e.Culture })
                .WithSave(NamespaceHelpOperation.Save)
                .WithDelete(NamespaceHelpOperation.Delete)
                .WithQuery(() => n => new
                {
                    Entity = n,
                    n.Id,
                    n.Name,
                    n.Culture,
                    Description = n.Description.Try(d => d.Etc(100))
                });

                sb.Include <AppendixHelpEntity>()
                .WithUniqueIndex(e => new { e.UniqueName, e.Culture })
                .WithSave(AppendixHelpOperation.Save)
                .WithDelete(AppendixHelpOperation.Delete)
                .WithQuery(() => a => new
                {
                    Entity = a,
                    a.Id,
                    a.UniqueName,
                    a.Culture,
                    a.Title,
                    Description = a.Description.Try(d => d.Etc(100))
                });

                sb.Include <QueryHelpEntity>()
                .WithUniqueIndex(e => new { e.Query, e.Culture })
                .WithUniqueIndexMList(e => e.Columns, mle => new { mle.Parent, mle.Element.ColumnName })
                .WithSave(QueryHelpOperation.Save)
                .WithDelete(QueryHelpOperation.Delete)
                .WithQuery(() => q => new
                {
                    Entity = q,
                    q.Id,
                    q.Query,
                    q.Culture,
                    Description = q.Description.Try(d => d.Etc(100))
                });

                sb.Schema.Synchronizing += Schema_Synchronizing;

                sb.Schema.Table <OperationSymbol>().PreDeleteSqlSync += operation =>
                                                                        Administrator.UnsafeDeletePreCommandMList((TypeHelpEntity eh) => eh.Operations, Database.MListQuery((TypeHelpEntity eh) => eh.Operations).Where(mle => mle.Element.Operation == (OperationSymbol)operation));

                sb.Schema.Table <PropertyRouteEntity>().PreDeleteSqlSync += property =>
                                                                            Administrator.UnsafeDeletePreCommandMList((TypeHelpEntity eh) => eh.Properties, Database.MListQuery((TypeHelpEntity eh) => eh.Properties).Where(mle => mle.Element.Property == (PropertyRouteEntity)property));

                sb.Schema.Table <TypeEntity>().PreDeleteSqlSync += type =>
                                                                   Administrator.UnsafeDeletePreCommand(Database.Query <TypeHelpEntity>().Where(e => e.Type == (TypeEntity)type));

                sb.Schema.Table <QueryEntity>().PreDeleteSqlSync += query =>
                                                                    Administrator.UnsafeDeletePreCommand(Database.Query <QueryHelpEntity>().Where(e => e.Query == (QueryEntity)query));

                Types = sb.GlobalLazy <ConcurrentDictionary <CultureInfo, Dictionary <Type, TypeHelp> > >(() => new ConcurrentDictionary <CultureInfo, Dictionary <Type, TypeHelp> >(),
                                                                                                          invalidateWith: new InvalidateWith(typeof(TypeHelpEntity)));

                Namespaces = sb.GlobalLazy <ConcurrentDictionary <CultureInfo, Dictionary <string, NamespaceHelp> > >(() => new ConcurrentDictionary <CultureInfo, Dictionary <string, NamespaceHelp> >(),
                                                                                                                      invalidateWith: new InvalidateWith(typeof(NamespaceHelpEntity)));

                Appendices = sb.GlobalLazy <ConcurrentDictionary <CultureInfo, Dictionary <string, AppendixHelpEntity> > >(() => new ConcurrentDictionary <CultureInfo, Dictionary <string, AppendixHelpEntity> >(),
                                                                                                                           invalidateWith: new InvalidateWith(typeof(AppendixHelpEntity)));

                Queries = sb.GlobalLazy <ConcurrentDictionary <CultureInfo, Dictionary <object, QueryHelp> > >(() => new ConcurrentDictionary <CultureInfo, Dictionary <object, QueryHelp> >(),
                                                                                                               invalidateWith: new InvalidateWith(typeof(QueryHelpEntity)));

                PermissionAuthLogic.RegisterPermissions(HelpPermissions.ViewHelp);
            }
        }
Ejemplo n.º 25
0
        public static void Start(SchemaBuilder sb, DynamicQueryManager dqm)
        {
            if (sb.NotDefined(MethodInfo.GetCurrentMethod()))
            {
                sb.Include <ProcessAlgorithmSymbol>()
                .WithQuery(dqm, () => pa => new
                {
                    Entity = pa,
                    pa.Id,
                    pa.Key
                });

                sb.Include <ProcessEntity>()
                .WithQuery(dqm, () => p => new
                {
                    Entity = p,
                    p.Id,
                    p.Algorithm,
                    p.Data,
                    p.State,
                    p.MachineName,
                    p.ApplicationName,
                    p.CreationDate,
                    p.PlannedDate,
                    p.CancelationDate,
                    p.QueuedDate,
                    p.ExecutionStart,
                    p.ExecutionEnd,
                    p.SuspendDate,
                    p.ExceptionDate,
                });

                sb.Include <ProcessExceptionLineEntity>()
                .WithQuery(dqm, () => p => new
                {
                    Entity = p,
                    p.Line,
                    p.Process,
                    p.Exception,
                });

                PermissionAuthLogic.RegisterPermissions(ProcessPermission.ViewProcessPanel);

                SymbolLogic <ProcessAlgorithmSymbol> .Start(sb, dqm, () => registeredProcesses.Keys.ToHashSet());

                OperationLogic.AssertStarted(sb);

                ProcessGraph.Register();

                dqm.RegisterExpression((ProcessAlgorithmSymbol p) => p.Processes(), () => typeof(ProcessEntity).NicePluralName());
                dqm.RegisterExpression((ProcessAlgorithmSymbol p) => p.LastProcess(), () => ProcessMessage.LastProcess.NiceToString());

                dqm.RegisterExpression((IProcessDataEntity p) => p.Processes(), () => typeof(ProcessEntity).NicePluralName());
                dqm.RegisterExpression((IProcessDataEntity p) => p.LastProcess(), () => ProcessMessage.LastProcess.NiceToString());

                dqm.RegisterExpression((IProcessLineDataEntity p) => p.ExceptionLines(), () => ProcessMessage.ExceptionLines.NiceToString());

                PropertyAuthLogic.AvoidAutomaticUpgradeCollection.Add(PropertyRoute.Construct((ProcessEntity p) => p.User));

                ExceptionLogic.DeleteLogs += ExceptionLogic_DeleteLogs;
            }
        }
 public static void RegisterName <T>(string userAssetName) where T : IUserAssetEntity
 {
     PermissionAuthLogic.RegisterPermissions(UserAssetPermission.UserAssetsToXML);
     UserAssetNames.Add(userAssetName, typeof(T));
 }
Ejemplo n.º 27
0
 public ViewResult Permissions(Lite <RoleEntity> role)
 {
     return(Navigator.NormalPage(this, PermissionAuthLogic.GetPermissionRules(role.FillToString())));
 }
Ejemplo n.º 28
0
        public static void Start(SchemaBuilder sb)
        {
            if (sb.NotDefined(MethodInfo.GetCurrentMethod()))
            {
                PermissionAuthLogic.RegisterPermissions(DashboardPermission.ViewDashboard);

                UserAssetsImporter.Register <DashboardEntity>("Dashboard", DashboardOperation.Save);

                UserAssetsImporter.PartNames.AddRange(new Dictionary <string, Type>
                {
                    { "UserChartPart", typeof(UserChartPartEntity) },
                    { "CombinedUserChartPart", typeof(CombinedUserChartPartEntity) },
                    { "UserQueryPart", typeof(UserQueryPartEntity) },
                    { "LinkListPart", typeof(LinkListPartEntity) },
                    { "ValueUserQueryListPart", typeof(ValueUserQueryListPartEntity) },
                    { "UserTreePart", typeof(UserTreePartEntity) },
                });

                sb.Include <DashboardEntity>()
                .WithQuery(() => cp => new
                {
                    Entity = cp,
                    cp.Id,
                    cp.DisplayName,
                    cp.EntityType,
                    cp.Owner,
                    cp.DashboardPriority,
                });

                if (sb.Settings.ImplementedBy((DashboardEntity cp) => cp.Parts.First().Content, typeof(UserQueryPartEntity)))
                {
                    sb.Schema.EntityEvents <UserQueryEntity>().PreUnsafeDelete += query =>
                    {
                        Database.MListQuery((DashboardEntity cp) => cp.Parts).Where(mle => query.Contains(((UserQueryPartEntity)mle.Element.Content).UserQuery)).UnsafeDeleteMList();
                        Database.Query <UserQueryPartEntity>().Where(uqp => query.Contains(uqp.UserQuery)).UnsafeDelete();
                        return(null);
                    };

                    sb.Schema.Table <UserQueryEntity>().PreDeleteSqlSync += arg =>
                    {
                        var uq = (UserQueryEntity)arg;

                        var parts = Administrator.UnsafeDeletePreCommandMList((DashboardEntity cp) => cp.Parts, Database.MListQuery((DashboardEntity cp) => cp.Parts)
                                                                              .Where(mle => ((UserQueryPartEntity)mle.Element.Content).UserQuery == uq));

                        var parts2 = Administrator.UnsafeDeletePreCommand(Database.Query <UserQueryPartEntity>()
                                                                          .Where(mle => mle.UserQuery == uq));

                        return(SqlPreCommand.Combine(Spacing.Simple, parts, parts2));
                    };
                }

                if (sb.Settings.ImplementedBy((DashboardEntity cp) => cp.Parts.First().Content, typeof(UserChartPartEntity)))
                {
                    sb.Schema.EntityEvents <UserChartEntity>().PreUnsafeDelete += query =>
                    {
                        Database.MListQuery((DashboardEntity cp) => cp.Parts).Where(mle => query.Contains(((UserChartPartEntity)mle.Element.Content).UserChart)).UnsafeDeleteMList();
                        Database.Query <UserChartPartEntity>().Where(uqp => query.Contains(uqp.UserChart)).UnsafeDelete();

                        Database.MListQuery((DashboardEntity cp) => cp.Parts).Where(mle => ((CombinedUserChartPartEntity)mle.Element.Content).UserCharts.Any(uc => query.Contains(uc))).UnsafeDeleteMList();
                        Database.Query <CombinedUserChartPartEntity>().Where(cuqp => cuqp.UserCharts.Any(uc => query.Contains(uc))).UnsafeDelete();

                        return(null);
                    };

                    sb.Schema.Table <UserChartEntity>().PreDeleteSqlSync += arg =>
                    {
                        var uc = (UserChartEntity)arg;

                        var mlistElems = Administrator.UnsafeDeletePreCommandMList((DashboardEntity cp) => cp.Parts, Database.MListQuery((DashboardEntity cp) => cp.Parts)
                                                                                   .Where(mle => ((UserChartPartEntity)mle.Element.Content).UserChart == uc));

                        var parts = Administrator.UnsafeDeletePreCommand(Database.Query <UserChartPartEntity>()
                                                                         .Where(mle => mle.UserChart == uc));

                        var mlistElems2 = Administrator.UnsafeDeletePreCommandMList((DashboardEntity cp) => cp.Parts, Database.MListQuery((DashboardEntity cp) => cp.Parts)
                                                                                    .Where(mle => ((CombinedUserChartPartEntity)mle.Element.Content).UserCharts.Contains(uc)));

                        var parts2 = Administrator.UnsafeDeletePreCommand(Database.Query <CombinedUserChartPartEntity>()
                                                                          .Where(mle => mle.UserCharts.Contains(uc)));

                        return(SqlPreCommand.Combine(Spacing.Simple, mlistElems, parts, mlistElems2, parts2));
                    };
                }

                DashboardGraph.Register();


                Dashboards = sb.GlobalLazy(() => Database.Query <DashboardEntity>().ToDictionary(a => a.ToLite()),
                                           new InvalidateWith(typeof(DashboardEntity)));

                DashboardsByType = sb.GlobalLazy(() => Dashboards.Value.Values.Where(a => a.EntityType != null)
                                                 .SelectCatch(d => KeyValuePair.Create(TypeLogic.IdToType.GetOrThrow(d.EntityType !.Id), d.ToLite()))
                                                 .GroupToDictionary(),
                                                 new InvalidateWith(typeof(DashboardEntity)));
            }
        }
Ejemplo n.º 29
0
        public static void Start(HttpConfiguration config, Func <AuthTokenConfigurationEmbedded> tokenConfig, string hashableEncryptionKey)
        {
            SignumControllerFactory.RegisterArea(MethodInfo.GetCurrentMethod());

            AuthTokenServer.Start(tokenConfig, hashableEncryptionKey);

            ReflectionServer.GetContext = () => new
            {
                Culture = ReflectionServer.GetCurrentValidCulture(),
                Role    = UserEntity.Current == null ? null : RoleEntity.Current,
            };

            AuthLogic.OnRulesChanged += () => ReflectionServer.cache.Clear();

            if (TypeAuthLogic.IsStarted)
            {
                ReflectionServer.AddTypeExtension += (ti, t) =>
                {
                    if (typeof(Entity).IsAssignableFrom(t))
                    {
                        ti.Extension.Add("typeAllowed", UserEntity.Current == null ? TypeAllowedBasic.None : TypeAuthLogic.GetAllowed(t).MaxUI());
                    }
                };
            }

            if (QueryAuthLogic.IsStarted)
            {
                ReflectionServer.AddTypeExtension += (ti, t) =>
                {
                    if (ti.QueryDefined)
                    {
                        ti.Extension.Add("queryAllowed", UserEntity.Current == null ? QueryAllowed.None : QueryAuthLogic.GetQueryAllowed(t));
                    }
                };

                ReflectionServer.AddFieldInfoExtension += (mi, fi) =>
                {
                    if (fi.DeclaringType.Name.EndsWith("Query"))
                    {
                        mi.Extension.Add("queryAllowed", UserEntity.Current == null ? QueryAllowed.None : QueryAuthLogic.GetQueryAllowed(fi.GetValue(null)));
                    }
                };
            }

            if (PropertyAuthLogic.IsStarted)
            {
                ReflectionServer.AddPropertyRouteExtension += (mi, pr) =>
                {
                    mi.Extension.Add("propertyAllowed", UserEntity.Current == null ? PropertyAllowed.None : pr.GetPropertyAllowed());
                };
            }

            if (OperationAuthLogic.IsStarted)
            {
                ReflectionServer.AddFieldInfoExtension += (mi, fi) =>
                {
                    if (fi.DeclaringType.Name.EndsWith("Operation"))
                    {
                        if (fi.GetValue(null) is IOperationSymbolContainer container)
                        {
                            mi.Extension.Add("operationAllowed",
                                             UserEntity.Current == null ? false
                                    : OperationAuthLogic.GetOperationAllowed(container.Symbol, inUserInterface: true));
                        }
                    }
                };
            }

            if (PermissionAuthLogic.IsStarted)
            {
                ReflectionServer.AddFieldInfoExtension += (mi, fi) =>
                {
                    if (fi.FieldType == typeof(PermissionSymbol))
                    {
                        mi.Extension.Add("permissionAllowed",
                                         UserEntity.Current == null
                                ? false
                                : PermissionAuthLogic.IsAuthorized((PermissionSymbol)fi.GetValue(null)));
                    }
                };
            }


            var piPasswordHash = ReflectionTools.GetPropertyInfo((UserEntity e) => e.PasswordHash);
            var pcs            = PropertyConverter.GetPropertyConverters(typeof(UserEntity));

            pcs.GetOrThrow("passwordHash").CustomWriteJsonProperty = ctx => { };
            pcs.Add("newPassword", new PropertyConverter
            {
                AvoidValidate           = true,
                CustomWriteJsonProperty = ctx => { },
                CustomReadJsonProperty  = ctx =>
                {
                    EntityJsonConverter.AssertCanWrite(ctx.ParentPropertyRoute.Add(piPasswordHash));

                    var password = (string)ctx.JsonReader.Value;

                    var error = UserEntity.OnValidatePassword(password);
                    if (error != null)
                    {
                        throw new ApplicationException(error);
                    }

                    ((UserEntity)ctx.Entity).PasswordHash = Security.EncodePassword(password);
                }
            });

            if (TypeAuthLogic.IsStarted)
            {
                Omnibox.OmniboxServer.IsNavigable += type => TypeAuthLogic.GetAllowed(type).MaxUI() >= TypeAllowedBasic.Read;
            }

            SchemaMap.GetColorProviders += GetMapColors;
        }
Ejemplo n.º 30
0
        public static void Start(SchemaBuilder sb)
        {
            if (sb.NotDefined(MethodInfo.GetCurrentMethod()))
            {
                AuthLogic.AssertStarted(sb);
                OperationLogic.AssertStarted(sb);

                Implementations imp  = sb.Settings.GetImplementations((ScheduledTaskEntity st) => st.Task);
                Implementations imp2 = sb.Settings.GetImplementations((ScheduledTaskLogEntity st) => st.Task);

                if (!imp2.Equals(imp2))
                {
                    throw new InvalidOperationException("Implementations of ScheduledTaskEntity.Task should be the same as in ScheduledTaskLogEntity.Task");
                }

                PermissionAuthLogic.RegisterPermissions(SchedulerPermission.ViewSchedulerPanel);

                ExecuteTask.Register((ITaskEntity t, ScheduledTaskContext ctx) => { throw new NotImplementedException("SchedulerLogic.ExecuteTask not registered for {0}".FormatWith(t.GetType().Name)); });

                SimpleTaskLogic.Start(sb);
                sb.Include <ScheduledTaskEntity>()
                .WithQuery(() => st => new
                {
                    Entity = st,
                    st.Id,
                    st.Task,
                    st.Rule,
                    st.Suspended,
                    st.MachineName,
                    st.ApplicationName
                });

                sb.Include <ScheduledTaskLogEntity>()
                .WithIndex(s => s.ScheduledTask, includeFields: s => s.StartTime)
                .WithQuery(() => cte => new
                {
                    Entity = cte,
                    cte.Id,
                    cte.Task,
                    cte.ScheduledTask,
                    cte.StartTime,
                    cte.EndTime,
                    cte.ProductEntity,
                    cte.MachineName,
                    cte.User,
                    cte.Exception,
                });

                sb.Include <SchedulerTaskExceptionLineEntity>()
                .WithQuery(() => cte => new
                {
                    Entity = cte,
                    cte.Id,
                    cte.ElementInfo,
                    cte.Exception,
                    cte.SchedulerTaskLog,
                });

                new Graph <ScheduledTaskLogEntity> .Execute(ScheduledTaskLogOperation.CancelRunningTask)
                {
                    CanExecute = e => RunningTasks.ContainsKey(e) ? null : SchedulerMessage.TaskIsNotRunning.NiceToString(),
                    Execute    = (e, _) => { RunningTasks[e].CancellationTokenSource.Cancel(); },
                }

                .Register();

                sb.Include <HolidayCalendarEntity>()
                .WithQuery(() => st => new
                {
                    Entity = st,
                    st.Id,
                    st.Name,
                    Holidays = st.Holidays.Count,
                });

                QueryLogic.Expressions.Register((ITaskEntity ct) => ct.Executions(), () => ITaskMessage.Executions.NiceToString());
                QueryLogic.Expressions.Register((ITaskEntity ct) => ct.LastExecution(), () => ITaskMessage.LastExecution.NiceToString());
                QueryLogic.Expressions.Register((ScheduledTaskEntity ct) => ct.Executions(), () => ITaskMessage.Executions.NiceToString());
                QueryLogic.Expressions.Register((ScheduledTaskLogEntity ct) => ct.ExceptionLines(), () => ITaskMessage.ExceptionLines.NiceToString());

                new Graph <HolidayCalendarEntity> .Execute(HolidayCalendarOperation.Save)
                {
                    CanBeNew      = true,
                    CanBeModified = true,
                    Execute       = (c, _) => { },
                }

                .Register();

                new Graph <HolidayCalendarEntity> .Delete(HolidayCalendarOperation.Delete)
                {
                    Delete = (c, _) => { c.Delete(); },
                }

                .Register();

                new Graph <ScheduledTaskEntity> .Execute(ScheduledTaskOperation.Save)
                {
                    CanBeNew      = true,
                    CanBeModified = true,
                    Execute       = (st, _) => { },
                }

                .Register();

                new Graph <ScheduledTaskEntity> .Delete(ScheduledTaskOperation.Delete)
                {
                    Delete = (st, _) =>
                    {
                        st.Executions().UnsafeUpdate().Set(l => l.ScheduledTask, l => null).Execute();
                        var rule = st.Rule; st.Delete(); rule.Delete();
                    },
                }

                .Register();


                new Graph <ScheduledTaskLogEntity> .ConstructFrom <ITaskEntity>(ITaskOperation.ExecuteSync)
                {
                    Construct = (task, _) => ExecuteSync(task, null, UserHolder.Current)
                }

                .Register();

                new Graph <ITaskEntity> .Execute(ITaskOperation.ExecuteAsync)
                {
                    Execute = (task, _) => ExecuteAsync(task, null, UserHolder.Current)
                }

                .Register();

                ScheduledTasksLazy = sb.GlobalLazy(() =>
                                                   Database.Query <ScheduledTaskEntity>().Where(a => !a.Suspended &&
                                                                                                (a.MachineName == ScheduledTaskEntity.None || a.MachineName == Environment.MachineName && a.ApplicationName == Schema.Current.ApplicationName)).ToList(),
                                                   new InvalidateWith(typeof(ScheduledTaskEntity)));

                ScheduledTasksLazy.OnReset += ScheduledTasksLazy_OnReset;

                sb.Schema.EntityEvents <ScheduledTaskLogEntity>().PreUnsafeDelete += query =>
                {
                    query.SelectMany(e => e.ExceptionLines()).UnsafeDelete();
                    return(null);
                };

                ExceptionLogic.DeleteLogs += ExceptionLogic_DeleteLogs;
            }
        }