예제 #1
0
 private void SaveAuthorsToDatabase(List <Author> toAddToDatabase)
 {
     using (ApplicationDatabase ctxt = new ApplicationDatabase())
     {
         foreach (Author authorToAdd in toAddToDatabase)
         {
             if (!ctxt.Authors.Any(pa => pa.Id == authorToAdd.Id))
             {
                 Console.Write("☻");
                 try
                 {
                     ctxt.Authors.Add(authorToAdd);
                 }
                 catch (Exception e)
                 {
                     Console.WriteLine(e.Message);
                 }
             }
             else
             {
                 Console.Write("☺");
             }
         }
         Console.Write('\n');
         ctxt.SaveChanges();
     }
 }
예제 #2
0
        //private static string _timeout = ParseTimeout();
        //private static int _candidateTimeOut;

        //private static readonly string TimeoutSuffix = "Connection Timeout=" + _timeout + ";";
        //private static readonly string InternetConnStrTesting = ConfigurationManager.ConnectionStrings[ConnectionStringKeys.INTERNET_TEST].ConnectionString + TimeoutSuffix;
        //private static readonly string FTDataConnStrTesting   = ConfigurationManager.ConnectionStrings[ConnectionStringKeys.FTDATA_TEST].ConnectionString + TimeoutSuffix;

        public string GetConnectionString(ApplicationEnvironment environment, ApplicationDatabase context)
        {
            //string connectionString;
            if (environment == ApplicationEnvironment.Production)
            {
                throw new NotImplementedException();
            }

            return("UNIDATA");

            //else
            //{
            //    switch (context)
            //    {
            //        case ApplicationDatabase.FTData:
            //            throw new NotImplementedException();
            //            connectionString = FTDataConnStrTesting;
            //            break;
            //        case ApplicationDatabase.Internet:
            //            connectionString = InternetConnStrTesting;
            //            break;
            //        default:
            //            throw new NotImplementedException();
            //    }
            //}

            //return connectionString;
        }
예제 #3
0
        public static void SaveBlockWithParameters(Block blockToSave, string[] parameters)
        {
            //We want to avoid having to create a explosive if-tree where we fill each parameter column.
            //Instead, we simply compile an insert query.
            string SqlQuery = "INSERT INTO Blocks (ScriptId,BlockRank,Indent,OpCodeId,param1,param2,param3,param4,param5,param6,param7,param8,param9,param10,param11,param12,param13,param14,param15,param16,param17,param18,param19,param20,param21,param22,param23,param24) ";

            SqlQuery += $"VALUES ({(blockToSave.Script == null ? blockToSave.ScriptId : blockToSave.Script.ScriptId)},{blockToSave.BlockRank},{blockToSave.Indent},{blockToSave.OpCodeId}, @param1,@param2,@param3,@param4,@param5,@param6,@param7,@param8,@param9,@param10,@param11,@param12,@param13,@param14,@param15,@param16,@param17,@param18,@param19,@param20,@param21,@param22,@param23,@param24)";
            List <MySqlParameter> blockParameters = new List <MySqlParameter>();

            try
            {
                if (parameters == null)
                {
                    parameters = new string[] { }
                }
                ;
                using (ApplicationDatabase ctxt = new ApplicationDatabase())
                {
                    int paramCount    = 0;
                    int maxParamCount = 24;

                    for (paramCount = 1; paramCount <= maxParamCount; paramCount++)
                    {
                        blockParameters.Add(new MySqlParameter($"@param{paramCount}", $"{(parameters.Length >= paramCount ? $"{parameters[paramCount - 1]}" : "NULL")}"));
                    }

                    ctxt.Database.ExecuteSqlCommand(SqlQuery, blockParameters.ToArray());
                }
            }
            catch (Exception e)
            {
                Say(e.Message);
            }
        }
예제 #4
0
        public void TestInitialise()
        {
            this.testData = new BudgetAnalyserStorageRoot
            {
                BudgetCollectionRootDto = new StorageBranch {
                    Source = "Budget.xml"
                },
                LedgerBookRootDto = new StorageBranch {
                    Source = "Ledger.xml"
                },
                MatchingRulesCollectionRootDto = new StorageBranch {
                    Source = "Rules.xml"
                },
                StatementModelRootDto = new StorageBranch {
                    Source = "Statement.xml"
                },
                LedgerReconciliationToDoCollection = new List <ToDoTaskDto>
                {
                    new ToDoTaskDto {
                        CanDelete = true, Description = "Foo1", SystemGenerated = false
                    },
                    new ToDoTaskDto {
                        CanDelete = false, Description = "Foo2", SystemGenerated = true
                    }
                }
            };

            var subject = new Mapper_BudgetAnalyserStorageRoot_ApplicationDatabase();

            this.result = subject.ToModel(this.testData);
        }
 public MarkMainChainQueryHandler(ApplicationDatabase applicationDatabase,
                                  IQueryHandler <GetHeadBlockQuery, Database.Block> queryHandlerGetHeadBlock
                                  )
 {
     _applicationDatabase      = applicationDatabase;
     _queryHandlerGetHeadBlock = queryHandlerGetHeadBlock;
 }
예제 #6
0
        public async Task LoadAsync(ApplicationDatabase applicationDatabase)
        {
            this.matchingRules.Clear();
            this.matchingRulesGroupedByBucket.Clear();
            this.rulesStorageKey = applicationDatabase.FullPath(applicationDatabase.MatchingRulesCollectionStorageKey);
            List <MatchingRule> repoRules;

            try
            {
                repoRules = (await this.ruleRepository.LoadAsync(this.rulesStorageKey, applicationDatabase.IsEncrypted))
                            .OrderBy(r => r.Description)
                            .ToList();
            }
            catch (FileNotFoundException)
            {
                // If file not found occurs here, assume this is the first time the app has run, and create a new one.
                this.rulesStorageKey = await BuildDefaultFileName();

                repoRules = this.ruleRepository.CreateNew().ToList();
            }

            InitialiseTheRulesCollections(repoRules);

            this.monitorableDependencies.NotifyOfDependencyChange <ITransactionRuleService>(this);
            NewDataSourceAvailable?.Invoke(this, EventArgs.Empty);
        }
예제 #7
0
        private static Dictionary <string, OpCode> GetOpcodes(bool sb2, bool sb3, bool verbose = false)
        {
            Dictionary <string, OpCode> opCodes = new Dictionary <string, OpCode>();

            using (ApplicationDatabase ctxt = new ApplicationDatabase())
            {
                if (sb2)
                {
                    opCodes = ctxt.OpCodes.Where(o => !string.IsNullOrEmpty(o.OpCodeSymbolLegacy)).ToDictionary(p => p.OpCodeSymbolLegacy);
                }
                if (sb3)
                {
                    foreach (OpCode toAdd in ctxt.OpCodes.Where(o => !string.IsNullOrEmpty(o.OpCodeSymbolSb3)))
                    {
                        if (opCodes.ContainsKey(toAdd.OpCodeSymbolSb3))
                        {
                            if (verbose)
                            {
                                Say($"Sb3 opcode: {toAdd.OpCodeSymbolSb3} already in OpCode cache. Skipping.");
                            }
                            continue;
                        }
                        opCodes.Add(toAdd.OpCodeSymbolSb3, toAdd);
                    }
                }
            }
            return(opCodes);
        }
예제 #8
0
 /// <summary>
 /// This method seeds the SpriteTypes table
 /// Since these were added manually, we have to do that too.
 /// </summary>
 private static void SeedSpriteTypeTable()
 {
     using (ApplicationDatabase ctxt = new ApplicationDatabase())
     {
         List <SpriteType> spriteTypesInDb = ctxt.SpriteTypes.ToList();
         if (!spriteTypesInDb.Any(o => o.Id == 1 && o.spriteTypeName == "sprite"))
         {
             ctxt.SpriteTypes.Add(new SpriteType()
             {
                 Id = 1, spriteTypeName = "sprite"
             });
         }
         if (!spriteTypesInDb.Any(o => o.Id == 2 && o.spriteTypeName == "stage"))
         {
             ctxt.SpriteTypes.Add(new SpriteType()
             {
                 Id = 2, spriteTypeName = "stage"
             });
         }
         if (!spriteTypesInDb.Any(o => o.Id == 3 && o.spriteTypeName == "procDef"))
         {
             ctxt.SpriteTypes.Add(new SpriteType()
             {
                 Id = 3, spriteTypeName = "procDef"
             });
         }
         ctxt.SaveChanges();
     }
 }
예제 #9
0
        public SettingsViewModel(IDialogCoordinator coordinator)
        {
            _dialogCoordinator = coordinator;

            DatabaseImport = new RelayCommand(x =>
            {
                var dlg = new OpenFileDialog {
                    Filter = "Zip filer (.zip)|*.zip"
                };
                dlg.FileOk += ValidateDatabaseFile;
                var result  = dlg.ShowDialog();
                if (result == true)
                {
                    ApplicationDatabase.Import(dlg.FileName);
                    DisplayTimedMessage("Succes", "Databasen er importeret succesfuldt. ", 2);
                }
                DatabaseExport.NotifyCanExecuteChanged();
            });

            DatabaseExport = new RelayCommand(x =>
            {
                var dlg = new SaveFileDialog {
                    Filter = "Zip filer (.zip)|*.zip", FileName = "database", DefaultExt = ".zip"
                };
                var result = dlg.ShowDialog();
                if (result != true)
                {
                    return;
                }
                ApplicationDatabase.Export(dlg.FileName);
                DisplayTimedMessage("Succes", "Databasen er eksporteret succesfuldt. ", 2);
            }, x => ApplicationDatabase.Exists);

            RunOfferSettingsDialogCmd = new RelayCommand(x =>
            {
                OpenOfferSettingsDialog(instanceCanceled =>
                {
                    _dialogCoordinator.HideMetroDialogAsync(this, _customDialog);
                }, async instanceCompleted =>
                {
                    await _dialogCoordinator.HideMetroDialogAsync(this, _customDialog);
                    DisplayTimedMessage("Information gemt!", "", 2);
                });
            });

            NavigateBackCmd = new RelayCommand(async x =>
            {
                if (!IsDataSaved)
                {
                    var result = await NavigationService.ConfirmDiscardChanges(_dialogCoordinator);
                    if (result == false)
                    {
                        return;
                    }
                }
                NavigationService.GoBack();
            });
        }
예제 #10
0
 public DatabaseSeedingService(
     ApplicationDatabase database,
     UserManager <UserModel> userManager,
     RoleManager <UserRole> roleManager)
 {
     _database    = database;
     _userManager = userManager;
     _roleManager = roleManager;
 }
        public async Task CreateAsync(ApplicationDatabase applicationDatabase)
        {
            if (applicationDatabase.BudgetCollectionStorageKey.IsNothing())
            {
                throw new ArgumentNullException(nameof(applicationDatabase));
            }

            await this.budgetRepository.CreateNewAndSaveAsync(applicationDatabase.BudgetCollectionStorageKey);
            await LoadAsync(applicationDatabase);
        }
예제 #12
0
        /// <summary>
        ///     Loads a data source with the provided database reference data asynchronously.
        /// </summary>
        public Task LoadAsync(ApplicationDatabase applicationDatabase)
        {
            if (applicationDatabase == null)
            {
                throw new ArgumentNullException(nameof(applicationDatabase));
            }

            // The To Do Collection persistence is managed by the ApplicationDatabaseService.
            ReconciliationToDoList = applicationDatabase.LedgerReconciliationToDoCollection;
            return(Task.CompletedTask);
        }
예제 #13
0
        private List <Author> GetAllAuthorsFromDatabase(int skip = 0)
        {
            List <Author> allAuthorsInDatabase = null;

            using (ApplicationDatabase ctxt = new ApplicationDatabase())
            {
                allAuthorsInDatabase = ctxt.Authors.AsNoTracking().ToList();
                allAuthorsInDatabase = allAuthorsInDatabase.Skip(skip).ToList();
            }
            return(allAuthorsInDatabase);
        }
예제 #14
0
        public async Task LoadAsync(ApplicationDatabase applicationDatabase)
        {
            if (applicationDatabase == null)
            {
                throw new ArgumentNullException(nameof(applicationDatabase));
            }

            LedgerBook = await this.ledgerRepository.LoadAsync(applicationDatabase.FullPath(applicationDatabase.LedgerBookStorageKey), applicationDatabase.IsEncrypted);

            this.monitorableDependencies.NotifyOfDependencyChange(LedgerBook);
            NewDataSourceAvailable?.Invoke(this, EventArgs.Empty);
        }
예제 #15
0
        public static void UpdateDatabase(IProvideUserSettings settings)
        {
            var connectionString = CreateSqliteConnectionString(settings, "application.dat");
            var optionsBuilder   = new DbContextOptionsBuilder <ApplicationDatabase>();

            optionsBuilder.UseSqlite(connectionString.ConnectionString);

            using (var context = new ApplicationDatabase(optionsBuilder.Options))
            {
                context.Database.Migrate();
            }
        }
예제 #16
0
 private void Awake()
 {
     if (Instance == null)
     {
         Instance = this;
         DontDestroyOnLoad(this.gameObject);
     }
     else
     {
         Destroy(this.gameObject);
     }
 }
예제 #17
0
        public void TestInitialise()
        {
            this.subject = new XamlOnDiskApplicationDatabaseRepositoryTestHarness(new Mapper_BudgetAnalyserStorageRoot_ApplicationDatabase())
            {
                FileExistsOverride = fileName => true
            };

            Task <ApplicationDatabase> task = this.subject.LoadAsync(TestDataConstants.DemoBudgetAnalyserFileName);

            task.Wait();
            this.result = task.Result;
        }
        public async Task LoadAsync(ApplicationDatabase applicationDatabase)
        {
            if (applicationDatabase == null)
            {
                throw new ArgumentNullException(nameof(applicationDatabase));
            }

            Budgets = await this.budgetRepository.LoadAsync(applicationDatabase.FullPath(applicationDatabase.BudgetCollectionStorageKey), applicationDatabase.IsEncrypted);

            UpdateServiceMonitor();
            NewDataSourceAvailable?.Invoke(this, EventArgs.Empty);
        }
        /// <summary>
        /// Get All Video reels
        /// </summary>
        /// <returns>collection of video reels</returns>
        public IList <VideoReel> GetVideoReels()
        {
            IList <VideoReel> videoReels;

            var database = ApplicationDatabase.Create();

            using (var command = database.GetStoredProcCommand(Constants.Procedure_GetAllVideoReels))
            {
                videoReels = this.Populate(database.ExecuteDataSet(command));
            }

            return(videoReels);
        }
예제 #20
0
        public void ValidateAllAuthorsInDatabase()
        {
            string authorDirectory = Path.Combine(this.WorkingDirectoryPath, "authors/");

            if (!Directory.Exists(authorDirectory))
            {
                Directory.CreateDirectory(authorDirectory);
            }

            ConcurrentStack <Author> allAuthorsInDatabase = new ConcurrentStack <Author>();

            using (ApplicationDatabase ctxt = new ApplicationDatabase())
            {
                allAuthorsInDatabase = new ConcurrentStack <Author>(ctxt.Authors.OrderBy(o => o.Id));
            }
            int maxThreads = 12; //Change this to the amount of cores on the target PC

            int totalAmountOfAuthorsInDatabase = allAuthorsInDatabase.Count();
            int totalAuthorsValidated          = 0;

            System.Timers.Timer titleBarUpdateTimer = new System.Timers.Timer();
            titleBarUpdateTimer.Elapsed += (sender, args) => Console.Title = $"{totalAuthorsValidated}/{totalAmountOfAuthorsInDatabase}";
            titleBarUpdateTimer.Interval = 1000;
            titleBarUpdateTimer.Start();

            for (int i = 0; i < maxThreads; i++)
            {
                Console.WriteLine($"Starting author validator {i + 1} of {maxThreads}");
                ThreadPool.QueueUserWorkItem((Action) =>
                {
                    while (true)
                    {
                        try
                        {
                            Author toHandle = null;
                            while (toHandle == null)
                            {
                                allAuthorsInDatabase.TryPop(out toHandle);
                            }
                            ValidateAuthor(toHandle, authorDirectory);
                            Interlocked.Increment(ref totalAuthorsValidated);
                        }
                        catch (Exception e)
                        {
                            try { File.AppendAllText(@"C:\ScratchScrapeData\AuthorScraper\errors\errors.txt", e.Message); }
                            catch (Exception) { }
                        }
                    }
                }, null);
            }
        }
        /// <summary>
        /// Return empty database with genesis block
        /// </summary>
        /// <param name="seed"></param>
        /// <returns></returns>
        public static ApplicationDatabase GetDatabase(Action <ApplicationDatabase> seed)
        {
            var options = new DbContextOptionsBuilder <ApplicationDatabase>()
                          .UseInMemoryDatabase(Guid.NewGuid().ToString())
                          .ConfigureWarnings(w => w.Ignore(InMemoryEventId.TransactionIgnoredWarning))
                          .Options;
            var context = new ApplicationDatabase(options);

            context.BlockChain.Add(BlockchainConsensus.GenesisBlock);
            context.SaveChanges();

            seed(context);
            return(context);
        }
        /// <summary>
        /// Get a Video reel
        /// </summary>
        /// <param name="reelId">
        /// The reel Id.
        /// </param>
        /// <returns>
        /// video reel
        /// </returns>
        public VideoReel GetVideoReel(int reelId)
        {
            IList <VideoReel> videoReels;

            var database = ApplicationDatabase.Create();

            using (var command = database.GetStoredProcCommand(Constants.Procedure_GetVideoReel))
            {
                database.AddInParameter(command, Constants.Parameter_VideoReelId, DbType.Int32, reelId);

                videoReels = this.Populate(database.ExecuteDataSet(command));
            }

            return(videoReels.Count > 0 ? videoReels[0] : null);
        }
        /// <summary>
        /// Get All Clips
        /// </summary>
        /// <param name="clipId">Clip Id</param>
        /// <returns>Video Clip details</returns>
        public VideoClip GetClipDetails(int clipId)
        {
            IList <VideoClip> videoClips;

            var database = ApplicationDatabase.Create();

            using (var command = database.GetStoredProcCommand(Constants.Procedure_GetVideoClipById))
            {
                database.AddInParameter(command, Constants.Parameter_VideoClipId, DbType.Int32, clipId);

                videoClips = this.Populate(database.ExecuteDataSet(command));
            }

            return(videoClips[0]);
        }
예제 #24
0
 /// <summary>
 /// Reload data from database.
 /// </summary>
 private void ReLoadData(Action actionBeforeRestart = null)
 {
     ActionCloseTranslatedWindows.PerformClick();
     ActionSearchClear.PerformClick();
     PanelViewVerses.AutoScrollPosition    = new Point(0, 0);
     PanelSearchResults.AutoScrollPosition = new Point(0, 0);
     PanelViewVerses.Controls.Clear();
     PanelSearchResults.Controls.Clear();
     SearchResults = null;
     Refresh();
     ApplicationDatabase.Instance.Close();
     actionBeforeRestart?.Invoke();
     ApplicationDatabase.Restart();
     LoadData();
     DoStartGoToReference();
 }
예제 #25
0
        public async Task SaveAsync(ApplicationDatabase applicationDatabase)
        {
            Saving?.Invoke(this, new AdditionalInformationRequestedEventArgs());

            var messages = new StringBuilder();

            if (!LedgerBook.Validate(messages))
            {
                throw new ValidationWarningException("Ledger Book is invalid, cannot save at this time:\n" + messages);
            }

            await this.ledgerRepository.SaveAsync(LedgerBook, applicationDatabase.FullPath(applicationDatabase.LedgerBookStorageKey), applicationDatabase.IsEncrypted);

            this.monitorableDependencies.NotifyOfDependencyChange(LedgerBook);
            Saved?.Invoke(this, EventArgs.Empty);
        }
예제 #26
0
 private void UpdateAuthor(Author toUpdate)
 {
     using (ApplicationDatabase _dbContext = new ApplicationDatabase())
     {
         var entity = _dbContext.Authors.Where(c => c.Id == toUpdate.Id).AsQueryable().FirstOrDefault();
         if (entity == null)
         {
             _dbContext.Authors.Add(toUpdate);
         }
         else
         {
             _dbContext.Entry(entity).CurrentValues.SetValues(toUpdate);
         }
         _dbContext.SaveChanges();
     }
 }
예제 #27
0
        public async Task SaveAsync(ApplicationDatabase applicationDatabase)
        {
            var messages = new StringBuilder();

            if (ValidateModel(messages))
            {
                // Prefer to use the file name from the applicationDatabase in case it has been changed upstream.
                await this.ruleRepository.SaveAsync(MatchingRules, applicationDatabase.FullPath(applicationDatabase.MatchingRulesCollectionStorageKey), applicationDatabase.IsEncrypted);
            }
            else
            {
                throw new ValidationWarningException("Unable to save matching rules at this time, some data is invalid.\n" + messages);
            }

            this.monitorableDependencies.NotifyOfDependencyChange <ITransactionRuleService>(this);
            Saved?.Invoke(this, EventArgs.Empty);
        }
        public async Task <ApplicationDatabase> LoadAsync(string storageKey)
        {
            if (storageKey.IsNothing())
            {
                throw new ArgumentNullException(nameof(storageKey));
            }

            ClearDirtyDataFlags();
            var encryptionKey = this.credentialStore.RetrievePasskey();

            this.budgetAnalyserDatabase = await this.applicationRepository.LoadAsync(storageKey);

            if (this.budgetAnalyserDatabase.IsEncrypted && encryptionKey == null)
            {
                throw new EncryptionKeyNotProvidedException($"{this.budgetAnalyserDatabase.FileName} is encrypted and no password has been provided.");
            }

            try
            {
                foreach (var service in this.databaseDependents) // Already sorted ascending by sequence number.
                {
                    this.logger.LogInfo(l => $"Loading service: {service}");
                    await service.LoadAsync(this.budgetAnalyserDatabase);
                }
            }
            catch (DataFormatException ex)
            {
                Close();
                throw new DataFormatException("A subordindate data file is invalid or corrupt unable to load " + storageKey, ex);
            }
            catch (KeyNotFoundException ex)
            {
                Close();
                throw new KeyNotFoundException("A subordinate data file cannot be found: " + ex.Message, ex);
            }
            catch (NotSupportedException ex)
            {
                Close();
                throw new DataFormatException("A subordinate data file contains unsupported data.", ex);
            }

            this.monitorableDependencies.NotifyOfDependencyChange(this.budgetAnalyserDatabase);
            this.monitorableDependencies.NotifyOfDependencyChange <IApplicationDatabaseService>(this);
            return(this.budgetAnalyserDatabase);
        }
        public async Task <ApplicationDatabase> CreateNewDatabaseAsync(string storageKey)
        {
            if (storageKey.IsNothing())
            {
                throw new ArgumentNullException(nameof(storageKey));
            }

            ClearDirtyDataFlags();
            this.budgetAnalyserDatabase = await this.applicationRepository.CreateNewAsync(storageKey);

            foreach (var service in this.databaseDependents)
            {
                await service.CreateAsync(this.budgetAnalyserDatabase);
            }

            this.monitorableDependencies.NotifyOfDependencyChange(this.budgetAnalyserDatabase);
            return(this.budgetAnalyserDatabase);
        }
        public async Task SaveAsync(ApplicationDatabase applicationDatabase)
        {
            EnsureAllBucketsUsedAreInBucketRepo();

            var messages = new StringBuilder();

            if (Budgets.Validate(messages))
            {
                await this.budgetRepository.SaveAsync(applicationDatabase.FullPath(applicationDatabase.BudgetCollectionStorageKey), applicationDatabase.IsEncrypted);

                var savedHandler = Saved;
                savedHandler?.Invoke(this, EventArgs.Empty);
                return;
            }

            this.logger.LogWarning(l => l.Format("BudgetMaintenanceService.Save: unable to save due to validation errors:\n{0}", messages));
            throw new ValidationWarningException("Unable to save Budget:\n" + messages);
        }
예제 #31
0
        protected override void Execute(CommandExecutionContext context)
        {
            if (string.IsNullOrEmpty(ConnectionString) && ConnectionStringBuilder != null)
            {
                ConnectionString = ConnectionStringBuilder.ToString();
            }
            if (string.IsNullOrEmpty(ConnectionString) && ConnectionStringBuilder != null)
            {
                ConnectionString = "Server=(local);Database=BindableCMS;trusted_connection=yes;";
            }

            try
            {
                // Validate the connection string
                SqlDatabaseHelper.ValidateConnectionStringOrThrow(ConnectionString);

                // Ensure the database exists - if not, create it
                UltraConsole.WriteHeading("Database upgrade");
                UltraConsole.WriteParagraph("  Connection string: {0}", ConnectionString);
                UltraConsole.WriteLine("Ensuring database exists...");
                var manager = new ApplicationDatabase(ConnectionString);
                if (!manager.DoesDatabaseExist())
                {
                    UltraConsole.WriteLine("Database does not exist. ");
                    return;
                }
                UltraConsole.WriteLine("Database exists.");

                UltraConsole.WriteHeading("Getting information about current setup...");
                using (UltraConsole.Indent())
                {
                    UltraConsole.WriteColumns("Database version:", manager.GetCurrentVersion().ToString());
                    UltraConsole.WriteColumns("Can be upgraded to:", manager.GetApplicationVersion().ToString());
                }

                // Display the result
                UltraConsole.WriteLine(ConsoleColor.Green, "Success");
            }
            catch (FormatException ex)
            {
                UltraConsole.WriteLine(ConsoleColor.Red, "Connection string was invalid: {0}", ex.Message);
                return;
            }
        }
예제 #32
0
        protected override void Execute(CommandExecutionContext context)
        {
            if (string.IsNullOrEmpty(ConnectionString) && ConnectionStringBuilder != null)
            {
                ConnectionString = ConnectionStringBuilder.ToString();
            }
            if (string.IsNullOrEmpty(ConnectionString) && ConnectionStringBuilder != null)
            {
                ConnectionString = "Server=(local);Database=BindableCMS;trusted_connection=yes;";
            }

            try
            {
                SqlDatabaseHelper.ValidateConnectionStringOrThrow(ConnectionString);

                UltraConsole.WriteHeading("Database upgrade");
                UltraConsole.WriteParagraph("  Connection string: {0}", ConnectionString);
                UltraConsole.WriteLine("Ensuring database exists...");
                var manager = new ApplicationDatabase(ConnectionString);
                if (!manager.DoesDatabaseExist())
                {
                    UltraConsole.WriteLine("Database does not exist. ");
                    if (!NoCreate)
                    {
                        UltraConsole.WriteLine("Creating database...");
                        manager.CreateDatabase();
                        UltraConsole.WriteLine("Database created");
                    }
                    else
                    {
                        return;
                    }
                }
                else
                {
                    UltraConsole.WriteLine("Database exists.");
                }

                UltraConsole.WriteHeading("Granting access to user '{0}'", UserAccount);
                manager.GrantAccessToLogin(UserAccount);

                UltraConsole.WriteHeading("Getting information about current setup...");
                using (UltraConsole.Indent())
                {
                    UltraConsole.WriteColumns("Current database version:", manager.GetCurrentVersion().ToString());
                    UltraConsole.WriteColumns("Will be upgraded to:", manager.GetApplicationVersion().ToString());
                }
                UltraConsole.WriteHeading("Performing upgrade...");
                var result = manager.PerformUpgrade();

                UltraConsole.WriteParagraph("Upgraded from {0} to {1}", result.OriginalVersion, result.UpgradedVersion);
                if (result.Scripts != null && result.Scripts.Count() > 0)
                {
                    UltraConsole.WriteHeading("The following scripts were executed:");
                    UltraConsole.WriteTable(
                        result.Scripts,
                        table => table.AddColumn("Version", script => script.VersionNumber)
                        );
                }

                if (result.Successful)
                {
                    UltraConsole.WriteLine(ConsoleColor.Green, "Database upgrade was successful.");
                }
                else
                {
                    UltraConsole.WriteLine(ConsoleColor.Red, "Database upgrade failed. Please see the list of scripts that were executed above and the error below.");
                    UltraConsole.WriteLine(result.Error.ToString());
                }
            }
            catch (FormatException ex)
            {
                UltraConsole.WriteLine(ConsoleColor.Red, "Connection string was invalid: {0}", ex.Message);
            }
        }