Example #1
0
        public void Backup(BackupParameters parameters)
        {
            var server = new Server(parameters.Server);
            try
            {
                server.ConnectionContext.LoginSecure = true;
                server.ConnectionContext.Connect();

                var backup = new Backup
                {
                    Action = BackupActionType.Database,
                    Database = parameters.DatabaseName
                };

                var backupPath = GenerateBackupPath(parameters);
                Logger.WriteLine("Backing up to {0}", backupPath);
                backup.Devices.AddDevice(backupPath, DeviceType.File);
                backup.BackupSetName = string.Format("{0} backup", parameters.DatabaseName);
                backup.PercentComplete += HandlePercentComplete;
                backup.Complete += HandleComplete;
                Logger.WriteLine("Running backup...");
                backup.SqlBackup(server);
            }
            finally
            {
                if (server.ConnectionContext.IsOpen)
                {
                    Logger.Write("Closing connection...");
                    server.ConnectionContext.Disconnect();
                    Logger.WriteLine("OK");
                }
            }
        }
Example #2
0
        // TODO: Abstract parameters into class.
        public static void BackupDatabase(Server server, String databaseName, String destinationPath, int completionCallbackInterval, Action<int, String> completionCallback, Action<SqlError> errorCallback)
        {
            // TODO: Expose as parameter.
            String backupSetName = String.Format("Backup_{0}", databaseName);

            // TODO: Expose as parameter.
            String backupSetDescription = "User-requested backup for Self-Service Tools";

            // Define a Backup object variable.
            var bk = new Backup
            {
                Action = BackupActionType.Database,
                BackupSetDescription = backupSetDescription,
                BackupSetName = backupSetName,
                Database = databaseName,
                Incremental = false, // This is a full database backup.
                ExpirationDate = DateTime.UtcNow.AddYears(-1), // Already expired.  Allows us to overwrite them easily with subsequent backups.
                LogTruncation = BackupTruncateLogType.NoTruncate, // I'm not sure what the implications of truncating the log are, so don't do that.
                CopyOnly = true,
                PercentCompleteNotification = completionCallbackInterval,
                Initialize = true,
            };

            // We're going to save this backup as a file.
            String backupDeviceName = String.Format(destinationPath, databaseName);
            var bdi = new BackupDeviceItem(backupDeviceName, DeviceType.File);
            bk.Devices.Add(bdi);

            //bk.Information += (sender, args) => { bk.Devices.Remove(bdi); errorCallback(args.Error); };
            bk.PercentComplete += (sender, args) => { bk.Devices.Remove(bdi); completionCallback(args.Percent, args.Message); };

            bk.SqlBackup(server);
        }
        //通过描述分页得到客户页面
        public List<Backup> GetBackupByDescriptionByPage(MyPage page, string BackupDescription)
        {
            BackupDescription = "%" + BackupDescription + "%";
            page.CountPerPage = 10;
            page.WholePage = (int)data.getBackupByDescriptionPageCount(page.CountPerPage, BackupDescription);
            var table = data.getBackupByDescriptionByPage(page.CurrentPage, page.CountPerPage, BackupDescription);
            List<Backup> backups = new List<Backup>();

            foreach (var col in table)
            {

                Backup backup = new Backup();
                backup.BackupId = col.backup_set_id;
                backup.BackupSize = (decimal)col.backup_size;
                backup.BackupTime = (DateTime)col.backup_finish_date;
                backup.Description = col.description;
                backup.Name = col.name;
                backup.Version = (int)col.database_version;
                backup.CreationTime = (DateTime)col.database_creation_date;
                backups.Add(backup);

            }

            return backups;
        }
Example #4
0
        public void BackupDataBase(string destinationPath, Action<int> percentCompleteCallback, Action completeCallback)
        {
            var server = GetDbServer();

            var backup = new Backup();
            backup.Action = BackupActionType.Database;
            backup.Database = this.DatabaseName;
            backup.Devices.Add(new BackupDeviceItem(GetFileName(destinationPath, this.DatabaseName, ".bak"), DeviceType.File));
            backup.Initialize = true;
            backup.Checksum = true;
            backup.ContinueAfterError = true;
            backup.Incremental = false;
            backup.PercentCompleteNotification = 1;
            backup.LogTruncation = BackupTruncateLogType.Truncate;

            backup.Complete += (s, e) =>
            {
                if (completeCallback != null)
                {
                    completeCallback();
                }
            };

            backup.PercentComplete += (s, e) =>
            {
                if (percentCompleteCallback != null)
                {
                    percentCompleteCallback(e.Percent);
                }
            };

            backup.SqlBackupAsync(server);
        }
Example #5
0
 /// <summary>
 /// 备份数据库
 /// </summary>
 /// <param name="serverName">数据实例名</param>
 /// <param name="userName">用户</param>
 /// <param name="password">密码</param>
 /// <param name="databaseName">库名</param>
 /// <param name="path">备份路径</param>
 public static void CompressDatabase(string serverName,string userName,string password,string databaseName,string path)
 {
     Backup oBackup = new Backup();
     SQLServer oSQLServer = new SQLServer();
     try
     {
         oSQLServer.LoginSecure = false;
         oSQLServer.Connect(serverName, userName, password);
         oBackup.Action = SQLDMO_BACKUP_TYPE.SQLDMOBackup_Database;
         oBackup.Database = databaseName;
         oBackup.Files = path;
         oBackup.BackupSetName = databaseName;
         oBackup.BackupSetDescription = string.Format("{0} {1}", databaseName, DateTime.Now);
         oBackup.Initialize = true;
         oBackup.SQLBackup(oSQLServer);
     }
     catch
     {
         throw;
     }
     finally
     {
         oSQLServer.DisConnect();
     }
 }
Example #6
0
 /// <summary>
 /// Adds a file to the archive
 /// </summary>
 /// <param name="entry">
 /// The backup metadata for the file
 /// </param>
 /// <param name="stream">
 /// The file stream to add to the archive
 /// </param>
 public void Backup(Backup.Entry entry, Stream stream)
 {
     // if we are not currently uploading a vault archive,
      // then attach a new uploader and create a blob for it
      if (this.uploader == null)
      {
     this.uploader = new GlacierUploader(
        this.archive.Glacier,
        this.archive.Vault
     );
     this.archive.BackupIndex.InsertBlob(
        new Backup.Blob()
        {
           Name = this.uploader.UploadID
        }
     );
      }
      // fetch the upload blob and sync it with the uploader's offset
      var blob = this.archive.BackupIndex.LookupBlob(this.uploader.UploadID);
      if (blob.Length != this.uploader.Length)
     blob.Length = this.uploader.Resync(blob.Length);
      // upload the incoming stream and update the backup entry
      var offset = this.uploader.Length;
      var length = this.uploader.Upload(stream);
      entry.Blob = blob;
      entry.Offset = offset;
      entry.Length = length;
 }
 private void BackupDataBase(string databaseName)
 {
     SplashScreenManager.ShowForm(typeof(F_wait_form));
     var destinationPath = "HRM_PVMD_v" + DateTime.Now.Year + "." + DateTime.Now.Month + "." + DateTime.Now.Day + "." + DateTime.Now.Hour + "h." + DateTime.Now.Minute + "p.bak";
     Server myServer = GetServer();
     Backup backup = new Backup();
     backup.Action = BackupActionType.Database;
     backup.Database = databaseName;
     // destinationPath = System.IO.Path.Combine(destinationPath, databaseName);
     backup.Devices.Add(new BackupDeviceItem(destinationPath, DeviceType.File));
     backup.Initialize = true;
     backup.Checksum = true;
     backup.ContinueAfterError = true;
     backup.Incremental = false;
     backup.LogTruncation = BackupTruncateLogType.Truncate;
     // Perform backup.
     US_HT_BACKUP_HISTORY v_us = new US_HT_BACKUP_HISTORY();
     try
     {
         v_us.strNGUOI_BACKUP = CAppContext_201.getCurrentUserName();
         v_us.datNGAY_BACKUP = DateTime.Now.Date;
         v_us.strNOI_LUU = destinationPath;
         v_us.Insert();
         backup.SqlBackup(myServer);
     }
     catch(Exception)
     {
         throw;
     }
     finally
     {
         SplashScreenManager.CloseForm();
     }
     XtraMessageBox.Show("Sao lưu File : " + destinationPath + " thành công!", "THÔNG BÁO", MessageBoxButtons.OK, MessageBoxIcon.Information);
 }
 public void BackupDataBase(string databaseName, string destinationPath)
 {
     Server srv = GetServer();
     Backup backup = new Backup
     {
         Action = BackupActionType.Database,
         Database = databaseName
     };
     try
     {
         destinationPath = Path.Combine(destinationPath, databaseName + ".bak");
         backup.Devices.Add(new BackupDeviceItem(destinationPath, DeviceType.File));
         backup.Initialize = true;
         backup.Checksum = true;
         backup.ContinueAfterError = true;
         backup.Incremental = false;
         backup.LogTruncation = BackupTruncateLogType.Truncate;
         backup.PercentCompleteNotification = 5;
         backup.PercentComplete += Progreso_PercentComplete;
         backup.Complete += Progreso_Complete;
         backup.SqlBackup(srv);
     }
     catch (SqlException sqlex)
     {
         XtraMessageBox.Show(sqlex.Message, "Respaldando Base de Datos", MessageBoxButtons.OK, MessageBoxIcon.Warning);
     }
     catch (Exception ex)
     {
         XtraMessageBox.Show(ex.Message, "Error al Respaldar", MessageBoxButtons.OK, MessageBoxIcon.Error);
     }
 }
Example #9
0
        private void button1_Click(object sender, EventArgs e)
        {
            DataTable dataTable = SmoApplication.EnumAvailableSqlServers(true);

            dataGridView2.DataSource = dataTable;

            Server srv = new Server(@".\SQLEXPRESS");
            if (srv == null)
            {
                Console.WriteLine(srv.Information.Version);
                Database db = srv.Databases["AssociGestorDb"];
                Backup bk = new Backup();
                bk.Action = BackupActionType.Database;
                bk.BackupSetDescription = "Full backup of AssociGestorDb";
                bk.BackupSetName = "AssociGestorDb Backup";
                bk.Database = "AssociGestorDb";
                BackupDeviceItem bdi = new BackupDeviceItem(@"c:\temp\AssociGestorDb" + DateTime.Now.ToString("_yyyyMMdd"), DeviceType.File);
                bk.Devices.Add(bdi);
                bk.Incremental = false;
                bk.LogTruncation = BackupTruncateLogType.Truncate;
                bk.SqlBackup(srv);
            }
            else
            {
                MessageBox.Show("No server found.");
            }
        }
Example #10
0
        public Task<BackupResult> CreateBackup(string backupFilePath, string instanceName, string database, string username, string password)
        {
            return new Task<BackupResult>(() =>
            {
                var filePath = string.Format("{0}\\{1}_{2}.bak", backupFilePath, DateTime.Now.ToString("yyyyMMdd_HHmm"), database);

                var backupDeviceItem = new BackupDeviceItem(filePath, DeviceType.File);
                var backup = new Backup
                {
                    Database = database,
                    Initialize = true,
                    Incremental = false,
                    CopyOnly = true,
                    Action = BackupActionType.Database,
                };

                backup.Devices.Add(backupDeviceItem);

                var serverConnection = new ServerConnection(instanceName, username, password);
                var server = new Server(serverConnection);

                backup.PercentComplete += PercentComplete;

                backup.SqlBackup(server);

                return new BackupResult(filePath, BackupType.Sql);
            });
        }
Example #11
0
        public void BackupDatabase(String databaseName, String userName, String password, String serverName, String destinationPath)
        {
            Backup sqlBackup = new Backup();
            
            sqlBackup.Action = BackupActionType.Database;
            sqlBackup.BackupSetDescription = "ArchiveDataBase:" + DateTime.Now.ToShortDateString();
            sqlBackup.BackupSetName = "Archive";

            sqlBackup.Database = databaseName;

            BackupDeviceItem deviceItem = new BackupDeviceItem(destinationPath, DeviceType.File);
            ServerConnection connection = new ServerConnection(serverName, userName, password);
            Server sqlServer = new Server(connection);
            
            Database db = sqlServer.Databases[databaseName];
            
            sqlBackup.Initialize = true;
            sqlBackup.Checksum = true;
            sqlBackup.ContinueAfterError = true;
            
            sqlBackup.Devices.Add(deviceItem);
            sqlBackup.Incremental = false;

            sqlBackup.ExpirationDate = DateTime.Now.AddDays(3);
            sqlBackup.LogTruncation = BackupTruncateLogType.Truncate;

            sqlBackup.FormatMedia = false;

            sqlBackup.SqlBackup(sqlServer);
        }
Example #12
0
 /// <summary>
 /// Performs a differencing operation
 /// </summary>
 /// <param name="node">
 /// The root backup node to difference
 /// </param>
 /// <returns>
 /// The list of differences between the root node and the file system
 /// </returns>
 public IEnumerable<DiffResult> Enumerate(Backup.Node node)
 {
     var path = (IO.Path)node.Name;
      var mapPath = IO.Path.Empty;
      if (this.Request.RootPathMap.TryGetValue(path, out mapPath))
     path = mapPath;
      return DiffPathIndex(path, node).Concat(DiffIndexPath(node, path));
 }
        public BackupViewModel(Backup backup, RepositoryManager repositoryManager, IDialogService dialogService)
        {
            this.backup = backup;
            this.repositoryManager = repositoryManager;
            this.dialogService = dialogService;

            BackupCommand = new RelayCommand(CreateBackup);
            RestoreCommand = new RelayCommand(RestoreBackup);
        }
        public ActionResult Backups_Destroy(Backup backup)
        {
            System.IO.File.Delete(Path.Combine(this.Server.MapPath("~/App_Data/Backups"), this.backupsService.GetFileName(backup.Id)));
            this.backupsService.Delete(backup.Id);

            var routeValues = this.GridRouteValues();

            return this.RedirectToAction("Index", routeValues);
        }
        public void Patch(TimeWarp timeQuadrant)
        {
            if (mBackup != null) {
                throw new InvalidOperationException("Patcher is already in use.");
            }
            ScreenSafeUISlideTab tab = timeQuadrant.timeQuadrantTab;
            mBackup = new Backup() {
                TimeQuadrant = timeQuadrant,
                Texture = tab.renderer.material.mainTexture,
                Scale = tab.transform.localScale,
                Center = ((BoxCollider) tab.collider).center,
                ExpandedPosition = tab.expandedPos,
                CollapsedPosition = tab.collapsedPos,
            };

            List<Transform> children = new List<Transform>();

            foreach (Transform child in tab.transform) {
                children.Add(child);
            }

            foreach (Transform child in children) {
                child.parent = tab.transform.parent;
            }

            // Set the new texture
            Texture2D newTexture;
            RTUtil.LoadImage(out newTexture, "texTimeQuadrant.png");
            tab.renderer.material.mainTexture = newTexture;

            // Apply new scale, positions
            tab.transform.localScale = new Vector3(tab.transform.localScale.x,
                                                   tab.transform.localScale.y,
                                                   tab.transform.localScale.z *
                                                   1.3970588235294117647058823529412f);
            tab.collapsedPos += new Vector3(0, -0.013f, 0);
            tab.expandedPos += new Vector3(0, -0.013f, 0);
            foreach (Transform child in children) {
                child.localPosition += new Vector3(0, 0.013f, 0);
            }
            tab.Expand();

            foreach (Transform child in children) {
                child.parent = tab.transform;
            }

            ((BoxCollider) tab.collider).center += new Vector3(0, 0, -0.37f);

            ScreenSafeGUIText text =
                tab.transform.FindChild("MET timer").GetComponent<ScreenSafeGUIText>();
            mTextStyle = text.textStyle;
            mTextStyle.fontSize = (int)(text.textSize * ScreenSafeUI.PixelRatio);

            RenderingManager.AddToPostDrawQueue(0, Draw);
        }
Example #16
0
        /// <summary>
        /// Method to Backup a Database
        /// </summary>
        public void CreateDBBackup()
        {
            Server myServer = new Server(CF.Server);

            //Using SQL Server authentication
            myServer.ConnectionContext.LoginSecure = false;
            myServer.ConnectionContext.Login = CF.UserName;
            myServer.ConnectionContext.Password = CF.Password;

            // Loop through Databases, when DBName is found perform backup
            foreach (Database myDatabase in myServer.Databases)
            {
                Console.WriteLine(myDatabase.Name);

                if(myDatabase.Name.Equals(CF.DBName))
                {

                    Console.Write("Found DB!" + myDatabase.Name);

                    Backup DBFull = new Backup();

                    // Specify backup of Database
                    DBFull.Action = BackupActionType.Database;

                    // Set Name of Database to backup
                    DBFull.Database = myDatabase.Name;

                    // Save Backup to File
                    DBFull.Devices.AddDevice(CF.DevicePath, DeviceType.File);

                    // Set Backup Set Name
                    DBFull.BackupSetName = CF.BackUpName;

                    // Set Backup Description
                    DBFull.BackupSetDescription = CF.BackUpDescription;

                    // Initialize to False, appends backup as last backup on media.
                    DBFull.Initialize = false;

                    // Will write to console.
                    DBFull.PercentComplete += CompletionStatusInPercent;
                    DBFull.Complete += Backup_Completed;

                   // Take Backup
                    DBFull.SqlBackup(myServer);

                    return;

                }
            }

            // Close Connection
            if (myServer.ConnectionContext.IsOpen)
                myServer.ConnectionContext.Disconnect();
        }
Example #17
0
        public void Execute(IJobExecutionContext jobContext)
        {
            try
            {
                var backupDirectory = Configuration.Backup.Directory.EndsWith(@"\") ?
                        Configuration.Backup.Directory.TrimEnd('\\') :
                        Configuration.Backup.Directory;

                if (!Directory.Exists(backupDirectory))
                    Directory.CreateDirectory(backupDirectory);

                BackupRequest request;
                using (var context = new DatabaseContext())
                {
                    context.BackupRequests.TryGetNext(out request);
                }

                if (request != null)
                {
                    var backupName = string.Format(@"{0}\{1}-{2}-{3}.bak", backupDirectory, Configuration.Backup.FileName, request.Schedule.ToString(), DateTime.UtcNow.ToString("yyyy-MM-dd-H-mm"));

                    ConsoleHelper.WriteLine(ConsoleColor.Green, string.Format("Backup Job: Starting backup '{0}'", backupName));

                    var backup = new Backup();
                    backup.Action = BackupActionType.Database;
                    backup.Database = Configuration.Backup.DatabaseName;
                    backup.Devices.AddDevice(backupName, DeviceType.File);
                    backup.BackupSetName = "TeamMashup Backup";
                    backup.BackupSetDescription = "TeamMashup Backup";
                    backup.ExpirationDate = DateTime.UtcNow.AddMonths(1);

                    var server = new Server(Configuration.Backup.ServerName);
                    backup.SqlBackup(server);

                    using (var context = new DatabaseContext())
                    {
                        var storedRequest = context.BackupRequests.GetById(request.Id);
                        storedRequest.State = BackupState.Completed;
                        storedRequest.Path = backupName;
                        context.SaveChanges();
                    }

                    Console.WriteLine("Backup Job: Successfuly finished backup '{0}'", backupName);
                }
                else
                {
                    Console.WriteLine("Backup Job: No backup requests found.");
                }
            }
            catch (Exception ex)
            {
                LogHelper.Error(ex);
                ConsoleHelper.WriteLine(ConsoleColor.Magenta, "Backup Job: " + ex.Message);
            }
        }
        public static void BackupDatabase(string databaseName, string backupName, string serverName = Server) {
            Server server = string.IsNullOrEmpty(serverName) ? new Server() : new Server(serverName);
            var backup = new Backup {
                Database = databaseName,
                Action = BackupActionType.Database,
                Initialize = true
            };

            backup.Devices.AddDevice(backupName + ".bak", DeviceType.File);
            backup.SqlBackup(server);
        }
        public bool BackupDataBase(Configuracoes config)
        {
            #region Declaração

              if (config.SqlServer != null)
              {

            Backup bkpDataBase = null;
            string data = DateTime.Now.Date.ToString("dd-mm-yyyy");
            BackupDeviceItem bkpDeviceItem = null;
            string fileName = string.Empty;
            string path = string.Empty;
              #endregion

              #region Implementação

            fileName = "Backup_" + data + ".bak";

            bkpDataBase = new Backup();
            bkpDeviceItem = new BackupDeviceItem();

            bkpDataBase.Action = BackupActionType.Database;
            bkpDataBase.Database = config.Database;

            path = "C:\\Sistema\\Backup\\";

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

            path = path + fileName.Replace(" ","_").Replace("/","_").Replace(":","_");

            if (!File.Exists(path))
            {
              File.CreateText(path);
            }

            bkpDataBase.Incremental = false;
            bkpDataBase.BackupSetName = fileName;

            bkpDataBase.Checksum = true;
            bkpDataBase.Devices.Add(new BackupDeviceItem(path, DeviceType.File));

            bkpDataBase.SqlBackup(config.SqlServer);

            return true;

              }
              else
            return false;

              #endregion
        }
Example #20
0
 public static void BackupDatabase(string backUpFile)
 {
     ServerConnection con = new ServerConnection(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=D:\works\Work\.Net\Divan\Divan\bin\Debug\Database.mdf;Integrated Security=True;Connect Timeout=30");
     Server server = new Server(con);
     Backup source = new Backup();
     source.Action = BackupActionType.Database;
     source.Database = "divan";
     BackupDeviceItem destination = new BackupDeviceItem(backUpFile, DeviceType.File);
     source.Devices.Add(destination);
     source.SqlBackup(server);
     con.Disconnect();
 }
 public static void BackupDatabase(string backUpFile)
 {
     ServerConnection con = new ServerConnection(Constants.DatabaseServerName);
     Server server = new Server(con);
     Backup source = new Backup();
     source.Action = BackupActionType.Database;
     source.Database = Constants.DatabaseName;
     BackupDeviceItem destination = new BackupDeviceItem(backUpFile, DeviceType.File);
     source.Devices.Add(destination);
     source.SqlBackup(server);
     con.Disconnect();
 }
        public void Backup(string BackupPath)
        {
            BackupDeviceItem d = new BackupDeviceItem(BackupPath, DeviceType.File);

            Backup b = new Backup() {
                Database = to,
                CompressionOption = BackupCompressionOptions.Default,
                Initialize = true,
                Action = BackupActionType.Database,
                Incremental = false
            };
            b.Devices.Add(d);
            b.SqlBackup(smoServer);
        }
Example #23
0
        public static void BackupDatabase(string backUpFile)
        {
            ServerConnection con = new ServerConnection(@"YasarMalik-PC\SQLEXPRESS");

            
            Server server = new Server(con);
            Backup source = new Backup();
            source.Action = BackupActionType.Database;
            source.Database = "AQSMS";
            BackupDeviceItem destination = new BackupDeviceItem(backUpFile, DeviceType.File);
            source.Devices.Add(destination);
            source.SqlBackup(server);
            con.Disconnect();
        }
 public static void CreateDbBackup(string dbName, string backupFileName, string connectionString = null, SqlConnectionStringBuilder csBuilder = null)
 {
     var backupDb = new Backup {
         Action = BackupActionType.Database,
         Database = dbName,
         CompressionOption = BackupCompressionOptions.On,
         BackupSetName = String.Format("backup for {0}", dbName),
         Devices = { new BackupDeviceItem(backupFileName, DeviceType.File) }
     };
     using (var connection = new SqlConnection(connectionString ?? csBuilder.ConnectionString)) {
         connection.Open();
         var server = new Server(new ServerConnection(connection));
         backupDb.SqlBackup(server);
     }
 }
Example #25
0
        static void Main4(string[] args)
        {
            string templateDbName = "MyTestDB";
            string templateServer = "localhost";
            Server server = new Server(templateServer);
            Database templateDb = server.Databases[templateDbName];

            //Backup backup = new Backup();
            //backup.SqlBackup

            Backup backup = new Backup();
            backup.Action = BackupActionType.Database;
            backup.Database = templateDbName;
            string backUpFilePath = @"D:\myDb20160504.bak";
            BackupDeviceItem backupDeviceItem = new BackupDeviceItem(backUpFilePath, DeviceType.File);
            backup.Devices.Add(backupDeviceItem);
            backup.Initialize = true;

            Console.WriteLine("begin back。。。");

            String script = backup.Script(server);
            backup.SqlBackup(server);

            string sqlFilePath = @"D:\sqlScript_backUp.sql";
            using (StreamWriter sw = new StreamWriter(sqlFilePath, true, Encoding.UTF8))
            {
                sw.WriteLine(script);
                sw.WriteLine("GO");
            }

            //--------方式1-----------




            //--------方式2-----------



            Console.WriteLine("end。。。");


            Console.ReadKey();
        }
 public override void backup_database(string backup_path)
 {
     var sql_server = new Server(new ServerConnection(new SqlConnection(build_connection_string(server_name, database_name, connect_options))));
     sql_server.BackupDevices.Add(new BackupDevice(sql_server, database_name));
     var backupMgr = new Backup
                         {
                             Initialize = true,
                             BackupSetName = database_name
                         };
     if (sql_server_supports_backup_compression(sql_server)) //compression works only for SQL Server 2008 and newer
     {
         backupMgr.CompressionOption = BackupCompressionOptions.On;
         Log.bound_to(this).log_an_info_event_containing(" SQL Server 2008 or newer detected. Creating compressed backup.");
     }
     backupMgr.Devices.AddDevice(backup_path, DeviceType.File);
     backupMgr.Database = database_name;
     backupMgr.Action = BackupActionType.Database;
     backupMgr.SqlBackup(sql_server);
 }
Example #27
0
        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            Backup bkp = new Backup();
            try
            {
                FolderBrowserDialog fbd = new FolderBrowserDialog();
                if (fbd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    string PathtobackUp = fbd.SelectedPath.ToString();
                    string str2 = DateTime.Today.Date.ToString().Split(' ')[0];
                    string fileName = PathtobackUp + "BackUp.bak";
                    string databaseName = "LoanManagement.Domain.finalContext";

                bkp.Action = BackupActionType.Database;
                bkp.Database = databaseName;
                bkp.Devices.AddDevice(fileName, DeviceType.File);

                //bkp.Incremental = chkIncremental.Checked;
                //this.progressBar1.Value = 0;
                //this.progressBar1.Maximum = 100;
                //this.progressBar1.Value = 10;

                //bkp.PercentCompleteNotification = 10;
                //bkp.PercentComplete += new PercentCompleteEventHandler(ProgressEventHandler);
                //bkp.Incremental = true;
                Server srv = new Server("(localdb)\\v11.0");
                bkp.SqlBackup(srv);
                System.Windows.MessageBox.Show("Database was successfully backed up to: " + fileName, "Info");
                }

                
            }

            catch (Exception ex)
            {
                System.Windows.MessageBox.Show(ex.Message);
            }
            finally
            {
                //this.Cursor = Cursors.Default;
                //this.progressBar1.Value = 0;
            }
        }
        public void Backup()
        {
            EventLog.WriteEntry("SQLBackupService", "Starting backup...");
            string serverName = SqlBackup.Properties.Settings.Default.servername;
            string database = SqlBackup.Properties.Settings.Default.database;
            string filePath;

            Server srv = new Server(@serverName);
            if (SqlBackup.Properties.Settings.Default.filepath == "" || SqlBackup.Properties.Settings.Default.filepath == null)
            {
                filePath = srv.BackupDirectory;
            }
            else
            {
                filePath = SqlBackup.Properties.Settings.Default.filepath;
            }

            backup = new Backup();

            // specify what you want to backup
            backup.Action = BackupActionType.Database;

            // specify the name of the database
            backup.Database = database;

            // specify what kind of devides to use, in this example we are using the File Device
            backup.Devices.AddDevice(@filePath, DeviceType.File);
            backup.BackupSetName = SqlBackup.Properties.Settings.Default.backupsetname;
            backup.BackupSetDescription = SqlBackup.Properties.Settings.Default.backupsetdescription;

            // setting the expiration date
            backup.ExpirationDate = DateTime.Today.AddDays(SqlBackup.Properties.Settings.Default.expirationDays);

            // setting incremental backup
            backup.Incremental = SqlBackup.Properties.Settings.Default.incremental;

            // events called to show progress and when the backup finish
            backup.PercentComplete += CompletionStatusInPercent;
            backup.Complete += Backup_Completed;

            // start backup, this method is asynchronous
            backup.SqlBackup(srv);
        }
        public static void backup()
        {
            string caminho = System.IO.Directory.GetCurrentDirectory();

            caminho = caminho + @"\Backup";
            if (!System.IO.Directory.Exists(caminho))
            {
                System.IO.Directory.CreateDirectory(caminho);
            }

            var path = caminho + @"\SGA-" + System.DateTime.Now.ToString("dd-MM-yyy") + @".bkp";

            try
            {
                SqlConnection objConexao = new SqlConnection(ConfigurationManager.ConnectionStrings["sga"].ConnectionString);
                ServerConnection objServers = new ServerConnection(objConexao);

                Server objServer = new Server(objServers);
                objServer.ConnectionContext.Connect();
                string edition = objServer.Information.Edition;
                Microsoft.SqlServer.Management.Smo.Backup objBackup = new Backup();
                objBackup.Action = BackupActionType.Database;
                objBackup.Database = "sga";
                objBackup.MediaName = "FileSystem";

                BackupDeviceItem objDevice = new BackupDeviceItem();
                objDevice.DeviceType = DeviceType.File;
                objDevice.Name = path;
                objBackup.Checksum = true;
                objBackup.Incremental = false;
                objBackup.Devices.Add(objDevice);
                objBackup.Initialize = true;
                objBackup.SqlBackup(objServer);
                objBackup.Devices.Remove(objDevice);

            }
            catch (Exception err)
            {

                throw new Exception(err.Message);
            }
        }
Example #30
0
        // @"\\tranquillity-pc\Temp\"
        public static void MakeBackup(ServerMessageEventHandler onComplete, Guid id, int experimentNumber,
            string serverName, string dbName, string uncDir, string userName, string password)
        {
            var sc = new ServerConnection(serverName);
            sc.LoginSecure = false;
            sc.Login = userName;
            sc.Password = password;

            var srv = new Server(sc);
            var bkp = new Backup();

            bkp.Action = BackupActionType.Database;
            bkp.Database = dbName;
            bkp.BackupSetName = id.ToString();
            bkp.BackupSetDescription = string.Format("VisLab auto-backup (experiment N{0}).", experimentNumber);
            bkp.Devices.AddDevice(Path.Combine(uncDir, bkp.Database + ".bak"), DeviceType.File);
            bkp.Incremental = false;
            if (onComplete != null) bkp.Complete += onComplete;
            bkp.SqlBackup(srv);
        }
Example #31
0
 public static BackupViewModel MapModelToViewModel(this Backup entity)
 {
     return(Mapper.Map <Backup, BackupViewModel>(entity));
 }
        public void Main(string[] args)
        {
            var app = new CommandLineApplication();

            app.HelpOption();

            app.Command("backup", throwOnUnexpectedArg: false, configuration: command =>
            {
                command.HelpOption();

                var sourceArgument = command.Argument("[SOURCE]", "");
                var targetArgument = command.Argument("[TARGET]", "");

                var sourceOptions = command.Option("--source <PATH>", "", CommandOptionType.SingleValue);
                var targetOptions = command.Option("--target <PATH>", "", CommandOptionType.SingleValue);

                var sourceConfigurationOptions = command.Option("-sc|--sourceConfiguration <OPTIONS>", "", CommandOptionType.MultipleValue);
                var targetConfigurationOptions = command.Option("-tc|--targetConfiguration <OPTIONS>", "", CommandOptionType.MultipleValue);

                var keepHistoryOption       = command.Option("--keepHistory", "Preserve all versions of a file in the target file system (sufix the file name with the utc date)", CommandOptionType.NoValue);
                var readHistoryOption       = command.Option("--readHistory", "", CommandOptionType.NoValue);
                var writeHistoryOption      = command.Option("--writeHistory", "", CommandOptionType.NoValue);
                var equalityOption          = command.Option("--equality <EqualityMethods>", "Length, LastWriteTime, Content, ContentMd5, ContentSha1, ContentSha256, ContentSha512", CommandOptionType.SingleValue);
                var createDirectoryOption   = command.Option("--createDirectories <TRUE,FALSE>", "Can create directories in the target file system", CommandOptionType.SingleValue);
                var deleteDirectoriesOption = command.Option("--deleteDirectories <TRUE,FALSE>", "Can delete directories in the target file system", CommandOptionType.SingleValue);
                var createFilesOption       = command.Option("--createFiles <TRUE,FALSE>", "Can create files in the target file system", CommandOptionType.SingleValue);
                var updateFilesOption       = command.Option("--updateFiles <TRUE,FALSE>", "Can update files in the target file system", CommandOptionType.SingleValue);
                var deleteFilesOption       = command.Option("--deleteFiles <TRUE,FALSE>", "Can delete files in the target file system", CommandOptionType.SingleValue);
                var deleteSourceFilesOption = command.Option("--deleteSourceFiles <TRUE,FALSE>", "Delete source files after being processed", CommandOptionType.SingleValue);
                var retryCountOption        = command.Option("--retry <RetryCount>", "Number of attempts of an operation", CommandOptionType.SingleValue);
                var continueOnErrorOption   = command.Option("--ignoreErrors", "continue on error", CommandOptionType.NoValue);
                var diffFilesPathOption     = command.Option("--diffFilesPath", "", CommandOptionType.SingleValue);

                var sourceAesMethodOption                = command.Option("--sourceAesMethod <METHOD>", "AES128, AES256", CommandOptionType.SingleValue);
                var sourceAesPasswordOption              = command.Option("--sourceAesPassword <PASSWORD>", "Password to decrypt files", CommandOptionType.SingleValue);
                var sourceAesPasswordNameOption          = command.Option("--sourceAesPasswordName <NAME>", "Name of the application in the Windows Credential Manager", CommandOptionType.SingleValue);
                var sourceAesAskPasswordOption           = command.Option("--sourceAesAskPassword", "Ask for password", CommandOptionType.NoValue);
                var sourceAesEncryptFileNamesOption      = command.Option("--sourceAesEncryptFileNames", "Decrypt file names", CommandOptionType.NoValue);
                var sourceAesEncryptDirectoryNamesOption = command.Option("--sourceAesEncryptDirectoryNames", "Decrypt directory names", CommandOptionType.NoValue);

                var targetAesMethodOption                = command.Option("--targetAesMethod <METHOD>", "AES128, AES256", CommandOptionType.SingleValue);
                var targetAesPasswordOption              = command.Option("--targetAesPassword <PASSWORD>", "Password to encrypt files", CommandOptionType.SingleValue);
                var targetAesPasswordNameOption          = command.Option("--targetAesPasswordName <NAME>", "Name of the application in the Windows Credential Manager", CommandOptionType.SingleValue);
                var targetAesAskPasswordOption           = command.Option("--targetAesAskPassword", "Ask for password", CommandOptionType.NoValue);
                var targetAesEncryptFileNamesOption      = command.Option("--targetAesEncryptFileNames", "Encrypt file names", CommandOptionType.NoValue);
                var targetAesEncryptDirectoryNamesOption = command.Option("--targetAesEncryptDirectoryNames", "Encrypt directory names", CommandOptionType.NoValue);

                var logLevelOption = command.Option("--log", "", CommandOptionType.SingleValue);
                var testConfig     = command.Option("--test-config", "for testing purpose only", CommandOptionType.NoValue);

                command.OnExecute(() =>
                {
                    var backup          = new Backup();
                    var backupConsole   = new ConsoleLogger(backup);
                    backupConsole.Level = GetValue(logLevelOption, ConsoleLoggerLevel.Default);

                    backup.EqualityMethods         = GetValue(equalityOption, FileInfoEqualityMethods.Default);
                    backup.RetryCount              = GetValue(retryCountOption, 3);
                    backup.CanCreateDirectories    = GetValue(createDirectoryOption, true);
                    backup.CanDeleteDirectories    = GetValue(deleteDirectoriesOption, false);
                    backup.CanCreateFiles          = GetValue(createFilesOption, true);
                    backup.CanUpdateFiles          = GetValue(updateFilesOption, true);
                    backup.CanDeleteFiles          = GetValue(deleteFilesOption, false);
                    backup.ContinueOnError         = GetValue(continueOnErrorOption, false);
                    backup.ReadHistory             = GetValue(readHistoryOption, GetValue(keepHistoryOption, false));
                    backup.WriteHistory            = GetValue(writeHistoryOption, GetValue(keepHistoryOption, false));
                    backup.DeleteSourceFiles       = GetValue(deleteSourceFilesOption, false);
                    backup.DeleteSourceDirectories = GetValue(deleteSourceFilesOption, false);

                    string writeDiffFilesPath = GetValue(diffFilesPathOption, null);
                    if (writeDiffFilesPath != null)
                    {
                        backup.Action += (sender, e) =>
                        {
                            if (e.Action == BackupAction.Creating || e.Action == BackupAction.Deleting)
                            {
                                if (e.SourceItem is IFileInfo fi)
                                {
                                    e.Cancel     = true;
                                    var fullPath = Path.Combine(writeDiffFilesPath, string.Join(Path.DirectorySeparatorChar.ToString(), e.Path));
                                    Directory.CreateDirectory(fullPath);
                                    using var stream       = fi.OpenReadAsync(CancellationToken.None).Result;
                                    using var streamWriter = File.Create(Path.Combine(fullPath, e.SourceItem.Name));
                                    stream.CopyTo(streamWriter);
                                }
                            }
                        };
                    }

                    var summary = new BackupSummary(backup);
                    try
                    {
                        var sourceFileSystem = GetFileSystem(new object[] { sourceArgument, sourceOptions }, sourceConfigurationOptions, out string sourcePath);
                        if (sourceFileSystem == null)
                        {
                            return(1);
                        }

                        var targetFileSystem = GetFileSystem(new object[] { targetArgument, targetOptions }, targetConfigurationOptions, out string targetPath);
                        if (targetFileSystem == null)
                        {
                            return(2);
                        }

                        sourceFileSystem = CreateAesFileSystem(sourceFileSystem, sourceAesMethodOption, sourceAesPasswordOption, sourceAesPasswordNameOption, sourceAesAskPasswordOption, sourceAesEncryptFileNamesOption, sourceAesEncryptDirectoryNamesOption);
                        if (sourceFileSystem == null)
                        {
                            return(3);
                        }

                        targetFileSystem = CreateAesFileSystem(targetFileSystem, targetAesMethodOption, targetAesPasswordOption, targetAesPasswordNameOption, targetAesAskPasswordOption, targetAesEncryptFileNamesOption, targetAesEncryptDirectoryNamesOption);
                        if (targetFileSystem == null)
                        {
                            return(4);
                        }

                        using var cts = new CancellationTokenSource();
                        System.Console.CancelKeyPress += (sender, eventArgs) =>
                        {
                            cts.Cancel();
                            eventArgs.Cancel = true;
                        };

                        if (!GetValue(testConfig, false))
                        {
                            var backupAsync = RunAsync(backup, sourceFileSystem, sourcePath, targetFileSystem, targetPath, cts.Token);
                            var awaiter     = backupAsync.GetAwaiter();
                            awaiter.GetResult();
                        }
                    }
                    catch (OperationCanceledException)
                    {
                        System.Console.WriteLine("Operation was canceled");
                    }

                    System.Console.WriteLine("Directories: " + summary.DirectoryCount);
                    System.Console.WriteLine("  Created: " + summary.DirectoryCreatedCount);
                    System.Console.WriteLine("  Deleted: " + summary.DirectoryDeletedCount);

                    System.Console.WriteLine("File: " + summary.FileCount);
                    System.Console.WriteLine("  Created: " + summary.FileCreatedCount);
                    System.Console.WriteLine("  Updated: " + summary.FileUpdatedCount);
                    System.Console.WriteLine("  Deleted: " + summary.FileDeletedCount);

                    System.Console.WriteLine("Errors: " + summary.ErrorCount);

                    return(0);
                });
            });

            app.Execute(args);
        }
 public Backup Add(Backup backup)
 {
     this.db.tbBackup.Add(backup);
     this.db.SaveChanges();
     return(backup);
 }
Example #34
0
        public async Task Tombstones_should_be_cleaned_only_after_backup_when_delete_is_not_a_last_operation(BackupType backupType, string taskName)
        {
            var backupPath = NewDataPath(suffix: "BackupFolder");

            using (var store = GetDocumentStore())
            {
                var config = Backup.CreateBackupConfiguration(backupPath, backupType: backupType, incrementalBackupFrequency: "* */6 * * *");
                var result = await store.Maintenance.SendAsync(new UpdatePeriodicBackupOperation(config));

                using (var session = store.OpenSession())
                {
                    session.Store(new FooBar {
                        Foo = "Bar1"
                    }, "foo/bar1");
                    session.Store(new FooBar {
                        Foo = "Bar2"
                    }, "foo/bar2");
                    session.SaveChanges();
                }

                var documentDatabase = (await GetDocumentDatabaseInstanceFor(store));

                using (var session = store.OpenSession())
                {
                    session.Delete("foo/bar1");
                    session.Delete("foo/bar2");
                    session.SaveChanges();
                }

                await documentDatabase.TombstoneCleaner.ExecuteCleanup(1);

                using (documentDatabase.DocumentsStorage.ContextPool.AllocateOperationContext(out DocumentsOperationContext context))
                    using (context.OpenReadTransaction())
                    {
                        var tombstones = documentDatabase.DocumentsStorage.GetTombstonesFrom(context, 0, 0, int.MaxValue).ToList();

                        //since we didn't backup the tombstones yet, they will not get cleaned
                        Assert.Equal(2, tombstones.Count);
                    }

                //do a document PUT, so latest etag won't belong to tombstone
                using (var session = store.OpenSession())
                {
                    session.Store(new FooBar {
                        Foo = "Bar3"
                    }, "foo/bar3");
                    session.SaveChanges();
                }

                await Backup.RunBackupAsync(Server, result.TaskId, store, isFullBackup : false);

                //force tombstone cleanup - now, after backup, tombstones should be cleaned
                await documentDatabase.TombstoneCleaner.ExecuteCleanup(1);

                using (documentDatabase.DocumentsStorage.ContextPool.AllocateOperationContext(out DocumentsOperationContext context))
                    using (context.OpenReadTransaction())
                    {
                        var tombstonesCount = documentDatabase.DocumentsStorage.GetTombstonesFrom(context, 0, 0, int.MaxValue).Count();
                        Assert.Equal(0, tombstonesCount);
                    }
            }
        }
        public void Patch()
        {
            var timeQuadrant = TimeWarp.fetch;

            if (timeQuadrant == null)
            {
                return;
            }
            if (mBackup != null)
            {
                throw new InvalidOperationException("Patcher is already in use.");
            }
            var tab = timeQuadrant.timeQuadrantTab;

            mBackup = new Backup()
            {
                TimeQuadrant      = timeQuadrant,
                Texture           = tab.renderer.material.mainTexture,
                Scale             = tab.transform.localScale,
                Center            = ((BoxCollider)tab.collider).center,
                ExpandedPosition  = tab.expandedPos,
                CollapsedPosition = tab.collapsedPos,
            };

            List <Transform> children = new List <Transform>();

            foreach (Transform child in tab.transform)
            {
                children.Add(child);
            }

            foreach (Transform child in children)
            {
                child.parent = tab.transform.parent;
            }

            // Set the new texture
            float     old_height = tab.renderer.material.mainTexture.height;
            Texture2D newTexture;

            RTUtil.LoadImage(out newTexture, "texTimeQuadrant.png");
            newTexture.filterMode             = FilterMode.Trilinear;
            newTexture.wrapMode               = TextureWrapMode.Clamp;
            tab.renderer.material.mainTexture = newTexture;

            // Apply new scale, positions
            float scale = Screen.height / (float)GameSettings.UI_SIZE;

            tab.transform.localScale = new Vector3(tab.transform.localScale.x,
                                                   tab.transform.localScale.y,
                                                   tab.transform.localScale.z * (tab.renderer.material.mainTexture.height / old_height));
            tab.collapsedPos += new Vector3(0, -0.013f, 0);
            tab.expandedPos  += new Vector3(0, -0.013f, 0);
            foreach (Transform child in children)
            {
                child.localPosition += new Vector3(0, 0.013f, 0);
            }
            tab.Expand();

            foreach (Transform child in children)
            {
                child.parent = tab.transform;
            }

            ((BoxCollider)tab.collider).center += new Vector3(0, 0, -0.37f);

            var text = tab.transform.FindChild("MET timer").GetComponent <ScreenSafeGUIText>();

            mTextStyle          = new GUIStyle(text.textStyle);
            mTextStyle.fontSize = (int)(text.textSize * ScreenSafeUI.PixelRatio);

            RenderingManager.AddToPostDrawQueue(0, Draw);
        }
Example #36
0
        public async Task ExportFullThanDeleteAttachmentAndCreateAnotherOneThanExportIncrementalThanImport()
        {
            var backupPath = NewDataPath(suffix: "BackupFolder");

            using (var store = GetDocumentStore(new Options
            {
                ModifyDatabaseName = s => $"{s}_store1"
            }))
            {
                using (var session = store.OpenSession())
                {
                    session.Store(new User
                    {
                        Name = "Fitzchak"
                    }, "users/1");
                    session.SaveChanges();
                }

                using (var stream = new MemoryStream(new byte[] { 1, 2, 3 }))
                    store.Operations.Send(new PutAttachmentOperation("users/1", "file1", stream, "image/png"));

                var config                  = Backup.CreateBackupConfiguration(backupPath);
                var backupTaskId            = Backup.UpdateConfigAndRunBackup(Server, config, store);
                var operation               = new GetPeriodicBackupStatusOperation(backupTaskId);
                var getPeriodicBackupResult = store.Maintenance.Send(operation);
                var etagForBackups          = getPeriodicBackupResult.Status.LastEtag;

                store.Operations.Send(new DeleteAttachmentOperation("users/1", "file1"));
                using (var stream = new MemoryStream(new byte[] { 4, 5, 6 }))
                    store.Operations.Send(new PutAttachmentOperation("users/1", "file2", stream, "image/png"));

                var status = await Backup.RunBackupAndReturnStatusAsync(Server, backupTaskId, store, isFullBackup : false);

                Assert.True(status.LastEtag != etagForBackups);

                var stats = await store.Maintenance.SendAsync(new GetStatisticsOperation());

                Assert.Equal(1, stats.CountOfDocuments);
                Assert.Equal(1, stats.CountOfAttachments);
                Assert.Equal(1, stats.CountOfUniqueAttachments);
            }

            using (var store = GetDocumentStore(new Options
            {
                ModifyDatabaseName = s => $"{s}_store2"
            }))
            {
                await store.Smuggler.ImportIncrementalAsync(new DatabaseSmugglerImportOptions(), Directory.GetDirectories(backupPath).First());

                var stats = await store.Maintenance.SendAsync(new GetStatisticsOperation());

                Assert.Equal(1, stats.CountOfDocuments);
                Assert.Equal(1, stats.CountOfAttachments);
                Assert.Equal(1, stats.CountOfUniqueAttachments);

                using (var session = store.OpenSession())
                {
                    var user = session.Load <User>("users/1");

                    var metadata = session.Advanced.GetMetadataFor(user);
                    Assert.Equal(DocumentFlags.HasAttachments.ToString(), metadata[Constants.Documents.Metadata.Flags]);
                    var attachment = metadata.GetObjects(Constants.Documents.Metadata.Attachments).Single();
                    Assert.Equal("file2", attachment.GetString(nameof(AttachmentName.Name)));
                }
            }
        }
        public async Task CanExportImportCompareExchangeWithExpiration()
        {
            using var server = GetNewServer();
            int count      = 15;
            var expiry     = DateTime.Now.AddMinutes(2);
            var longExpiry = DateTime.Now.AddMinutes(4);
            var compareExchangesWithShortExpiration = new Dictionary <string, User>();
            var compareExchangesWithLongExpiration  = new Dictionary <string, User>();
            var compareExchanges = new Dictionary <string, User>();
            var amountToAdd      = count / 3;
            var backupPath       = NewDataPath(suffix: "BackupFolder");
            var databaseName     = GetDatabaseName() + "restore";

            using (var store = GetDocumentStore(new Options
            {
                Server = server
            }))
            {
                await AddCompareExchangesWithExpire(amountToAdd, compareExchanges, store, expiry : null);
                await AddCompareExchangesWithExpire(amountToAdd, compareExchangesWithShortExpiration, store, expiry);
                await AddCompareExchangesWithExpire(amountToAdd, compareExchangesWithLongExpiration, store, longExpiry);

                await AssertCompareExchanges(compareExchangesWithShortExpiration, store, expiry);
                await AssertCompareExchanges(compareExchangesWithLongExpiration, store, longExpiry);
                await AssertCompareExchanges(compareExchanges, store, expiry : null);

                var config       = Backup.CreateBackupConfiguration(backupPath);
                var backupTaskId = Backup.UpdateConfigAndRunBackup(server, config, store);

                var backupDirectory = Directory.GetDirectories(backupPath).First();
                var restoreConfig   = new RestoreBackupConfiguration()
                {
                    BackupLocation = backupDirectory,
                    DatabaseName   = databaseName
                };

                var restoreOperation = new RestoreBackupOperation(restoreConfig);
                var o = await store.Maintenance.Server.SendAsync(restoreOperation);

                await o.WaitForCompletionAsync(TimeSpan.FromSeconds(30));

                using (var store2 = GetDocumentStore(new Options
                {
                    Server = server,
                    CreateDatabase = false,
                    ModifyDatabaseName = s => databaseName
                }))
                {
                    var stats1 = await store.Maintenance.SendAsync(new GetDetailedStatisticsOperation());

                    Assert.Equal(count, stats1.CountOfCompareExchange);
                    var stats = await store2.Maintenance.SendAsync(new GetDetailedStatisticsOperation());

                    Assert.Equal(count, stats.CountOfCompareExchange);
                    server.ServerStore.Observer.Time.UtcDateTime = () => DateTime.UtcNow.AddMinutes(3);

                    var val = await WaitForValueAsync(async() =>
                    {
                        var stats = await store2.Maintenance.SendAsync(new GetDetailedStatisticsOperation());
                        return(stats.CountOfCompareExchange);
                    }, count - amountToAdd);

                    Assert.Equal(count - amountToAdd, val);

                    server.ServerStore.Observer.Time.UtcDateTime = () => DateTime.UtcNow.AddMinutes(5);

                    var nextVal = await WaitForValueAsync(async() =>
                    {
                        var stats = await store2.Maintenance.SendAsync(new GetDetailedStatisticsOperation());
                        return(stats.CountOfCompareExchange);
                    }, amountToAdd);

                    Assert.Equal(amountToAdd, nextVal);

                    stats1 = await store.Maintenance.SendAsync(new GetDetailedStatisticsOperation());

                    Assert.Equal(amountToAdd, stats1.CountOfCompareExchange);
                    stats = await store2.Maintenance.SendAsync(new GetDetailedStatisticsOperation());

                    Assert.Equal(amountToAdd, stats.CountOfCompareExchange);
                }
            }
        }
 private void ValidateBackups(Backup backup)
 {
     Assert.NotNull(backup);
     Assert.NotNull(backup.EncryptionCertThumbprint);
 }
        private void BackUpDatabase()
        {
            lblMessage.Text = String.Empty;
            RefreshServerReference();
            db = server.Databases[DBtoBackup];

            //Store the current recovery model in a variable.

            recoverymod = (int)db.DatabaseOptions.RecoveryModel;

            //Define a Backup object variable.
            Backup bk = new Backup();

            //Specify the type of backup, the description, the name, and the database to be backed up.
            bk.Action = BackupActionType.Database;
            bk.BackupSetDescription = "Full backup of " + DBtoBackup;
            bk.BackupSetName        = DBtoBackup + " Backup";
            bk.Database             = DBtoBackup;

            //Declare a BackupDeviceItem by supplying the backup device file name in the constructor, and the type of device is a file.
            bdi = default(BackupDeviceItem);
            bdi = new BackupDeviceItem("Full_Backup1" + DBtoBackup, DeviceType.File);

            //Add the device to the Backup object.
            bk.Devices.Add(bdi);
            //Set the Incremental property to False to specify that this is a full database backup.
            bk.Incremental = false;

            /*
             * //Set the expiration date.
             * System.DateTime backupdate = new System.DateTime();
             * backupdate = new System.DateTime(2006, 10, 5);
             * bk.ExpirationDate = backupdate;
             */

            //Specify that the log must be truncated after the backup is complete.
            bk.LogTruncation = BackupTruncateLogType.Truncate;

            //Run SqlBackup to perform the full database backup on the instance of SQL Server.
            bk.SqlBackup(server);

            //Inform the user that the backup has been completed.
            lblMessage.Text      = "Full Backup complete.";
            lblMessage.ForeColor = System.Drawing.Color.Green;

            //Remove the backup device from the Backup object.
            bk.Devices.Remove(bdi);

            /*
             * //Make a change to the database, in this case, add a table called test_table.
             * Table t = default(Table);
             * t = new Table(db, "test_table");
             * Column c = default(Column);
             * c = new Column(t, "col", DataType.Int);
             * t.Columns.Add(c);
             * t.Create();
             *
             * //Create another file device for the differential backup and add the Backup object.
             * BackupDeviceItem bdid = default(BackupDeviceItem);
             * bdid = new BackupDeviceItem("Test_Differential_Backup1", DeviceType.File);
             *
             * //Add the device to the Backup object.
             * bk.Devices.Add(bdid);
             *
             * //Set the Incremental property to True for a differential backup.
             * bk.Incremental = true;
             *
             * //Run SqlBackup to perform the incremental database backup on the instance of SQL Server.
             * bk.SqlBackup(server);
             *
             * //Inform the user that the differential backup is complete.
             * Console.WriteLine("Differential Backup complete.");
             *
             * //Remove the device from the Backup object.
             * bk.Devices.Remove(bdid);
             */
        }
Example #40
0
        public static bool DbBackupEx(string string_0, string string_1, string string_2, string string_3,
                                      string string_4, string string_5, string string_6)
        {
            bool      flag;
            bool      flag1          = false;
            Backup    backupClass    = new Backup();
            SQLServer sQLServerClass = new SQLServer();

            try
            {
                if (!File.Exists(string_4))
                {
                    FileStream fileStream = File.Create(string_4);
                    try
                    {
                    }
                    finally
                    {
                        if (fileStream != null)
                        {
                            ((IDisposable)fileStream).Dispose();
                        }
                    }
                }
            }
            catch (Exception exception)
            {
                MessageBox.Show(exception.ToString());
                flag = false;
                return(flag);
            }
            if ((string_5 == null ? true : string_5 == ""))
            {
                string_5 = string.Concat("你现在进行了数据库", string_3.Trim(), "的备份设置");
            }
            if ((string_6 == null ? true : string_6 == ""))
            {
                string_6 = string.Concat("你现在备份的数据库为", string_3.Trim());
            }
            try
            {
                try
                {
                    sQLServerClass.LoginSecure = false;
                    sQLServerClass.Connect(string_0.Trim(), string_1.Trim(), string_2.Trim());
                    backupClass.Action               = 0;
                    backupClass.Database             = string_3.Trim();
                    backupClass.Files                = string_4;
                    backupClass.BackupSetName        = string_5;
                    backupClass.BackupSetDescription = string_6;
                    backupClass.Initialize           = true;
                    backupClass.SQLBackup(sQLServerClass);
                    flag1 = true;
                }
                catch (Exception exception1)
                {
                    MessageBox.Show(exception1.Message.ToString());
                }
            }
            finally
            {
                sQLServerClass.DisConnect();
            }
            flag = flag1;
            return(flag);
        }
 public void Remove(Backup pc)
 {
     this.db.tbBackup.Remove(pc);
     this.db.SaveChanges();
 }
        private void btn_salvarBackup_Click(object sender, EventArgs e)
        {
            Backup backup = new Backup();

            backup.Realizar_Backup();
        }
Example #43
0
        public async Task <UserSettings> StartAsync()
        {
            Backup backup = new Backup(userSettings);

            try // Обработка ошибок связанных с файловой системой и загрузки настроек.
            {
                if (!backup.LoadBackup(out userSettings))
                {
                    return(null); // мы не можем загрузить настройки. Нет возможности и подключиться к таблицам
                }

                JwBookExcel excel = new JwBookExcel(userSettings.JWBookSettings.JWBookPuth);
                try
                {
                    excel.ConnectFile();
                }
                catch (Exception)
                {
                    ;
                }

                // Если отчёт не отправлен в филиал.
                if (DateTime.Now.Day > 15 && DateTime.Now.Day < 20) // TODO: вынести в настройки
                {
                    JwBookExcel.ArchiveReports archive = new JwBookExcel.ArchiveReports(excel);
                    var checkDate = JwBookExcel.ConvertDateTimeToStringArray(DateTime.Now);
                    if (archive.ContainsMonthReport(checkDate[0], checkDate[1]) == false)
                    {
                        MyMessageBox.Show("Не забудьте отправить отчёт в филиал!", "Уведомление");
                        mainWindow.AddNotification(MainWindow.CreateNotification("Уведомление", "Пожалуйста заполните и отправьте отчёт в филиал!"));
                    }
                }
                mainWindow.AddNotification(MainWindow.CreateNotification("Cистемное уведомление", "Настройки успешно загружены."));
                return(userSettings);
            }
            catch (InvalidOperationException ex) // Битый файл или неправильно сгенерированна розметка.
            {
                waitWindow.Close();
                MyMessageBox.Show("Не удаеться правильно прочитать файл XML. Неккоректроне содержимое.", "Ошибка");
                mainWindow.AddNotification(MainWindow.CreateNotification("Cистемное уведомление", "Не удаеться правильно прочитать файл XML. Неккоректроне содержимое."));
            }
            catch (IndexOutOfRangeException ex) // Не нашли файл с настройками. Но директория уже создана.
            {
                var root = System.IO.Path.GetPathRoot(Environment.CurrentDirectory);
                waitWindow.Close();
                MyMessageBox.Show($@"Не обнаружен файл настроект (XML) в директории: {root}MisistryReports\Settings", "Ошибка");
                mainWindow.AddNotification(MainWindow.CreateNotification("Cистемное уведомление", "Чтобы начать пользоваться программой - пожалуйста настройте. После того, как укажете все необходимые настройки - не забудьте сохранить. Если у вас уже есть файл настроек - пожалуйста загрузите его."));
                mainWindow.AddNotification(MainWindow.CreateNotification("Cистемное уведомление", $@"Не обнаружен файл XML в директории: {root}MisistryReports\Settings"));
            }
            catch (System.IO.DirectoryNotFoundException)
            {
                // Create Dirictory -- Пользователь первый раз использует программу.
                CreateProgramDirectory();  // Создали необходимые системные директории.
                waitWindow.Close();
                mainWindow.AddNotification(MainWindow.CreateNotification("Системное уведомления", "Добро пожаловать! Ministry Reports это программа, которая поможет вам составлять и отправлять годовой отчёт в филиал. В это программе собраны все необходимые функции для удобного формирования годового отчета. Также вы можете отслеживать активность возвещателя, либо любого другого служителя собрания. Мы надеемся, что эта программа поможет вам формировать годовой отчет правильно и удобно. Чтобы начать пользоваться программой - настройте её."));
            }
            catch (NotSupportedException ex)
            {
                waitWindow.Close();
                MyMessageBox.Show("JWBook: " + ex.Message, "Ошибка");
                mainWindow.AddNotification(MainWindow.CreateNotification("Cистемное уведомление", "JWBook: " + ex.Message));
            }
            //catch (Exception ex)
            //{
            //    waitWindow.Close();
            //    MyMessageBox.Show($"Непредвиденная ошибка. Подробности: {ex.Message}", "Ошибка");
            //}
            return(null);
        }
Example #44
0
        /// <summary>
        /// Perform common initialization/finailzation. Performs backup action before running the test;
        /// run test and restores device settings (independently from passed/failed test status).
        /// </summary>
        /// <typeparam name="T">Type of backup data.</typeparam>
        /// <param name="backupAction">Method to backup device settings.</param>
        /// <param name="action">Test method.</param>
        /// <param name="restoreAction">Method to restore device settings.</param>
        protected void RunTest <T>(Backup <T> backupAction,
                                   Action action,
                                   Action <T> restoreAction)
        {
            if (allPassedModeOn())
            {
                return;
            }

            try
            {
                T         data          = default(T);
                Exception exc           = null;
                bool      backupNotNull = false;
                _halted = false;

                try
                {
                    System.Diagnostics.Debug.WriteLine("Begin test");

                    // initialize object for test run;
                    BeginTest();

                    System.Diagnostics.Debug.WriteLine("Backup");

                    // backup device settings
                    data          = backupAction();
                    backupNotNull = true;

                    System.Diagnostics.Debug.WriteLine("Main action");

                    // run test
                    action();

                    System.Diagnostics.Debug.WriteLine("Main action completed");
                }
                catch (StopEventException)
                {
                    System.Diagnostics.Debug.WriteLine("HALT");

                    if (_videoForm != null)
                    {
                        _videoForm.CloseWindow();
                    }

                    Release();
                    _halted = true;

                    LogStepEvent("Halted");
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine(string.Format("Exception: {0}", ex.Message));
                    StepFailed(ex);
                    exc = ex;
                }
                finally
                {
                    try
                    {
                        if (backupNotNull && !_halted)
                        {
                            System.Diagnostics.Debug.WriteLine("Restore");
                            restoreAction(data);
                        }
                        else
                        {
                            System.Diagnostics.Debug.WriteLine("No backup data");
                        }
                    }
                    catch (Exception ex)
                    {
                        System.Diagnostics.Debug.WriteLine("Exception when trying to restore settings");
                        StepFailed(ex);
                        exc = ex;
                    }

                    if (!_halted)
                    {
                        if (exc == null)
                        {
                            System.Diagnostics.Debug.WriteLine("End test - passed");
                            EndTest(TestStatus.Passed);
                        }
                        else
                        {
                            System.Diagnostics.Debug.WriteLine("Test failed");
                            try
                            {
                                Release();
                            }
                            catch (Exception)
                            {
                            }
                            TestFailed(exc);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine("new catch - Test failed");
                TestFailed(ex);
            }
        }
Example #45
0
        void WorkerThread()
        {
            try
            {
                while (!Closing)
                {
                    Thread.Sleep(0);

                    lock (SearchStateLock)
                    {
                        BackupProject Project = CurrentProject;
                        if (Project == null)
                        {
                            Thread.Sleep(100);
                            IsArchiveNamesComplete = true;
                            IsFolderNamesComplete  = true;
                            continue;
                        }
                        string[] SearchWords = CurrentSearchWords;

                        if (SearchWords == null || SearchWords.Length == 0)
                        {
                            // In the case where the user has selected a project but no search details,
                            // we want to show all available backup archives.

                            if (!IsArchiveNamesComplete)
                            {
                                lock (Project.ArchiveFileList)
                                {
                                    foreach (ArchiveFilename Backup in Project.ArchiveFileList.Archives)
                                    {
                                        if (!AllResults.Contains(Backup))
                                        {
                                            AllResults.Add(Backup);
                                            lock (NewResults) NewResults.Add(Backup);
                                        }
                                    }
                                }

                                IsArchiveNamesComplete = true;
                            }
                            IsFolderNamesComplete = true;
                            Thread.Sleep(100);
                            continue;
                        }

                        if (!IsArchiveNamesComplete && IncludeArchiveNames)
                        {
                            lock (Project.ArchiveFileList)
                            {
                                foreach (ArchiveFilename Backup in Project.ArchiveFileList.Archives)
                                {
                                    string BackupFile = Backup.ToString().ToLower();

                                    bool Match = true;
                                    foreach (string Word in SearchWords)
                                    {
                                        if (!BackupFile.Contains(Word))
                                        {
                                            Match = false; break;
                                        }
                                    }
                                    if (!Match)
                                    {
                                        continue;
                                    }

                                    if (!AllResults.Contains(Backup))
                                    {
                                        AllResults.Add(Backup);
                                        lock (NewResults) NewResults.Add(Backup);
                                    }
                                }
                            }
                            IsArchiveNamesComplete = true;
                            continue;
                        }

                        if (!IsFolderNamesComplete && IncludeFolderNames)
                        {
                            ArchiveFilename ExamineNext = null;
                            lock (Project.ArchiveFileList)
                            {
                                foreach (ArchiveFilename Backup in Project.ArchiveFileList.Archives)
                                {
                                    bool AlreadyDone = false;
                                    foreach (ArchiveFilename PosRes in AllResults)
                                    {
                                        if (Backup == PosRes)
                                        {
                                            AlreadyDone = true; break;
                                        }
                                    }
                                    if (AlreadyDone)
                                    {
                                        continue;
                                    }
                                    foreach (ArchiveFilename NegRes in NegFolderNameResults)
                                    {
                                        if (Backup == NegRes)
                                        {
                                            AlreadyDone = true; break;
                                        }
                                    }
                                    if (AlreadyDone)
                                    {
                                        continue;
                                    }
                                    ExamineNext = Backup;
                                    break;
                                }
                            }
                            if (ExamineNext == null)
                            {
                                IsFolderNamesComplete = true;
                                continue;
                            }

                            /** Examine a single archive on this pass of the loop **/

                            Manifest Manifest;
                            lock (Project.ManifestCache)
                            {
                                if (!Project.ManifestCache.TryGetValue(ExamineNext, out Manifest))
                                {
                                    try
                                    {
                                        using (NetworkConnection newconn = new NetworkConnection(Project.CompleteBackupFolder, Project.BackupCredentials))
                                            Manifest = ExamineNext.LoadArchiveManifest(Project, false);
                                        Project.ManifestCache.Add(ExamineNext, Manifest);
                                    }
                                    catch (Ionic.Zip.BadPasswordException)
                                    {
                                        PasswordBlockedSearch = true;
                                        NegFolderNameResults.Add(ExamineNext);
                                        continue;
                                    }
                                }
                            }

                            if (SearchManifestForFolderName(ExamineNext, Manifest.ArchiveRoot, SearchWords))
                            {
                                if (!AllResults.Contains(ExamineNext))
                                {
                                    AllResults.Add(ExamineNext);
                                    lock (NewResults) NewResults.Add(ExamineNext);
                                }
                            }
                            else
                            {
                                NegFolderNameResults.Add(ExamineNext);
                            }

                            continue;
                        }

                        // If we reach this point, the search has already completed.  Idle time.
                        Thread.Sleep(100);
                    }
                }
            }
            catch (Exception ex)
            {
                lock (ExceptionLock)
                {
                    WorkerException = ex;
                }
            }
        }
Example #46
0
        // 下载资源,保存到备份文件
        static int WriteResToBackupFile(
            IWin32Window owner,
            RmsChannel channel,
            DigitalPlatform.Stop stop,
            Stream outputfile,
            string strXmlRecPath,
            string[] res_ids,
            out string strError)
        {
            strError = "";

            long lRet;

            for (int i = 0; i < res_ids.Length; i++)
            {
                Application.DoEvents(); // 出让界面控制权

                if (stop.State != 0)
                {
                    DialogResult result = MessageBox.Show(owner,
                                                          "确实要中断当前批处理操作?",
                                                          "导出数据",
                                                          MessageBoxButtons.YesNo,
                                                          MessageBoxIcon.Question,
                                                          MessageBoxDefaultButton.Button2);
                    if (result == DialogResult.Yes)
                    {
                        strError = "用户中断";
                        return(-1);
                    }
                    else
                    {
                        stop.Continue();
                    }
                }

                string strID = res_ids[i].Trim();

                if (strID == "")
                {
                    continue;
                }

                string strResPath = strXmlRecPath + "/object/" + strID;

                string strMetaData;

                if (stop != null)
                {
                    stop.SetMessage("正在下载 " + strResPath);
                }

                long lResStart = 0;
                // 写res的头。
                // 如果不能预先确知整个res的长度,可以用随便一个lTotalLength值调用本函数,
                // 但是需要记忆下函数所返回的lStart,最后调用EndWriteResToBackupFile()。
                // 如果能预先确知整个res的长度,则最后不必调用EndWriteResToBackupFile()
                lRet = Backup.BeginWriteResToBackupFile(
                    outputfile,
                    0,  // 未知
                    out lResStart);

                byte[] baOutputTimeStamp = null;
                string strOutputPath;

REDO_GETRES:
                lRet = channel.GetRes(strResPath,
                                      (Stream)null, // 故意不获取资源体
                                      stop,
                                      "metadata,timestamp,outputpath",
                                      null,
                                      out strMetaData, // 但是要获得metadata
                                      out baOutputTimeStamp,
                                      out strOutputPath,
                                      out strError);
                if (lRet == -1)
                {
                    // TODO: 允许重试
                    DialogResult redo_result = MessageBox.Show(owner,
                                                               "获取记录 '" + strResPath + "' 时出现错误: " + strError + "\r\n\r\n重试,还是中断当前批处理操作?\r\n(Retry 重试;Cancel 中断批处理)",
                                                               "导出数据",
                                                               MessageBoxButtons.RetryCancel,
                                                               MessageBoxIcon.Question,
                                                               MessageBoxDefaultButton.Button1);
                    if (redo_result == DialogResult.Cancel)
                    {
                        return(-1);
                    }
                    goto
                    REDO_GETRES;
                }

                byte[] timestamp = baOutputTimeStamp;

                ResPath respath = new ResPath();
                respath.Url  = channel.Url;
                respath.Path = strOutputPath;   // strResPath;

                // strMetaData还要加入资源id?
                StringUtil.ChangeMetaData(ref strMetaData,
                                          strID,
                                          null,
                                          null,
                                          null,
                                          respath.FullPath,
                                          ByteArray.GetHexTimeStampString(baOutputTimeStamp));


                lRet = Backup.WriteResMetadataToBackupFile(outputfile,
                                                           strMetaData);
                if (lRet == -1)
                {
                    return(-1);
                }

                long lBodyStart = 0;
                // 写res body的头。
                // 如果不能预先确知body的长度,可以用随便一个lBodyLength值调用本函数,
                // 但是需要记忆下函数所返回的lBodyStart,最后调用EndWriteResBodyToBackupFile()。
                // 如果能预先确知body的长度,则最后不必调用EndWriteResBodyToBackupFile()
                lRet = Backup.BeginWriteResBodyToBackupFile(
                    outputfile,
                    0, // 未知
                    out lBodyStart);
                if (lRet == -1)
                {
                    return(-1);
                }

                if (stop != null)
                {
                    stop.SetMessage("正在下载 " + strResPath + " 的数据体");
                }

REDO_GETRES_1:
                lRet = channel.GetRes(strResPath,
                                      outputfile,
                                      stop,
                                      "content,data,timestamp", //"content,data,timestamp"
                                      timestamp,
                                      out strMetaData,
                                      out baOutputTimeStamp,
                                      out strOutputPath,
                                      out strError);
                if (lRet == -1)
                {
                    if (channel.ErrorCode == ChannelErrorCode.EmptyRecord)
                    {
                        // 空记录
                    }
                    else
                    {
                        // TODO: 允许重试
                        DialogResult redo_result = MessageBox.Show(owner,
                                                                   "获取记录 '" + strResPath + "' 时出现错误: " + strError + "\r\n\r\n重试,还是中断当前批处理操作?\r\n(Retry 重试;Cancel 中断批处理)",
                                                                   "导出数据",
                                                                   MessageBoxButtons.RetryCancel,
                                                                   MessageBoxIcon.Question,
                                                                   MessageBoxDefaultButton.Button1);
                        if (redo_result == DialogResult.Cancel)
                        {
                            return(-1);
                        }
                        goto
                        REDO_GETRES_1;
                    }
                }

                long lBodyLength = outputfile.Position - lBodyStart - 8;
                // res body收尾
                lRet = Backup.EndWriteResBodyToBackupFile(
                    outputfile,
                    lBodyLength,
                    lBodyStart);
                if (lRet == -1)
                {
                    return(-1);
                }

                long lTotalLength = outputfile.Position - lResStart - 8;
                lRet = Backup.EndWriteResToBackupFile(
                    outputfile,
                    lTotalLength,
                    lResStart);
                if (lRet == -1)
                {
                    return(-1);
                }
            }

            /*
             * if (stop != null)
             *  stop.SetMessage("保存资源到备份文件全部完成");
             */

            return(0);
        }
Example #47
0
        public ProcessingResult Process(RequestContext context)
        {
            int      intServerID = 0;
            MCServer s;
            string   json;
            JObject  jProps;

            if (context.Request.Uri.AbsoluteUri.Contains(@"/api/"))
            {
                //must be authenticated

                //what is the action?
                if (context.Request.Method == Method.Post && WebSession.Current.UserName == "admin")
                {
                    String strResponse         = "";
                    IParameterCollection param = context.Request.Parameters;
                    switch (context.Request.Parameters["action"])
                    {
                    case "log":
                        //grabs lines from the log.
                        int    intStartID = Convert.ToInt32(context.Request.Parameters["start"]);
                        int    intNumRows = Convert.ToInt32(context.Request.Parameters["rows"]);
                        int    intServer  = Convert.ToInt32(context.Request.Parameters["serverid"]);
                        string strLevel   = context.Request.Parameters["level"];

                        DataSet ds = Database.ReturnLogRows(intStartID, intNumRows, strLevel, intServer);

                        strResponse = JsonConvert.SerializeObject(ds, Formatting.Indented);
                        break;

                    case "list":
                        //List available servers
                        strResponse = "{ \"servers\" : [";
                        foreach (KeyValuePair <int, MCServer> kvp in Core.Servers)
                        {
                            strResponse += "{ \"id\" : " + kvp.Value.ServerID + ", " +
                                           "\"title\" : \"" + kvp.Value.ServerTitle + "\", " +
                                           "\"ver\" : \"" + kvp.Value.ServerVersion + "\" } ,";
                        }
                        ;
                        strResponse  = strResponse.Remove(strResponse.Length - 1);
                        strResponse += "]}";
                        break;

                    case "status":
                        //Get status of a server
                        s           = Core.Servers[Convert.ToInt32(context.Request.Parameters["serverid"])];
                        strResponse = "{ \"serverid\" : " + s.ServerID + "," +
                                      "\"status\" : \"" + s.Running + "\"," +
                                      "\"ram\" : " + s.GetMemory() + "," +
                                      "\"vm\" : " + s.GetVMemory() + "," +
                                      "\"restartneeded\" : \"" + s.RestartNeeded + "\"," +
                                      "\"restartwhenfree\" : \"" + s.RestartWhenFree + "\"," +
                                      "\"gamemode\" : \"" + s.GameMode + "\"," +
                                      "\"players\" : [";
                        if (s.Players.Count > 0)
                        {
                            foreach (KeyValuePair <string, Player> kvp in s.Players)
                            {
                                Vector playerPos = kvp.Value.Position;
                                strResponse += " { \"name\": \"" + kvp.Value.Username + "\", " +
                                               "\"level\": \"" + kvp.Value.Level + "\", " +
                                               "\"x\": \"" + playerPos.x.ToString("0.##") + "\", " +
                                               "\"y\": \"" + playerPos.y.ToString("0.##") + "\", " +
                                               "\"z\": \"" + playerPos.z.ToString("0.##") + "\" },";
                            }
                            ;
                            strResponse = strResponse.Remove(strResponse.Length - 1);
                        }
                        strResponse += "]}";
                        break;

                    case "get-players":
                        DataSet dsPlayers = Database.GetPlayers(Convert.ToInt32(context.Request.Parameters["serverid"]));
                        JsonConvert.SerializeObject(dsPlayers, Formatting.Indented);
                        break;

                    case "overviewer":
                        //Maps a server
                        s = Core.Servers[Convert.ToInt32(context.Request.Parameters["serverid"])];
                        string strRenderModes = "";
                        if (param["normal"] == "true")
                        {
                            strRenderModes += "normal";
                        }
                        if (param["lighting"] == "true")
                        {
                            if (strRenderModes != "")
                            {
                                strRenderModes += ",";
                            }
                            strRenderModes += "lighting";
                        }
                        if (param["night"] == "true")
                        {
                            if (strRenderModes != "")
                            {
                                strRenderModes += ",";
                            }
                            strRenderModes += "night";
                        }
                        if (param["spawn"] == "true")
                        {
                            if (strRenderModes != "")
                            {
                                strRenderModes += ",";
                            }
                            strRenderModes += "spawn";
                        }
                        if (param["cave"] == "true")
                        {
                            if (strRenderModes != "")
                            {
                                strRenderModes += ",";
                            }
                            strRenderModes += "cave";
                        }
                        AddOns.Overviewer over = new AddOns.Overviewer(s, "rendermodes=" + strRenderModes);
                        over.Start();
                        strResponse = "{ \"result\" : \"sent\" }";
                        break;

                    case "c10t":
                        //Images a server
                        s = Core.Servers[Convert.ToInt32(context.Request.Parameters["serverid"])];
                        AddOns.c10t c10t = new AddOns.c10t(s, "night=" + param["night"] + "&mode=" + param["mode"]);
                        c10t.Start();
                        strResponse = "{ \"result\" : \"sent\" }";
                        break;

                    case "tectonicus":
                        //Maps a server
                        s = Core.Servers[Convert.ToInt32(context.Request.Parameters["serverid"])];
                        AddOns.Tectonicus tecton = new AddOns.Tectonicus(s, "lighting=" + param["lighting"] + "&night=" + param["night"] + "&delete=" + param["delete"]);
                        tecton.Start();
                        strResponse = "{ \"result\" : \"sent\" }";
                        break;

                    case "start":
                        //Starts a server
                        Core.Servers[Convert.ToInt32(context.Request.Parameters["serverid"])].Start();
                        strResponse = "{ \"result\" : \"sent\" }";
                        break;

                    case "stop":
                        //Stops a server
                        Core.Servers[Convert.ToInt32(context.Request.Parameters["serverid"])].Stop();
                        strResponse = "{ \"result\" : \"sent\" }";
                        break;

                    case "forcestop":
                        //Force stops a server
                        Core.Servers[Convert.ToInt32(context.Request.Parameters["serverid"])].ForceStop();
                        strResponse = "{ \"result\" : \"sent\" }";
                        break;

                    case "restart":
                        //Restarts a server
                        Core.Servers[Convert.ToInt32(context.Request.Parameters["serverid"])].Restart();
                        strResponse = "{ \"result\" : \"sent\" }";
                        break;

                    case "delayed-restart":
                        //Restarts a server after a specified time and warns players
                        Core.Servers[Convert.ToInt32(context.Request.Parameters["serverid"])].DelayedRestart(Convert.ToInt32(param["delay"]));
                        strResponse = "{ \"result\" : \"sent\" }";
                        break;

                    case "restart-when-free":
                        Core.Servers[Convert.ToInt32(context.Request.Parameters["serverid"])].RestartIfEmpty();
                        strResponse = "{ \"result\" : \"sent\" }";
                        break;

                    case "command":
                        //Sends literal command to a server
                        Core.Servers[Convert.ToInt32(context.Request.Parameters["serverid"])].Send(context.Request.Parameters["message"]);
                        strResponse = "{ \"result\" : \"sent\" }";
                        break;

                    case "get-yams-settings":
                        DataSet dsSettings = Database.ReturnSettings();
                        JsonConvert.SerializeObject(dsSettings, Formatting.Indented);
                        break;

                    case "save-yams-settings":
                        //Settings update
                        foreach (Parameter p in param)
                        {
                            if (p.Name != "action")
                            {
                                Database.SaveSetting(p.Name, p.Value);
                            }
                        }
                        break;

                    case "get-server-settings":
                        //retrieve all server settings as JSON
                        List <string> listIPsMC  = new List <string>();
                        IPHostEntry   ipListenMC = Dns.GetHostEntry("");
                        foreach (IPAddress ipaddress in ipListenMC.AddressList)
                        {
                            if (ipaddress.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
                            {
                                listIPsMC.Add(ipaddress.ToString());
                            }
                        }

                        intServerID = Convert.ToInt32(param["serverid"]);
                        strResponse = "{ \"serverid\" : " + intServerID + "," +
                                      "\"title\" : \"" + Database.GetSetting(intServerID, "ServerTitle") + "\"," +
                                      "\"optimisations\" : \"" + Database.GetSetting(intServerID, "ServerEnableOptimisations") + "\"," +
                                      "\"memory\" : \"" + Database.GetSetting(intServerID, "ServerAssignedMemory") + "\"," +
                                      "\"autostart\" : \"" + Database.GetSetting(intServerID, "ServerAutoStart") + "\"," +
                                      "\"type\" : \"" + Database.GetSetting(intServerID, "ServerType") + "\"," +
                                      "\"custom\" : \"" + Database.GetSetting(intServerID, "ServerCustomJAR").ToString().Replace("\\", "\\\\").Replace("\"", "\\\"") + "\"," +
                                      "\"motd\" : \"" + Database.GetSetting("motd", "MC", intServerID) + "\"," +
                                      "\"listen\" : \"" + Core.Servers[Convert.ToInt32(context.Request.Parameters["serverid"])].GetProperty("server-ip") + "\"," +
                                      "\"port\" : \"" + Core.Servers[Convert.ToInt32(context.Request.Parameters["serverid"])].GetProperty("server-port") + "\"," +
                                      "\"IPs\": " + JsonConvert.SerializeObject(listIPsMC, Formatting.None);
                        strResponse += "}";
                        break;

                    case "get-server-connections":
                        intServerID = Convert.ToInt32(param["serverid"]);
                        strResponse = "{ \"dnsname\" : \"" + Database.GetSetting("DNSName", "YAMS") + "\", " +
                                      "\"externalip\" : \"" + Networking.GetExternalIP().ToString() + "\", " +
                                      "\"internalip\" : \"" + Core.Servers[Convert.ToInt32(context.Request.Parameters["serverid"])].GetProperty("server-ip") + "\", " +
                                      "\"mcport\" : " + Core.Servers[Convert.ToInt32(context.Request.Parameters["serverid"])].GetProperty("server-port") + ", " +
                                      "\"publicport\" : " + Database.GetSetting("PublicListenPort", "YAMS") + ", " +
                                      "\"message\" : " + JsonConvert.SerializeObject(Database.GetSetting(intServerID, "ServerWebBody"), Formatting.None) + "}";
                        break;

                    case "save-website-settings":
                        intServerID = Convert.ToInt32(param["serverid"]);
                        Database.UpdateServer(intServerID, "ServerWebBody", param["message"]);
                        break;

                    case "get-mc-settings":
                        //retrieve all server settings as JSON
                        intServerID = Convert.ToInt32(param["serverid"]);

                        json   = File.ReadAllText(YAMS.Core.RootFolder + @"\lib\properties.json");
                        jProps = JObject.Parse(json);

                        strResponse = "";

                        foreach (JObject option in jProps["options"])
                        {
                            strResponse += "<p><label for=\"" + (string)option["key"] + "\" title=\"" + (string)option["description"] + "\">" + (string)option["name"] + "</label>";

                            string strValue = Core.Servers[Convert.ToInt32(context.Request.Parameters["serverid"])].GetProperty((string)option["key"]);

                            switch ((string)option["type"])
                            {
                            case "string":
                                strResponse += "<input type=\"text\" name=\"" + (string)option["key"] + "\" value=\"" + strValue + "\" />";
                                break;

                            case "boolean":
                                strResponse += "<select name=\"" + (string)option["key"] + "\">";
                                strResponse += "<option value=\"true\"";
                                if (strValue == "true")
                                {
                                    strResponse += " selected";
                                }
                                strResponse += ">True</option>";
                                strResponse += "<option value=\"false\"";
                                if (strValue == "false")
                                {
                                    strResponse += " selected";
                                }
                                strResponse += ">False</option>";
                                strResponse += "</select>";
                                break;

                            case "integer":
                                strResponse += "<select name=\"" + (string)option["key"] + "\">";
                                int intValue = Convert.ToInt32(strValue);
                                for (var i = Convert.ToInt32((string)option["min"]); i <= Convert.ToInt32((string)option["max"]); i++)
                                {
                                    strResponse += "<option value=\"" + i.ToString() + "\"";
                                    if (intValue == i)
                                    {
                                        strResponse += " selected";
                                    }
                                    strResponse += ">" + i.ToString() + "</option>";
                                }
                                strResponse += "</select>";
                                break;

                            case "array":
                                strResponse += "<select name=\"" + (string)option["key"] + "\">";
                                string   strValues = (string)option["values"];
                                string[] elements  = strValues.Split(',');
                                foreach (string values in elements)
                                {
                                    string[] options = values.Split('|');
                                    strResponse += "<option value=\"" + options[0] + "\"";
                                    if (strValue == options[0])
                                    {
                                        strResponse += " selected";
                                    }
                                    strResponse += ">" + options[1] + "</option>";
                                }
                                strResponse += "</select>";
                                break;
                            }

                            strResponse += "</p>";
                        }

                        break;

                    case "save-server-settings":
                        intServerID = Convert.ToInt32(param["serverid"]);
                        Database.UpdateServer(intServerID, "ServerTitle", param["title"]);
                        Database.UpdateServer(intServerID, "ServerType", param["type"]);
                        Database.UpdateServer(intServerID, "ServerCustomJAR", param["custom"]);
                        Database.UpdateServer(intServerID, "ServerAssignedMemory", Convert.ToInt32(param["memory"]));
                        if (param["optimisations"] == "true")
                        {
                            Database.UpdateServer(intServerID, "ServerEnableOptimisations", true);
                        }
                        else
                        {
                            Database.UpdateServer(intServerID, "ServerEnableOptimisations", false);
                        }
                        if (param["autostart"] == "true")
                        {
                            Database.UpdateServer(intServerID, "ServerAutoStart", true);
                        }
                        else
                        {
                            Database.UpdateServer(intServerID, "ServerAutoStart", false);
                        }
                        Database.SaveSetting(intServerID, "motd", param["message"]);

                        //Save the server's MC settings
                        MCServer thisServer = Core.Servers[Convert.ToInt32(context.Request.Parameters["serverid"])];
                        thisServer.SaveProperty("server-ip", param["cfg_listen-ip"]);
                        thisServer.SaveProperty("server-port", param["cfg_port"]);

                        json   = File.ReadAllText(YAMS.Core.RootFolder + @"\lib\properties.json");
                        jProps = JObject.Parse(json);

                        strResponse = "";

                        foreach (JObject option in jProps["options"])
                        {
                            thisServer.SaveProperty((string)option["key"], param[(string)option["key"]]);
                        }

                        //If they've selected a Bukkit but not chosen to have them installed, do it for them
                        if (param["type"] == "bukkit")
                        {
                            if (Database.GetSetting("BukkitInstalled", "YAMS") == "false")
                            {
                                Database.SaveSetting("BukkitInstalled", "true");
                                AutoUpdate.CheckUpdates();
                            }
                        }
                        else if (param["type"] == "bukkit-beta")
                        {
                            if (Database.GetSetting("BukkitBetaInstalled", "YAMS") == "false")
                            {
                                Database.SaveSetting("BukkitBetaInstalled", "true");
                                AutoUpdate.CheckUpdates();
                            }
                        }
                        else if (param["type"] == "bukkit-dev")
                        {
                            if (Database.GetSetting("BukkitDevInstalled", "YAMS") == "false")
                            {
                                Database.SaveSetting("BukkitDevInstalled", "true");
                                AutoUpdate.CheckUpdates();
                            }
                        }

                        if (thisServer.Running)
                        {
                            thisServer.RestartIfEmpty();
                        }

                        break;

                    case "get-config-file":
                        List <string> listConfig = Core.Servers[Convert.ToInt32(context.Request.Parameters["serverid"])].ReadConfig(param["file"]);
                        strResponse = JsonConvert.SerializeObject(listConfig, Formatting.Indented);
                        break;

                    case "get-server-whitelist":
                        strResponse = "{ \"enabled\" : " + Core.Servers[Convert.ToInt32(context.Request.Parameters["serverid"])].GetProperty("white-list") + " }";
                        break;

                    case "upload-world":
                        var test = context.Request.Files["new-world"];
                        break;

                    case "delete-world":
                        bool bolRandomSeed = false;
                        if (param["randomseed"] == "true")
                        {
                            bolRandomSeed = true;
                        }
                        Core.Servers[Convert.ToInt32(context.Request.Parameters["serverid"])].ClearWorld(bolRandomSeed);
                        strResponse = "{ \"result\" : \"sent\" }";
                        break;

                    case "remove-server":
                        Core.Servers[Convert.ToInt32(context.Request.Parameters["serverid"])].Stop();
                        Core.Servers.Remove(Convert.ToInt32(context.Request.Parameters["serverid"]));
                        Database.DeleteServer(Convert.ToInt32(context.Request.Parameters["serverid"]));
                        strResponse = "{ \"result\" : \"removed\" }";
                        break;

                    case "about":
                        Dictionary <string, string> dicAbout = new Dictionary <string, string> {
                            { "dll", FileVersionInfo.GetVersionInfo(Path.Combine(Core.RootFolder, "YAMS-Library.dll")).FileVersion },
                            { "svc", FileVersionInfo.GetVersionInfo(Path.Combine(Core.RootFolder, "YAMS-Service.exe")).FileVersion },
                            { "gui", FileVersionInfo.GetVersionInfo(Path.Combine(Core.RootFolder, "YAMS-Updater.exe")).FileVersion },
                            { "db", Database.GetSetting("DBSchema", "YAMS") }
                        };
                        strResponse = JsonConvert.SerializeObject(dicAbout, Formatting.Indented);
                        break;

                    case "installed-apps":
                        Dictionary <string, string> dicApps = new Dictionary <string, string> {
                            { "bukkit", Database.GetSetting("BukkitInstalled", "YAMS") },
                            { "bukkitBeta", Database.GetSetting("BukkitBetaInstalled", "YAMS") },
                            { "bukkitDev", Database.GetSetting("BukkitDevInstalled", "YAMS") },
                            { "overviewer", Database.GetSetting("OverviewerInstalled", "YAMS") },
                            { "c10t", Database.GetSetting("C10tInstalled", "YAMS") },
                            { "biomeextractor", Database.GetSetting("BiomeExtractorInstalled", "YAMS") },
                            { "tectonicus", Database.GetSetting("TectonicusInstalled", "YAMS") },
                            { "nbtoolkit", Database.GetSetting("NBToolkitInstalled", "YAMS") }
                        };
                        strResponse = JsonConvert.SerializeObject(dicApps, Formatting.Indented);
                        break;

                    case "update-apps":
                        Database.SaveSetting("OverviewerInstalled", param["overviewer"]);
                        Database.SaveSetting("C10tInstalled", param["c10t"]);
                        Database.SaveSetting("BiomeExtractorInstalled", param["biomeextractor"]);
                        Database.SaveSetting("BukkitInstalled", param["bukkit"]);
                        Database.SaveSetting("BukkitBetaInstalled", param["bukkitBeta"]);
                        Database.SaveSetting("BukkitDevInstalled", param["bukkitDev"]);
                        strResponse = "done";
                        break;

                    case "force-autoupdate":
                        AutoUpdate.CheckUpdates(false, true);
                        break;

                    case "network-settings":
                        List <string> listIPs  = new List <string>();
                        IPHostEntry   ipListen = Dns.GetHostEntry("");
                        foreach (IPAddress ipaddress in ipListen.AddressList)
                        {
                            if (ipaddress.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
                            {
                                listIPs.Add(ipaddress.ToString());
                            }
                        }

                        Dictionary <string, string> dicNetwork = new Dictionary <string, string> {
                            { "portForwarding", Database.GetSetting("EnablePortForwarding", "YAMS") },
                            { "openFirewall", Database.GetSetting("EnableOpenFirewall", "YAMS") },
                            { "publicEnable", Database.GetSetting("EnablePublicSite", "YAMS") },
                            { "adminPort", Database.GetSetting("AdminListenPort", "YAMS") },
                            { "publicPort", Database.GetSetting("PublicListenPort", "YAMS") },
                            { "currentIP", Database.GetSetting("YAMSListenIP", "YAMS") },
                            { "telnetEnable", Database.GetSetting("EnableTelnet", "YAMS") },
                            { "telnetPort", Database.GetSetting("TelnetPort", "YAMS") },
                            { "IPs", JsonConvert.SerializeObject(listIPs, Formatting.None) }
                        };
                        strResponse = JsonConvert.SerializeObject(dicNetwork, Formatting.Indented).Replace(@"\", "").Replace("\"[", "[").Replace("]\"", "]");
                        break;

                    case "save-network-settings":
                        int intTester = 0;
                        try
                        {
                            //Try to convert to integers to make sure something silly isn't put in. TODO: Javascript validation
                            intTester = Convert.ToInt32(param["adminPort"]);
                            intTester = Convert.ToInt32(param["publicPort"]);
                            IPAddress ipTest = IPAddress.Parse(param["listenIp"]);
                        }
                        catch (Exception e)
                        {
                            YAMS.Database.AddLog("Invalid input on network settings", "web", "warn");
                            return(ProcessingResult.Abort);
                        }

                        Database.SaveSetting("EnablePortForwarding", param["portForwarding"]);
                        Database.SaveSetting("EnableOpenFirewall", param["openFirewall"]);
                        Database.SaveSetting("EnablePublicSite", param["publicEnable"]);
                        Database.SaveSetting("AdminListenPort", param["adminPort"]);
                        Database.SaveSetting("PublicListenPort", param["publicPort"]);
                        Database.SaveSetting("YAMSListenIP", param["listenIp"]);
                        Database.SaveSetting("EnableTelnet", param["telnetEnable"]);
                        Database.SaveSetting("TelnetPort", param["telnetPort"]);

                        Database.AddLog("Network settings have been saved, to apply changes a service restart is required. Please check they are correct before restarting", "web", "warn");
                        break;

                    case "job-list":
                        DataSet rdJobs = Database.ListJobs();
                        strResponse = JsonConvert.SerializeObject(rdJobs, Formatting.Indented);
                        break;

                    case "delete-job":
                        string strJobID = param["jobid"];
                        Database.DeleteJob(strJobID);
                        strResponse = "done";
                        break;

                    case "add-job":
                        intServerID = Convert.ToInt32(param["job-server"]);
                        int intHour   = Convert.ToInt32(param["job-hour"]);
                        int intMinute = Convert.ToInt32(param["job-minute"]);
                        Database.AddJob(param["job-type"], intHour, intMinute, param["job-params"], intServerID);
                        break;

                    case "logout":
                        WebSession.Current.UserName = "";
                        break;

                    case "newserver":
                        var NewServer = new List <KeyValuePair <string, string> >();
                        NewServer.Add(new KeyValuePair <string, string>("motd", "Welcome to a YAMS server!"));
                        NewServer.Add(new KeyValuePair <string, string>("server-ip", Networking.GetListenIP().ToString()));
                        NewServer.Add(new KeyValuePair <string, string>("server-name", param["name"]));
                        NewServer.Add(new KeyValuePair <string, string>("server-port", Networking.TcpPort.FindNextAvailablePort(25565).ToString()));
                        Database.NewServerWeb(NewServer, param["name"], 1024);
                        strResponse = "done";
                        break;

                    case "updateDNS":
                        Database.SaveSetting("DNSName", param["dns-name"]);
                        Database.SaveSetting("DNSSecret", param["dns-secret"]);
                        Database.SaveSetting("LastExternalIP", param["dns-external"]);
                        strResponse = "done";
                        break;

                    case "getDNS":
                        strResponse = "{ \"name\":\"" + Database.GetSetting("DNSName", "YAMS") + "\", \"secret\": \"" + Database.GetSetting("DNSSecret", "YAMS") + "\", \"external\" : \"" + Networking.GetExternalIP().ToString() + "\" }";
                        break;

                    case "backup-now":
                        Backup.BackupNow(Core.Servers[Convert.ToInt32(param["serverid"])], param["title"]);
                        strResponse = "{ \"result\" : \"sent\" }";
                        break;

                    default:
                        return(ProcessingResult.Abort);
                    }

                    context.Response.Reason          = "Completed - YAMS";
                    context.Response.Connection.Type = ConnectionType.Close;
                    byte[] buffer = Encoding.UTF8.GetBytes(strResponse);
                    context.Response.Body.Write(buffer, 0, buffer.Length);
                }
                else
                {
                    // not a post, so say bye bye!
                    return(ProcessingResult.Abort);
                }

                return(ProcessingResult.SendResponse);
            }
            else if (context.Request.Uri.AbsoluteUri.Contains(@"/admin"))
            {
                if (WebSession.Current.UserName != "admin")
                {
                    context.Response.Reason          = "Completed - YAMS";
                    context.Response.Connection.Type = ConnectionType.Close;
                    byte[] buffer = Encoding.UTF8.GetBytes(File.ReadAllText(YAMS.Core.RootFolder + @"\web\admin\login.html"));
                    context.Response.Body.Write(buffer, 0, buffer.Length);
                    return(ProcessingResult.SendResponse);
                }
                else
                {
                    context.Response.Reason          = "Completed - YAMS";
                    context.Response.Connection.Type = ConnectionType.Close;
                    byte[] buffer = Encoding.UTF8.GetBytes(File.ReadAllText(YAMS.Core.RootFolder + @"\web\admin\index.html"));
                    context.Response.Body.Write(buffer, 0, buffer.Length);
                    return(ProcessingResult.SendResponse);
                }
            }
            else if (context.Request.Uri.AbsoluteUri.Contains(@"/login"))
            {
                //This is a login request, check it's legit
                string userName = context.Request.Form["strUsername"];
                string password = context.Request.Form["strPassword"];

                if (userName == "admin" && password == Database.GetSetting("AdminPassword", "YAMS"))
                {
                    WebSession.Create();
                    WebSession.Current.UserName = "******";
                    context.Response.Redirect(@"/admin");
                    return(ProcessingResult.SendResponse);
                }
                else
                {
                    context.Response.Reason          = "Completed - YAMS";
                    context.Response.Connection.Type = ConnectionType.Close;
                    byte[] buffer = Encoding.UTF8.GetBytes(File.ReadAllText(YAMS.Core.RootFolder + @"\web\admin\login.html"));
                    context.Response.Body.Write(buffer, 0, buffer.Length);
                    return(ProcessingResult.SendResponse);
                }
            }
            else if (context.Request.Uri.AbsoluteUri.Equals(@"/"))
            {
                context.Response.Redirect(@"/admin");
                return(ProcessingResult.SendResponse);
            }
            else
            {
                return(ProcessingResult.Abort);
            }
        }
 public Backup Update(Backup backup)
 {
     this.db.Entry(backup).State = Microsoft.EntityFrameworkCore.EntityState.Modified;
     this.db.SaveChanges();
     return(backup);
 }
Example #49
0
        private async void StartImportingAsync()
        {
            if (HIOStaticValues.CheckSyncingData())
            {
                return;
            }

            List <LoginFieldS> listUser = new List <LoginFieldS>();

            try
            {
                if (HIOStaticValues.CONNECTIONBHIO == true)
                {
                    Commands cmd          = new Backend.Commands();
                    int      userImported = 0;
                    DataBase dbLocal      = new DataBase();
LabelImport:
                    if (cmd.AmISync() == SyncronizingStateEnum.Synced)
                    {
                        IsImporting = true;

                        await Task.Run(() =>
                        {
                            Backup bk       = new Backup();
                            Chrome chrome   = new Chrome();
                            Firefox firefox = new Firefox();
                            Edge edge       = new Edge();
                            double progress = ImportProgressPercent;
                            //  var itemList = Items.Where(t => t.IsChecked);

                            foreach (var item in Items.Where(t => t.IsChecked))
                            {
                                if (item.Title == "Load Backup")
                                {
                                    listUser.AddRange(bk.LoadBackup());
                                }
                                if (item.Title == "Google Chrome")
                                {
                                    listUser.AddRange(chrome.getDataFromChrome());
                                }
                                if (item.Title == "Mozilla Firefox")
                                {
                                    listUser.AddRange(firefox.FetchPassword());
                                }
                                if (item.Title == "Edge")
                                {
                                    listUser.AddRange(edge.ReadPasswords());
                                }
                            }
                            listUser = listUser.Distinct(new loginFieldsCompare()).ToList();
                            int rows = listUser.Count;
                            // ImportVisible = true;

                            try
                            {
                                HIOStaticValues.IMPORT_ON = true;
                                if (rows == 0)
                                {
                                    MessageErr = "No account exist in your browsers";
                                    return;
                                }
                                for (int i = 0; i < rows; i++)
                                {
                                    ImportProgressPercent = (progress == 0) ? (i * 100) / (rows) : progress + ((i * 100) / (rows)) / 2;
                                    int res = HIOStaticValues.BaS.InsertToSwitch(new LoginFieldS {
                                        password = listUser[i].password, userName = listUser[i].userName, title = listUser[i].title, url = listUser[i].url
                                    });

                                    if (res <= 0)
                                    {
                                        if (res == -2)
                                        {
                                            throw new Exception($"Time out.\n {i}  accounts are imported successfully from {rows} accounts");
                                        }
                                        if (res == -3)
                                        {
                                            throw new Exception($"No space is available.\n {userImported} accounts are imported successfully");
                                        }

                                        break;
                                    }
                                    userImported++;
                                    dbLocal.insertToDatabase(res.ToString(), listUser[i].url, (string)listUser[i].userName, "", listUser[i].title);
                                }
                            }
                            catch (SQLiteException ex) when(ex.ErrorCode == 5)
                            {
                                MessageErr = $"HIO needs to close all browsers!{Environment.NewLine}Please save or close your Tabs if your are using any browsers.";
                                return;
                            }
                            catch (Exception ex)
                            {
                                MessageErr = ex.Message;
                                return;
                            }

                            HIOStaticValues.IMPORT_ON = false;
                            System.Windows.Application.Current.Dispatcher.Invoke(new Action(() =>
                            {
                                IsImporting           = false;
                                ImportVisible         = false;
                                ImportProgressPercent = 0;
                                IsComplete            = true;
                                //  if (db_way2 != "")
                                //    System.IO.File.Delete(db_way2);
                            }));
                        });



                        if (Items.Any(t => t.IsChecked))
                        {
                            MoveNextPage();
                        }
                    }
                    else
                    {
                        HIOStaticValues.popUp("You are not sync!\nPlease wait,We are syncing data...");
                        IsImporting = true;
                        DispatcherTimer dt = new DispatcherTimer();
                        dt.Interval = TimeSpan.FromSeconds(1);
                        dt.Tick    += Dt_Tick;
                        dt.Start();
                        int res = await Task.Run(() =>
                        {
                            DataBase db       = new DataBase();
                            Commands resetCmd = new Backend.Commands();
                            resetCmd.ResetSync();
                            return(resetCmd.Sync());
                        });

                        dt.Stop();

                        if (res == 1)
                        {
                            goto LabelImport;
                        }
                    }
                }
                else
                {
                    TMessageBox.Show("HIO is not connect!");
                }
            }
            finally
            {
                IsImporting = false;

                HIOStaticValues.IMPORT_ON = false;
            }
        }
        /// <summary>
        /// Backups the database.
        /// </summary>
        /// <returns></returns>
        public static bool BackupDatabase(SplashScreenManager splashScreenManager, string backupName, bool openBackupFolder)
        {
            try
            {
                var globalVariable = new GlobalVariable();
                if (splashScreenManager != null)
                {
                    splashScreenManager.ShowWaitForm();
                    splashScreenManager.SetWaitFormCaption("Đang sao lưu dữ liệu");
                    splashScreenManager.SetWaitFormDescription("Vui lòng đợi ..");
                }

                var databaseNameForBackup = RegistryHelper.GetValueByRegistryKey("DatabaseName");
                var databaseForBackup     = GlobalVariable.Server.Databases[databaseNameForBackup];
                var backup = new Backup
                {
                    //option for backup
                    Action = BackupActionType.Database,
                    BackupSetDescription = "Sao lưu CSDL, ngày " + DateTime.Now,
                    BackupSetName        = databaseNameForBackup + " Backup",
                    Database             = databaseForBackup.Name
                };

                //create backupdevice
                var folderBackup   = globalVariable.DailyBackupPath;
                var dateTimeString = "NG" + DateTime.Now.Day.ToString(CultureInfo.InvariantCulture) +
                                     "T" + DateTime.Now.Month.ToString(CultureInfo.InvariantCulture) +
                                     "N" + DateTime.Now.Year.ToString(CultureInfo.InvariantCulture) +
                                     "_" + DateTime.Now.Hour.ToString(CultureInfo.InvariantCulture) + "GI" +
                                     DateTime.Now.Minute.ToString(CultureInfo.InvariantCulture) + "P";

                var databaseName = databaseNameForBackup + "_" + (string.IsNullOrEmpty(backupName) ? "" : backupName) + "_" + dateTimeString + ".bak";

                //LINHMC kiem tra neu folder ko ton tai thi tao
                if (string.IsNullOrEmpty(folderBackup))
                {
                    DriveInfo[] allDrives = DriveInfo.GetDrives();
                    if (allDrives.Length > 1)
                    {
                        folderBackup = allDrives[1].Name + @"BACKUP_A_BIGTIME";
                    }
                    else
                    {
                        folderBackup = allDrives[0].Name + @"BACKUP_A_BIGTIME";
                    }
                }
                if (!Directory.Exists(folderBackup))
                {
                    Directory.CreateDirectory(folderBackup);
                }

                var fileBackup = folderBackup + @"\" + databaseName;
                if (File.Exists(fileBackup))
                {
                    XtraMessageBox.Show(ResourceHelper.GetResourceValueByName("ResFileBackupExits"),
                                        ResourceHelper.GetResourceValueByName("ResExceptionCaption"), MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return(false);
                }
                var backupDevice = new BackupDeviceItem(fileBackup, DeviceType.File);

                backup.Devices.Add(backupDevice);
                backup.Incremental = false;

                backup.SqlBackup(GlobalVariable.Server);

                //Cách nén file này chỉ dùng trong trường hợp hệ quản trị dữ liệu và chương trình cùng nằm trên 1 máy
                using (var zip = new ZipFile())
                {
                    zip.AddFile(fileBackup, "");
                    var zipFileName = fileBackup.Replace(".bak", ".zip");
                    zip.ParallelDeflateThreshold = -1;
                    zip.Save(zipFileName);
                    File.Delete(fileBackup);
                }
                if (splashScreenManager != null)
                {
                    splashScreenManager.CloseWaitForm();
                }

                if (openBackupFolder)
                {
                    Process.Start(folderBackup);
                }
                return(true);
            }
            catch (Exception ex)
            {
                if (splashScreenManager != null)
                {
                    splashScreenManager.CloseWaitForm();
                }
                XtraMessageBox.Show(ex.ToString(),
                                    ResourceHelper.GetResourceValueByName("ResExceptionCaption"), MessageBoxButtons.OK, MessageBoxIcon.Error);
                return(false);
            }
        }
        public async Task CleanTombstonesInTheClusterWithBackup()
        {
            var cluster = await CreateRaftCluster(3);

            var database = GetDatabaseName();

            await CreateDatabaseInCluster(database, 3, cluster.Leader.WebUrl);

            var backupPath = NewDataPath(suffix: "BackupFolder");

            using (var store = GetDocumentStore(new Options
            {
                CreateDatabase = false,
                Server = cluster.Leader,
                ModifyDatabaseName = _ => database,
                // Backup.RunBackupInClusterAsync uses node tag to wait for backup occurrence
                ModifyDocumentStore = s => s.Conventions.DisableTopologyUpdates = false
            }))
            {
                var config = Backup.CreateBackupConfiguration(backupPath, incrementalBackupFrequency: "0 0 1 1 *");
                var result = await store.Maintenance.SendAsync(new UpdatePeriodicBackupOperation(config));

                using (var session = store.OpenSession())
                {
                    session.Store(new User {
                        Name = "Karmel"
                    }, "foo/bar");
                    session.SaveChanges();
                }

                using (var session = store.OpenSession())
                {
                    session.Advanced.WaitForReplicationAfterSaveChanges(replicas: 2);
                    session.Delete("foo/bar");
                    session.SaveChanges();
                }

                using (var session = store.OpenSession())
                {
                    session.Advanced.WaitForReplicationAfterSaveChanges(replicas: 2);
                    session.Store(new User {
                        Name = "Karmel"
                    }, "marker");
                    session.SaveChanges();

                    Assert.True(await WaitForDocumentInClusterAsync <User>(cluster.Nodes, database, "marker", (u) => u.Id == "marker", TimeSpan.FromSeconds(15)));
                }

                // wait for CV to merge after replication
                Assert.True(await WaitForChangeVectorInClusterAsync(cluster.Nodes, database));

                var total = 0L;
                foreach (var server in cluster.Nodes)
                {
                    var storage = await server.ServerStore.DatabasesLandlord.TryGetOrCreateResourceStore(store.Database);

                    await storage.TombstoneCleaner.ExecuteCleanup();

                    using (storage.DocumentsStorage.ContextPool.AllocateOperationContext(out DocumentsOperationContext context))
                        using (context.OpenReadTransaction())
                        {
                            total += storage.DocumentsStorage.GetNumberOfTombstones(context);
                        }
                }

                Assert.Equal(3, total);

                await Backup.RunBackupInClusterAsync(store, result.TaskId, isFullBackup : true);
                await ActionWithLeader(async x => await WaitForRaftCommandToBeAppliedInCluster(x, nameof(UpdatePeriodicBackupStatusCommand)), cluster.Nodes);

                var res = await WaitForValueAsync(async() =>
                {
                    var c = 0L;
                    foreach (var server in cluster.Nodes)
                    {
                        var storage = await server.ServerStore.DatabasesLandlord.TryGetOrCreateResourceStore(store.Database);
                        await storage.TombstoneCleaner.ExecuteCleanup();
                        using (storage.DocumentsStorage.ContextPool.AllocateOperationContext(out DocumentsOperationContext context))
                            using (context.OpenReadTransaction())
                            {
                                c += storage.DocumentsStorage.GetNumberOfTombstones(context);
                            }
                    }
                    return(c);
                }, 0, interval : 333);

                Assert.Equal(0, res);
            }
        }
Example #52
0
        public void Patch(TimeWarp timeQuadrant)
        {
            if (mBackup != null)
            {
                throw new InvalidOperationException("Patcher is already in use.");
            }
            ScreenSafeUISlideTab tab = timeQuadrant.timeQuadrantTab;

            mBackup = new Backup()
            {
                TimeQuadrant      = timeQuadrant,
                Texture           = tab.renderer.material.mainTexture,
                Scale             = tab.transform.localScale,
                Center            = ((BoxCollider)tab.collider).center,
                ExpandedPosition  = tab.expandedPos,
                CollapsedPosition = tab.collapsedPos,
            };

            List <Transform> children = new List <Transform>();

            foreach (Transform child in tab.transform)
            {
                children.Add(child);
            }

            foreach (Transform child in children)
            {
                child.parent = tab.transform.parent;
            }

            // Set the new texture
            Texture2D newTexture;

            RTUtil.LoadImage(out newTexture, "texTimeQuadrant.png");
            tab.renderer.material.mainTexture = newTexture;

            // Apply new scale, positions
            tab.transform.localScale = new Vector3(tab.transform.localScale.x,
                                                   tab.transform.localScale.y,
                                                   tab.transform.localScale.z *
                                                   1.3970588235294117647058823529412f);
            tab.collapsedPos += new Vector3(0, -0.013f, 0);
            tab.expandedPos  += new Vector3(0, -0.013f, 0);
            foreach (Transform child in children)
            {
                child.localPosition += new Vector3(0, 0.013f, 0);
            }
            tab.Expand();

            foreach (Transform child in children)
            {
                child.parent = tab.transform;
            }

            ((BoxCollider)tab.collider).center += new Vector3(0, 0, -0.37f);

            ScreenSafeGUIText text =
                tab.transform.FindChild("MET timer").GetComponent <ScreenSafeGUIText>();

            mTextStyle          = text.textStyle;
            mTextStyle.fontSize = (int)(text.textSize * ScreenSafeUI.PixelRatio);

            RenderingManager.AddToPostDrawQueue(0, Draw);
        }
Example #53
0
 protected override int UnwantedPointsCount(Backup backup) => backup.RestorePoints.Count - PointsToSaveCount(backup) > 0
     ? backup.RestorePoints.Count - PointsToSaveCount(backup)
     : 0;
        public async Task CleanTombstonesInTheClusterWithOnlyFullBackup()
        {
            var cluster = await CreateRaftCluster(3);

            var database = GetDatabaseName();

            await CreateDatabaseInCluster(database, 3, cluster.Leader.WebUrl);

            var backupPath = NewDataPath(suffix: "BackupFolder");

            using (var store = GetDocumentStore(new Options
            {
                CreateDatabase = false,
                Server = cluster.Leader,
                ModifyDatabaseName = _ => database
            }))
            {
                var config = Backup.CreateBackupConfiguration(backupPath);
                await store.Maintenance.SendAsync(new UpdatePeriodicBackupOperation(config));

                using (var session = store.OpenSession())
                {
                    session.Store(new User {
                        Name = "Karmel"
                    }, "foo/bar");
                    session.SaveChanges();
                }

                using (var session = store.OpenSession())
                {
                    session.Advanced.WaitForReplicationAfterSaveChanges(replicas: 2);
                    session.Delete("foo/bar");
                    session.SaveChanges();
                }

                using (var session = store.OpenSession())
                {
                    session.Advanced.WaitForReplicationAfterSaveChanges(replicas: 2);
                    session.Store(new User {
                        Name = "Karmel"
                    }, "marker");
                    session.SaveChanges();

                    Assert.True(await WaitForDocumentInClusterAsync <User>(cluster.Nodes, database, "marker", (u) => u.Id == "marker", TimeSpan.FromSeconds(15)));
                }

                // wait for CV to merge after replication
                Assert.True(await WaitForChangeVectorInClusterAsync(cluster.Nodes, database));

                var res = await WaitForValueAsync(async() =>
                {
                    var c = 0L;
                    foreach (var server in cluster.Nodes)
                    {
                        var storage = await server.ServerStore.DatabasesLandlord.TryGetOrCreateResourceStore(store.Database);
                        await storage.TombstoneCleaner.ExecuteCleanup();
                        using (storage.DocumentsStorage.ContextPool.AllocateOperationContext(out DocumentsOperationContext context))
                            using (context.OpenReadTransaction())
                            {
                                c += storage.DocumentsStorage.GetNumberOfTombstones(context);
                            }
                    }
                    return(c);
                }, 0, interval : 333);

                Assert.Equal(0, res);
            }
        }
Example #55
0
        // 将主记录和相关资源写入备份文件
        // 本函数如果失败,会自动把本次写入的局部内容从文件末尾抹去
        // TODO: 测试磁盘空间耗尽的情况
        static int WriteRecordToBackupFile(
            IWin32Window owner,
            RmsChannel channel,
            DigitalPlatform.Stop stop,
            Stream outputfile,
            string strPath, // 记录路径
            string strMetaData,
            string strXmlBody,
            byte[] body_timestamp,
            out string strError)
        {
            strError = "";
            Debug.Assert(String.IsNullOrEmpty(strXmlBody) == false, "strXmlBody不能为空");

            Debug.Assert(channel != null, "");
            // string strPath = strDbName + "/" + strID;

            long lStart = outputfile.Position;  // 记忆起始位置
            bool bDone  = false;

            try
            {
                byte[] length = new byte[8];

                outputfile.Write(length, 0, 8); // 临时写点数据,占据记录总长度位置

                ResPath respath = new ResPath();
                respath.Url  = channel.Url;
                respath.Path = strPath;

                // 加工元数据
                StringUtil.ChangeMetaData(ref strMetaData,
                                          null,
                                          null,
                                          null,
                                          null,
                                          respath.FullPath,
                                          ByteArray.GetHexTimeStampString(body_timestamp)); // 2005/6/11

                // 向backup文件中保存第一个 res
                long lRet = Backup.WriteFirstResToBackupFile(
                    outputfile,
                    strMetaData,
                    strXmlBody);

                // 其余
                string[] ids = null;

                // 得到Xml记录中所有<file>元素的id属性值
                int nRet = GetFileIds(strXmlBody,
                                      out ids,
                                      out strError);
                if (nRet == -1)
                {
                    // outputfile.SetLength(lStart);	// 把本次追加写入的全部去掉
                    strError = "GetFileIds()出错,无法获得 XML 记录 (" + strPath + ") 中的 <dprms:file>元素的 id 属性, 因此保存记录失败,原因: " + strError;
                    goto ERROR1;
                }

                nRet = WriteResToBackupFile(
                    owner,
                    channel,
                    stop,
                    outputfile,
                    respath.Path,
                    ids,
                    out strError);
                if (nRet == -1)
                {
                    // outputfile.SetLength(lStart);	// 把本次追加写入的全部去掉
                    strError = "WriteResToBackupFile()出错,因此保存记录 (" + strPath + ") 失败,原因: " + strError;
                    goto ERROR1;
                }

                ///


                // 写入总长度
                long   lTotalLength = outputfile.Position - lStart - 8;
                byte[] data         = BitConverter.GetBytes(lTotalLength);

                // 返回记录最开头位置
                outputfile.Seek(lStart - outputfile.Position, SeekOrigin.Current);
                Debug.Assert(outputfile.Position == lStart, "");

                // outputfile.Seek(lStart, SeekOrigin.Begin);   // 文件大了以后这句话的性能会很差
                outputfile.Write(data, 0, 8);

                // 跳到记录末尾位置
                outputfile.Seek(lTotalLength, SeekOrigin.Current);
                bDone = true;
            }
            finally
            {
                if (bDone == false)
                {
                    outputfile.SetLength(lStart);       // 把本次追加写入的全部去掉
                    outputfile.Seek(0, SeekOrigin.End); // 把文件指针恢复到文件末尾位置,便于下次调用继续写入
                }
            }

            return(0);

ERROR1:
            return(-1);
        }
        /// <summary>
        /// Create database back up in Zip format and kept in path
        /// </summary>
        /// <returns>int 0 -not success, 1- success, 2 - already backkup available</returns>
        public int CreateSqlDatabaseBackUp(FactoryReset oFactoryResetEntity)
        {
            SqlConnection    SqlConn = null;
            ServerConnection svrConnServerConnection = null;
            Server           SqlSever = null;
            Backup           bak      = null;
            BackupDeviceItem bkpitem  = null;
            DateTime         dt       = DateTime.Now;
            int iResult = 0;

            String[] format      = { "ddMMMyyyyHHmm" };
            string   bkpFileName = "";
            string   Backuppath  = "";
            string   date        = "";
            string   zipFileName = "";

            try
            {
                date        = dt.ToString(format[0], DateTimeFormatInfo.InvariantInfo);
                Backuppath  = oFactoryResetEntity.strBackupPath;
                bkpFileName = Backuppath + "\\" + "[" + date + "]" + "_BAK_" + "[" +
                              CommonDataAccess.GetSettingValue("TICKET_LOCATION_CODE") + "]" +
                              "[" + BMC.Transport.Settings.SiteName + "]" + "_" +
                              oFactoryResetEntity.BackUpDataBase + ".BAK";
                oFactoryResetEntity.strBackupFileName = bkpFileName;
                if (Directory.Exists(Backuppath))
                {
                    if (File.Exists(bkpFileName) == false)
                    {
                        try
                        {
                            SqlConn = new SqlConnection(CommonDataAccess.ExchangeConnectionString);
                            svrConnServerConnection = new ServerConnection(SqlConn);
                            SqlSever = new Server(svrConnServerConnection);

                            if (SqlSever != null)
                            {
                                bak        = new Microsoft.SqlServer.Management.Smo.Backup();
                                bak.Action = BackupActionType.Database;
                                bkpitem    = new BackupDeviceItem(bkpFileName, DeviceType.File);
                                bak.Devices.Add(bkpitem);
                                bak.Database = oFactoryResetEntity.BackUpDataBase;
                                bak.SqlBackup(SqlSever);
                            }
                        }
                        catch (SqlException sqlex)
                        {
                            ExceptionManager.Publish(sqlex);
                            iResult = 0;
                        }
                        catch (TimeoutException tex)
                        {
                            ExceptionManager.Publish(tex);
                            iResult = 0;
                        }

                        zipFileName = Backuppath + "\\" + "bkp" + oFactoryResetEntity.BackUpDataBase + date + ".ZIP";
                        zipFileName = Backuppath + "\\" + "[" + date + "]" + "_BAK_" + "[" +
                                      CommonDataAccess.GetSettingValue("TICKET_LOCATION_CODE") + "]" +
                                      "[" + BMC.Transport.Settings.SiteName + "]" + "_" +
                                      oFactoryResetEntity.BackUpDataBase + ".ZIP";
                        oFactoryResetEntity.strZipFileName = zipFileName;
                        iResult = 1;
                    }
                    else
                    {
                        iResult = 2;
                    }
                }
                else
                {
                    Directory.CreateDirectory(Backuppath);
                    try
                    {
                        SqlConn = new SqlConnection(CommonDataAccess.ExchangeConnectionString);
                        svrConnServerConnection = new ServerConnection(SqlConn);
                        SqlSever = new Server(svrConnServerConnection);

                        if (SqlSever != null)
                        {
                            bak        = new Microsoft.SqlServer.Management.Smo.Backup();
                            bak.Action = BackupActionType.Database;
                            bkpitem    = new BackupDeviceItem(bkpFileName, DeviceType.File);
                            bak.Devices.Add(bkpitem);
                            bak.Database = oFactoryResetEntity.BackUpDataBase;
                            bak.SqlBackup(SqlSever);
                        }
                    }
                    catch (SqlException sqlex)
                    {
                        ExceptionManager.Publish(sqlex);
                        iResult = 0;
                    }
                    catch (TimeoutException tex)
                    {
                        ExceptionManager.Publish(tex);
                        iResult = 0;
                    }
                    zipFileName = Backuppath + "bkp" + oFactoryResetEntity.BackUpDataBase + date + ".zip";
                    oFactoryResetEntity.strZipFileName = zipFileName;
                    iResult = 1;
                }
            }
            catch (FileNotFoundException fex)
            {
                ExceptionManager.Publish(fex);
                iResult = 0;
            }
            catch (FileLoadException flx)
            {
                ExceptionManager.Publish(flx);
                iResult = 0;
            }
            catch (Exception ex)
            {
                ExceptionManager.Publish(ex);
                iResult = 0;
            }
            return(iResult);
        }
Example #57
0
        /// <summary>
        /// ...
        /// </summary>
        private static bool DoBackup(Dictionary <string, string> parameters)
        {
            // Google Apps
            bool   appsMode        = parameters.ContainsKey("appsMode") ? parameters["appsMode"] == "1" : false;
            string appsDomain      = null;
            string appsOAuthSecret = null;
            bool   appsOAuthOnly   = false;

            if (appsMode)
            {
                appsDomain      = parameters.ContainsKey("appsDomain") ? parameters["appsDomain"] : null;
                appsOAuthSecret = parameters.ContainsKey("appsOAuthSecret") ? parameters["appsOAuthSecret"] : null;
                appsOAuthOnly   = parameters.ContainsKey("appsOAuthOnly") ? parameters["appsOAuthOnly"] == "1" : false;
                if (String.IsNullOrEmpty(appsDomain))
                {
                    throw new ApplicationException("Empty appsDomain parameter");
                }
                if (String.IsNullOrEmpty(appsOAuthSecret))
                {
                    throw new ApplicationException("Empty appsOAuthSecret parameter");
                }
            }

            // Get username
            string username = parameters.ContainsKey("username") ? parameters["username"] : null;

            if ((appsMode == false && username == null) ||
                (appsMode == true && appsOAuthOnly == false && username == null))
            {
                throw new ApplicationException("Empty username parameter");
            }

            // Get password
            string password = null;

            if (parameters.ContainsKey("password"))
            {
                password = parameters["password"];
            }
            if (parameters.ContainsKey("passwordEnc"))
            {
                password = Utility.UnprotectData(parameters["passwordEnc"]);
            }
            if (parameters.ContainsKey("passwordEncFile"))
            {
                password = Utility.UnprotectData(File.ReadAllText(parameters["passwordEncFile"]));
            }
            if ((appsMode == false && password == null) ||
                (appsMode == true && appsOAuthOnly == false && password == null))
            {
                throw new ApplicationException("Empty password parameter");
            }

            // Get destDir
            string destDir = parameters.ContainsKey("destDir") ? parameters["destDir"] : null;

            if (destDir == null)
            {
                throw new ApplicationException("Empty destDir parameter");
            }

            // Get document export format
            string docF  = parameters.ContainsKey("docF") ? parameters["docF"] : null;
            string sprsF = parameters.ContainsKey("sprsF") ? parameters["sprsF"] : null;
            string presF = parameters.ContainsKey("presF") ? parameters["presF"] : null;
            string drawF = parameters.ContainsKey("drawF") ? parameters["drawF"] : null;

            if (docF == null)
            {
                throw new ApplicationException("Empty docF parameter");
            }
            if (sprsF == null)
            {
                throw new ApplicationException("Empty sprsF parameter");
            }
            if (presF == null)
            {
                throw new ApplicationException("Empty presF parameter");
            }
            if (drawF == null)
            {
                throw new ApplicationException("Empty drawF parameter");
            }
            List <Document.DownloadType> docTypes  = Utility.DecodeDownloadTypeArray(docF, '+');
            List <Document.DownloadType> sprsTypes = Utility.DecodeDownloadTypeArray(sprsF, '+');
            List <Document.DownloadType> presTypes = Utility.DecodeDownloadTypeArray(presF, '+');
            List <Document.DownloadType> drawTypes = Utility.DecodeDownloadTypeArray(drawF, '+');
            string downloadAll = parameters.ContainsKey("downloadAll") ? parameters["downloadAll"] : null;

            // Get BypassHttpsCertChecks
            bool bypassHttpsCertChecks = parameters.ContainsKey("bypassHttpsCertChecks");

            // Output parameters
            Console.WriteLine(new String('-', 40));
            Console.WriteLine("Parameters: ");
            Console.WriteLine("Username:        "******"Password:        "******"[hidden]");
            Console.WriteLine("DestDir:         " + destDir);
            Console.WriteLine("Document:        " + docF);
            Console.WriteLine("Spreadsheet:     " + sprsF);
            Console.WriteLine("Presentation:    " + presF);
            Console.WriteLine("Drawing:         " + drawF);
            Console.WriteLine("DownloadAll:     " + downloadAll);
            Console.WriteLine("appsMode:        " + appsMode);
            Console.WriteLine("appsDomain:      " + appsDomain);
            Console.WriteLine("appsOAuthSecret: " + appsOAuthSecret);
            Console.WriteLine("appsOAuthOnly:   " + appsOAuthOnly);
            Console.WriteLine(new String('-', 40));

            // Exec backup
            Config config = new Config(
                username, password,
                destDir,
                downloadAll == "yes",
                docTypes.ToArray(), sprsTypes.ToArray(), presTypes.ToArray(), drawTypes.ToArray(),
                null,
                bypassHttpsCertChecks,
                false,
                null,
                appsMode,
                appsDomain,
                appsOAuthSecret,
                appsOAuthOnly);

            Backup backup = new Backup(config);

            backup.Feedback += new EventHandler <FeedbackEventArgs>(backup_Feedback);
            bool resOK = backup.Exec();

            return(resOK);
        }
Example #58
0
        static void Main(string[] args)
        {
            string command;
            Game   game    = new Game();
            bool   resumed = true;

            game = Backup.Load("savedgame.xml");
            if (game != null)
            {
                Console.WriteLine("The is an open game available! Would you like to resume the saved game?");
                Console.WriteLine("Type \"continue\" to resume or \"new\" for a new game");

                while (resumed)
                {
                    command = Console.ReadLine();
                    switch (command)
                    {
                    case "new":
                        game = new Game();
                        game.board.RandomizeBoard();
                        resumed = false;
                        break;

                    case "continue":
                        game    = Backup.Load("savedgame.xml");
                        resumed = false;
                        break;

                    case "exit":
                        System.Environment.Exit(1);
                        break;

                    default:
                        Console.WriteLine("Invalid command! Type \"continue\" to resume or \"new\" for a new game");
                        break;
                    }
                }
            }

            while ((command = Console.ReadLine()) != null)
            {
                switch (command)
                {
                case "show":
                    if (game.board.chosen_numbers.Count == 0)
                    {
                        game.board.RandomizeBoard();
                    }
                    Printer.PrintBoard(game.board, game.state);
                    break;

                case "end":
                    if (game.board.chosen_numbers.Count == 0)
                    {
                        Console.WriteLine("There is no active game! Type \"show\" in order to populate the board!");
                    }
                    else
                    {
                        Console.WriteLine("The game has ended! This is the board and your credit:");
                        Printer.PrintBoard(game.board, game.state);
                        game = new Game();
                    }

                    break;

                case "exit":
                    if (game.state.guesses > 0 && game.state.guesses < 5)
                    {
                        Backup.Save(game, "savedgame.xml");
                    }
                    System.Environment.Exit(1);
                    break;

                default:
                    try
                    {
                        int number = Int32.Parse(command);

                        if (number >= 90)
                        {
                            Console.WriteLine("The Number must be between 0 and 89!");
                        }
                        else if (number < 0)
                        {
                            Console.WriteLine("The Number must be between 0 and 89!");
                        }
                        else
                        {
                            if (game.board.chosen_numbers.Count == 0)
                            {
                                Console.WriteLine("The board is empty! Type \"show\" in order to populate the board!");
                            }
                            else
                            {
                                game.board.ChooseNumber(number, game.state);
                                if (game.state.guesses == 5)
                                {
                                    var save_credit = game.state.credit;
                                    game = new Game();
                                    game.state.credit = save_credit;
                                }
                            }
                        }
                    }
                    catch (FormatException)
                    {
                        Console.WriteLine("Invalid Command!");
                    }
                    break;
                }
            }
        }
Example #59
0
        public async Task Tomstones_should_be_cleaned_properly_for_multiple_backup_tasks(BackupType backupType)
        {
            var backupPath1 = NewDataPath(suffix: "BackupFolder");
            var backupPath2 = NewDataPath(suffix: "BackupFolder");

            using (var store = GetDocumentStore())
            {
                using (var session = store.OpenSession())
                {
                    session.Store(new FooBar
                    {
                        Foo = "Bar1"
                    }, "foo/bar1");
                    session.Store(new FooBar
                    {
                        Foo = "Bar2"
                    }, "foo/bar2");
                    session.SaveChanges();
                }

                var documentDatabase = (await GetDocumentDatabaseInstanceFor(store));

                using (var session = store.OpenSession())
                {
                    session.Delete("foo/bar1");
                    session.SaveChanges();
                }
                var config1       = Backup.CreateBackupConfiguration(backupPath1, backupType: backupType, incrementalBackupFrequency: "* */6 * * *");
                var config2       = Backup.CreateBackupConfiguration(backupPath2, backupType: backupType, incrementalBackupFrequency: "* */6 * * *");
                var backupTaskId1 = await Backup.UpdateConfigAndRunBackupAsync(Server, config1, store, isFullBackup : false);

                await Backup.UpdateConfigAndRunBackupAsync(Server, config2, store, isFullBackup : false);

                //force tombstone cleanup - now, after backup, tombstones should be cleaned
                await documentDatabase.TombstoneCleaner.ExecuteCleanup(1);

                using (documentDatabase.DocumentsStorage.ContextPool.AllocateOperationContext(out DocumentsOperationContext context))
                    using (context.OpenReadTransaction())
                    {
                        var tombstonesCount = documentDatabase.DocumentsStorage.GetTombstonesFrom(context, 0, 0, int.MaxValue).Count();
                        Assert.Equal(0, tombstonesCount);
                    }

                //now delete one more document, but execute backup only for ONE of backup tasks.
                //because the tombstone is not backed up by both tasks, only ONE will get deleted.
                using (var session = store.OpenSession())
                {
                    session.Delete("foo/bar2");
                    session.SaveChanges();
                }

                await Backup.RunBackupAsync(Server, backupTaskId1, store, isFullBackup : false);

                await documentDatabase.TombstoneCleaner.ExecuteCleanup(1);

                //since we ran only one of backup tasks, only tombstones with minimal last etag get cleaned
                using (documentDatabase.DocumentsStorage.ContextPool.AllocateOperationContext(out DocumentsOperationContext context))
                    using (context.OpenReadTransaction())
                    {
                        var tombstonesCount = documentDatabase.DocumentsStorage.GetTombstonesFrom(context, 0, 0, int.MaxValue).Count();
                        Assert.Equal(1, tombstonesCount);
                    }
            }
        }
Example #60
0
 public override bool IsLimitExceeded(Backup backup)
 {
     return(_limitSize < backup.Size);
 }