示例#1
0
        public async Task <MigrationResult> ExecuteAsync()
        {
            // Fail if cannot connect to db
            if (_connectDb.Database.TryTestConnection() == false)
            {
                return(MigrationResult.Failed("Cannot connect to database."));
            }

            if (_connectDb.Database.HasColumn("Page", "cms", "Keywords"))
            {
                return(MigrationResult.Skipped("Column [Page].[Keywords] already exists."));
            }

            // Keywords column
            await _connectDb.Database.ExecuteNonQueryAsync(
                "ALTER TABLE [cms].[Page] ADD [Keywords] nvarchar(1000) NULL"
                );

            // Summary column
            await _connectDb.Database.ExecuteNonQueryAsync(
                "ALTER TABLE [cms].[Page] ADD [Summary] nvarchar(2000) NULL"
                );


            return(MigrationResult.Success("Added Keywords & Summary columns."));
        }
示例#2
0
        public async Task <MigrationResult> ExecuteAsync()
        {
            var output = new System.Text.StringBuilder();

            // Fail if cannot connect to db
            if (_connectDb.Database.TryTestConnection() == false)
            {
                return(MigrationResult.Failed("Cannot connect to database."));
            }

            // site for each environment
            List <string> siteDomains = new List <string>(new string[] { "mcpss.Mysites.com", "localhost:60002", "cityscapetemplateqa.Mysites.com", "cityscapetemplateuat.Mysites.com" });
            List <string> siteIds     = new List <string>();
            Site          site        = new Site();

            siteIds = _connectDb.SiteDomains.Where(x => siteDomains.Any(y => y == x.DomainKey)).Select(id => id.SiteId).ToList();

            foreach (var siteId in siteIds)
            {
                site.Id = siteId;
                _sitePublisher.CreateSysMasterPageV0(site);
            }


            return(MigrationResult.Success($"System Master Page created for Mobile County"));
        }
        public async Task <MigrationResult> ExecuteAsync()
        {
            // Fail if cannot connect to db
            if (_NewsDbContext.Database.TryTestConnection() == false)
            {
                return(MigrationResult.Failed("Cannot connect to database."));
            }

            // Skip if Tenant.Key already exists
            if (_NewsDbContext.Database.HasColumn("NewsPost", "plugin", "IsActive"))
            {
                return(MigrationResult.Skipped("Column NewsPost.IsActive already exists."));
            }

            // create column initially and allow null
            await _NewsDbContext.Database.ExecuteNonQueryAsync("ALTER TABLE [plugin].[NewsPost] ADD [IsActive] BIT NULL DEFAULT (1)");

            // update the table, set all values to 0
            await _NewsDbContext.Database.ExecuteNonQueryAsync("UPDATE [plugin].[NewsPost] SET IsActive = 1");

            // add the not null constraint
            await _NewsDbContext.Database.ExecuteNonQueryAsync("ALTER TABLE [plugin].[Newspost] ALTER COLUMN IsActive bit NOT NULL");

            return(MigrationResult.Success("Added column [NewsPost].[IsActive]"));
        }
        public async Task <MigrationResult> ExecuteAsync()
        {
            if (_dbContext.Database.TableExists("DocumentListWidget", "plugin"))
            {
                return(MigrationResult.Skipped());
            }


            await _dbContext.Database.ExecuteSqlCommandAsync(@"
                    CREATE TABLE [plugin].[DocumentListWidget](
	                    [Id] [nvarchar](50) NOT NULL,
                        [SiteId] [nvarchar](50) NOT NULL,
                        [Title] [nvarchar](500) NULL,
                        CONSTRAINT [PK_DocumentListWidget] PRIMARY KEY CLUSTERED ([Id] ASC)
                    )
                ");

            await _dbContext.Database.ExecuteSqlCommandAsync(@"
                    CREATE TABLE [plugin].[DocumentListDocument](
                        [Id] [nvarchar](50) NOT NULL,
                        [WidgetId] [nvarchar](50) NOT NULL,
                        [DocumentId] [nvarchar](50) NULL,
                        [Title] [nvarchar](500) NULL,
                        [Url] [nvarchar](2048) NULL,
                        [ThumbnailUrl] [nvarchar](2048)  NULL
                        CONSTRAINT [PK_DocumentListDocument] PRIMARY KEY CLUSTERED ([Id] ASC)
                    )
                ");


            return(MigrationResult.Success());
        }
        public MigrationResult Execute(System.Reflection.Assembly generatedAssembly, string scriptFileName)
        {
            var programType = generatedAssembly.GetType(LinqPadCSharpCreator.GeneratedClass);
            var programInstance = Activator.CreateInstance(programType);
            var method = programInstance.GetType().GetMethod(LinqPadCSharpCreator.GeneratedMethod);

            // Execute Script!
            object result = method.Invoke(programInstance, null);

            int? enumerableItemCount = GetEnumerableItemCount(result);

            // Expect Null or True or IEnumerable.Count == 0 results
            bool success = result == null || Equals(result, true) || (enumerableItemCount != null && enumerableItemCount == 0);

            string[] errorMessages = null;
            if (success)
            {
                return new MigrationResult(scriptFileName, true, errorMessages, null);
            }
            else
            {
                errorMessages = new[] { "Linq Unit Test returned a failing value. Expected Null, True, or a collection of Zero items. Instead, collection count is: " + enumerableItemCount + ". Actual value: " + result.ToString() };
                var migrationResult = new MigrationResult(scriptFileName, success, errorMessages, null);
                throw new MigrationException(migrationResult);
            }
        }
示例#6
0
        public async Task <MigrationResult> ExecuteAsync()
        {
            // Fail if cannot connect to db
            if (_dbContext.Database.TryTestConnection() == false)
            {
                return(MigrationResult.Failed("Cannot connect to database."));
            }

            // Skip if MonthView already exists
            if (_dbContext.Database.HasColumn("CalendarWidgetSetting", "plugin", "MonthView"))
            {
                return(MigrationResult.Skipped("Column BlogPost.IsPrivate already exists."));
            }

            //
            await _dbContext.Database.ExecuteNonQueryAsync("ALTER TABLE [plugin].[CalendarWidgetSetting] ADD [MonthView] BIT NOT NULL DEFAULT(1)");

            await _dbContext.Database.ExecuteNonQueryAsync("ALTER TABLE [plugin].[CalendarWidgetSetting] ADD [WeekView] BIT NOT NULL DEFAULT(1)");

            await _dbContext.Database.ExecuteNonQueryAsync("ALTER TABLE [plugin].[CalendarWidgetSetting] ADD [DayView] BIT NOT NULL DEFAULT(1)");

            await _dbContext.Database.ExecuteNonQueryAsync("ALTER TABLE [plugin].[CalendarWidgetSetting] ADD [ListView] BIT NOT NULL DEFAULT(1)");


            return(MigrationResult.Success("Successfully added view columns."));
        }
        public async Task <MigrationResult> ExecuteAsync()
        {
            // Fail if cannot connect to db
            if (_blogDbContext.Database.TryTestConnection() == false)
            {
                return(MigrationResult.Failed("Cannot connect to database."));
            }

            // Skip if column already exists
            if (_blogDbContext.Database.HasColumn("BlogPost", "plugin", "Published"))
            {
                return(MigrationResult.Skipped("Column already exists."));
            }

            // create column initially and allow null
            await _blogDbContext.Database.ExecuteNonQueryAsync("ALTER TABLE [plugin].[BlogPost] ADD [Published] BIT NULL");

            // update the table, set default value
            await _blogDbContext.Database.ExecuteNonQueryAsync("UPDATE [plugin].[BlogPost] SET [Published] = 1");

            // add the not null constraint
            await _blogDbContext.Database.ExecuteNonQueryAsync("ALTER TABLE [plugin].[BlogPost] ALTER COLUMN [Published] BIT NOT NULL");

            return(MigrationResult.Success("Added column [BlogPost].[Published]"));
        }
        public async Task <MigrationResult> ExecuteAsync()
        {
            if (_dbContext.Database.TableExists("VideoWidget", "plugin"))
            {
                return(MigrationResult.Skipped());
            }

            // else create the tables
            await _dbContext.Database.ExecuteSqlCommandAsync(@"
                CREATE TABLE [plugin].[VideoWidget](
	                [Id] [nvarchar](50) NOT NULL,
	                [Title] [nvarchar](500) NULL,
                    [VideoSourceType] [nvarchar](500) NULL,
	                [VideoId] [nvarchar](500) NULL,
                    [VideoUrl] [nvarchar](500) NULL,
	                CONSTRAINT [PK_VideoLink] PRIMARY KEY CLUSTERED ([Id] ASC)
                )
            ");

            await _dbContext.Database.ExecuteSqlCommandAsync(@"
                CREATE TABLE [plugin].[VideoStreamLink](
	                [Id] [nvarchar](50) NOT NULL,
                    [ClientId] [nvarchar](50) NULL,
	                [Title] [nvarchar](500) NULL,
	                [Path] [nvarchar](500) NULL,
	                CONSTRAINT [PK_VideoLinkSource] PRIMARY KEY CLUSTERED ([Id] ASC)
                )
            ");

            return(MigrationResult.Success());
        }
示例#9
0
        public async Task <MigrationResult> ExecuteAsync()
        {
            if (_connectDb.Database.TryTestConnection() == true)
            {
                return(MigrationResult.Skipped());
            }


            var cnInfo = _connectDb.Database.GetDbConnection();

            if (!string.IsNullOrEmpty(cnInfo?.ConnectionString))
            {
                var cnBuilder    = new SqlConnectionStringBuilder(cnInfo.ConnectionString);
                var databaseName = cnBuilder.InitialCatalog;

                // can't connect to the db specified because it doesn't exist so setting
                // thus, connecting to master instead so we can create
                cnBuilder.InitialCatalog = "master";

                var connection = new SqlConnection(cnBuilder.ToString());

                connection.Open();
                using (var command = connection.CreateCommand())
                {
                    command.CommandText = $"CREATE DATABASE [{databaseName}]";
                    await command.ExecuteNonQueryAsync();
                }
                connection.Close();

                return(MigrationResult.Success($"Created [{databaseName}]"));
            }

            //else failed
            return(MigrationResult.Failed("Connetion string missing"));
        }
示例#10
0
        public MigrationResult Execute(System.Reflection.Assembly generatedAssembly, string scriptFileName)
        {
            var programType     = generatedAssembly.GetType(LinqPadCSharpCreator.GeneratedClass);
            var programInstance = Activator.CreateInstance(programType);
            var method          = programInstance.GetType().GetMethod(LinqPadCSharpCreator.GeneratedMethod);

            // Execute Script!
            object result = method.Invoke(programInstance, null);

            int?enumerableItemCount = GetEnumerableItemCount(result);

            // Expect Null or True or IEnumerable.Count == 0 results
            bool success = result == null || Equals(result, true) || (enumerableItemCount != null && enumerableItemCount == 0);

            string[] errorMessages = null;
            if (success)
            {
                return(new MigrationResult(scriptFileName, true, errorMessages, null));
            }
            else
            {
                errorMessages = new[] { "Linq Unit Test returned a failing value. Expected Null, True, or a collection of Zero items. Instead, collection count is: " + enumerableItemCount + ". Actual value: " + result.ToString() };
                var migrationResult = new MigrationResult(scriptFileName, success, errorMessages, null);
                throw new MigrationException(migrationResult);
            }
        }
示例#11
0
        public static Player CreateAndMigrate(string json, out MigrationResult migrationResult)
        {
            Player player = null;

            migrationResult = MigrationResult.Unspecified;
            try
            {
                if (!string.IsNullOrEmpty(json))
                {
                    if (IsSl1LegacyPlayer(json))
                    {
                        Debug.Log("Legacy player data detected, skipping data migration..");
                        migrationResult = MigrationResult.LegacyPlayer;
                        return(null);
                    }
                    int version = JsonUtils.Deserialize <Versionable>(json, true).Version;
                    if (version < ConfigApp.InternalClientVersion)
                    {
                        if (!ConfigApp.MigratePlayerProgressUponDataModelVersionChange)
                        {
                            json            = ResourceUtil.LoadSafe <TextAsset>("Players/humanPlayer1", false).text;
                            migrationResult = MigrationResult.OverridenWithDefaultData;
                        }
                        else
                        {
                            json            = PreMigrateToCurrentDataModelVersion(version, json);
                            migrationResult = MigrationResult.Migrated;
                        }
                    }
                    else
                    {
                        migrationResult = MigrationResult.UpToDate;
                    }
                    player = JsonUtils.Deserialize <Player>(json, true);
                    if (((player.Version == 0) && (player.CharacterInstances != null)) && (player.CharacterInstances.Count == 0))
                    {
                        migrationResult = MigrationResult.Repaired;
                        Player player2 = CreateNew();
                        player2.Version = ConfigApp.InternalClientVersion;
                        return(player2);
                    }
                    if ((version < ConfigApp.InternalClientVersion) && ConfigApp.MigratePlayerProgressUponDataModelVersionChange)
                    {
                        PostMigrateToCurrentDataModelVersion(player, json);
                    }
                    player.Version = ConfigApp.InternalClientVersion;
                }
            }
            catch (Exception exception)
            {
                Debug.LogError(string.Concat(new object[] { "CreateAndMigrate error: ", exception, " -- ", json }));
            }
            if (((player == null) || (player.CharacterInstances == null)) || (player.CharacterInstances.Count == 0))
            {
                player          = null;
                migrationResult = MigrationResult.Error;
            }
            return(player);
        }
        public async Task <MigrationResult> ExecuteAsync()
        {
            var announcementContentType = AnnouncementManager.CONTENT_TYPE_ANNOUNCEMENTPOST;

            // Fail if cannot connect to db
            if (_announcementDbContext.Database.TryTestConnection() == false || _connectDbContext.Database.TryTestConnection() == false)
            {
                return(MigrationResult.Failed("Cannot connect to database."));
            }

            // remove any versioning records that are in an invalid state
            await _connectDbContext.Database.ExecuteNonQueryAsync($@"
                DELETE FROM cms.ContentVersion WHERE ContentType = '{announcementContentType}' AND JsonData IS NULL
            ");

            // Ensure UserId is set for remaining versions
            // NOTE: Will only affect QA / Dev environments where UserIds weren't being saved during early test versions
            await _announcementDbContext.Database.ExecuteNonQueryAsync(@"
                UPDATE cms.ContentVersion SET UserId = bp.UserId
                FROM plugin.AnnouncementPost bp
                WHERE cms.ContentVersion.ContentId = bp.Id
                    AND cms.ContentVersion.UserId IS NULL
            ");

            // Identify announcements with valid version data to skip in next step
            // NOTE: These won't exist on production but might exist in dev / test environments
            var announcementIdsToSkip = await _connectDbContext.ContentVersions
                                        .Where(x =>
                                               x.ContentType == announcementContentType &&
                                               x.JsonData != null
                                               )
                                        .Select(x => x.ContentId).ToArrayAsync();


            // Identify announcement posts that have missing version data
            var announcementPostsToMigrate = await _announcementDbContext.AnnouncementPosts
                                             .Where(x => !announcementIdsToSkip.Contains(x.Id))
                                             .ToListAsync();


            // Insert the missing verision data
            foreach (var announcementPost in announcementPostsToMigrate)
            {
                var version = new ContentVersion(announcementContentType, announcementPost.Id);

                version.VersionCode = announcementPost.VersionCode;
                version.Created     = announcementPost.Posted;
                version.Status      = announcementPost.Published ? ContentStatus.Published : ContentStatus.Draft;
                version.UserId      = announcementPost.UserId;
                version.JsonData    = SerializeVersionData(announcementPost);

                _connectDbContext.ContentVersions.Add(version);
            }

            await _connectDbContext.SaveChangesAsync();


            return(MigrationResult.Success($"Inserted {announcementPostsToMigrate.Count} missing AnnouncementPost version records"));
        }
示例#13
0
        public MigrationResult MigrateToOstor(DirectoryBlock directoryBlock, ICloudServiceIO cloudService)
        {
            MigrationResult        result            = new MigrationResult();
            DownloadCloudDirectory downloadDirectory = new DownloadCloudDirectory(directoryBlock, "C:\\CloudFiles\\", cloudService);

            downloadDirectory.DownloadAsync();
            return(result);
        }
        public async Task <MigrationResult> ExecuteAsync()
        {
            var output = new System.Text.StringBuilder();

            // Fail if cannot connect to db
            if (_connectDb.Database.TryTestConnection() == false)
            {
                return(MigrationResult.Failed("Cannot connect to database."));
            }

            // Check if internal product already exists
            var exists = await _connectDb.Products.AnyAsync(x => x.Id == DbKeys.ProductIds.Internal);

            if (exists)
            {
                // early terminate
                return(MigrationResult.Skipped("Product already exists"));
            }

            // Register the product
            var internalProduct = new Product
            {
                Id          = DbKeys.ProductIds.Internal,
                CategoryId  = DbKeys.ProductCategoryIds.Angelo,
                Name        = "Internal Corp Product",
                Description = "Internal product used for building PC|Mac demo sites.",
                SchemaFile  = "/schemas/products/Product-0-Internal.json",
                Active      = true
            };

            _connectDb.Products.Add(internalProduct);
            await _connectDb.SaveChangesAsync();


            // Update the PcMac Product Mapping
            var productMapping = await _connectDb.ClientProductApps
                                 .Include(x => x.AddOns)
                                 .FirstOrDefaultAsync(
                x => x.Id == DbKeys.ClientProductAppIds.PcMacApp1
                );

            productMapping.ProductId    = DbKeys.ProductIds.Internal;
            productMapping.Title        = internalProduct.Name;
            productMapping.MaxSiteCount = 500; // was previously 5

            // Remove any previously seeded add-ons (the new product doesn't support any)
            if (productMapping.AddOns != null)
            {
                (productMapping.AddOns as List <ClientProductAddOn>).RemoveAll(x => true);
            }

            // Done
            await _connectDb.SaveChangesAsync();

            return(MigrationResult.Success("Created product and mapped to PcMac client."));
        }
示例#15
0
        public static async Task AutoMigrateMyDB(DbContext db)
        {
            EFCoreAutoMigrator dbMigrator = new EFCoreAutoMigrator(db, new Logger());

            dbMigrator.ShouldAllowDestructive(true);
            MigrationScriptExecutor migrationScriptExcutor = await dbMigrator.PrepareMigration();

            // Checking if there are migrations
            if (migrationScriptExcutor.HasMigrations())
            {
                Console.WriteLine("The program `Example` wants to run the following script on your database: ");
                Console.WriteLine("------");

                // Printing out the script to be run if they are
                Console.WriteLine(migrationScriptExcutor.GetMigrationScript());
                Console.WriteLine("------");

                Console.WriteLine("Do you want (R)un it, (S)ave the script or (C)ancel. ?");
                string userInput = Console.ReadLine();
                if (userInput.Length == 0)
                {
                    Console.WriteLine("No value entered. Exiting...");
                    Environment.Exit(0);
                }
                if (userInput[0] == 'R')
                {
                    // Migrating
                    MigrationResult result = await migrationScriptExcutor.MigrateDB();

                    if (result == MigrationResult.Migrated)
                    {
                        Console.WriteLine("Completed succesfully.");
                    }
                    else if (result == MigrationResult.Noop)
                    {
                        Console.WriteLine("Completed. There was nothing to migrate.");
                    }
                    else if (result == MigrationResult.ErrorMigrating)
                    {
                        Console.WriteLine("Error occurred whilst migrating.");
                    }
                }
                else if (userInput[0] == 'S')
                {
                    using (StreamWriter writer = new StreamWriter(Path.Join(Environment.CurrentDirectory, "ERCoreAutoMigratorGenetaedScript.sql")))
                    {
                        writer.WriteLine(migrationScriptExcutor.GetMigrationScript());
                        Console.WriteLine("Migration script saved succefully.");
                    }
                }
            }
            else
            {
                Console.WriteLine("Completed. There was nothing to migrate.");
            }
        }
示例#16
0
        public async Task <MigrationResult> ExecuteAsync()
        {
            string schemaName = "app";
            string tableName  = "WebCache";
            var    output     = new System.Text.StringBuilder();

            // create schema if needed
            if (_connectDb.Database.SchemaExists(schemaName) == false)
            {
                await _connectDb.Database.ExecuteSqlCommandAsync($@"
                    CREATE SCHEMA [{schemaName}]
                ");

                output.Append($"Created schema [{schemaName}]. ");
            }


            // CREATE TABLE SCHEMA (if needed)
            if (_connectDb.Database.TableExists(tableName, schemaName) == false)
            {
                await _connectDb.Database.ExecuteSqlCommandAsync($@"
                    CREATE TABLE [{schemaName}].[{tableName}](
                        [Id] nvarchar(450) COLLATE SQL_Latin1_General_CP1_CS_AS NOT NULL,
                        [Value] varbinary(MAX) NOT NULL, 
                        [ExpiresAtTime] datetimeoffset NOT NULL,
                        [SlidingExpirationInSeconds] bigint NULL,
                        [AbsoluteExpiration] datetimeoffset NULL,
                        CONSTRAINT [PK_Id] PRIMARY KEY (Id));

                    CREATE NONCLUSTERED INDEX [IX_ExpiresAtTime] ON [{schemaName}].[{tableName}](ExpiresAtTime);
                ");

                output.Append($"Created [{schemaName}].[{tableName}]. ");
            }

            // Cleanup old dbo version if present
            if (_connectDb.Database.TableExists("WebCache", "dbo") == true)
            {
                // drop it
                await _connectDb.Database.ExecuteSqlCommandAsync(@"
                    DROP TABLE [dbo].[WebCache]
                ");

                output.Append("Removed [dbo].[WebCache] (old version). ");
            }

            // if we have any messages, then we did something.
            // otherwise everything got skipped
            var message = output.ToString().Trim();

            var result = string.IsNullOrEmpty(message)
                ? MigrationResult.Skipped()
                : MigrationResult.Success(message);

            return(await Task.FromResult(result));
        }
        public async Task <MigrationResult> ExecuteAsync()
        {
            // Fail if cannot connect to db
            if (_NewsDbContext.Database.TryTestConnection() == false)
            {
                return(MigrationResult.Failed("Cannot connect to database."));
            }

            // Skip if column already exists
            if (_NewsDbContext.Database.HasColumn("NewsPost", "plugin", "VersionCode"))
            {
                return(MigrationResult.Skipped("Versioning columns already exists."));
            }

            // drop documentid column
            await _NewsDbContext.Database.ExecuteNonQueryAsync("ALTER TABLE [plugin].[NewsPost] DROP COLUMN [DocumentId]");

            // create column initially and allow null
            await _NewsDbContext.Database.ExecuteNonQueryAsync("ALTER TABLE [plugin].[NewsPost] ADD [VersionCode] NVARCHAR(50) NULL");

            await _NewsDbContext.Database.ExecuteNonQueryAsync("ALTER TABLE [plugin].[NewsPost] ADD [Status] INT NULL");


            // update the value of the status column
            await _NewsDbContext.Database.ExecuteNonQueryAsync("UPDATE [plugin].[NewsPost] SET [Status] = 1 WHERE [Published] = 0");

            await _NewsDbContext.Database.ExecuteNonQueryAsync("UPDATE [plugin].[NewsPost] SET [Status] = 2 WHERE [Published] = 1");


            // update values for version code - tricky
            await _NewsDbContext.Database.ExecuteNonQueryAsync(@"
                UPDATE plugin.NewsPost SET VersionCode = ct.VersionCode 
                FROM cms.ContentTree ct 
                WHERE ContentTreeId = ct.Id"
                                                               );

            await _NewsDbContext.Database.ExecuteNonQueryAsync(@"
                UPDATE plugin.NewsPost SET VersionCode = 
                    SUBSTRING(REPLACE(REPLACE(REPLACE(REPLACE(CONVERT(NVARCHAR, Posted, 121), '-', ''), ':', ''), '.', ''), ' ', '-'), 1, 17)
                WHERE VersionCode IS NULL
            ");

            await _NewsDbContext.Database.ExecuteNonQueryAsync(@"
                UPDATE cms.ContentTree SET VersionCode = bp.VersionCode
                FROM plugin.NewsPost bp
                WHERE cms.ContentTree.Id = bp.ContentTreeId
            ");

            // add the not null constraint
            await _NewsDbContext.Database.ExecuteNonQueryAsync("ALTER TABLE [plugin].[NewsPost] ALTER COLUMN [VersionCode] NVARCHAR(50) NOT NULL");

            await _NewsDbContext.Database.ExecuteNonQueryAsync("ALTER TABLE [plugin].[NewsPost] ALTER COLUMN [Status] INT NOT NULL");

            return(MigrationResult.Success("Added [NewsPost].[VersionCode], Added [NewsPost].[Status], Removed [NewsPost].[DocumentId]"));
        }
示例#18
0
        public async Task <MigrationResult> ExecuteAsync()
        {
            if (_loggerDb.RequiresMigration())
            {
                await _loggerDb.Database.MigrateAsync();

                return(MigrationResult.Success("Created entity models."));
            }

            return(MigrationResult.Skipped("No action required"));
        }
        public async Task <MigrationResult> ExecuteAsync()
        {
            // Fail if cannot connect to db
            if (_connectDb.Database.TryTestConnection() == false)
            {
                return(MigrationResult.Failed("Cannot connect to database."));
            }

            await _connectDb.Database.ExecuteNonQueryAsync("ALTER TABLE [cms].[NavigationMenuItem] ALTER COLUMN [TargetType] bit");

            return(MigrationResult.Success("Altered [TargetType] to bit"));
        }
示例#20
0
        public async Task <MigrationResult> ExecuteAsync()
        {
            // Fail if cannot connect to db
            if (_dbContext.Database.TryTestConnection() == false)
            {
                return(MigrationResult.Failed("Cannot connect to database."));
            }

            // Skip if bg color already exists
            if (_dbContext.Database.HasColumn("SlideShowSlide", "plugin", "UseVideoBackground"))
            {
                return(MigrationResult.Skipped("Column SlideShowSlide.UseVideoBackground already exists."));
            }

            // Skip if VideoUrl already exists
            if (_dbContext.Database.HasColumn("SlideShowSlide", "plugin", "VideoUrl"))
            {
                return(MigrationResult.Skipped("Column SlideShowSlide.VideoUrl already exists."));
            }

            // Skip if VideoSource already exists
            if (_dbContext.Database.HasColumn("SlideShowSlide", "plugin", "VideoSource"))
            {
                return(MigrationResult.Skipped("Column SlideShowSlide.VideoSource already exists."));
            }

            // Skip if EnableVideoSound already exists
            if (_dbContext.Database.HasColumn("SlideShowSlide", "plugin", "EnableVideoSound"))
            {
                return(MigrationResult.Skipped("Column SlideShowSlide.EnableVideoSound already exists."));
            }

            await _dbContext.Database.ExecuteNonQueryAsync(
                "ALTER TABLE [plugin].[SlideShowSlide] ADD [UseVideoBackground] [Bit] NULL Default(0)");

            await _dbContext.Database.ExecuteNonQueryAsync(
                "ALTER TABLE [plugin].[SlideShowSlide] ADD [VideoUrl][nvarchar](500) NULL");

            await _dbContext.Database.ExecuteNonQueryAsync(
                "ALTER TABLE [plugin].[SlideShowSlide] ADD [VideoSource][nvarchar](20) NULL");

            await _dbContext.Database.ExecuteNonQueryAsync(
                "ALTER TABLE [plugin].[SlideShowSlide] ADD [EnableVideoSound][Bit] NULL Default(0)");

            // update the table, set all values to 0
            await _dbContext.Database.ExecuteNonQueryAsync("UPDATE [plugin].[SlideShowSlide] SET UseVideoBackground = 0");

            // update the table, set all values to 0
            await _dbContext.Database.ExecuteNonQueryAsync("UPDATE [plugin].[SlideShowSlide] SET EnableVideoSound = 0");

            return(MigrationResult.Success(
                       "Added Video Background supporting columns"));
        }
        public async Task <MigrationResult> ExecuteAsync()
        {
            // Fail if cannot connect to db
            if (_connectDb.Database.TryTestConnection() == false)
            {
                return(MigrationResult.Failed("Cannot connect to database."));
            }

            await _connectDb.Database.ExecuteNonQueryAsync("ALTER TABLE [cms].[PageMaster] ADD [IsSystemPage] bit NOT NULL DEFAULT 0");

            return(MigrationResult.Success("Added [IsSystemPage] to PageMaster"));
        }
        public async Task <MigrationResult> ExecuteAsync()
        {
            // Fail if cannot connect to db
            if (_identityDb.Database.TryTestConnection() == false)
            {
                return(MigrationResult.Failed("Cannot connect to database."));
            }

            await AddCorpUserClaimToCorpRoles();


            return(MigrationResult.Success("Successfully added the corp User"));
        }
示例#23
0
        public Task ImportSql()
        {
            using (ContextPool.AllocateOperationContext(out DocumentsOperationContext context))
            {
                using (var sqlImportDoc = context.ReadForMemory(RequestBodyStream(), "sql-migration-request"))
                {
                    MigrationRequest migrationRequest;

                    // we can't use JsonDeserializationServer here as it doesn't support recursive processing
                    var serializer = DocumentConventions.Default.CreateSerializer();
                    using (var blittableJsonReader = new BlittableJsonReader())
                    {
                        blittableJsonReader.Init(sqlImportDoc);
                        migrationRequest = serializer.Deserialize <MigrationRequest>(blittableJsonReader);
                    }

                    var operationId = Database.Operations.GetNextOperationId();

                    var sourceSqlDatabase = migrationRequest.Source;

                    var dbDriver = DatabaseDriverDispatcher.CreateDriver(sourceSqlDatabase.Provider, sourceSqlDatabase.ConnectionString);
                    var schema   = dbDriver.FindSchema();
                    var token    = CreateOperationToken();

                    var result = new MigrationResult(migrationRequest.Settings);

                    var collectionsCount     = migrationRequest.Settings.Collections.Count;
                    var operationDescription = "Importing " + collectionsCount + " " + (collectionsCount == 1 ? "collection" : "collections") + " from SQL database: " + schema.CatalogName;

                    Database.Operations.AddOperation(Database, operationDescription, Documents.Operations.Operations.OperationType.MigrationFromSql, onProgress =>
                    {
                        return(Task.Run(async() =>
                        {
                            try
                            {
                                // allocate new context as we executed this async
                                using (ContextPool.AllocateOperationContext(out DocumentsOperationContext migrationContext))
                                {
                                    await dbDriver.Migrate(migrationRequest.Settings, schema, Database, migrationContext, result, onProgress, token.Token);
                                }
                            }
                            catch (Exception e)
                            {
                                result.AddError($"Error occurred during import. Exception: {e.Message}");
                                onProgress.Invoke(result.Progress);
                                throw;
                            }

                            return (IOperationResult)result;
                        }));
                    }, operationId, token: token);
示例#24
0
 public override MigrationResult Migrate(DatabaseStatus preSchemaUpdateStatus)
 {
     using (var tx = persister.Repository.BeginTransaction())
     {
         var result = new MigrationResult(this);;
         foreach (var redirect in persister.Repository.Find(new Parameter("class", "Redirect")).Where(p => p.Parent is Models.Pages.LanguageRoot))
         {
             persister.Delete(redirect);
             result.UpdatedItems++;
         }
         tx.Commit();
         return(result);
     }
 }
        public async Task <MigrationResult> ExecuteAsync()
        {
            var output = new System.Text.StringBuilder();

            // Fail if cannot connect to db
            if (_identityDb.Database.TryTestConnection() == false)
            {
                return(MigrationResult.Failed("Cannot connect to database."));
            }

            // Insert claim into Client RoleClaims
            var clients = await _connectDb.Clients.ToListAsync();

            foreach (Client client in clients)
            {
                var roles = await _identityDb.Roles.Where(x => x.PoolId == client.SecurityPoolId && x.Name != "Registered Users").ToListAsync();

                var clientId = client.Id;

                foreach (Role role in roles)
                {
                    await _identityDb.Database.ExecuteSqlCommandAsync($@"
                        INSERT INTO auth.RoleClaim (RoleId, ClaimType, ClaimValue)
                        VALUES ('{role.Id}', 'user-library-owner', '{clientId}')
                    ");
                }
            }

            // Insert claim into Site RoleClaims
            var sites = await _connectDb.Sites.ToListAsync();

            foreach (Site site in sites)
            {
                var roles = await _identityDb.Roles.Where(x => x.PoolId == site.SecurityPoolId && x.Name != "Registered Users").ToListAsync();

                var siteId = site.Id;

                foreach (Role role in roles)
                {
                    await _identityDb.Database.ExecuteSqlCommandAsync($@"
                        INSERT INTO auth.RoleClaim (RoleId, ClaimType, ClaimValue)
                        VALUES ('{role.Id}', 'user-library-owner', '{siteId}')
                    ");
                }
            }


            return(MigrationResult.Success("Added user-library-owner claim to roles."));
        }
        public async Task <MigrationResult> ExecuteAsync()
        {
            var output = new System.Text.StringBuilder();

            // Fail if cannot connect to db
            if (_identityDb.Database.TryTestConnection() == false)
            {
                return(MigrationResult.Failed("Cannot connect to database."));
            }

            // Update the name for the wireless provider
            await _identityDb.Database.ExecuteNonQueryAsync($"UPDATE [auth].[WirelessProvider] SET [Name] = 'Boost Mobile' WHERE [Id] = '{DbKeys.WirelessProviderIds.BoostMobile}'");

            return(MigrationResult.Success($"Updated Boost Mobile Name from  Boos Mobile to Boost Mobile"));
        }
示例#27
0
        public async Task <MigrationResult> ExecuteAsync()
        {
            // Fail if cannot connect to db
            if (_dbContext.Database.TryTestConnection() == false)
            {
                return(MigrationResult.Failed("Cannot connect to database."));
            }


            await _dbContext.Database.ExecuteNonQueryAsync("ALTER TABLE [plugin].[SlideShowLayer] ALTER COLUMN [Title] [nvarchar](MAX) NULL");

            await _dbContext.Database.ExecuteNonQueryAsync("ALTER TABLE [plugin].[SlideShowLayer] ALTER COLUMN [SourceUrl] [nvarchar](MAX) NULL");

            return(MigrationResult.Success("Successful Increase Title And Url Column Size "));
        }
示例#28
0
        public async Task <MigrationResult> ExecuteAsync()
        {
            if (_identityDb.RequiresMigration())
            {
                await _identityDb.Database.MigrateAsync();

                // EF migrations sometimes report back complete before the underlying DB transaction
                // has completed so stalling a bit. This only affects drop / recreate scenarios.
                await Task.Delay(1200);

                return(MigrationResult.Success("Created entity models"));
            }

            return(MigrationResult.Skipped("No action required"));
        }
示例#29
0
        private static MigrationResult MigrateSingleRedirectRule(UrlRewriteModel urlRewriteModel, IRedirectRuleRepository redirectRuleRepository)
        {
            var migrationResult = new MigrationResult(urlRewriteModel.Id);

            try {
                var newRedirectRule = MapUrlRewriteToRedirectRule(urlRewriteModel);
                redirectRuleRepository.Add(newRedirectRule);
            }
            catch (Exception e)
            {
                migrationResult.ErrorMessage = e.Message;
            }

            return(migrationResult);
        }
        public async Task <MigrationResult> ExecuteAsync()
        {
            // Fail if cannot connect to db
            if (_connectDb.Database.TryTestConnection() == false)
            {
                return(MigrationResult.Failed("Cannot connect to database."));
            }

            // Add the new column
            await _connectDb.Database.ExecuteNonQueryAsync("ALTER TABLE [cms].[Page] ADD [IsHomePage] BIT NOT NULL DEFAULT(0)");

            await UpdateFlagOnExistingSites();

            return(MigrationResult.Success("Successfully added Column IsHomePage to Pages."));
        }
示例#31
0
        protected override void Execute()
        {
            MigrationResult response = this.Client.Shares.GetMigrationStatus(this.ResourceGroupName, this.FarmName, this.JobId);

            this.WriteVerbose(String.Format(
                                  "migration result = ContainerName = {0}, DestinationShareName = {1}, FailureReason = {2} " +
                                  "\nJobId = {3}, MigrationStatus = {4}, SourceShareName = {5} StorageAccountName = {6}",
                                  response.ContainerName,
                                  response.DestinationShareName,
                                  response.FailureReason,
                                  response.JobId,
                                  response.MigrationStatus,
                                  response.SourceShareName,
                                  response.StorageAccountName));
            this.WriteObject(response, true);
        }
 private static string GetMessage(MigrationResult result)
 {
     var messages = String.Join(", ", result.ErrorMessages);
     return String.Format("Script '{0}' resulted in an exception. {1}", result.ScriptFile, messages);
 }
 public MigrationException(MigrationResult result)
     : base(GetMessage(result), result.MigrationException)
 {
     Result = result;
 }