示例#1
0
        private bool UpgradeDatabase(string fromVersion)
        {
            var upgrader = new DatabaseUpgrader(connection);

            var currentVersion = fromVersion;

            while (upgrader.HasUpgrade(currentVersion))
            {
                var newVersion = upgrader.UpgradeFrom(currentVersion);
                Logger.Log(this, $"Successfully upgraded the database from version {currentVersion} to version {newVersion}", LogLevel.Info);
                currentVersion = newVersion;
            }

            metadata.Where(entry => entry.Key == "version").Set(entry => entry.Value, currentVersion).Update();

            if (currentVersion == Bot.DatabaseVersion)
            {
                Logger.Log(this, "Database upgrade completed.", LogLevel.Info);
                return(true);
            }
            else
            {
                Logger.Log(this, $"Unable to upgrade the database (current version: {currentVersion}) to match the bot (current version {Bot.DatabaseVersion})", LogLevel.Error);
                return(false);
            }
        }
示例#2
0
        public static void Main(string[] args)
        {
            _logger = log4net.LogManager.GetLogger(typeof (Program));

            var connectionString = ConfigurationManager.AppSettings["FluentNHibernateConnection"];

            var upgrader = new DatabaseUpgrader(
                //"server=(local);Initial Catalog=TeamTimeWarp;Integrated Security=True",
                connectionString,
                new EmbeddedScriptProvider(typeof(Program).Assembly)
            );

            var result = upgrader.PerformUpgrade();

            foreach (var script in result.Scripts)
                _logger.InfoFormat("executed script ({0})", script.Name);
                

            if (result.Successful)
            {
                _logger.Info("Success");
                Environment.Exit(0);
            }
            else
            {
                _logger.Error("Failed",result.Error);
                Environment.Exit(1);
            }
        }
示例#3
0
        private bool UpGradeDataBase()
        {
            string path = System.IO.Path.Combine(Environment.CurrentDirectory, "DbUpdate.sql");

            if (System.IO.File.Exists(path))
            {
                return(DatabaseUpgrader.ExeSQLFile(AppSettings.CurrentSetting.ConnectUri, path));
            }
            return(false);
        }
示例#4
0
        private void DeployDatabase()
        {
            var upgrader = new DatabaseUpgrader(
                "server=(local);Initial Catalog=TeamTimeWarp;Integrated Security=True",
                new EmbeddedScriptProvider(typeof(DbScripts).Assembly)
                );

            var result = upgrader.PerformUpgrade();

            if (!result.Successful)
            {
                throw result.Error;
            }
        }
示例#5
0
        private bool UpGradeDataBase()
        {
            bool   result = false;
            string path   = System.IO.Path.Combine(Environment.CurrentDirectory, "DbUpdate.sql");

            if (System.IO.File.Exists(path))
            {
                result = DatabaseUpgrader.ExeSQLFile(AppSettings.CurrentSetting.MasterParkConnect, path);
                if (!string.IsNullOrEmpty(AppSettings.CurrentSetting.StandbyParkConnect) &&
                    !DatabaseUpgrader.ExeSQLFile(AppSettings.CurrentSetting.StandbyParkConnect, path))
                {
                    result = false;
                }
            }
            return(result);
        }
示例#6
0
        public bool InitializeDatabase(string connectionString)
        {
            if (IsDatabaseBasePopulated(connectionString) == false)
            {
                using (TransactionScope scope = new TransactionScope())
                {
                    //Logging.Write("Applying database schema");
                    if (ApplyBaseDatabaseSchema(connectionString) == false)
                    {
                        return(false);
                    }

                    //Logging.Write("Applying database data");
                    if (ApplyBaseDatabaseData(connectionString) == false)
                    {
                        return(false);
                    }

                    scope.Complete();
                }
            }

            string path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase);

            path = path.Replace("file:\\", "");
            path = path + @"\db\Scripts";

            DirectoryInfo di = new DirectoryInfo(path);

            FileInfo[] sqlFiles = di.GetFiles("*.sql");

            var upgrader = new DatabaseUpgrader(connectionString, new FileEnumerationScriptProvider(sqlFiles));
            var result   = upgrader.PerformUpgrade(new MemoryLog());

            return(true);
        }
        private DatabaseUpgradeResult Upgrade(string connectionString, IScriptProvider scriptProvider, ILog log, IJournal journal, string schema)
        {
            var upgrader = new DatabaseUpgrader(
                connectionString,
                scriptProvider,
                journal,
                new SqlScriptExecutor(connectionString, log, schema));

            var result = upgrader.PerformUpgrade();
            return result;
        }
示例#8
0
 public void UpgradeTest()
 {
     DatabaseUpgrader.Upgrade();
 }
        private void Restore(object sender, DoWorkEventArgs args)
        {
            System.Data.LightDatamodel.DataFetcherNested con = new System.Data.LightDatamodel.DataFetcherNested(Program.DataConnection);
            Schedule s = con.Add <Schedule>();

            s.Task = con.Add <Task>();
            m_wrapper.UpdateSchedule(s);

            using (Library.Utility.TempFolder tf = new Duplicati.Library.Utility.TempFolder())
            {
                RestoreSetupTask            task    = new RestoreSetupTask(s, tf);
                Dictionary <string, string> options = new Dictionary <string, string>();
                string destination = task.GetConfiguration(options);
                Library.Main.Interface.RestoreControlFiles(destination, task.LocalPath, options);

                string filename = System.IO.Path.Combine(tf, System.IO.Path.GetFileName(Program.DatabasePath));
                if (System.IO.File.Exists(filename))
                {
                    //Connect to the downloaded database
                    using (System.Data.IDbConnection scon = (System.Data.IDbConnection)Activator.CreateInstance(SQLiteLoader.SQLiteConnectionType))
                    {
                        scon.ConnectionString = "Data Source=" + filename;

                        //Make sure encryption etc is handled correctly
                        Program.OpenDatabase(scon);

                        //Upgrade the database to the current version
                        DatabaseUpgrader.UpgradeDatabase(scon, filename);
                    }

                    //Shut down this connection
                    Program.LiveControl.Pause();
                    Program.DataConnection.ClearCache();
                    //We also need to remove any dirty objects as the ClearCache maintains those
                    foreach (System.Data.LightDatamodel.IDataClass o in Program.DataConnection.LocalCache.GetAllChanged())
                    {
                        Program.DataConnection.DiscardObject(o);
                    }
                    Program.DataConnection.Provider.Connection.Close();

                    //Replace the existing database with this one
                    System.IO.File.Copy(filename, Program.DatabasePath, true);

                    //Re-start the connection, using the new file
                    Program.DataConnection.Provider.Connection = (System.Data.IDbConnection)Activator.CreateInstance(SQLiteLoader.SQLiteConnectionType);
                    Program.DataConnection.Provider.Connection.ConnectionString = "Data Source=" + Program.DatabasePath;
                    Program.OpenDatabase(Program.DataConnection.Provider.Connection);

                    //Remove the downloaded database
                    try { System.IO.File.Delete(filename); }
                    catch { }
                }
                else
                {
                    throw new Exception(Strings.FinishedRestoreSetup.SetupFileMissingError);
                }

                NormalizeApplicationSettings();

                Program.Scheduler.Reschedule();
            }
        }
示例#10
0
        public static async Task Main(string[] args)
        {
            if (args.Length < 2)
            {
                Usage();
                return;
            }

            string paths = args[0];

            int.TryParse(args[1], out int startPacketIndex);

            // turn on log4net
            log4net.Config.XmlConfigurator.Configure();

            // catch all errors and log them
            AppDomain.CurrentDomain.UnhandledException += (sender, eventArgs) => Utility.LogException(eventArgs.ExceptionObject as Exception);

            // ignore all certificate validation issues
            ServicePointManager.ServerCertificateValidationCallback = (sender, cert, chain, sslPolicyErrors) => true;

            // console encoding will now be unicode
            Console.OutputEncoding = System.Text.Encoding.UTF8;

            // database init
            DatabasePool.Initialise();

            // configure fetcho
            await SetupConfiguration(paths);

            // upgrade the database
            DatabaseUpgrader.Upgrade();

            // buffers to connect the seperate tasks together
            BufferBlock <IEnumerable <QueueItem> > prioritisationBuffer = CreateBufferBlock(DefaultBufferBlockLimit);
            // really beef this buffers max size up since it takes for ever accumulate so we dont want to lose any
            BufferBlock <IEnumerable <QueueItem> > fetchQueueBuffer = CreateBufferBlock(DefaultBufferBlockLimit * 1000);
            //BufferBlock<IEnumerable<QueueItem>> requeueBuffer = CreateBufferBlock(DefaultBufferBlockLimit);
            ITargetBlock <IEnumerable <QueueItem> > outboxWriter   = CreateOutboxWriter();
            BufferBlock <IWebResourceWriter>        dataWriterPool = CreateDataWriterPool();

            // fetcho!
            var readLinko = new ReadLinko(prioritisationBuffer, startPacketIndex);
            var queueo    = new Queueo(prioritisationBuffer, fetchQueueBuffer, outboxWriter); // DataflowBlock.NullTarget<IEnumerable<QueueItem>>()
            var fetcho    = new Fetcho(fetchQueueBuffer, DataflowBlock.NullTarget <IEnumerable <QueueItem> >(), dataWriterPool);
            var stato     = new Stato("stats.csv", fetcho, queueo, readLinko);
            var controlo  = new Controlo(prioritisationBuffer, fetchQueueBuffer, dataWriterPool, () =>
            {
                readLinko.Shutdown();
                queueo.Shutdown();
                fetcho.Shutdown();
                stato.Shutdown();
            });
            //var requeueWriter = new BufferBlockObjectFileWriter<IEnumerable<QueueItem>>(cfg.DataSourcePath, "requeue", requeueBuffer);
            //var rejectsWriter = new BufferBlockObjectFileWriter<IEnumerable<QueueItem>>(cfg.DataSourcePath, "rejects", new NullTarget);

            // execute
            var tasks = new List <Task>();

            tasks.Add(stato.Process());
            tasks.Add(fetcho.Process());
            await Task.Delay(1000);

            tasks.Add(queueo.Process());
            await Task.Delay(1000);

            tasks.Add(readLinko.Process());
            tasks.Add(controlo.Process());

            await Task.WhenAll(tasks.ToArray()).ConfigureAwait(false);

            CloseAllWriters(dataWriterPool);
            DatabasePool.DestroyAll();
        }
示例#11
0
 public InitializeDatabaseCommand(Database database, DatabaseUpgrader upgrader, LocationModel locationModel)
 {
     this.database      = database;
     this.upgrader      = upgrader;
     this.locationModel = locationModel;
 }
        private void ConfigureReadyToUpgradeControls()
        {
            #region Database

            bool dbUpgradeOk = false;
            bool dbUpgradeNotNeeded = false;
            DatabaseUpgrader db = new DatabaseUpgrader(GspConfigSourcePath);

            lblReadyToUpgradeDbHeader.Text = String.Concat(db.DataProvider, " Database");

            if (db.IsUpgradeRequired)
            {
                if (db.IsAutoUpgradeSupported)
                {
                    string msg = Utils.HtmlEncode(String.Format(CultureInfo.InvariantCulture, Resources.GalleryServerPro.Installer_Upgrade_Db_Status_Upgrade_Reqd_Msg, db.GetDatabaseVersionString() ?? "<unknown>"));

                    if (db.DataProvider == ProviderDataStore.SQLite)
                    {
                        msg = msg.TrimEnd(new[] { '.' });
                        msg += " and migrated to the new SQL CE database format.";
                    }

                    lblReadyToUpgradeDbStatus.Text = msg;
                    lblReadyToUpgradeDbStatus.CssClass = "gsp_msgfriendly";
                    imgReadyToUpgradeDbStatus.ImageUrl = Utils.GetUrl("/images/go_14x14.png");

                    dbUpgradeOk = true;
                }
                else
                {
                    lblReadyToUpgradeDbStatus.Text = Utils.HtmlEncode(db.AutoUpgradeNotSupportedReason);
                    lblReadyToUpgradeDbStatus.CssClass = "gsp_msgwarning";
                    imgReadyToUpgradeDbStatus.ImageUrl = Utils.GetUrl("/images/error_16x16.png");
                    imgReadyToUpgradeDbStatus.Width = Unit.Pixel(16);
                    imgReadyToUpgradeDbStatus.Height = Unit.Pixel(16);
                }
            }
            else
            {
                // web.config has same settings as the source web.config. No update needed.
                lblReadyToUpgradeDbStatus.Text = Resources.GalleryServerPro.Installer_Upgrade_Db_Status_No_Upgrade_Reqd_Msg;
                lblReadyToUpgradeDbStatus.CssClass = String.Empty;
                imgReadyToUpgradeDbStatus.ImageUrl = Utils.GetUrl("/images/ok_16x16.png");
                imgReadyToUpgradeDbStatus.Width = Unit.Pixel(16);
                imgReadyToUpgradeDbStatus.Height = Unit.Pixel(16);
                dbUpgradeNotNeeded = true;
                dbUpgradeOk = true;
            }

            #endregion

            #region web.config

            bool webConfigUpdateOk = false;
            bool webConfigUpdateNotNeeded = false;
            // Check permissions on web.config
            WebConfigUpdater webCfg = null;
            try
            {
                webCfg = new WebConfigUpdater();
            }
            catch (FileNotFoundException ex)
            {
                lblReadyToUpgradeWebConfigStatus.Text = ex.Message;
                lblReadyToUpgradeWebConfigStatus.CssClass = "gsp_msgwarning";
                imgReadyToUpgradeWebConfigStatus.ImageUrl = Utils.GetUrl("/images/error_16x16.png");
            }

            if (webCfg != null)
            {
                if (webCfg.UpgradeRequired)
                {
                    if (webCfg.IsWritable)
                    {
                        // An update is needed and we have the necessary write permission to update the file, so we are good to go!
                        string msg = Utils.HtmlEncode(Resources.GalleryServerPro.Installer_Upgrade_Config_Status_Upgrade_Msg);

                        if (DbUpgrader.DataProvider == ProviderDataStore.SQLite)
                        {
                            msg = "Update required: The data provider sections will be updated to use the new SQL CE providers and the cachingConfiguration section will be deleted.";
                        }

                        lblReadyToUpgradeWebConfigStatus.Text = msg;
                        lblReadyToUpgradeWebConfigStatus.CssClass = "gsp_msgfriendly";
                        imgReadyToUpgradeWebConfigStatus.ImageUrl = Utils.GetUrl("/images/go_14x14.png");
                        webConfigUpdateOk = true;
                    }
                    else
                    {
                        // Web.config file needs updating, but installer doesn't have the required write permission.
                        lblReadyToUpgradeWebConfigStatus.Text = String.Format(CultureInfo.InvariantCulture, Resources.GalleryServerPro.Installer_Upgrade_ReadyToUpgrade_Config_Status_No_Perm_Msg, WebConfigPath);
                        lblReadyToUpgradeWebConfigStatus.CssClass = "gsp_msgwarning";
                        imgReadyToUpgradeWebConfigStatus.ImageUrl = Utils.GetUrl("/images/error_16x16.png");
                        imgReadyToUpgradeWebConfigStatus.Width = Unit.Pixel(16);
                        imgReadyToUpgradeWebConfigStatus.Height = Unit.Pixel(16);
                    }
                }
                else
                {
                    // web.config has same settings as the source web.config. The only update to do is delete the cachingConfiguration section.
                    lblReadyToUpgradeWebConfigStatus.Text = Resources.GalleryServerPro.Installer_Upgrade_WebConfig_Imported_Items1;
                    lblReadyToUpgradeWebConfigStatus.CssClass = "gsp_msgfriendly";
                    imgReadyToUpgradeWebConfigStatus.ImageUrl = Utils.GetUrl("/images/go_14x14.png");
                    webConfigUpdateNotNeeded = true;
                    webConfigUpdateOk = true;
                }
            }

            #endregion

            #region galleryserverpro.config

            bool gspConfigOk = false;
            bool gspConfigUpgradeNotNeeded = false;
            if (db.GetDatabaseVersion() <= GalleryDataSchemaVersion.V2_3_3421)
            {
                // Check permissions on galleryserverpro.config
                GspConfigImporter gspCfg = null;
                try
                {
                    gspCfg = new GspConfigImporter(GspConfigSourcePath, DbUpgrader);
                }
                catch (FileNotFoundException)
                {
                    lblReadyToUpgradeGspConfigStatus.Text = String.Format(CultureInfo.InvariantCulture, Resources.GalleryServerPro.Installer_Upgrade_ReadyToUpgrade_GspConfigNotFound, GspConfigSourcePath);
                    lblReadyToUpgradeGspConfigStatus.CssClass = "gsp_msgwarning";
                    imgReadyToUpgradeGspConfigStatus.ImageUrl = Utils.GetUrl("/images/error_16x16.png");
                    imgReadyToUpgradeGspConfigStatus.Width = Unit.Pixel(16);
                    imgReadyToUpgradeGspConfigStatus.Height = Unit.Pixel(16);
                }

                if (gspCfg != null)
                {
                    lblReadyToUpgradeGspConfigStatus.Text = String.Format(CultureInfo.InvariantCulture, Resources.GalleryServerPro.Installer_Upgrade_ReadyToUpgrade_Config_Status_OK_Msg, GspConfigSourcePath);
                    lblReadyToUpgradeGspConfigStatus.CssClass = "gsp_msgfriendly";
                    imgReadyToUpgradeGspConfigStatus.ImageUrl = Utils.GetUrl("/images/go_14x14.png");
                    gspConfigOk = true;
                }
            }
            else
            {
                lblReadyToUpgradeGspConfigStatus.Text = "Not needed: Version 2.4 and higher does not use galleryserverpro.config.";
                lblReadyToUpgradeGspConfigStatus.CssClass = "";
                imgReadyToUpgradeGspConfigStatus.ImageUrl = Utils.GetUrl("/images/ok_16x16.png");
                imgReadyToUpgradeGspConfigStatus.Width = Unit.Pixel(16);
                imgReadyToUpgradeGspConfigStatus.Height = Unit.Pixel(16);
                gspConfigUpgradeNotNeeded = true;
                gspConfigOk = true;
            }

            #endregion

            if (dbUpgradeNotNeeded && webConfigUpdateNotNeeded && gspConfigUpgradeNotNeeded)
            {
                // No updates are needed.
                lblReadyToUpgradeHdrMsg.Text = "No Update Needed";
                lblReadyToUpgradeDetail1Msg.Text = String.Format(CultureInfo.InvariantCulture, "The gallery is already up to date. <a href='{0}'>Go to your gallery</a>", Utils.GetCurrentPageUrl());
                btnNext.Enabled = false;
                imgReadyToUpgradeStatus.ImageUrl = Utils.GetUrl("/images/ok_26x26.png");
                imgReadyToUpgradeStatus.Width = Unit.Pixel(26);
                imgReadyToUpgradeStatus.Height = Unit.Pixel(26);

                DeleteInstallAndUpgradeFileTriggers();
            }
            else if (dbUpgradeOk && webConfigUpdateOk && gspConfigOk)
            {
                // Show the summary text that we are ready for the upgrade.
                lblReadyToUpgradeHdrMsg.Text = Resources.GalleryServerPro.Installer_Upgrade_ReadyToUpgrade_Hdr;
                lblReadyToUpgradeDetail1Msg.Text = Resources.GalleryServerPro.Installer_Upgrade_ReadyToUpgrade_OK_Dtl1;
                imgReadyToUpgradeStatus.ImageUrl = Utils.GetUrl("/images/ok_26x26.png");
                imgReadyToUpgradeStatus.Width = Unit.Pixel(26);
                imgReadyToUpgradeStatus.Height = Unit.Pixel(26);
            }
            else
            {
                // Show the summary text that something is wrong and we can't proceed.
                lblReadyToUpgradeHdrMsg.Text = Resources.GalleryServerPro.Installer_Upgrade_ReadyToUpgrade_Cannot_Upgrade_Hdr;
                lblReadyToUpgradeDetail1Msg.Text = Resources.GalleryServerPro.Installer_Upgrade_ReadyToUpgrade_CannotUpgrade_Dtl1;

                if ((webCfg != null) && (!webCfg.IsWritable))
                {
                    lblReadyToUpgradeDetail2Msg.Text = Resources.GalleryServerPro.Installer_Upgrade_ReadyToUpgrade_No_Perm_Dtl1;
                }

                lbTryAgain.Visible = true;
                btnNext.Enabled = false;
                imgReadyToUpgradeStatus.ImageUrl = Utils.GetUrl("/images/warning_32x32.png");
                imgReadyToUpgradeStatus.Width = Unit.Pixel(32);
                imgReadyToUpgradeStatus.Height = Unit.Pixel(32);
            }
        }
            /// <summary>
            /// Initializes a new instance of the <see cref="GspConfigImporter"/> class.
            /// </summary>
            /// <param name="sourceConfigPath">The full path to the galleryserverpro.config file containing the source data.
            /// 	Ex: C:\inetpub\wwwroot\gallery\gs\config\galleryserverpro_old.config</param>
            /// <param name="databaseUpgrader"></param>
            public GspConfigImporter(string sourceConfigPath, DatabaseUpgrader databaseUpgrader)
            {
                this._sourceConfigPath = sourceConfigPath;
                this._dbUpgrader = databaseUpgrader;

                ExtractConfigData();
            }
        /// <summary>
        /// Upgrade the database, returning <c>true</c> if the upgrade is successful and <c>false</c> if not. If any exceptions 
        /// occur, swallow them and grab the error message and callstack in member variables.
        /// </summary>
        /// <returns>Returns <c>true</c> if the upgrade is successful and <c>false</c> if not.</returns>
        private bool UpgradeDatabase()
        {
            try
            {
                DatabaseUpgrader dbUpgrader = new DatabaseUpgrader(GspConfigSourcePath);

                DatabaseUpgradeRequired = dbUpgrader.IsUpgradeRequired;

                dbUpgrader.Upgrade();

                DatabaseSuccessfullyUpgraded = true;
            }
            catch (Exception ex)
            {

                DbUpgradeErrorMsg = GetExceptionDetails(ex);

                if (ex.Data.Contains(SqlServerHelper.ExceptionDataId))
                {
                    DbUpgradeErrorSql = ex.Data[SqlServerHelper.ExceptionDataId].ToString();
                }
                if ((ex.InnerException != null) && (ex.InnerException.Data.Contains(SqlServerHelper.ExceptionDataId)))
                {
                    DbUpgradeErrorSql = ex.InnerException.Data[SqlServerHelper.ExceptionDataId].ToString();
                }
            }

            return DatabaseSuccessfullyUpgraded;
        }
示例#15
0
		public bool InitializeDatabase(string connectionString)
		{
			if (IsDatabaseBasePopulated(connectionString) == false)
			{
				using (TransactionScope scope = new TransactionScope())
				{

					//Logging.Write("Applying database schema");
					if (ApplyBaseDatabaseSchema(connectionString) == false)
						return false;

					//Logging.Write("Applying database data");
					if (ApplyBaseDatabaseData(connectionString) == false)
						return false;

					scope.Complete();
				}
			}

			string path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase);
			path = path.Replace("file:\\", "");
			path = path + @"\db\Scripts";

			DirectoryInfo di = new DirectoryInfo(path);
			FileInfo[] sqlFiles = di.GetFiles("*.sql");

			var upgrader = new DatabaseUpgrader(connectionString, new FileEnumerationScriptProvider(sqlFiles));
			var result = upgrader.PerformUpgrade(new MemoryLog());

			return true;
		}