//恢复数据 protected void Button4_Click(object sender, EventArgs e) { string beginDate = this.BeginDateBox.Text.Trim(); string endDate = this.EndDateBox.Text.Trim(); string fileName = beginDate + "~" + endDate + "-bak.sql"; string filePathName = GetFileBakName(fileName); if (!File.Exists(filePathName)) { Utility.Alert(this, "文件不存在!(" + fileName + ")"); return; } try { BackupHelper.ReaderBackupFile(filePathName); Utility.Alert(this, "恢复成功。"); } catch { Utility.Alert(this, "恢复失败!"); return; } }
public bool IsToBeProcessed() { try { if (BackupHelper.ExceedsMaxAvailableSize(TenantId)) { throw new Exception("Backup file exceed " + TenantId); } var cron = new CronExpression(Cron); var tenant = CoreContext.TenantManager.GetTenant(TenantId); var tenantTimeZone = tenant.TimeZone; var culture = tenant.GetCulture(); Thread.CurrentThread.CurrentCulture = culture; var lastBackupTime = LastBackupTime.Equals(default(DateTime)) ? DateTime.UtcNow.Date.AddSeconds(-1) : TenantUtil.DateTimeFromUtc(tenantTimeZone, LastBackupTime); var nextBackupTime = cron.GetTimeAfter(lastBackupTime); if (!nextBackupTime.HasValue) { return(false); } var now = TenantUtil.DateTimeFromUtc(tenantTimeZone, DateTime.UtcNow); return(nextBackupTime <= now); } catch (Exception e) { LogManager.GetLogger("ASC").Error("Schedule " + TenantId, e); return(false); } }
protected override void Process() { if (NpcMgr.HasChanges) { string npc_filename = Paths.GetNPCData(); setStatus("Saving NPC Data...", false); BackupHelper.Create(npc_filename); NpcMgr.Save(npc_filename, npc_Progress); } // if (ItemMgr.HasChanges) { string item_filename = Paths.GetItemData(); setStatus("Saving Item Data...", false); BackupHelper.Create(item_filename); ItemMgr.Save(item_filename, item_Progress); } // if (ScriptMgr.HasChanges) { string ai_filename = Paths.GetAIData(); setStatus("Compiling AI Scripts...", true); BackupHelper.Create(ai_filename); is_compiled = false; CompilerResult = ScriptMgr.Compile(ai_Progress); } }
//恢复APP数据 protected void Button5_Click(object sender, EventArgs e) { string strUserId = this.UserIDBox.Text.Trim(); if (strUserId == "") { Utility.Alert(this, "用户ID不能为空!"); return; } int userId = Convert.ToInt32(strUserId); UserInfo user = user_bll.GetUserByUserId(userId); string fileName = "aalife2(" + user.UserID + user.UserName + ").bak"; string filePathName = GetFilePathName(fileName); if (!File.Exists(filePathName)) { Utility.Alert(this, "文件不存在!(" + fileName + ")"); return; } try { BackupHelper.ReaderBackupFileFromApp(userId, filePathName); Utility.Alert(this, "恢复成功。"); } catch { Utility.Alert(this, "恢复失败!"); return; } }
public ActionResult DeleteConfirmed(int id) { try { TempRoutine temproutine = db.TempRoutines.Find(id); if (User.Identity.Name == temproutine.UserName) { BackupHelper aBackupHelper = new BackupHelper(); db.TempRoutineBackupModels.Add(aBackupHelper.GetTempRoputineBackupData(temproutine)); db.Routines.Remove(temproutine); db.SaveChanges(); return(RedirectToAction("Index")); } else { ViewBag.message = "You are not the creator of this Routine So You can not Delete It"; return(View("Delete", temproutine)); } } catch { ViewBag.M1 = "Unable to load DeleteConfirmed TempRoutineController"; return(View("Delete")); } }
private void DoBackUpIfNeeded(string dbfilename, bool beforeupgrade) { if (dbfilename.IsNOE()) { return; } var bp = MyData.Settings.BackUpPlanX; if (bp == EBackUpPlan.Never) { return; } var dt = BackupHelper.GetLastBackupDate(dbfilename, MyData.GetBackUpFolder()); if (dt.HasValue && (DateTime.Now >= dt.Value) && (DateTime.Now - dt.Value).TotalSeconds < 30d) { return; } if (bp == EBackUpPlan.Daily && dt.HasValue && dt.Value.Date == DateTime.Today) { return; } if (bp == EBackUpPlan.WhenUpgrading && !beforeupgrade) { return; } BackupHelper.BackupDbFile(dbfilename, MyData.GetBackUpFolder()); }
protected void BackupNow_OnClick(object sender, EventArgs e) { //DisplayErrorMessage("This functionality is not implemented"); if (!canAccessSection) { DisplayAccessError(); return; } try { Return returnObj = BackupHelper.BackupDatabase(); if (returnObj.IsError) { DisplayErrorMessage("Error backing up DB", returnObj.Error); } else { DisplaySuccessMessage("Successfully backed up DB"); BindDbBackUpsList(); } } catch (Exception ex) { ErrorHelper.LogException(ex); DisplayErrorMessage("Error backing up DB", ErrorHelper.CreateError(ex)); } }
public MiscSettingsPageViewModel(IWorkbook workbook, INavigationService navigationService, IMessageBoxService messageBoxService, INotificationService notificationService, IPlatformService platformService, ITrackingManager trackingManager, IPersistenceLayer persistenceLayer) : base(workbook, navigationService, messageBoxService, notificationService, platformService, trackingManager, persistenceLayer) { this.showLogCommand = new RelayCommand(this.ShowLogExecute); this.backupHelper = new BackupHelper(this.persistenceLayer, this.messageBoxService, this.trackingManager); this.isLogEnabled = this.Workbook.Settings.GetValue <LogLevel>(CoreSettings.LogLevel) > LogLevel.None; }
private async void SetLastBackupString() { var date = await BackupHelper.LastBackup(); LastBackup = date == DateTime.MinValue ? "Brak" : date.ToLocalTime().ToString(); RaisePropertyChanged(nameof(LastBackup)); }
protected override void Process() { if (ScriptMgr.HasChanges) { setStatus("Compiling AI Scripts...", true); BackupHelper.Create(Paths.GetAIData()); is_compiled = false; CompilerResult = ScriptMgr.Compile(ai_Progress); } }
public ActionResult DownloadBackup(int patientId) { var patient = this.db.Patients.First(p => p.Id == patientId); var backup = BackupHelper.GeneratePatientBackup(this.db, patient); return(this.File( backup, "application/zip", patient.Person.FullName + " - " + this.GetPracticeLocalNow().ToShortDateString() + ".zip")); }
private static string Restore(AllSchoolRunner <long> .Task task) { string connectionString = Settings.GetSchoolConnectionString(task.Server, "Master"); using (var uow = new UnitOfWork(connectionString, false)) { var cmd = uow.GetTextCommandWithParams(string.Format("drop database [{0}]", task.Database), new Dictionary <string, object>()); cmd.ExecuteNonQuery(); } return(BackupHelper.DoImport(task.Data, task.Server, task.Database)); }
public static async void CreateBackup() { using (var db = DbConnection) { DateTime now = DateTime.UtcNow.AddDays(-Settings.BackupFrequency); var yco = await BackupHelper.ListOfBackupDates(); if (yco == null || !yco.Any(i => DateTime.ParseExact(i, "yyyy-MM-dd_HH-mm-ss", null) > now)) { db.BackupDatabase(new SQLitePlatformWinRT(), "Backup"); } } }
public IActionResult ExportAllDataAsFileDownload() { string allDataString = BackupHelper.LoadAllDataFromDatabaseInfoJsonString(dataRepository); byte[] allDataBytes = BackupHelper.Zip(allDataString); var fileContentResult = new FileContentResult(allDataBytes, "application/json") { FileDownloadName = "AllData.json.gz" }; return(fileContentResult); }
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: //ORIGINAL LINE: protected void doWork() throws Exception protected internal override void DoWork() { BackupResult backupResult = BackupHelper.backup(_backupHostname, _backupPort, _backupDir); if (!backupResult.Consistent) { throw new Exception("Inconsistent backup"); } if (backupResult.TransientErrorOnBackup) { LockSupport.parkNanos(TimeUnit.MILLISECONDS.toNanos(10)); } }
private void BackupDatabaseToJsonFile() { string allDataString = BackupHelper.LoadAllDataFromDatabaseInfoJsonString(dataRepository); byte[] allDataZippedBytes = BackupHelper.Zip(allDataString); string allDataZippedString = Encoding.UTF8.GetString(allDataZippedBytes); string currentDateTime = VirtualDateTime.Now.ToString("yyyy-MM-ddTHH-mm-ss"); string fileName = $"{BackupFileNamePrefix}{currentDateTime}{BackupFileNameSuffix}"; string relativeFilePath = $"{BackupDirectory}/{fileName}"; fileRepository.Write(relativeFilePath, allDataZippedBytes); }
private Resolver(string commonPrefix = @"logs\") { var handHandleHelper = new BackupHelper(commonPrefix + nameof(HandHandleCases)); handHandle = (HandHandleCases)handHandleHelper.CreateBackupInstance(new HandHandleCases().GetType(), BackupHelper.SerializationType.JsonSerializable); var backupHelper = new BackupHelper(commonPrefix + nameof(Backup)); backup = (Backup)backupHelper.CreateBackupInstance(new Backup().GetType(), BackupHelper.SerializationType.JsonSerializable); var resolveResultHelper = new BackupHelper(commonPrefix + nameof(ResolveResult)); resolveResult = (ResolveResult)resolveResultHelper.CreateBackupInstance(new ResolveResult().GetType(), BackupHelper.SerializationType.Inline); }
private static AllSchoolRunner <long> .TaskStatusEnum CheckStatus(AllSchoolRunner <long> .Task task) { var statuses = BackupHelper.CheckRequestStatus(task.TrackingGuid, task.Server); if (statuses.Any(x => x.Status == "Failed")) { task.ErrorMessage = statuses.First(x => x.Status == "Failed").ErrorMessage; return(AllSchoolRunner <long> .TaskStatusEnum.Failed); } if (statuses.Any(x => x.Status == "Completed")) { return(AllSchoolRunner <long> .TaskStatusEnum.Completed); } return(AllSchoolRunner <long> .TaskStatusEnum.Running); }
public string StartFullBackup() { var errors = new List <string>(); using (var db = new CerebelloEntities()) { foreach (var patient in db.Patients) { patient.IsBackedUp = false; } db.SaveChanges(); BackupHelper.BackupEverything(db, errors); } return("Errors : " + string.Join(",", errors)); }
private void btnRespaldar_Click(object sender, EventArgs e) { if (txtPhat.Text.Trim() == "") { MessageBox.Show("Falta información para realizar respaldo...", "MENSAJE DEL SISTEMA"); return; } else { String RUTA = txtPhat.Text.Trim(); SqlServerBackupRestore.BackupHelper Respaldo = new BackupHelper(); Respaldo.BackupDatabase("anju", "sa", "4159", "AYALA\\AYALA", RUTA); //Respaldo.BackupDatabase("anju","sa","4159","ayala\\ayala",this.txtPhat.Text.Trim()); MessageBox.Show("La Base de Datos ha sido respaldada exitosamente !!!", "MENSAJE DEL SISTEMA"); } }
/// <summary> /// Marks all patients to backup /// </summary> /// <returns></returns> public ActionResult BackupDoctor() { foreach (var patient in this.db.Patients.Where(p => p.DoctorId == this.Doctor.Id)) { patient.IsBackedUp = false; } this.db.SaveChanges(); foreach (var patient in this.db.Patients) { patient.IsBackedUp = false; } this.db.SaveChanges(); BackupHelper.BackupEverything(this.db.innerDb); return(this.Json(new { Ok = true }, JsonRequestBehavior.AllowGet)); }
public ActionResult DeleteConfirmed(int id) { try { Routine routine = db.Routines.Find(id); BackupHelper aBackupHelper = new BackupHelper(); string username = User.Identity.Name; db.RoutineBackupModels.Add(aBackupHelper.GetRoutineBackup(routine, username)); db.Routines.Remove(routine); db.SaveChanges(); return(RedirectToAction("Index")); } catch { ViewBag.M1 = "Unable to load DeleteConfirmed RoutineController"; return(View("Delete")); } }
public void Backup() { string bakFileName = _dbContext.BackupDb(); FileInfo bakFile = new FileInfo(bakFileName); if (!bakFile.Exists) { return; } #if DEBUG if (!(CloudDirectories.Count() == 1)) { throw new InvalidOperationException("Backup called without cloud directories set to a single directory"); } #endif string uniqueFileNameSuffix = '_' + LocalStudyCentres.First().DuplicateIdCheck.ToString("N"); string cloudDir = CloudDirectories.First(); string cloudZipName = cloudDir + '\\' + Path.GetFileNameWithoutExtension(bakFileName) + uniqueFileNameSuffix + ".zip"; var cloudFile = new FileInfo(cloudZipName); if (cloudFile.Exists) { DateTime?mostRecentEntry = SyncronisationResult.MostRecentEntry(_dbContext); if (mostRecentEntry == null || cloudFile.LastWriteTimeUtc >= mostRecentEntry) { return; } } _dbContext.Dispose(); // only necessary for ce SyncronisationResult.RepairDb(bakFileName); int dotPos = bakFileName.LastIndexOf('.'); string copiedFileName = bakFileName.Insert(dotPos, uniqueFileNameSuffix); File.Copy(bakFileName, copiedFileName, true); void work() { BackupHelper.ZipVerifyAndPutInCloudDir(copiedFileName, cloudDir); } new Thread(work).Start(); _dbContext = _createContext.Invoke(); }
public IActionResult ImportAllDataFromFile(AdminFileUploadViewModel viewModel) { if (!IsUserAllowedToImportData()) { return(Unauthorized()); } byte[] fileAsBytes; using (var memoryStream = new MemoryStream()) { viewModel.File.OpenReadStream().CopyTo(memoryStream); fileAsBytes = memoryStream.ToArray(); } string fileAsString = BackupHelper.Unzip(fileAsBytes); ImportDataFromJsonString(fileAsString); return(Json("Succeeded!")); }
/// <summary> /// Runs the worker once to send e-mails. /// </summary> public override void RunOnce() { // If this method is already running, then leave the already running alone, and return. // If it is not running, set the value os locker to 1 to indicate that now it is running. if (Interlocked.Exchange(ref locker, 1) != 0) { return; } Trace.TraceInformation("GoogleDriveSynchronizerWorker.RunOnce(): service in execution"); using (var db = this.CreateNewCerebelloEntities()) BackupHelper.BackupEverything(db); // setting locker value to 0 if (Interlocked.Exchange(ref locker, 0) != 1) { throw new Exception("The value of locker should be 1 before setting it to 0."); } }
private static void timer_Elapsed(object state, EventArgs e) { AllEntitiesContext db = new AllEntitiesContext(); //Routine aRoutine = db.Routines.Where(a => a.Day == "Saturday").Select(a => a).FirstOrDefault(); List <TempRoutine> tempList = db.TempRoutines.Where(a => a.TempRoutineDate < DateTime.Now).Select(a => a).ToList(); try { foreach (var a in tempList) { BackupHelper aBackupHelper = new BackupHelper(); db.TempRoutineBackupModels.Add(aBackupHelper.GetTempRoputineBackupData(a)); db.TempRoutines.Remove(a); db.SaveChanges(); } } catch { } }
protected void RestoreBackUp_Click(object sender, EventArgs e) { if (!canAccessSection) { DisplayAccessError(); return; } var restoreButton = sender as LinkButton; if (!string.IsNullOrEmpty(restoreButton.CommandArgument) && File.Exists(restoreButton.CommandArgument)) { var returnObj = BaseMapper.GenerateReturn(); try { BackupNow_OnClick(sender, e); returnObj = BackupHelper.RestoreDatabase(restoreButton.CommandArgument); if (returnObj.IsError) { DisplayErrorMessage("Error restoring", returnObj.Error); } else { DisplaySuccessMessage($"Successfully restored file: ( {restoreButton.CommandArgument} )"); } } catch (Exception ex) { ErrorHelper.LogException(ex); returnObj.Error = ErrorHelper.CreateError(ex); DisplayErrorMessage(returnObj.Error.Message, returnObj.Error); } } }
public IActionResult ExportAllDataAsResponseBody(string password) { if (string.IsNullOrWhiteSpace(Global.DataMigrationPassword)) { // Don't allow access if no password is set return(Unauthorized()); } if (password != Global.DataMigrationPassword) { // Don't allow access is the user got the password wrong return(Unauthorized()); } string allDataString = BackupHelper.LoadAllDataFromDatabaseInfoJsonString(dataRepository); var fileContentResult = new ContentResult { Content = allDataString, ContentType = "application/json", StatusCode = 200 }; return(fileContentResult); }
protected async Task <RestoreSettings> SnapshotRestore(JsonOperationContext context, string backupPath, Action <IOperationProgress> onProgress, RestoreResult restoreResult) { Debug.Assert(onProgress != null); RestoreSettings restoreSettings = null; var fullBackupPath = GetBackupPath(backupPath); using (var zip = await GetZipArchiveForSnapshot(fullBackupPath)) { var restorePath = new VoronPathSetting(RestoreFromConfiguration.DataDirectory); if (Directory.Exists(restorePath.FullPath) == false) { Directory.CreateDirectory(restorePath.FullPath); } // validate free space var snapshotSize = zip.Entries.Sum(entry => entry.Length); BackupHelper.AssertFreeSpaceForSnapshot(restorePath.FullPath, snapshotSize, "restore a backup", Logger); foreach (var zipEntries in zip.Entries.GroupBy(x => x.FullName.Substring(0, x.FullName.Length - x.Name.Length))) { var directory = zipEntries.Key; if (string.IsNullOrWhiteSpace(directory)) { foreach (var zipEntry in zipEntries) { if (string.Equals(zipEntry.Name, RestoreSettings.SettingsFileName, StringComparison.OrdinalIgnoreCase)) { using (var entryStream = zipEntry.Open()) { var snapshotEncryptionKey = RestoreFromConfiguration.EncryptionKey != null ? Convert.FromBase64String(RestoreFromConfiguration.EncryptionKey) : null; using (var stream = GetInputStream(entryStream, snapshotEncryptionKey)) { var json = context.Read(stream, "read database settings for restore"); json.BlittableValidation(); restoreSettings = JsonDeserializationServer.RestoreSettings(json); restoreSettings.DatabaseRecord.DatabaseName = RestoreFromConfiguration.DatabaseName; DatabaseHelper.Validate(RestoreFromConfiguration.DatabaseName, restoreSettings.DatabaseRecord, _serverStore.Configuration); if (restoreSettings.DatabaseRecord.Encrypted && _hasEncryptionKey == false) { throw new ArgumentException("Database snapshot is encrypted but the encryption key is missing!"); } if (restoreSettings.DatabaseRecord.Encrypted == false && _hasEncryptionKey) { throw new ArgumentException("Cannot encrypt a non encrypted snapshot backup during restore!"); } } } } } continue; } var restoreDirectory = directory.StartsWith(Constants.Documents.PeriodicBackup.Folders.Documents, StringComparison.OrdinalIgnoreCase) ? restorePath : restorePath.Combine(directory); BackupMethods.Full.Restore( zipEntries, restoreDirectory, journalDir: null, onProgress: message => { restoreResult.AddInfo(message); restoreResult.SnapshotRestore.ReadCount++; onProgress.Invoke(restoreResult.Progress); }, cancellationToken: _operationCancelToken.Token); } } if (restoreSettings == null) { throw new InvalidDataException("Cannot restore the snapshot without the settings file!"); } return(restoreSettings); }
public BackupDatabase(IApplicationState applicationState, IMethodQueue methodQueue, BackupHelper backupHelper) { this._applicationState = applicationState; this._methodQueue = methodQueue; this._backupHelper = backupHelper; }