Ejemplo n.º 1
0
        internal static void Start(SchemaBuilder sb, DynamicQueryManager dqm)
        {
            if (sb.NotDefined(MethodInfo.GetCurrentMethod()))
            {
                sb.Include<ChartScriptEntity>();

                dqm.RegisterQuery(typeof(ChartScriptEntity), () =>
                    from uq in Database.Query<ChartScriptEntity>()
                    select new
                    {
                        Entity = uq,
                        uq.Id,
                        uq.Name,
                        uq.GroupBy,
                        uq.Columns.Count,
                        uq.Icon,
                    });

                Scripts = sb.GlobalLazy(() =>
                {
                    var result = Database.Query<ChartScriptEntity>().ToDictionary(a => a.Name);
                    foreach (var e in result.Values)
                        if (e.Icon != null)
                            e.Icon.Retrieve();

                    return result;
                }, new InvalidateWith(typeof(ChartScriptEntity)));

                RegisterOperations();
            }
        }
        public static void Start(SchemaBuilder sb, DynamicQueryManager dqm)
        {
            if (sb.NotDefined(MethodInfo.GetCurrentMethod()))
            {
                IsStarted = true;

                AuthLogic.AssertStarted(sb);
                sb.Include<UserTicketEntity>();

                dqm.RegisterQuery(typeof(UserTicketEntity), () =>
                    from ut in Database.Query<UserTicketEntity>()
                    select new
                    {
                        Entity = ut,
                        ut.Id,
                        ut.User,
                        ut.Ticket,
                        ut.ConnectionDate,
                        ut.Device,
                    });

                dqm.RegisterExpression((UserEntity u) => u.UserTickets(), () => typeof(UserTicketEntity).NicePluralName());

                sb.Schema.EntityEvents<UserEntity>().Saving += UserTicketLogic_Saving; 
            }
        }
Ejemplo n.º 3
0
 public static void Start(SchemaBuilder sb, DynamicQueryManager dqm)
 {
     if (sb.NotDefined(MethodInfo.GetCurrentMethod()))
     {
         PermissionAuthLogic.RegisterPermissions(MapPermission.ViewMap);
     }
 }
Ejemplo n.º 4
0
        public static void Start(SchemaBuilder sb, DynamicQueryManager dqm, HashSet<Type> registerExpression)
        {
            if (sb.NotDefined(MethodInfo.GetCurrentMethod()))
            {
                sb.Include<ViewLogEntity>();

                dqm.RegisterQuery(typeof(ViewLogEntity), () =>
                    from e in Database.Query<ViewLogEntity>()
                    select new
                    {
                        Entity = e,
                        e.Id,
                        e.Target,
                        e.ViewAction,
                        e.User,
                        e.Duration,
                        e.StartDate,
                        e.EndDate,
                    });

                ExceptionLogic.DeleteLogs += ExceptionLogic_DeleteLogs;

                var exp = Signum.Utilities.ExpressionTrees.Linq.Expr((Entity entity) => entity.ViewLogs());

                foreach (var t in registerExpression)
                {
                    dqm.RegisterExpression(new ExtensionInfo(t, exp, exp.Body.Type, "ViewLogs", () => typeof(ViewLogEntity).NicePluralName()));
                }

                DynamicQueryManager.Current.QueryExecuted += Current_QueryExecuted;
                sb.Schema.Table<TypeEntity>().PreDeleteSqlSync += Type_PreDeleteSqlSync;
            }
        }
Ejemplo n.º 5
0
        public static void Start(string connectionString)
        {
            DBMS dbms = DBMS.SqlServer2008;

            SchemaBuilder sb = new SchemaBuilder(dbms);
            DynamicQueryManager dqm = new DynamicQueryManager();
            if (dbms == DBMS.SqlCompact)
                Connector.Default = new SqlCeConnector(@"Data Source=C:\BaseDatos.sdf", sb.Schema, dqm);
            else
                Connector.Default = new SqlConnector(connectionString, sb.Schema, dqm);


            sb.Schema.Version = typeof(Starter).Assembly.GetName().Version;

            sb.Schema.Settings.OverrideAttributes((OperationLogDN ol) => ol.User, new ImplementedByAttribute());
            sb.Schema.Settings.OverrideAttributes((ExceptionDN e) => e.User, new ImplementedByAttribute());

            Validator.PropertyValidator((OperationLogDN e) => e.User).Validators.Clear();
            
            TypeLogic.Start(sb, dqm);

            OperationLogic.Start(sb, dqm);
            ExceptionLogic.Start(sb, dqm);

            MusicLogic.Start(sb, dqm);
        }
        public static void Start(SchemaBuilder sb, DynamicQueryManager dqm)
        {
            if (sb.NotDefined(MethodInfo.GetCurrentMethod()))
            {
                sb.Include<SmtpConfigurationEntity>();

                dqm.RegisterQuery(typeof(SmtpConfigurationEntity), () =>
                    from s in Database.Query<SmtpConfigurationEntity>()
                    select new
                    {
                        Entity = s,
                        s.Id,
                        s.DeliveryMethod,
                        s.Network.Host,
                        s.Network.Username,
                        s.PickupDirectoryLocation
                    });

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

                new Graph<SmtpConfigurationEntity>.Execute(SmtpConfigurationOperation.Save)
                {
                    AllowsNew = true,
                    Lite = false,
                    Execute = (sc, _) => { },
                }.Register();
            }
        }
Ejemplo n.º 7
0
        public static void Start(SchemaBuilder sb, DynamicQueryManager dqm)
        {
            if (sb.NotDefined(MethodInfo.GetCurrentMethod()))
            {
                sb.Include<DynamicValidationEntity>()
                    .WithSave(DynamicValidationOperation.Save)
                    .WithQuery(dqm, e => new
                    {
                        Entity = e,
                        e.Id,
                        e.Name,
                        e.EntityType,
                        e.PropertyRoute,
                        e.Eval,
                    });
                DynamicValidations = sb.GlobalLazy(() =>
                    Database.Query<DynamicValidationEntity>()
                    .Select(dv => new DynamicValidationPair { Validation = dv, PropertyRoute = dv.PropertyRoute.ToPropertyRoute() })
                    .GroupToDictionary(a => a.PropertyRoute.PropertyInfo),
                        new InvalidateWith(typeof(DynamicValidationEntity)));

                sb.Schema.Initializing += () => { initialized = true; };

                Validator.GlobalValidation += DynamicValidation;
            }
        }
Ejemplo n.º 8
0
        public static void Start(SchemaBuilder sb, DynamicQueryManager dqm)
        {
            if (sb.NotDefined(MethodInfo.GetCurrentMethod()))
            {
                sb.Include<ExceptionEntity>();

                dqm.RegisterQuery(typeof(ExceptionEntity),()=>
                    from r in Database.Query<ExceptionEntity>()
                    select new
                    {
                        Entity = r,
                        r.Id,
                        r.CreationDate,
                        r.ExceptionType,
                        ExcepcionMessage = r.ExceptionMessage,
                        r.StackTraceHash,
                    });

                dqm.RegisterQuery(typeof(ExceptionEntity), ()=>
                     from r in Database.Query<ExceptionEntity>()
                     select new
                     {
                         Entity = r,
                         r.Id,
                         r.CreationDate,
                         r.ExceptionType,
                         ExcepcionMessage = r.ExceptionMessage,
                         r.StackTraceHash,
                     });

                DefaultEnvironment = "Default"; 
            }
        }
Ejemplo n.º 9
0
 public override Schema GetOrCreateSchema()
 {
     SchemaBuilder sb = new SchemaBuilder(SchemaGuid);
      sb.SetSchemaName(SchemaName);
      sb.AddSimpleField("someBool", typeof(bool));
      return sb.Finish();
 }
Ejemplo n.º 10
0
        public static void Start(SchemaBuilder sb)
        {
            if (sb.NotDefined(MethodInfo.GetCurrentMethod()))
            {
                // QueryManagers = queryManagers;
                sb.Schema.Initializing += () =>
                {
                    queryNamesLazy.Load();

                    queryNameToEntityLazy.Load();
                };

                sb.Include<QueryEntity>();

                sb.Schema.Synchronizing += SynchronizeQueries;
                sb.Schema.Generating += Schema_Generating;

                queryNamesLazy = sb.GlobalLazy(()=>CreateQueryNames(), new InvalidateWith(typeof(QueryEntity)));

                queryNameToEntityLazy = sb.GlobalLazy(() => 
                    EnumerableExtensions.JoinStrict(
                        Database.Query<QueryEntity>().ToList(),
                        QueryNames,
                        q => q.Key,
                        kvp => kvp.Key,
                        (q, kvp) => KVP.Create(kvp.Value, q),
                        "caching QueryEntity. Consider synchronize").ToDictionary(),
                    new InvalidateWith(typeof(QueryEntity)));
            }
        }
        // Create a data structure, attach it to a wall, populate it with data, and retrieve the data back from the wall
        public void CreateSchemeAndStoreData(FamilySymbol titleblock)
        {
            SchemaBuilder schemaBuilder = new SchemaBuilder(new Guid("1a68d420-96dd-44aa-a1de-000774a6104b"));
            schemaBuilder.SetReadAccessLevel(AccessLevel.Public); // allow anyone to read the object
            schemaBuilder.SetSchemaName("TitleBlockSettings");

            // create a field to store data
            FieldBuilder fieldBuilder_titleblockName = schemaBuilder.AddSimpleField("titleblockName", typeof(string));

            FieldBuilder fieldBuilder_cellSizeDistance_X = schemaBuilder.AddSimpleField("cellSizeDistance_X", typeof(string));
            //fieldBuilder_cellSizeDistance_X.SetUnitType(UnitType.UT_Length);
            FieldBuilder fieldBuilder_lowerGap_X = schemaBuilder.AddSimpleField("lowerGap_X", typeof(string));
            //fieldBuilder_lowerGap_X.SetUnitType(UnitType.UT_Length);
            FieldBuilder fieldBuilder_additionalEdge_X = schemaBuilder.AddSimpleField("additionalEdge_X", typeof(string));
            //fieldBuilder_additionalEdge_X.SetUnitType(UnitType.UT_Length);
            FieldBuilder fieldBuilder_fineTune_X = schemaBuilder.AddSimpleField("fineTune_X", typeof(string));
            //fieldBuilder_fineTune_X.SetUnitType(UnitType.UT_Length);

            FieldBuilder fieldBuilder_cellSizeDistance_Y = schemaBuilder.AddSimpleField("cellSizeDistance_Y", typeof(string));
            //fieldBuilder_cellSizeDistance_Y.SetUnitType(UnitType.UT_Length);
            FieldBuilder fieldBuilder_lowerGap_Y = schemaBuilder.AddSimpleField("lowerGap_Y", typeof(string));
            //fieldBuilder_lowerGap_Y.SetUnitType(UnitType.UT_Length);
            FieldBuilder fieldBuilder_additionalEdge_Y = schemaBuilder.AddSimpleField("additionalEdge_Y", typeof(string));
            //fieldBuilder_additionalEdge_Y.SetUnitType(UnitType.UT_Length);
            FieldBuilder fieldBuilder_fineTune_Y = schemaBuilder.AddSimpleField("fineTune_Y", typeof(string));
            //fieldBuilder_fineTune_Y.SetUnitType(UnitType.UT_Length);

            FieldBuilder fieldBuilder_cellGrid_Length = schemaBuilder.AddSimpleField("cellGrid_Length", typeof(string));
            FieldBuilder fieldBuilder_cellGrid_Height = schemaBuilder.AddSimpleField("cellGrid_Height", typeof(string));

            //fieldBuilder.SetDocumentation("store length of cell size in X direction.");

            Schema schema = schemaBuilder.Finish(); // register the Schema object
        }
Ejemplo n.º 12
0
        public static void Start(SchemaBuilder sb, DynamicQueryManager dqm, bool excelReport)
        {
            if (excelReport)
            {
                QueryLogic.Start(sb);

                sb.Include<ExcelReportEntity>();
                dqm.RegisterQuery(typeof(ExcelReportEntity), () =>
                    from s in Database.Query<ExcelReportEntity>()
                    select new
                    {
                        Entity = s,
                        s.Id,
                        s.Query,
                        s.File.FileName,
                        s.DisplayName,
                    });

                new Graph<ExcelReportEntity>.Execute(ExcelReportOperation.Save)
                {
                    AllowsNew = true,
                    Lite = false,
                    Execute = (er, _) => { }
                }.Register();

                new Graph<ExcelReportEntity>.Delete(ExcelReportOperation.Delete)
                {
                    Lite = true,
                    Delete = (er, _) => { er.Delete(); }
                }.Register();
            }
        }
Ejemplo n.º 13
0
        public static void Start(string connectionString)
        {
            SchemaBuilder sb = new SchemaBuilder();
            DynamicQueryManager dqm = new DynamicQueryManager();
           
            //Connector.Default = new SqlCeConnector(@"Data Source=C:\BaseDatos.sdf", sb.Schema, dqm);
            
            Connector.Default = new SqlConnector(connectionString, sb.Schema, dqm, SqlServerVersion.SqlServer2008);


            sb.Schema.Version = typeof(MusicStarter).Assembly.GetName().Version;

            sb.Schema.Settings.FieldAttributes((OperationLogEntity ol) => ol.User).Add(new ImplementedByAttribute());
            sb.Schema.Settings.FieldAttributes((ExceptionEntity e) => e.User).Add(new ImplementedByAttribute());

            Validator.PropertyValidator((OperationLogEntity e) => e.User).Validators.Clear();
            
            TypeLogic.Start(sb, dqm);

            OperationLogic.Start(sb, dqm);
            ExceptionLogic.Start(sb, dqm);

            MusicLogic.Start(sb, dqm);

            sb.Schema.OnSchemaCompleted();
        }
Ejemplo n.º 14
0
 public override Schema GetOrCreateSchema()
 {
     SchemaBuilder sb = new SchemaBuilder(SchemaGuid);
      sb.SetSchemaName(SchemaName);
      sb.AddArrayField("someStringArray", typeof(string));
      return sb.Finish();
 }
Ejemplo n.º 15
0
        public static void Start(SchemaBuilder sb, DynamicQueryManager dqm)
        {
            if (sb.NotDefined(MethodInfo.GetCurrentMethod()))
            {
                AuthLogic.AssertStarted(sb);

                sb.Include<SessionLogEntity>();

                PermissionAuthLogic.RegisterPermissions(SessionLogPermission.TrackSession);

                dqm.RegisterQuery(typeof(SessionLogEntity), () =>
                    from sl in Database.Query<SessionLogEntity>()
                    select new
                    {
                        Entity = sl,
                        sl.Id,
                        sl.User,
                        sl.SessionStart,
                        sl.SessionEnd,
                        sl.SessionTimeOut
                    });

                ExceptionLogic.DeleteLogs += ExceptionLogic_DeleteLogs;
            }
        }
Ejemplo n.º 16
0
        public static void Start(SchemaBuilder sb, DynamicQueryManager dqm)
        {
            if (sb.NotDefined(MethodInfo.GetCurrentMethod()))
            {
                FileTypeLogic.Start(sb, dqm);

                sb.Include<FilePathEntity>();

                sb.Schema.EntityEvents<FilePathEntity>().Retrieved += FilePathLogic_Retrieved;
                sb.Schema.EntityEvents<FilePathEntity>().PreSaving += FilePath_PreSaving;
                sb.Schema.EntityEvents<FilePathEntity>().PreUnsafeDelete += new PreUnsafeDeleteHandler<FilePathEntity>(FilePathLogic_PreUnsafeDelete);

                dqm.RegisterQuery(typeof(FilePathEntity), () =>
                    from p in Database.Query<FilePathEntity>()
                    select new
                    {
                        Entity = p,
                        p.Id,
                        p.FileName,
                        p.FileType,
                        p.Sufix
                    });

                new Graph<FilePathEntity>.Execute(FilePathOperation.Save)
                {
                    AllowsNew = true,
                    Lite = false,
                    Execute = (fp, _) =>
                    {
                        if (!fp.IsNew)
                        {

                            var ofp = fp.ToLite().Retrieve();


                            if (fp.FileName != ofp.FileName || fp.Sufix != ofp.Sufix || fp.FullPhysicalPath != ofp.FullPhysicalPath)
                            {
                                using (Transaction tr = new Transaction())
                                {
                                    var preSufix = ofp.Sufix.Substring(0, ofp.Sufix.Length - ofp.FileName.Length);
                                    fp.Sufix = Path.Combine(preSufix, fp.FileName);
                                    fp.Save();
                                    System.IO.File.Move(ofp.FullPhysicalPath, fp.FullPhysicalPath);
                                    tr.Commit();
                                }
                            }
                        }
                    }
                }.Register();

                OperationLogic.SetProtectedSave<FilePathEntity>(false);

                sb.AddUniqueIndex<FilePathEntity>(f => new { f.Sufix, f.FileType }); //With mixins, add AttachToUniqueIndexes to field

                dqm.RegisterExpression((FilePathEntity fp) => fp.WebImage(), () => typeof(WebImage).NiceName(), "Image");
                dqm.RegisterExpression((FilePathEntity fp) => fp.WebDownload(), () => typeof(WebDownload).NiceName(), "Download");

            }
        }
Ejemplo n.º 17
0
 public override Schema GetSchema()
 {
     var schema = base.GetSchema();
     var schemaBuilder = new SchemaBuilder();
     schema.CombineWith(new Schema(schemaBuilder.Inject(@"<Attribute Name=""" + ClassTypeToInstantiate + @""" RefNodeName=""/Application/BOModel/Class""/>", ModelElement.ListView)));
     schema.CombineWith(new Schema(schemaBuilder.Inject(@"<Attribute Name=""" + ClassTypeToInstantiate + @""" RefNodeName=""/Application/BOModel/Class""/>", ModelElement.DetailView)));
     return schema;
 }   
Ejemplo n.º 18
0
        public static void Start(SchemaBuilder sb, DynamicQueryManager dqm)
        {
            if (sb.NotDefined(MethodInfo.GetCurrentMethod()))
            {
                sb.Include<PasswordExpiresIntervalEntity>();

                dqm.RegisterQuery(typeof(PasswordExpiresIntervalEntity), ()=>
                    from e in Database.Query<PasswordExpiresIntervalEntity>()
                     select new
                     {
                         Entity = e,
                         e.Id,
                         e.Enabled,
                         e.Days,
                         e.DaysWarning
                     });

                new Graph<PasswordExpiresIntervalEntity>.Execute(PasswordExpiresIntervalOperation.Save)
                {
                    AllowsNew = true,
                    Lite = false,
                    Execute = (pei, _) => { },
                }.Register();

                AuthLogic.UserLogingIn += (u =>
                {
                    if (u.PasswordNeverExpires)
                        return;

                    var ivp = Database.Query<PasswordExpiresIntervalEntity>().Where(p => p.Enabled).FirstOrDefault();
                    if (ivp == null)
                        return;
                    
                    if (TimeZoneManager.Now > u.PasswordSetDate.AddDays((double)ivp.Days))
                        throw new PasswordExpiredException(AuthMessage.ExpiredPassword.NiceToString());
                });

                AuthLogic.LoginMessage += (() =>
                {
                    UserEntity u = UserEntity.Current;

                    if (u.PasswordNeverExpires)
                        return null;

                    PasswordExpiresIntervalEntity ivp = null;
                    using (AuthLogic.Disable())
                        ivp = Database.Query<PasswordExpiresIntervalEntity>().Where(p => p.Enabled).FirstOrDefault();
                    
                    if (ivp == null)
                        return null;

                    if (TimeZoneManager.Now > u.PasswordSetDate.AddDays((double)ivp.Days).AddDays((double)-ivp.DaysWarning))
                        return AuthMessage.YourPasswordIsNearExpiration.NiceToString();

                    return null;
                });
            }
        }
        public void Generates_Create_Schema_Statement()
        {
            var builder = new SchemaBuilder("[procName]");
            var script = builder.GetScript();

            const string expected =
                @"CREATE SCHEMA [procName]";

            Assert.IsTrue(script.IndexOf(expected) >= 0);
        }
        public void Generates_Extended_Property_String()
        {
            var builder = new SchemaBuilder("procName");
            var script = builder.GetScript();

            const string expected =
                @"EXECUTE sp_addextendedproperty @name = 'tSQLt.TestClass', @value = 1, @level0type = 'SCHEMA', @level0name = 'procName'";

            Assert.IsTrue(script.IndexOf(expected) >= 0, script);
        }
Ejemplo n.º 21
0
        public static void Start(SchemaBuilder sb)
        {
            if (sb.NotDefined(MethodInfo.GetCurrentMethod()))
            {
                sb.Include<PropertyRouteEntity>();

                sb.AddUniqueIndex<PropertyRouteEntity>(p => new { p.Path, p.RootType }); 

                sb.Schema.Synchronizing += SyncronizeProperties;
            }
        }
Ejemplo n.º 22
0
        public static void Start(SchemaBuilder sb, DynamicQueryManager dqm)
        {
            if (sb.NotDefined(MethodInfo.GetCurrentMethod()))
            {
                sb.Include<EmailPackageEntity>();

                dqm.RegisterExpression((EmailPackageEntity ep) => ep.Messages(), () => EmailMessageMessage.Messages.NiceToString());
                dqm.RegisterExpression((EmailPackageEntity ep) => ep.RemainingMessages(), () => EmailMessageMessage.RemainingMessages.NiceToString());
                dqm.RegisterExpression((EmailPackageEntity ep) => ep.ExceptionMessages(), () => EmailMessageMessage.ExceptionMessages.NiceToString());

                ProcessLogic.AssertStarted(sb);
                ProcessLogic.Register(EmailMessageProcess.CreateEmailsSendAsync, new CreateEmailsSendAsyncProcessAlgorithm());
                ProcessLogic.Register(EmailMessageProcess.SendEmails, new SendEmailProcessAlgorithm());

                new Graph<ProcessEntity>.ConstructFromMany<EmailMessageEntity>(EmailMessageOperation.ReSendEmails)
                {
                    Construct = (messages, args) =>
                    {
                        EmailPackageEntity emailPackage = new EmailPackageEntity()
                        {
                            Name = args.TryGetArgC<string>()
                        }.Save();

                        foreach (var m in messages.Select(m => m.RetrieveAndForget()))
                        {
                            new EmailMessageEntity()
                            {
                                Package = emailPackage.ToLite(),
                                From = m.From,
                                Recipients = m.Recipients.ToMList(),
                                Target = m.Target,
                                Body = m.Body,
                                IsBodyHtml = m.IsBodyHtml,
                                Subject = m.Subject,
                                Template = m.Template,
                                EditableMessage = m.EditableMessage,
                                State = EmailMessageState.RecruitedForSending
                            }.Save();
                        }

                        return ProcessLogic.Create(EmailMessageProcess.SendEmails, emailPackage);
                    }
                }.Register();

                dqm.RegisterQuery(typeof(EmailPackageEntity), () =>
                    from e in Database.Query<EmailPackageEntity>()
                    select new
                    {
                        Entity = e,
                        e.Id,
                        e.Name,
                    });
            }
        }
        private Schema GetStorageSchema()
        {
            var bld = new SchemaBuilder(_schemaGuid);
            bld.SetSchemaName("BimLibraryData");
            bld.SetWriteAccessLevel(AccessLevel.Public);
            bld.SetReadAccessLevel(AccessLevel.Public);
            //bld.SetVendorId("ADSK");
            bld.SetDocumentation("This schema stores project specific application data of Czech BIM Library.");
            bld.AddSimpleField(FieldNameData, typeof(String)).SetDocumentation("Data field");

            return bld.Finish();
        }
Ejemplo n.º 24
0
        public static void Start(SchemaBuilder sb, DynamicQueryManager dqm)
        {
            sb.Include<ExcelAttachmentEntity>();
            dqm.RegisterQuery(typeof(ExcelAttachmentEntity), () =>
                from s in Database.Query<ExcelAttachmentEntity>()
                select new
                {
                    Entity = s,
                    s.Id,
                    s.FileName,
                    s.UserQuery,
                    s.Related,
                });


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

                if (uqe.Title != null)
                    EmailTemplateParser.Parse(uqe.Title, ctx.QueryDescription, ctx.ModelType).FillQueryTokens(ctx.QueryTokens);
            });

            Validator.PropertyValidator((ExcelAttachmentEntity e) => e.FileName).StaticPropertyValidation = ExcelAttachmentFileName_StaticPropertyValidation;
            Validator.PropertyValidator((ExcelAttachmentEntity e) => e.Title).StaticPropertyValidation = ExcelAttachmentTitle_StaticPropertyValidation;

            EmailTemplateLogic.GenerateAttachment.Register((ExcelAttachmentEntity uqe, EmailTemplateLogic.GenerateAttachmentContext ctx) =>
            {
                var finalEntity = uqe.Related?.Retrieve() ?? (Entity)ctx.Entity;

                using (finalEntity == null ? null : CurrentEntityConverter.SetCurrentEntity(finalEntity))
                using (CultureInfoUtils.ChangeBothCultures(ctx.Culture))
                {
                    QueryRequest request = UserQueryLogic.ToQueryRequest(uqe.UserQuery.Retrieve());

                    var title = GetTemplateString(uqe.Title, ref uqe.TitleNode, ctx);
                    var fileName = GetTemplateString(uqe.FileName, ref uqe.FileNameNode, ctx);

                    var bytes = ExcelLogic.ExecutePlainExcel(request, title);

                    return new List<EmailAttachmentEntity>
                        {
                            new EmailAttachmentEntity
                            {
                                File = Files.EmbeddedFilePathLogic.SaveFile(new Entities.Files.EmbeddedFilePathEntity(EmailFileType.Attachment, fileName, bytes)),
                                Type = EmailAttachmentType.Attachment,
                            }
                        };
                }
            });
        }
Ejemplo n.º 25
0
        public static void Start(SchemaBuilder sb)
        {
            if (sb.NotDefined(MethodInfo.GetCurrentMethod()))
            {
                sb.Include<PropertyRouteEntity>()
                    .WithUniqueIndex(p => new { p.Path, p.RootType }); 

                sb.Schema.Synchronizing += SynchronizeProperties;

                Properties = sb.GlobalLazy(() => Database.Query<PropertyRouteEntity>().AgGroupToDictionary(a => a.RootType, gr => gr.ToDictionary(a => a.Path)),
                    new InvalidateWith(typeof(PropertyRouteEntity)), Schema.Current.InvalidateMetadata);
            }
        }
Ejemplo n.º 26
0
        public override void Up()
        {
            var builder = new SchemaBuilder(Schema);

            builder.AddTable("Usuario",
                    Columns.PrimaryKey<int>("Id"),
                    Columns.Simple<string>("Nome", 100),
                    Columns.Simple<string>("Login", 20),
                    Columns.Simple<string>("Senha", 50),
                    Columns.Simple<int>("IsAtivo"),
                    Columns.Simple<int>("Perfil")
                );
        }
Ejemplo n.º 27
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.º 28
0
 /// <summary>
 /// the IFC File Header
 /// </summary>
 public IFCFileHeader()
 {
     if (m_schema == null)
     {
         m_schema = Schema.Lookup(s_schemaId);
     }
     if (m_schema == null)
     {
         SchemaBuilder fileHeaderBuilder = new SchemaBuilder(s_schemaId);
         fileHeaderBuilder.SetSchemaName("IFCFileHeader");
         fileHeaderBuilder.AddMapField(s_FileHeaderMapField, typeof(String), typeof(String));
         m_schema = fileHeaderBuilder.Finish();
     }
 }
Ejemplo n.º 29
0
 /// <summary>
 /// IFC address initialization
 /// </summary>
 public IFCAddress()
 {
     if (m_schema == null)
     {
         m_schema = Schema.Lookup(s_schemaId);
     }
     if (m_schema == null)
     {
         SchemaBuilder addressBuilder = new SchemaBuilder(s_schemaId);
         addressBuilder.SetSchemaName("IFCAddress");
         addressBuilder.AddMapField(s_addressMapField, typeof(String), typeof(String));
         m_schema = addressBuilder.Finish();
     }
 }
Ejemplo n.º 30
0
        public static void Start(SchemaBuilder sb, DynamicQueryManager dqm)
        {
            if (sb.NotDefined(MethodInfo.GetCurrentMethod()))
            {
                QueryLogic.Start(sb);

                PermissionAuthLogic.RegisterPermissions(UserQueryPermission.ViewUserQuery);

                UserAssetsImporter.RegisterName<UserQueryEntity>("UserQuery");

                sb.Schema.Synchronizing += Schema_Synchronizing;

                sb.Include<UserQueryEntity>();

                dqm.RegisterQuery(typeof(UserQueryEntity), () =>
                    from uq in Database.Query<UserQueryEntity>()
                    select new
                    {
                        Entity = uq,
                        uq.Query,
                        uq.Id,
                        uq.DisplayName,
                        uq.EntityType,
                    });

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

                new Graph<UserQueryEntity>.Execute(UserQueryOperation.Save)
                {
                    AllowsNew = true,
                    Lite = false,
                    Execute = (uq, _) => { }
                }.Register();

                new Graph<UserQueryEntity>.Delete(UserQueryOperation.Delete)
                {
                    Lite = true,
                    Delete = (uq, _) => uq.Delete()
                }.Register();

                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).GroupToDictionary(a => a.Query.ToQueryName(), a => a.ToLite()),
                    new InvalidateWith(typeof(UserQueryEntity)));

                UserQueriesByType = sb.GlobalLazy(() => UserQueries.Value.Values.Where(a => a.EntityType != null).GroupToDictionary(a => TypeLogic.IdToType.GetOrThrow(a.EntityType.Id), a => a.ToLite()),
                    new InvalidateWith(typeof(UserQueryEntity)));
            }
        }
Ejemplo n.º 31
0
 public int UpdateFrom1()
 {
     SchemaBuilder.AlterTable("GoogleAnalyticsSettingsPartRecord",
                              table => table.AddColumn <bool>("AnonymizeIp"));
     return(2);
 }
        public void FailsWhereWrongParameterType()
        {
            var ex = Assert.Throws <EntityGraphQLCompilerException>(() => EqlCompiler.Compile("people.where(name)", SchemaBuilder.FromObject <TestSchema>(), null, new DefaultMethodProvider(), null));

            Assert.Equal("Method 'where' expects parameter that evaluates to a 'System.Boolean' result but found result type 'System.String'", ex.Message);
        }
            public void Run(RegressionEnvironment env)
            {
                string epl = eventRepresentationEnum.GetAnnotationTextWJsonProvided<MyLocalJsonProvidedStartValueEvent>() +
                             " create schema StartValueEvent as (dummy string);\n";
                epl += eventRepresentationEnum.GetAnnotationTextWJsonProvided<MyLocalJsonProvidedTestForwardEvent>() +
                       " create schema TestForwardEvent as (prop1 string);\n";
                epl += eventRepresentationEnum.GetAnnotationTextWJsonProvided<MyLocalJsonProvidedTestInputEvent>() +
                       " create schema TestInputEvent as (dummy string);\n";
                epl += "insert into TestForwardEvent select'V1' as prop1 from TestInputEvent;\n";
                epl += eventRepresentationEnum.GetAnnotationTextWJsonProvided<MyLocalJsonProvidedNamedWin>() +
                       " create window NamedWin#unique(prop1) (prop1 string, prop2 string);\n";
                epl += "insert into NamedWin select 'V1' as prop1, 'O1' as prop2 from StartValueEvent;\n";
                epl += "on TestForwardEvent update NamedWin as work set prop2 = 'U1' where work.prop1 = 'V1';\n";
                epl += "@Name('select') select irstream prop1, prop2 from NamedWin;\n";
                env.CompileDeployWBusPublicType(epl, new RegressionPath()).AddListener("select");

                var fields = new[] {"prop1", "prop2"};
                if (eventRepresentationEnum.IsObjectArrayEvent()) {
                    env.SendEventObjectArray(new object[] {"dummyValue"}, "StartValueEvent");
                }
                else if (eventRepresentationEnum.IsMapEvent()) {
                    env.SendEventMap(new Dictionary<string, object>(), "StartValueEvent");
                }
                else if (eventRepresentationEnum.IsAvroEvent()) {
                    env.EventService.SendEventAvro(
                        new GenericRecord(
                            SchemaBuilder.Record("soemthing")),
                        "StartValueEvent");
                }
                else if (eventRepresentationEnum.IsJsonEvent() || eventRepresentationEnum.IsJsonProvidedClassEvent()) {
                    env.EventService.SendEventJson("{}", "StartValueEvent");
                }
                else {
                    Assert.Fail();
                }

                EPAssertionUtil.AssertProps(
                    env.Listener("select").AssertOneGetNewAndReset(),
                    fields,
                    new object[] {"V1", "O1"});

                if (eventRepresentationEnum.IsObjectArrayEvent()) {
                    env.SendEventObjectArray(new object[] {"dummyValue"}, "TestInputEvent");
                }
                else if (eventRepresentationEnum.IsMapEvent()) {
                    env.SendEventMap(new Dictionary<string, object>(), "TestInputEvent");
                }
                else if (eventRepresentationEnum.IsAvroEvent()) {
                    env.EventService.SendEventAvro(
                        new GenericRecord(
                            SchemaBuilder.Record("soemthing")),
                        "TestInputEvent");
                }
                else if (eventRepresentationEnum.IsJsonEvent() || eventRepresentationEnum.IsJsonProvidedClassEvent()) {
                    env.EventService.SendEventJson("{}", "TestInputEvent");
                }
                else {
                    Assert.Fail();
                }

                EPAssertionUtil.AssertProps(
                    env.Listener("select").LastOldData[0],
                    fields,
                    new object[] {"V1", "O1"});
                EPAssertionUtil.AssertProps(
                    env.Listener("select").GetAndResetLastNewData()[0],
                    fields,
                    new object[] {"V1", "U1"});
                env.UndeployAll();
            }
Ejemplo n.º 34
0
        private static void MergeComplexType(ISchema right, SchemaBuilder builder, ComplexType rightType)
        {
            if (builder.TryGetType <ComplexType>(rightType.Name, out var leftType))
            {
                var rightTypeFields = right.GetFields(rightType.Name);

                foreach (var rightTypeField in rightTypeFields)
                {
                    builder.Connections(connect =>
                    {
                        if (connect.TryGetField(leftType, rightTypeField.Key, out _))
                        {
                            return;
                        }

                        connect.Include(leftType, new[] { rightTypeField });

                        var resolver = right.GetResolver(rightType.Name, rightTypeField.Key);

                        if (resolver != null)
                        {
                            connect.GetOrAddResolver(leftType, rightTypeField.Key)
                            .Run(resolver);
                        }

                        var subscriber = right.GetSubscriber(rightType.Name, rightTypeField.Key);

                        if (subscriber != null)
                        {
                            connect.GetOrAddSubscriber(leftType, rightTypeField.Key)
                            .Run(subscriber);
                        }
                    });
                }
            }
            else
            {
                builder
                .Include(rightType)
                .Connections(connect =>
                {
                    var fields = right.GetFields(rightType.Name).ToList();
                    connect.Include(rightType, fields);

                    foreach (var rightTypeField in fields)
                    {
                        var resolver = right.GetResolver(rightType.Name, rightTypeField.Key);

                        if (resolver != null)
                        {
                            connect.GetOrAddResolver(rightType, rightTypeField.Key)
                            .Run(resolver);
                        }

                        var subscriber = right.GetSubscriber(rightType.Name, rightTypeField.Key);

                        if (subscriber != null)
                        {
                            connect.GetOrAddSubscriber(rightType, rightTypeField.Key)
                            .Run(subscriber);
                        }
                    }
                });
            }
        }
Ejemplo n.º 35
0
 public ServiceCollectionExtensionGenerator(SchemaBuilder schema, string schemaName)
 {
     _schema     = schema;
     _schemaName = schemaName;
 }
Ejemplo n.º 36
0
        protected override void ProcessRecord()
        {
            base.ProcessRecord();

            WriteObject($"{Ansi.Color.Foreground.LightCyan}** GENERATE model **{Ansi.Color.Foreground.Default}");
            if (!Model.Exists)
            {
                WriteObject($"{Ansi.Color.Foreground.LightRed}Model file {Model?.FullName} not found.{Ansi.Color.Foreground.Default}");
                return;
            }
            WriteObject($"Loading model: {Model.FullName}");

            string modelBim = File.ReadAllText(Model.FullName);

            TabModel.Database database = TabModel.JsonSerializer.DeserializeDatabase(modelBim);

            // Create the schema
            if (!SchemaBuilder.CheckModel(
                    database.Model,
                    out List <TabModel.Table> unsupportedTables,
                    out List <TabModel.Measure> unsupportedMeasures,
                    out List <TabModel.Relationship> unsupportedRelationships))
            {
                if (unsupportedMeasures.Count > 0)
                {
                    WriteObject($"{Ansi.Color.Foreground.LightYellow}Removing {unsupportedMeasures.Count} unsupported measures.{Ansi.Color.Foreground.Default}");
                    foreach (TabModel.Measure m in unsupportedMeasures)
                    {
                        WriteObject($"  {Ansi.Color.Foreground.Yellow}{m.Name}{Ansi.Color.Foreground.Default}");
                        m.Table.Measures.Remove(m);
                    }
                }

                if (unsupportedRelationships.Count > 0)
                {
                    WriteObject($"{Ansi.Color.Foreground.LightYellow}Removing {unsupportedRelationships.Count} unsupported relationships.{Ansi.Color.Foreground.Default}");
                    foreach (TabModel.Relationship r in unsupportedRelationships)
                    {
                        string relationshipDescription = (r is TabModel.SingleColumnRelationship sr)
                                ? $"*** SKIP *** '{sr.FromTable.Name}'[{sr.FromColumn.Name}]{sr.CardinalityText()}'{sr.ToTable.Name}'[{sr.ToColumn.Name}] ({sr.CrossFilteringBehavior})"
                                : $"*** SKIP *** '{r.FromTable.Name}'-->'{r.ToTable.Name}' ({r.CrossFilteringBehavior})";
                        WriteObject($"  {Ansi.Color.Foreground.Yellow}{relationshipDescription}{Ansi.Color.Foreground.Default}");
                        database.Model.Relationships.Remove(r);
                    }
                }

                if (unsupportedTables.Count > 0)
                {
                    WriteObject($"{Ansi.Color.Foreground.LightYellow}Removing {unsupportedTables.Count} unsupported tables.{Ansi.Color.Foreground.Default}");
                    foreach (TabModel.Table t in unsupportedTables)
                    {
                        WriteObject($"  {Ansi.Color.Foreground.Yellow}{t.Name}{Ansi.Color.Foreground.Default}");
                        database.Model.Tables.Remove(t);
                    }
                }

                WriteObject($"{Ansi.Color.Foreground.LightCyan}Prepared model compatible with Push Dataset.{Ansi.Color.Foreground.Default}");
            }
            else
            {
                WriteObject($"{Ansi.Color.Foreground.LightGreen}Copying model compatible with Push Dataset.{Ansi.Color.Foreground.Default}");
            }

            string modelCompatibleBim = TabModel.JsonSerializer.SerializeDatabase(database);

            WriteObject($"Saving model: {Out.FullName}");
            File.WriteAllText(Out.FullName, modelCompatibleBim);
        }
Ejemplo n.º 37
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;
            }
        }
Ejemplo n.º 38
0
        public static void Start(SchemaBuilder sb)
        {
            if (sb.NotDefined(MethodInfo.GetCurrentMethod()))
            {
                sb.Include <ProcessAlgorithmSymbol>()
                .WithQuery(() => pa => new
                {
                    Entity = pa,
                    pa.Id,
                    pa.Key
                });

                sb.Include <ProcessEntity>()
                .WithQuery(() => 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(() => p => new
                {
                    Entity = p,
                    p.Process,
                    p.Line,
                    p.ElementInfo,
                    p.Exception,
                });

                PermissionAuthLogic.RegisterPermissions(ProcessPermission.ViewProcessPanel);

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

                OperationLogic.AssertStarted(sb);

                ProcessGraph.Register();

                QueryLogic.Expressions.Register((ProcessAlgorithmSymbol p) => p.Processes(), () => typeof(ProcessEntity).NicePluralName());
                QueryLogic.Expressions.Register((ProcessAlgorithmSymbol p) => p.LastProcess(), () => ProcessMessage.LastProcess.NiceToString());

                QueryLogic.Expressions.Register((IProcessDataEntity p) => p.Processes(), () => typeof(ProcessEntity).NicePluralName());
                QueryLogic.Expressions.Register((IProcessDataEntity p) => p.LastProcess(), () => ProcessMessage.LastProcess.NiceToString());

                QueryLogic.Expressions.Register((ProcessEntity p) => p.ExceptionLines(), () => ProcessMessage.ExceptionLines.NiceToString());
                QueryLogic.Expressions.Register((IProcessLineDataEntity p) => p.ExceptionLines(), () => ProcessMessage.ExceptionLines.NiceToString());

                PropertyAuthLogic.SetMaxAutomaticUpgrade(PropertyRoute.Construct((ProcessEntity p) => p.User), PropertyAllowed.Read);

                ExceptionLogic.DeleteLogs += ExceptionLogic_DeleteLogs;
            }
        }
Ejemplo n.º 39
0
 private string GetFullTableName(AuditEvent auditEvent)
 {
     return(SchemaBuilder != null
         ? string.Format("[{0}].[{1}]", SchemaBuilder.Invoke(auditEvent), TableNameBuilder.Invoke(auditEvent))
         : string.Format("[{0}]", TableNameBuilder.Invoke(auditEvent)));
 }
Ejemplo n.º 40
0
 public static void AssertStarted(SchemaBuilder sb)
 {
     sb.AssertDefined(ReflectionTools.GetMethodInfo(() => ProcessLogic.Start(null !)));
 }
Ejemplo n.º 41
0
        private void RunAssertionVariantStream(EventRepresentationChoice eventRepresentationEnum)
        {
            _epService.EPAdministrator.Configuration.AddEventType(
                "SupportBean", typeof(SupportBean));

            _epService.EPAdministrator.CreateEPL(
                eventRepresentationEnum.GetAnnotationText()
                + " create schema EventOne as (key string)");
            _epService.EPAdministrator.CreateEPL(
                eventRepresentationEnum.GetAnnotationText()
                + " create schema EventTwo as (key string)");
            _epService.EPAdministrator.CreateEPL(
                eventRepresentationEnum.GetAnnotationText()
                + " create schema S0 as "
                + typeof(SupportBean_S0).FullName);
            _epService.EPAdministrator.CreateEPL(
                eventRepresentationEnum.GetAnnotationText()
                + " create variant schema VarSchema as *");

            _epService.EPAdministrator.CreateEPL(
                "insert into VarSchema select * from EventOne");
            _epService.EPAdministrator.CreateEPL(
                "insert into VarSchema select * from EventTwo");
            _epService.EPAdministrator.CreateEPL(
                "insert into VarSchema select * from S0");
            _epService.EPAdministrator.CreateEPL(
                "insert into VarSchema select * from SupportBean");

            String      stmtText = "select Typeof(A) as t0 from VarSchema as A";
            EPStatement stmt     = _epService.EPAdministrator.CreateEPL(stmtText);

            stmt.Events += _listener.Update;

            if (eventRepresentationEnum.IsObjectArrayEvent())
            {
                _epService.EPRuntime.SendEvent(new Object[] { "value" }, "EventOne");
            }
            else if (eventRepresentationEnum.IsMapEvent())
            {
                _epService.EPRuntime.SendEvent(
                    Collections.SingletonMap <string, object>("key", "value"), "EventOne");
            }
            else if (eventRepresentationEnum.IsAvroEvent())
            {
                var record = new GenericRecord(SchemaBuilder.Record("EventOne", TypeBuilder.RequiredString("key")));
                record.Put("key", "value");
                _epService.EPRuntime.SendEventAvro(record, "EventOne");
            }
            else
            {
                Assert.Fail();
            }
            Assert.AreEqual("EventOne", _listener.AssertOneGetNewAndReset().Get("t0"));

            if (eventRepresentationEnum.IsObjectArrayEvent())
            {
                _epService.EPRuntime.SendEvent(new Object[] { "value" }, "EventTwo");
            }
            else if (eventRepresentationEnum.IsMapEvent())
            {
                _epService.EPRuntime.SendEvent(
                    Collections.SingletonMap <string, object>("key", "value"), "EventTwo");
            }
            else if (eventRepresentationEnum.IsAvroEvent())
            {
                var record = new GenericRecord(SchemaBuilder.Record("EventTwo", TypeBuilder.RequiredString("key")));
                record.Put("key", "value");
                _epService.EPRuntime.SendEventAvro(record, "EventTwo");
            }
            else
            {
                Assert.Fail();
            }
            Assert.AreEqual("EventTwo", _listener.AssertOneGetNewAndReset().Get("t0"));

            _epService.EPRuntime.SendEvent(new SupportBean_S0(1));
            Assert.AreEqual("S0", _listener.AssertOneGetNewAndReset().Get("t0"));

            _epService.EPRuntime.SendEvent(new SupportBean());
            Assert.AreEqual("SupportBean", _listener.AssertOneGetNewAndReset().Get("t0"));

            stmt.Dispose();
            _listener.Reset();
            stmt = _epService.EPAdministrator.CreateEPL(
                "select * from VarSchema Match_recognize(\n"
                + "  measures A as a, B as b\n" + "  pattern (A B)\n"
                + "  define A as Typeof(A) = \"EventOne\",\n"
                + "         B as Typeof(B) = \"EventTwo\"\n" + "  )");
            stmt.Events += _listener.Update;

            if (eventRepresentationEnum.IsObjectArrayEvent())
            {
                _epService.EPRuntime.SendEvent(new Object[] { "value" }, "EventOne");
                _epService.EPRuntime.SendEvent(new Object[] { "value" }, "EventTwo");
            }
            else if (eventRepresentationEnum.IsMapEvent())
            {
                _epService.EPRuntime.SendEvent(
                    Collections.SingletonMap <string, object>("key", "value"), "EventOne");
                _epService.EPRuntime.SendEvent(
                    Collections.SingletonMap <string, object>("key", "value"), "EventTwo");
            }
            else if (eventRepresentationEnum.IsAvroEvent())
            {
                var schema   = SchemaBuilder.Record("EventTwo", TypeBuilder.RequiredString("key"));
                var eventOne = new GenericRecord(schema);
                eventOne.Put("key", "value");
                var eventTwo = new GenericRecord(schema);
                eventTwo.Put("key", "value");
                _epService.EPRuntime.SendEventAvro(eventOne, "EventOne");
                _epService.EPRuntime.SendEventAvro(eventTwo, "EventTwo");
            }
            else
            {
                Assert.Fail();
            }
            Assert.IsTrue(_listener.GetAndClearIsInvoked());

            _listener.Reset();
            _epService.Initialize();
        }
Ejemplo n.º 42
0
        protected IRequestExecutor CreateSchema <TEntity, T>(
            TEntity[] entities,
            FilterConvention?convention           = null,
            bool withPaging                       = false,
            Action <ISchemaBuilder>?configure     = null,
            Action <ModelBuilder>?onModelCreating = null)
            where TEntity : class
            where T : FilterInputType <TEntity>
        {
            convention ??= new FilterConvention(x => x.AddDefaults().BindRuntimeType <TEntity, T>());

            Func <IResolverContext, IEnumerable <TEntity> >?resolver =
                BuildResolver(onModelCreating, entities);

            ISchemaBuilder builder = SchemaBuilder.New()
                                     .AddConvention <IFilterConvention>(convention)
                                     .AddFiltering()
                                     .AddQueryType(
                c =>
            {
                ApplyConfigurationToField <TEntity, T>(
                    c.Name("Query").Field("root").Resolver(resolver),
                    withPaging);

                ApplyConfigurationToField <TEntity, T>(
                    c.Name("Query")
                    .Field("rootExecutable")
                    .Resolver(
                        ctx => resolver(ctx).AsExecutable()),
                    withPaging);
            });

            configure?.Invoke(builder);

            ISchema schema = builder.Create();

            return(new ServiceCollection()
                   .Configure <RequestExecutorSetup>(
                       Schema.DefaultName,
                       o => o.Schema = schema)
                   .AddGraphQL()
                   .UseRequest(
                       next => async context =>
            {
                await next(context);
                if (context.Result is IReadOnlyQueryResult result &&
                    context.ContextData.TryGetValue("sql", out var queryString))
                {
                    context.Result =
                        QueryResultBuilder
                        .FromResult(result)
                        .SetContextData("sql", queryString)
                        .Create();
                }
            })
                   .UseDefaultPipeline()
                   .Services
                   .BuildServiceProvider()
                   .GetRequiredService <IRequestExecutorResolver>()
                   .GetRequestExecutorAsync()
                   .Result);
        }
Ejemplo n.º 43
0
 private static Schema BuildSchema(IEnumerable <Type> types, ITypeMapper typeMapper)
 {
     return(SchemaBuilder.BuildSchema(types, typeMapper));
 }
Ejemplo n.º 44
0
        // This method gets called by the runtime.
        // Use this method to add services to the container.
        // For more information on how to configure your application,
        // visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors();

            // configure jwt authentication
            services
            .AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(options =>
            {
                options.RequireHttpsMetadata      = false;
                options.SaveToken                 = true;
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey         = new SymmetricSecurityKey(SharedSecret),
                    ValidateIssuer           = false,
                    ValidateAudience         = false
                };
                options.Events = new JwtBearerEvents
                {
                    OnMessageReceived = context =>
                    {
                        if (context.HttpContext.Request.Query.ContainsKey("token"))
                        {
                            context.Token = context.HttpContext.Request.Query["token"];
                        }
                        return(Task.CompletedTask);
                    }
                };
            });

            var databaseUrl = Configuration["DATABASE_URL"];
            var databaseUri = new Uri(databaseUrl);
            var userInfo    = databaseUri.UserInfo.Split(':');

            var builder = new NpgsqlConnectionStringBuilder
            {
                Host     = databaseUri.Host,
                Port     = databaseUri.Port,
                Username = userInfo[0],
                Password = userInfo[1],
                Database = databaseUri.LocalPath.TrimStart('/'),
                SslMode  = SslMode.Prefer,
                TrustServerCertificate = true
            };

            var redisConfigurationOptions = new ConfigurationOptions
            {
                AllowAdmin = false,
                Ssl        = false,
                Password   = "******",
                EndPoints  =
                {
                    { "ec2-3-86-75-248.compute-1.amazonaws.com", 20849 }
                }
            };

            var conn = ConnectionMultiplexer.Connect(redisConfigurationOptions);

            // Adds GraphQL Schema
            services
            .AddEntityFrameworkNpgsql()
            .AddDbContext <SlackCloneDbContext>((sp, opt) =>
                                                opt.UseNpgsql(builder.ToString())
                                                .UseInternalServiceProvider(sp))
            //.AddInMemorySubscriptions()
            .AddRedisSubscriptions(conn)
            .AddGraphQL(sp =>
                        SchemaBuilder.New()
                        .AddServices(sp)
                        .AddQueryType(d => d.Name("Query"))
                        .AddType <UserQueries>()
                        .AddType <ChannelQueries>()
                        .AddMutationType(d => d.Name("Mutation"))
                        .AddType <UserMutations>()
                        .AddType <ChannelMutations>()
                        .AddSubscriptionType(d => d.Name("Subscription"))
                        .AddType <UserSubscriptions>()
                        .AddType <ChannelSubscriptions>()
                        .AddAuthorizeDirectiveType()
                        .Create());

            services.AddQueryRequestInterceptor((context, builder, ct) =>
            {
                if (context.User.Identity.IsAuthenticated)
                {
                    builder.AddProperty(
                        "currentUserEmail",
                        context.User.FindFirst(ClaimTypes.Email).Value);
                }
                return(Task.CompletedTask);
            });
        }
Ejemplo n.º 45
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>()
                .WithConstruct(WorkflowOperation.Create)
                .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.º 46
0
 public int UpdateFrom4()
 {
     SchemaBuilder.AlterTable("GoogleAnalyticsSettingsPartRecord",
                              table => table.AddColumn <bool>("UseGA4", c => c.NotNull().WithDefault(false)));
     return(5);
 }
Ejemplo n.º 47
0
        public static void Start(SchemaBuilder sb)
        {
            if (sb.NotDefined(MethodInfo.GetCurrentMethod()))
            {
                sb.Include <ProductEntity>()
                .WithSave(ProductOperation.Save)
                .WithQuery(() => p => new
                {
                    Entity = p,
                    p.Id,
                    p.ProductName,
                    p.Supplier,
                    p.Category,
                    p.QuantityPerUnit,
                    p.UnitPrice,
                    p.UnitsInStock,
                    p.Discontinued
                });

                sb.AddUniqueIndexMList((ProductEntity pe) => pe.AdditionalInformation, mle => new { mle.Parent, mle.Element.Key });
                QueryLogic.Expressions.RegisterDictionary((ProductEntity p) => p.AdditionalInformation, ai => ai.Key, ai => ai.Value);

                ActiveProducts = sb.GlobalLazy(() =>
                                               Database.Query <ProductEntity>()
                                               .Where(a => !a.Discontinued)
                                               .Select(p => new { Category = p.Category.Entity, Product = p })
                                               .GroupToDictionary(a => a.Category !, a => a.Product !), /*CSBUG*/
                                               new InvalidateWith(typeof(ProductEntity)));

                QueryLogic.Queries.Register(ProductQuery.CurrentProducts, () =>
                                            from p in Database.Query <ProductEntity>()
                                            where !p.Discontinued
                                            select new
                {
                    Entity = p,
                    p.Id,
                    p.ProductName,
                    p.Supplier,
                    p.Category,
                    p.QuantityPerUnit,
                    p.UnitPrice,
                    p.UnitsInStock,
                });

                sb.Include <SupplierEntity>()
                .WithSave(SupplierOperation.Save)
                .WithQuery(() => s => new
                {
                    Entity = s,
                    s.Id,
                    s.CompanyName,
                    s.ContactName,
                    s.Phone,
                    s.Fax,
                    s.HomePage,
                    s.Address
                });

                sb.Include <CategoryEntity>()
                .WithSave(CategoryOperation.Save)
                .WithQuery(() => s => new
                {
                    Entity = s,
                    s.Id,
                    s.CategoryName,
                    s.Description,
                    s.Picture
                });
            }
        }
Ejemplo n.º 48
0
    public static void Start(SchemaBuilder sb, bool packages, bool packageOperations)
    {
        if (sb.NotDefined(MethodInfo.GetCurrentMethod()))
        {
            ProcessLogic.AssertStarted(sb);

            sb.Settings.AssertImplementedBy((ProcessExceptionLineEntity pel) => pel.Line, typeof(PackageLineEntity));

            sb.Include <PackageLineEntity>()
            .WithQuery(() => pl => new
            {
                Entity = pl,
                pl.Package,
                pl.Id,
                pl.Target,
                pl.Result,
                pl.FinishTime,
            });

            QueryLogic.Queries.Register(PackageQuery.PackageLineLastProcess, () =>
                                        from pl in Database.Query <PackageLineEntity>()
                                        let p = pl.Package.Entity.LastProcess()
                                                select new
            {
                Entity = pl,
                pl.Package,
                pl.Id,
                pl.Target,
                pl.Result,
                pl.FinishTime,
                LastProcess = p,
                Exception   = pl.Exception(p),
            });


            QueryLogic.Expressions.Register((PackageEntity p) => p.Lines(), ProcessMessage.Lines);

            if (packages)
            {
                sb.Settings.AssertImplementedBy((PackageLineEntity pl) => pl.Package, typeof(PackageEntity));
                sb.Settings.AssertImplementedBy((ProcessEntity pe) => pe.Data, typeof(PackageEntity));

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

                QueryLogic.Queries.Register(PackageQuery.PackageLastProcess, () =>
                                            from pk in Database.Query <PackageEntity>()
                                            let pe = pk.LastProcess()
                                                     select new
                {
                    Entity = pk,
                    pk.Id,
                    pk.Name,
                    NumLines    = pk.Lines().Count(),
                    LastProcess = pe,
                    NumErrors   = pk.Lines().Count(l => l.Exception(pe) != null),
                });

                ExceptionLogic.DeleteLogs += ExceptionLogic_DeletePackages <PackageEntity>;
            }

            if (packageOperations)
            {
                sb.Settings.AssertImplementedBy((PackageLineEntity pl) => pl.Package, typeof(PackageOperationEntity));
                sb.Settings.AssertImplementedBy((ProcessEntity pe) => pe.Data, typeof(PackageOperationEntity));

                sb.Include <PackageOperationEntity>()
                .WithQuery(() => pk => new
                {
                    Entity = pk,
                    pk.Id,
                    pk.Name,
                    pk.Operation,
                });

                QueryLogic.Queries.Register(PackageQuery.PackageOperationLastProcess, () =>
                                            from p in Database.Query <PackageOperationEntity>()
                                            let pe = p.LastProcess()
                                                     select new
                {
                    Entity = p,
                    p.Id,
                    p.Name,
                    p.Operation,
                    NumLines    = p.Lines().Count(),
                    LastProcess = pe,
                    NumErrors   = p.Lines().Count(l => l.Exception(pe) != null),
                });

                ProcessLogic.Register(PackageOperationProcess.PackageOperation, new PackageOperationAlgorithm());
                ExceptionLogic.DeleteLogs += ExceptionLogic_DeletePackages <PackageOperationEntity>;
            }
        }
    }
Ejemplo n.º 49
0
 public int UpdateFrom5()
 {
     SchemaBuilder.AlterTable("GoogleAnalyticsSettingsPartRecord",
                              table => table.AddColumn <string>("CookieLevel"));
     return(6);
 }
        /// <summary>
        /// This executes whenever this module is activated.
        /// </summary>
        public int Create()
        {
            // Creating table ActivityPartRecord
            SchemaBuilder.CreateTable("ActivityPartRecord", table => table
                                      .ContentPartRecord()
                                      .Column <DateTime>("DateTimeStart")
                                      .Column <DateTime>("DateTimeEnd")
                                      .Column <bool>("AllDay")
                                      .Column <bool>("Repeat")
                                      .Column <string>("RepeatType", column => column.WithLength(1))
                                      .Column <int>("RepeatValue")
                                      .Column <string>("RepeatDetails")
                                      .Column <bool>("RepeatEnd")
                                      .Column <DateTime>("RepeatEndDate")
                                      );

            //Creating the ActivityPart
            ContentDefinitionManager.AlterPartDefinition(
                typeof(ActivityPart).Name,
                part => part
                .Attachable()
                .WithDescription("Used by the Event content type. Contains the data telling when an event must be displayed.")
                );

            //Creating the fields for the content type Event
            ContentDefinitionManager.AlterPartDefinition(
                "CalendarEvent",
                part => part
                .WithField("Gallery",
                           field => field
                           .OfType("MediaLibraryPickerField")
                           .WithDisplayName("Gallery"))
                .WithField("Relatedevents",
                           field => field
                           .OfType("ContentPickerField")
                           .WithDisplayName("Related events"))
                );

            //Creating the content type Event
            ContentDefinitionManager.AlterTypeDefinition(
                "CalendarEvent",
                type => type
                .WithPart("TitlePart")
                .WithPart("AutoroutePart")
                .WithPart("CommonPart")
                .WithPart("BodyPart")
                .WithPart("CalendarEvent")
                .WithPart("LocalizationPart")
                .WithPart("ActivityPart")
                .Creatable()
                );

            //Creating the table CalendarPartRecord
            SchemaBuilder.CreateTable("CalendarPartRecord", table => table
                                      .ContentPartRecord()
                                      .Column <int>("QueryPartRecord_Id")
                                      .Column <int>("LayoutRecord_Id")
                                      .Column <int>("ItemsPerPage")
                                      .Column <string>("PagerSuffix", column => column.WithLength(255))
                                      .Column <bool>("DisplayPager")
                                      );

            //Creating the CalendarPart
            ContentDefinitionManager.AlterPartDefinition(
                typeof(CalendarPart).Name,
                part => part
                .Attachable()
                .WithDescription("Used by the Calendar content type. Contains the source query that retrieves the events and some information about how to display them.")
                );

            //Creating the content type Calendar
            ContentDefinitionManager.AlterTypeDefinition(
                "Calendar",
                type => type
                .WithPart("TitlePart")
                .WithPart("AutoroutePart")
                .WithPart("CommonPart")
                .WithPart("BodyPart")
                .WithPart("LocalizationPart")
                .WithPart("CalendarPart")
                .Creatable()
                );

            //Creating the Calendar widget
            ContentDefinitionManager.AlterTypeDefinition("CalendarWidget",
                                                         cfg => cfg
                                                         .WithPart("WidgetPart")
                                                         .WithPart("CommonPart")
                                                         .WithPart("IdentityPart")
                                                         .WithPart("CalendarPart")
                                                         .WithSetting("Stereotype", "Widget")
                                                         );

            return(1);
        }
        private void RunAssertionDispatchBackQueue(EPServiceProvider epService, EventRepresentationChoice eventRepresentationEnum)
        {
            epService.EPAdministrator.CreateEPL(eventRepresentationEnum.GetAnnotationText() + " create schema StartValueEvent as (dummy string)");
            epService.EPAdministrator.CreateEPL(eventRepresentationEnum.GetAnnotationText() + " create schema TestForwardEvent as (prop1 string)");
            epService.EPAdministrator.CreateEPL(eventRepresentationEnum.GetAnnotationText() + " create schema TestInputEvent as (dummy string)");
            epService.EPAdministrator.CreateEPL("insert into TestForwardEvent select'V1' as prop1 from TestInputEvent");

            epService.EPAdministrator.CreateEPL(eventRepresentationEnum.GetAnnotationText() + " create window NamedWin#unique(prop1) (prop1 string, prop2 string)");

            epService.EPAdministrator.CreateEPL("insert into NamedWin select 'V1' as prop1, 'O1' as prop2 from StartValueEvent");

            epService.EPAdministrator.CreateEPL("on TestForwardEvent update NamedWin as work set prop2 = 'U1' where work.prop1 = 'V1'");

            string[] fields    = "prop1,prop2".Split(',');
            string   eplSelect = "select irstream prop1, prop2 from NamedWin";
            var      listener  = new SupportUpdateListener();

            epService.EPAdministrator.CreateEPL(eplSelect).Events += listener.Update;

            if (eventRepresentationEnum.IsObjectArrayEvent())
            {
                epService.EPRuntime.SendEvent(new object[] { "dummyValue" }, "StartValueEvent");
            }
            else if (eventRepresentationEnum.IsMapEvent())
            {
                epService.EPRuntime.SendEvent(new Dictionary <string, object>(), "StartValueEvent");
            }
            else if (eventRepresentationEnum.IsAvroEvent())
            {
                epService.EPRuntime.SendEventAvro(new GenericRecord(
                                                      SchemaBuilder.Record("soemthing")), "StartValueEvent");
            }
            else
            {
                Assert.Fail();
            }

            EPAssertionUtil.AssertProps(listener.AssertOneGetNewAndReset(), fields, new object[] { "V1", "O1" });

            if (eventRepresentationEnum.IsObjectArrayEvent())
            {
                epService.EPRuntime.SendEvent(new object[] { "dummyValue" }, "TestInputEvent");
            }
            else if (eventRepresentationEnum.IsMapEvent())
            {
                epService.EPRuntime.SendEvent(new Dictionary <string, object>(), "TestInputEvent");
            }
            else if (eventRepresentationEnum.IsAvroEvent())
            {
                epService.EPRuntime.SendEventAvro(new GenericRecord(
                                                      SchemaBuilder.Record("soemthing")), "TestInputEvent");
            }
            else
            {
                Assert.Fail();
            }

            EPAssertionUtil.AssertProps(listener.LastOldData[0], fields, new object[] { "V1", "O1" });
            EPAssertionUtil.AssertProps(listener.GetAndResetLastNewData()[0], fields, new object[] { "V1", "U1" });
            epService.EPAdministrator.DestroyAllStatements();
            foreach (string name in "StartValueEvent,TestForwardEvent,TestInputEvent,NamedWin".Split(','))
            {
                epService.EPAdministrator.Configuration.RemoveEventType(name, true);
            }
        }
Ejemplo n.º 52
0
        private void TryAssertionSchemaCopyProperties(EPServiceProvider epService, EventRepresentationChoice eventRepresentationEnum)
        {
            epService.EPAdministrator.CreateEPL(eventRepresentationEnum.GetAnnotationText() + " create schema BaseOne (prop1 string, prop2 int)");
            epService.EPAdministrator.CreateEPL(eventRepresentationEnum.GetAnnotationText() + " create schema BaseTwo (prop3 long)");

            // test define and send
            epService.EPAdministrator.CreateEPL(eventRepresentationEnum.GetAnnotationText() + " create schema E1 () copyfrom BaseOne");
            var stmtOne  = epService.EPAdministrator.CreateEPL("select * from E1");
            var listener = new SupportUpdateListener();

            stmtOne.Events += listener.Update;
            Assert.IsTrue(eventRepresentationEnum.MatchesClass(stmtOne.EventType.UnderlyingType));
            Assert.AreEqual(typeof(string), stmtOne.EventType.GetPropertyType("prop1"));
            Assert.AreEqual(typeof(int?), stmtOne.EventType.GetPropertyType("prop2").GetBoxedType());

            if (eventRepresentationEnum.IsObjectArrayEvent())
            {
                epService.EPRuntime.SendEvent(new object[] { "v1", 2 }, "E1");
            }
            else if (eventRepresentationEnum.IsMapEvent())
            {
                IDictionary <string, object> @event = new LinkedHashMap <string, object>();
                @event.Put("prop1", "v1");
                @event.Put("prop2", 2);
                epService.EPRuntime.SendEvent(@event, "E1");
            }
            else if (eventRepresentationEnum.IsAvroEvent())
            {
                var @event = new GenericRecord(SchemaBuilder.Record("name",
                                                                    RequiredString("prop1"), RequiredInt("prop2")));
                @event.Put("prop1", "v1");
                @event.Put("prop2", 2);
                epService.EPRuntime.SendEventAvro(@event, "E1");
            }
            else
            {
                Assert.Fail();
            }
            EPAssertionUtil.AssertProps(listener.AssertOneGetNewAndReset(), "prop1,prop2".Split(','), new object[] { "v1", 2 });

            // test two copy-from types
            epService.EPAdministrator.CreateEPL(eventRepresentationEnum.GetAnnotationText() + " create schema E2 () copyfrom BaseOne, BaseTwo");
            var stmtTwo = epService.EPAdministrator.CreateEPL("select * from E2");

            Assert.AreEqual(typeof(string), stmtTwo.EventType.GetPropertyType("prop1"));
            Assert.AreEqual(typeof(int?), stmtTwo.EventType.GetPropertyType("prop2").GetBoxedType());
            Assert.AreEqual(typeof(long?), stmtTwo.EventType.GetPropertyType("prop3").GetBoxedType());

            // test API-defined type
            if (eventRepresentationEnum.IsMapEvent() ||
                eventRepresentationEnum.IsObjectArrayEvent())
            {
                var def = new Dictionary <string, object>();
                def.Put("a", "string");
                def.Put("b", typeof(string));
                def.Put("c", "BaseOne");
                def.Put("d", "BaseTwo[]");
                epService.EPAdministrator.Configuration.AddEventType("MyType", def);
            }
            else
            {
                epService.EPAdministrator.CreateEPL("create avro schema MyType(a string, b string, c BaseOne, d BaseTwo[])");
            }

            epService.EPAdministrator.CreateEPL(eventRepresentationEnum.GetAnnotationText() + " create schema E3(e long, f BaseOne) copyfrom MyType");
            var stmtThree = epService.EPAdministrator.CreateEPL("select * from E3");

            Assert.AreEqual(typeof(string), stmtThree.EventType.GetPropertyType("a"));
            Assert.AreEqual(typeof(string), stmtThree.EventType.GetPropertyType("b"));
            if (eventRepresentationEnum.IsObjectArrayEvent())
            {
                Assert.AreEqual(typeof(object[]), stmtThree.EventType.GetPropertyType("c"));
                Assert.AreEqual(typeof(object[][]), stmtThree.EventType.GetPropertyType("d"));
                Assert.AreEqual(typeof(object[]), stmtThree.EventType.GetPropertyType("f"));
            }
            else if (eventRepresentationEnum.IsMapEvent())
            {
                Assert.AreEqual(typeof(Map), stmtThree.EventType.GetPropertyType("c"));
                Assert.AreEqual(typeof(Map[]), stmtThree.EventType.GetPropertyType("d"));
                Assert.AreEqual(typeof(Map), stmtThree.EventType.GetPropertyType("f"));
            }
            else if (eventRepresentationEnum.IsAvroEvent())
            {
                Assert.AreEqual(typeof(GenericRecord), stmtThree.EventType.GetPropertyType("c"));
                Assert.AreEqual(typeof(GenericRecord[]), stmtThree.EventType.GetPropertyType("d"));
                Assert.AreEqual(typeof(GenericRecord), stmtThree.EventType.GetPropertyType("f"));
            }
            else
            {
                Assert.Fail();
            }
            Assert.AreEqual(typeof(long?), stmtThree.EventType.GetPropertyType("e").GetBoxedType());

            // invalid tests
            TryInvalid(epService, eventRepresentationEnum.GetAnnotationText() + " create schema E4(a long) copyFrom MyType",
                       "Error starting statement: Type by name 'MyType' contributes property 'a' defined as 'System.String' which overides the same property of type '" + Name.Clean <long>(false) + "' [");
            TryInvalid(epService, eventRepresentationEnum.GetAnnotationText() + " create schema E4(c BaseTwo) copyFrom MyType",
                       "Error starting statement: Property by name 'c' is defined twice by adding type 'MyType' [");
            TryInvalid(epService, eventRepresentationEnum.GetAnnotationText() + " create schema E4(c BaseTwo) copyFrom XYZ",
                       "Error starting statement: Type by name 'XYZ' could not be located [");
            TryInvalid(epService, eventRepresentationEnum.GetAnnotationText() + " create schema E4 as " + typeof(SupportBean).FullName + " copyFrom XYZ",
                       "Error starting statement: Copy-from types are not allowed with class-provided types [");
            TryInvalid(epService, eventRepresentationEnum.GetAnnotationText() + " create variant schema E4(c BaseTwo) copyFrom XYZ",
                       "Error starting statement: Copy-from types are not allowed with variant types [");

            // test SODA
            var createEPL = eventRepresentationEnum.GetAnnotationText() + " create schema EX as () copyFrom BaseOne, BaseTwo";
            var model     = epService.EPAdministrator.CompileEPL(createEPL);

            Assert.AreEqual(createEPL.Trim(), model.ToEPL());
            var stmt = epService.EPAdministrator.Create(model);

            Assert.AreEqual(createEPL.Trim(), stmt.Text);

            epService.EPAdministrator.DestroyAllStatements();
            foreach (var name in "BaseOne,BaseTwo,E1,E2,E3,MyType".Split(','))
            {
                epService.EPAdministrator.Configuration.RemoveEventType(name, true);
            }
        }
Ejemplo n.º 53
0
        public SubscriptionsFacts()
        {
            // schema
            var builder = new SchemaBuilder();

            builder.Object("Message", out var messageType)
            .Connections(connect => connect
                         .Field(messageType, "content", ScalarType.String));

            var messageListType = new List(messageType);

            builder.Query(out var query)
            .Connections(connect => connect
                         .Field(query, "messages", messageListType));

            builder.Subscription(out var subscription)
            .Connections(connect => connect
                         .Field(subscription, "messageAdded", messageType));

            var schema = builder.Build();

            // data
            var messages = new List <Message>();

            _messagesChannel = new EventChannel <Message>();

            // resolvers
            ValueTask <IResolveResult> GetMessagesAsync(ResolverContext context)
            {
                return(ResolveSync.As(messages));
            }

            ValueTask <ISubscribeResult> OnMessageAdded(ResolverContext context, CancellationToken unsubscribe)
            {
                return(ResolveSync.Subscribe(_messagesChannel, unsubscribe));
            }

            ValueTask <IResolveResult> ResolveMessage(ResolverContext context)
            {
                return(ResolveSync.As(context.ObjectValue));
            }

            var resolvers = new ResolverMap
            {
                ["Query"] = new FieldResolverMap
                {
                    { "messages", GetMessagesAsync }
                },
                ["Subscription"] = new FieldResolverMap
                {
                    { "messageAdded", OnMessageAdded, ResolveMessage }
                },
                ["Message"] = new FieldResolverMap
                {
                    { "content", Resolve.PropertyOf <Message>(r => r.Content) }
                }
            };

            // make executable
            _executable = SchemaTools.MakeExecutableSchema(
                schema,
                resolvers,
                resolvers);
        }
Ejemplo n.º 54
0
        /// <summary>
        /// Updates the setups to save into the document.
        /// </summary>
        public void UpdateSavedConfigurations()
        {
            // delete the old schema and the DataStorage.
            if (m_schema == null)
            {
                m_schema = Schema.Lookup(s_schemaId);
            }
            if (m_schema != null)
            {
                IList <DataStorage> oldSavedConfigurations = GetSavedConfigurations(m_schema);
                if (oldSavedConfigurations.Count > 0)
                {
                    Transaction deleteTransaction = new Transaction(IFCCommandOverrideApplication.TheDocument,
                                                                    Properties.Resources.DeleteOldSetups);
                    try
                    {
                        deleteTransaction.Start();
                        List <ElementId> dataStorageToDelete = new List <ElementId>();
                        foreach (DataStorage dataStorage in oldSavedConfigurations)
                        {
                            dataStorageToDelete.Add(dataStorage.Id);
                        }
                        IFCCommandOverrideApplication.TheDocument.Delete(dataStorageToDelete);
                        deleteTransaction.Commit();
                    }
                    catch (System.Exception)
                    {
                        if (deleteTransaction.HasStarted())
                        {
                            deleteTransaction.RollBack();
                        }
                    }
                }
            }

            // update the configurations to new map schema.
            if (m_mapSchema == null)
            {
                m_mapSchema = Schema.Lookup(s_mapSchemaId);
            }

            // Are there any setups to save or resave?
            List <IFCExportConfiguration> setupsToSave = new List <IFCExportConfiguration>();

            foreach (IFCExportConfiguration configuration in m_configurations.Values)
            {
                if (configuration.IsBuiltIn)
                {
                    continue;
                }

                // Store in-session settings in the cached in-session configuration
                if (configuration.IsInSession)
                {
                    IFCExportConfiguration.SetInSession(configuration);
                    continue;
                }

                setupsToSave.Add(configuration);
            }

            // If there are no setups to save, and if the schema is not present (which means there are no
            // previously existing setups which might have been deleted) we can skip the rest of this method.
            if (setupsToSave.Count <= 0 && m_mapSchema == null)
            {
                return;
            }

            if (m_mapSchema == null)
            {
                SchemaBuilder builder = new SchemaBuilder(s_mapSchemaId);
                builder.SetSchemaName("IFCExportConfigurationMap");
                builder.AddMapField(s_configMapField, typeof(String), typeof(String));
                m_mapSchema = builder.Finish();
            }

            // Overwrite all saved configs with the new list
            Transaction transaction = new Transaction(IFCCommandOverrideApplication.TheDocument, Properties.Resources.UpdateExportSetups);

            try
            {
                transaction.Start();
                IList <DataStorage> savedConfigurations = GetSavedConfigurations(m_mapSchema);
                int savedConfigurationCount             = savedConfigurations.Count <DataStorage>();
                int savedConfigurationIndex             = 0;
                foreach (IFCExportConfiguration configuration in setupsToSave)
                {
                    DataStorage configStorage;
                    if (savedConfigurationIndex >= savedConfigurationCount)
                    {
                        configStorage = DataStorage.Create(IFCCommandOverrideApplication.TheDocument);
                    }
                    else
                    {
                        configStorage = savedConfigurations[savedConfigurationIndex];
                        savedConfigurationIndex++;
                    }

                    Entity mapEntity = new Entity(m_mapSchema);
                    IDictionary <string, string> mapData = new Dictionary <string, string>();
                    mapData.Add(s_setupName, configuration.Name);
                    mapData.Add(s_setupDescription, configuration.Description);
                    mapData.Add(s_setupVersion, configuration.IFCVersion.ToString());
                    mapData.Add(s_setupFileFormat, configuration.IFCFileType.ToString());
                    mapData.Add(s_setupSpaceBoundaries, configuration.SpaceBoundaries.ToString());
                    mapData.Add(s_setupQTO, configuration.ExportBaseQuantities.ToString());
                    mapData.Add(s_setupCurrentView, configuration.VisibleElementsOfCurrentView.ToString());
                    mapData.Add(s_splitWallsAndColumns, configuration.SplitWallsAndColumns.ToString());
                    mapData.Add(s_setupExport2D, configuration.Export2DElements.ToString());
                    mapData.Add(s_setupExportRevitProps, configuration.ExportInternalRevitPropertySets.ToString());
                    mapData.Add(s_setupExportIFCCommonProperty, configuration.ExportIFCCommonPropertySets.ToString());
                    mapData.Add(s_setupUse2DForRoomVolume, configuration.Use2DRoomBoundaryForVolume.ToString());
                    mapData.Add(s_setupUseFamilyAndTypeName, configuration.UseFamilyAndTypeNameForReference.ToString());
                    mapData.Add(s_setupExportPartsAsBuildingElements, configuration.ExportPartsAsBuildingElements.ToString());
                    mapData.Add(s_setupExportBoundingBox, configuration.ExportBoundingBox.ToString());
                    mapData.Add(s_setupExportSolidModelRep, configuration.ExportSolidModelRep.ToString());
                    mapData.Add(s_setupExportSchedulesAsPsets, configuration.ExportSchedulesAsPsets.ToString());
                    mapData.Add(s_setupExportUserDefinedPsets, configuration.ExportUserDefinedPsets.ToString());
                    mapData.Add(s_setupExportUserDefinedPsetsFileName, configuration.ExportUserDefinedPsetsFileName);
                    mapData.Add(s_setupExportLinkedFiles, configuration.ExportLinkedFiles.ToString());
                    mapData.Add(s_setupIncludeSiteElevation, configuration.IncludeSiteElevation.ToString());
                    mapData.Add(s_setupUseCoarseTessellation, configuration.UseCoarseTessellation.ToString());
                    mapData.Add(s_setupStoreIFCGUID, configuration.StoreIFCGUID.ToString());
                    mapData.Add(s_setupActivePhase, configuration.ActivePhaseId.ToString());
                    mapEntity.Set <IDictionary <string, String> >(s_configMapField, mapData);

                    configStorage.SetEntity(mapEntity);
                }

                List <ElementId> elementsToDelete = new List <ElementId>();
                for (; savedConfigurationIndex < savedConfigurationCount; savedConfigurationIndex++)
                {
                    DataStorage configStorage = savedConfigurations[savedConfigurationIndex];
                    elementsToDelete.Add(configStorage.Id);
                }
                if (elementsToDelete.Count > 0)
                {
                    IFCCommandOverrideApplication.TheDocument.Delete(elementsToDelete);
                }

                transaction.Commit();
            }
            catch (System.Exception)
            {
                if (transaction.HasStarted())
                {
                    transaction.RollBack();
                }
            }
        }
Ejemplo n.º 55
0
 public SdlReader(TypeSystemDocument document, SchemaBuilder?builder = null)
 {
     _document = document;
     _builder  = builder ?? new SchemaBuilder();
 }
Ejemplo n.º 56
0
 public override void Configure(IFunctionsHostBuilder builder)
 {
     builder.Services.AddDbContext <BloggingContext>(opt => opt.UseSqlServer(@"Server=(localdb)\mssqllocaldb;Database=Blogging;Integrated Security=True"));
     builder.Services.AddSingleton(SchemaBuilder.FromObject <BloggingContext>());
 }
        public void CompilesFirst()
        {
            var exp    = EqlCompiler.Compile(@"people.first(guid = ""6492f5fe-0869-4279-88df-7f82f8e87a67"")", SchemaBuilder.FromObject <TestSchema>(), null, new DefaultMethodProvider(), null);
            var result = exp.Execute(new TestSchema()) as Person;

            Assert.Equal(new Guid("6492f5fe-0869-4279-88df-7f82f8e87a67"), result.Guid);
        }
        public void FailsWhereNoParameter()
        {
            var ex = Assert.Throws <EntityGraphQLCompilerException>(() => EqlCompiler.Compile("people.where()", SchemaBuilder.FromObject <TestSchema>(), null, new DefaultMethodProvider(), null));

            Assert.Equal("Method 'where' expects 1 argument(s) but 0 were supplied", ex.Message);
        }
Ejemplo n.º 59
0
 public static void AssertStarted(SchemaBuilder sb)
 {
     sb.AssertDefined(ReflectionTools.GetMethodInfo(() => Start(null, null)));
 }
Ejemplo n.º 60
0
        private string SetupInternal(SetupContext context)
        {
            string executionId;

            Logger.Information("Running setup for tenant '{0}'.", _shellSettings.Name);

            // The vanilla Orchard distibution has the following features enabled.
            string[] hardcoded =
            {
                // Framework
                "Orchard.Framework",
                // Core
                "Common",           "Containers",             "Contents",       "Dashboard",     "Feeds",         "Navigation",      "Scheduling", "Settings", "Shapes", "Title",
                // Modules
                "Orchard.Pages",    "Orchard.ContentPicker",  "Orchard.Themes", "Orchard.Users", "Orchard.Roles", "Orchard.Modules",
                "PackagingServices","Orchard.Packaging",      "Gallery",        "Orchard.Recipes"
            };

            context.EnabledFeatures = hardcoded.Union(context.EnabledFeatures ?? Enumerable.Empty <string>()).Distinct().ToList();

            // Set shell state to "Initializing" so that subsequent HTTP requests are responded to with "Service Unavailable" while Orchard is setting up.
            _shellSettings.State = TenantState.Initializing;

            var shellSettings = new ShellSettings(_shellSettings);

            if (String.IsNullOrEmpty(shellSettings.DataProvider))
            {
                shellSettings.DataProvider         = context.DatabaseProvider;
                shellSettings.DataConnectionString = context.DatabaseConnectionString;
                shellSettings.DataTablePrefix      = context.DatabaseTablePrefix;
            }

            shellSettings.EncryptionAlgorithm = "AES";

            // Randomly generated key.
            shellSettings.EncryptionKey = SymmetricAlgorithm.Create(shellSettings.EncryptionAlgorithm).Key.ToHexString();
            shellSettings.HashAlgorithm = "HMACSHA256";

            // Randomly generated key.
            shellSettings.HashKey = HMAC.Create(shellSettings.HashAlgorithm).Key.ToHexString();

            var shellDescriptor = new ShellDescriptor {
                Features = context.EnabledFeatures.Select(name => new ShellFeature {
                    Name = name
                })
            };

            var shellBlueprint = _compositionStrategy.Compose(shellSettings, shellDescriptor);

            // Initialize database explicitly, and store shell descriptor.
            using (var bootstrapLifetimeScope = _shellContainerFactory.CreateContainer(shellSettings, shellBlueprint)) {
                using (var environment = bootstrapLifetimeScope.CreateWorkContextScope()) {
                    // Check if the database is already created (in case an exception occured in the second phase).
                    var schemaBuilder       = new SchemaBuilder(environment.Resolve <IDataMigrationInterpreter>());
                    var installationPresent = true;
                    try {
                        var tablePrefix = String.IsNullOrEmpty(shellSettings.DataTablePrefix) ? "" : shellSettings.DataTablePrefix + "_";
                        schemaBuilder.ExecuteSql("SELECT * FROM " + tablePrefix + "Settings_ShellDescriptorRecord");
                    }
                    catch {
                        installationPresent = false;
                    }

                    if (installationPresent)
                    {
                        throw new OrchardException(T("A previous Orchard installation was detected in this database with this table prefix."));
                    }

                    // Workaround to avoid some Transaction issue for PostgreSQL.
                    environment.Resolve <ITransactionManager>().RequireNew();

                    schemaBuilder.CreateTable("Orchard_Framework_DataMigrationRecord", table => table
                                              .Column <int>("Id", column => column.PrimaryKey().Identity())
                                              .Column <string>("DataMigrationClass")
                                              .Column <int>("Version"));

                    schemaBuilder.AlterTable("Orchard_Framework_DataMigrationRecord",
                                             table => table.AddUniqueConstraint("UC_DMR_DataMigrationClass_Version", "DataMigrationClass", "Version"));

                    var dataMigrationManager = environment.Resolve <IDataMigrationManager>();
                    dataMigrationManager.Update("Settings");

                    foreach (var feature in context.EnabledFeatures)
                    {
                        dataMigrationManager.Update(feature);
                    }

                    environment.Resolve <IShellDescriptorManager>().UpdateShellDescriptor(
                        0,
                        shellDescriptor.Features,
                        shellDescriptor.Parameters);
                }
            }

            // In effect "pump messages" see PostMessage circa 1980.
            while (_processingEngine.AreTasksPending())
            {
                _processingEngine.ExecuteNextTask();
            }

            // Creating a standalone environment.
            // in theory this environment can be used to resolve any normal components by interface, and those
            // components will exist entirely in isolation - no crossover between the safemode container currently in effect.
            using (var environment = _orchardHost.CreateStandaloneEnvironment(shellSettings)) {
                try {
                    executionId = CreateTenantData(context, environment);
                }
                catch {
                    environment.Resolve <ITransactionManager>().Cancel();
                    throw;
                }
            }

            _shellSettingsManager.SaveSettings(shellSettings);
            return(executionId);
        }