private void DeleteOldEntries(string fileName, int overflow) { var backupFileName = fileName + ".bak"; try { if (_fileStoreService.Exists(backupFileName)) { _fileStoreService.DeleteFile(backupFileName); } // Creating a backup copy of the log in case a crash happends. _fileStoreService.TryMove(fileName, backupFileName, false); // read the content of file and remove old entries string fileContentString = string.Empty; _fileStoreService.TryReadTextFile(fileName, out fileContentString); var logContent = RemoveOlderEntries(fileContentString, overflow); // delete current log file en rewrite it without old entries _fileStoreService.DeleteFile(fileName); _fileStoreService.WriteFile(fileName, x => GenerateStreamFromString(logContent)); // deleting the backup copy _fileStoreService.DeleteFile(backupFileName); } catch (Exception ex) { LogError(ex); } }
public async Task <TaskCompletionType> Restore() { if (!IsLoggedIn) { await Login(); } try { var children = await OneDriveClient.Drive.Items[BackupFolder?.Id].Children.Request().GetAsync(); var existingBackup = children.FirstOrDefault(x => x.Name == OneDriveAuthenticationConstants.BACKUP_NAME); if (existingBackup != null) { var backup = await OneDriveClient.Drive.Items[existingBackup.Id].Content.Request().GetAsync(); if (fileStore.Exists(OneDriveAuthenticationConstants.DB_NAME)) { fileStore.DeleteFile(OneDriveAuthenticationConstants.DB_NAME); } fileStore.WriteFile(OneDriveAuthenticationConstants.DB_NAME, backup.ReadToEnd()); } } catch (OneDriveException ex) { Insights.Report(ex, Insights.Severity.Error); return(TaskCompletionType.Unsuccessful); } return(TaskCompletionType.Successful); }
/// <summary> /// Delete a file on a certain location /// </summary> /// <param name="folder">The name of the folder</param> /// <param name="fullName">The name of the file</param> public override void DeleteFile(string folder, string fullName) { try { _fileStore.DeleteFile(_fileStore.PathCombine(folder, fullName)); } catch (Exception ex) { Mvx.Resolve <IMvxTrace>().Trace(MvxTraceLevel.Error, "ExStorageService.DeleteFile", ex.Message + " - " + ex.StackTrace); } }
/// <summary> /// Delete a file on a certain location /// </summary> /// <param name="folder">The name of the folder</param> /// <param name="fullName">The name of the file</param> public override void DeleteFile(string folder, string fullName) { try { _fileStore.DeleteFile(_fileStore.PathCombine(folder, fullName)); } catch (Exception ex) { Mvx.Resolve <IMvxLog>().ErrorException("ExStorageService.DeleteFile", ex); } }
private void Save() { lock (_locker) { string serialized = JsonConvert.SerializeObject(_favorites); // for some reason need to delete, revisit this sometime if (_fileStore.Exists(FavoritesFile)) { _fileStore.DeleteFile(FavoritesFile); } _fileStore.WriteFile(FavoritesFile, serialized); } }
public void MigrateDatabase() { if (fileStore.Exists(DatabaseConstants.DB_NAME_OLD)) { using ( var dbOld = connectionFactory.GetConnection(new SqLiteConfig(DatabaseConstants.DB_NAME_OLD, false))) { using (var db = GetConnection()) { db.InsertAll(dbOld.Table <AccountViewModel>()); db.InsertAll(dbOld.Table <CategoryViewModel>()); var recPaymentList = dbOld.Table <RecurringPaymentViewModel>().ToList(); var accounts = db.Table <AccountViewModel>().ToList(); var paymentsToMigrate = new List <PaymentViewModel>(); foreach (var payment in dbOld.Table <PaymentViewModel>().ToList()) { if (accounts.Exists(x => x.Id == payment.ChargedAccountId)) { paymentsToMigrate.Add(payment); } } foreach ( var payment in paymentsToMigrate.Where(x => x.IsRecurring && (x.RecurringPaymentId == 0))) { payment.IsRecurring = false; } foreach (var recurringPayment in recPaymentList) { var recIdOld = recurringPayment.Id; db.Insert(recurringPayment); foreach (var payment in paymentsToMigrate.Where(x => x.RecurringPaymentId == recIdOld)) { payment.RecurringPaymentId = db.Table <RecurringPaymentViewModel>().LastOrDefault().Id; } } db.InsertAll(paymentsToMigrate); } } fileStore.DeleteFile(DatabaseConstants.DB_NAME_OLD); } }
/// <summary> /// Restores an existing backup from the backupservice. /// If it was an old backup, it will delete the existing db an make an migration. /// After the restore it will perform a reload of the data so that the cache works with the new data. /// </summary> public async Task RestoreBackup() { var backupNames = GetBackupName(await backupService.GetFileNames()); await backupService.Restore(backupNames.Item1, backupNames.Item2); if (oldBackupRestored && fileStore.Exists(DatabaseConstants.DB_NAME)) { fileStore.DeleteFile(DatabaseConstants.DB_NAME); } databaseManager.CreateDatabase(); databaseManager.MigrateDatabase(); repositoryManager.ReloadData(); SettingsHelper.LastDatabaseUpdate = DateTime.Now; }
/// <inheritdoc /> public async Task RestoreBackup() { if (!connectivity.IsConnected) { return; } var backups = await backupService.GetFileNames(); // Dispose dbfactory to release the dbFile. dbFactory.Dispose(); if (backups.Contains(DatabaseConstants.BACKUP_NAME)) { var backupStream = await backupService.Restore(DatabaseConstants.BACKUP_NAME, DatabaseConstants.BACKUP_NAME); fileStore.WriteFile(DatabaseConstants.BACKUP_NAME, backupStream.ReadToEnd()); var moveSucceed = fileStore.TryMove(DatabaseConstants.BACKUP_NAME, DatabaseConstants.DB_NAME, true); if (!moveSucceed) { throw new BackupException("Error Moving downloaded backup file"); } } else if (backups.Contains(DatabaseConstants.BACKUP_NAME_OLD)) { var backupStream = await backupService.Restore(DatabaseConstants.BACKUP_NAME_OLD, DatabaseConstants.BACKUP_NAME_OLD); fileStore.WriteFile(DatabaseConstants.BACKUP_NAME_OLD, backupStream.ReadToEnd()); // Execute migration await dbFactory.Init(); fileStore.TryMove(DatabaseConstants.BACKUP_NAME_OLD, DatabaseConstants.DB_NAME_OLD, true); await dbFactory.MigrateOldDatabase(); fileStore.DeleteFile(DatabaseConstants.DB_NAME_OLD); } dbFactory.Dispose(); settingsManager.LastDatabaseUpdate = DateTime.Now; }
public override void RemoveAttachment(string id, string attachmentName) { var entityAttachmentDir = AttachmentsDirectoryPath + "/" + id; var attachmentFilePath = entityAttachmentDir + "/" + attachmentName; if (!Exist(id)) { throw new KeyNotFoundNoSQLException(); } if (!fileStore.Exists(attachmentFilePath)) { throw new AttachmentNotFoundNoSQLException(); } fileStore.DeleteFile(attachmentFilePath); }
private void MigrateDb() { if (fileStore.Exists(OneDriveAuthenticationConstants.DB_NAME_OLD)) { using (var dbOld = connectionFactory.GetConnection(OneDriveAuthenticationConstants.DB_NAME_OLD)) { using (var db = connectionFactory.GetConnection(OneDriveAuthenticationConstants.DB_NAME)) { db.InsertAll(dbOld.Table <Account>()); db.InsertAll(dbOld.Table <Category>()); db.InsertAll(dbOld.Table <RecurringPayment>()); db.InsertAll(dbOld.Table <Payment>()); } } fileStore.DeleteFile(OneDriveAuthenticationConstants.DB_NAME_OLD); } }
/// <summary> /// Restores the file with the passed name /// </summary /// <param name="backupname">Name of the backup to restore</param> /// <param name="dbName">filename in which the database shall be restored.</param> /// <returns>TaskCompletionType which indicates if the task was successful or not</returns> public async Task Restore(string backupname, string dbName) { if (OneDriveClient.IsAuthenticated) { await GetBackupFolder(); } var children = await OneDriveClient.Drive.Items[BackupFolder?.Id].Children.Request().GetAsync(); var existingBackup = children.FirstOrDefault(x => x.Name == backupname); if (existingBackup != null) { var backup = await OneDriveClient.Drive.Items[existingBackup.Id].Content.Request().GetAsync(); if (fileStore.Exists(dbName)) { fileStore.DeleteFile(dbName); } fileStore.WriteFile(dbName, backup.ReadToEnd()); } }
/// <summary> /// Restores an existing backup from the backupservice. /// If it was an old backup, it will delete the existing db an make an migration. /// After the restore it will perform a reload of the data so that the cache works with the new data. /// </summary> public async Task RestoreBackup() { if (!connectivity.IsConnected) { return; } var backupNames = GetBackupName(await backupService.GetFileNames()); await backupService.Restore(backupNames.Item1, backupNames.Item2); if (oldBackupRestored && fileStore.Exists(DatabaseConstants.DB_NAME)) { fileStore.DeleteFile(DatabaseConstants.DB_NAME); } databaseManager.CreateDatabase(); databaseManager.MigrateDatabase(); paymentRepository.ReloadCache(); settingsManager.LastDatabaseUpdate = DateTime.Now; }
private async Task LoadDataService(IDataService dataService, bool overrideCache = false) { List <Item> currentItems = new List <Item>(); bool loadedFromCache = false; if (fileStore != null) { string lastRefreshText; if (fileStore.TryReadTextFile("LastRefresh-" + dataService.GetType().ToString(), out lastRefreshText)) { var lastRefreshTime = DateTime.Parse(lastRefreshText); var timeSinceLastRefreshInMinutes = (DateTime.Now - lastRefreshTime).TotalMinutes; //has cache expired? if (overrideCache || timeSinceLastRefreshInMinutes > AppSettings.CacheIntervalInMinutes) { currentItems = await dataService.GetItems(); } else //load from cache { string cachedItemsText; pool.WaitOne(); try { if (fileStore.TryReadTextFile("CachedItems-" + dataService.GetType().ToString(), out cachedItemsText)) { currentItems = mvxJsonConverter.DeserializeObject <List <Item> >(cachedItemsText); loadedFromCache = true; } } catch { ServiceLocator.MessageService.ShowErrorAsync("Error Deserializing " + dataService.GetType().ToString(), "Error loading cache"); } finally { pool.Release(); } } } else { currentItems = await dataService.GetItems(); } } try { if (!loadedFromCache && currentItems.Count > 0) { if (fileStore.Exists("CachedItems-" + dataService.GetType().ToString())) { fileStore.DeleteFile("CachedItems-" + dataService.GetType().ToString()); } if (fileStore.Exists("LastRefresh-" + dataService.GetType().ToString())) { fileStore.DeleteFile("LastRefresh-" + dataService.GetType().ToString()); } fileStore.WriteFile("CachedItems-" + dataService.GetType().ToString(), mvxJsonConverter.SerializeObject(currentItems)); fileStore.WriteFile("LastRefresh-" + dataService.GetType().ToString(), DateTime.Now.ToString()); } items.AddRange(currentItems); } catch { ServiceLocator.MessageService.ShowErrorAsync("Error retrieving items from " + dataService.GetType().ToString() + "\n\nPossible Causes:\nNo internet connection\nRemote Service unavailable", "Application Error"); } }
private void deleteFile(string name) { storage.DeleteFile(name); }
public async void GetMorningJuice() { try { Recipes = await _recipeService.GetRecipes(); int counter = Recipes.Count; Random rnd = new Random(); int RandomNumber = rnd.Next(1, counter); string rndNumToStr = RandomNumber.ToString(); DateTime dateAndTime = DateTime.Now; string day = dateAndTime.ToString("dd/MM/yyyy"); string folderValue = (day + "," + rndNumToStr); var _folderName = "TextFilesFolder1"; var _fileName = "MorningJuice"; if (!_fileStore.FolderExists(_folderName)) { _fileStore.EnsureFolderExists(_folderName); } //Content van de file uitlezen string value = string.Empty; _fileStore.TryReadTextFile(_folderName + "/" + _fileName, out (value)); string CheckFileContent = value; string[] TextFileList; //Als er niets in zit, default data in steken if (CheckFileContent == null) { _fileStore.WriteFile(_folderName + "/" + _fileName, "00/00/00,0"); string d = "00/00/00,0"; TextFileList = d.Split(','); } else { TextFileList = CheckFileContent.Split(','); } if (TextFileList[0] != day) { try { //File verwijderen om overbodige data te verwijderen. _fileStore.DeleteFile(_folderName + "/" + _fileName); //File aanmaken. if (!_fileStore.FolderExists(_folderName)) { _fileStore.EnsureFolderExists(_folderName); } _fileStore.WriteFile(_folderName + "/" + _fileName, folderValue); string NewValue = string.Empty; _fileStore.TryReadTextFile(_folderName + "/" + _fileName, out (NewValue)); string NValue = NewValue; List <string> NewTextFileList = new List <string>( NValue.Split(new string[] { "," }, StringSplitOptions.None)); int numVall = Int32.Parse(NewTextFileList[1]); int NewRandomValue = numVall; MorningContent = await _recipeService.GetRecipeById(NewRandomValue); RaisePropertyChanged(() => MorningContent); } catch (Exception ex) { throw ex; } } else { int numVall = Int32.Parse(TextFileList[1]); int NewRandomValue = numVall; MorningContent = await _recipeService.GetRecipeById(NewRandomValue); RaisePropertyChanged(() => MorningContent); } } catch (Exception ex) { throw ex; } }