Exemplo n.º 1
0
        public void SaveImage(byte[] bytes, string name, int maxDimenSize = -1)
        {
            var path = this.fileStore.NativePath(ImagePath) + name;

            if (maxDimenSize != -1)
            {
                var    stream = new MemoryStream();
                Bitmap bitmap = BitmapFactory.DecodeByteArray(bytes, 0, bytes.Length);
                float  scaleRatio;
                if (bitmap.Width >= bitmap.Height)
                {
                    scaleRatio = (float)maxDimenSize / (float)bitmap.Width;
                }
                else
                {
                    scaleRatio = (float)maxDimenSize / (float)bitmap.Height;
                }

                var matrix = new Matrix();
                matrix.PostScale(scaleRatio, scaleRatio);

                var scaledBitmap = Bitmap.CreateBitmap(bitmap, 0, 0, bitmap.Width, bitmap.Height, matrix, false);
                scaledBitmap.Compress(Bitmap.CompressFormat.Jpeg, 75, stream);
                bitmap.Recycle();
                fileStore.WriteFile(path, stream.ToArray());
            }
            else
            {
                fileStore.WriteFile(path, bytes);
            }
        }
Exemplo n.º 2
0
        private void writeEntries()
        {
            List <Entry> toSave;

            toSave = _indexByHttp.Values.ToList();

            var text = JsonConvert.SerializeObject(toSave);


            storage.WriteFile(_indexFileName, text);;
        }
Exemplo n.º 3
0
        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);
            }
        }
Exemplo n.º 4
0
        /// <inheritdoc />
        public async Task RestoreBackup()
        {
            if (!connectivity.IsConnected)
            {
                return;
            }

            var backups = await backupService.GetFileNames();

            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, ApplicationContext.DbPath, true);

                if (!moveSucceed)
                {
                    throw new BackupException("Error Moving downloaded backup file");
                }
                settingsManager.LastDatabaseUpdate = DateTime.Now;
            }
        }
        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);
        }
Exemplo n.º 6
0
        private async Task DownloadBackup()
        {
            if (!connectivity.IsConnected)
            {
                return;
            }

            var backups = await cloudBackupService.GetFileNames()
                          .ConfigureAwait(false);

            if (backups.Contains(DatabaseConstants.BACKUP_NAME))
            {
                var backupStream = await cloudBackupService.Restore(DatabaseConstants.BACKUP_NAME, DatabaseConstants.BACKUP_NAME)
                                   .ConfigureAwait(false);

                fileStore.WriteFile(DatabaseConstants.BACKUP_NAME, backupStream.ReadToEnd());

                var moveSucceed = fileStore.TryMove(DatabaseConstants.BACKUP_NAME, EfCoreContext.DbPath, true);

                if (!moveSucceed)
                {
                    throw new BackupException("Error Moving downloaded backup file");
                }
            }
        }
Exemplo n.º 7
0
        public void SaveImage(byte[] bytes, string name, int compressionRate = 100)
        {
            var path = this.fileStore.NativePath(nativePath) + name;

            if (compressionRate != 100)
            {
                var    stream = new MemoryStream();
                Bitmap bitmap = BitmapFactory.DecodeByteArray(bytes, 0, bytes.Length);
                bitmap.Compress(Bitmap.CompressFormat.Jpeg, compressionRate, stream);
                fileStore.WriteFile(path, stream.ToArray());
            }
            else
            {
                fileStore.WriteFile(path, bytes);
            }
        }
Exemplo n.º 8
0
        /// <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;
        }
Exemplo n.º 9
0
        private void SaveJSONFile()
        {
            var settings = new JsonSerializerSettings()
            {
                TypeNameHandling     = TypeNameHandling.Auto,
                NullValueHandling    = NullValueHandling.Ignore,
                DefaultValueHandling = DefaultValueHandling.Ignore,
                // TypeNameAssemblyFormat = System.Runtime.Serialization.Formatters.FormatterAssemblyStyle.Simple
            };

            string content = JsonConvert.SerializeObject(this.localDb, Formatting.Indented, settings);

            fileStore.EnsureFolderExists(DbDirectoryPath);
            fileStore.WriteFile(DbFilePath, content);

            SavedDbConfig();
        }
Exemplo n.º 10
0
        private void MyCommandExecute()
        {
            //Escrever o valor que deve ser passado em um arquivo
            _fileStore.WriteFile(Constants.FileName, "2");

            //Passar o valor para o método init
            ShowViewModel <CommunicationViewModel>(CommunicationParameters.FromInteger(2));
        }
Exemplo n.º 11
0
 public void SaveState(PropertyFinderPersistentState state)
 {
     _fileStore.WriteFile(FileName, stream =>
     {
         XmlSerializer serializer = new XmlSerializer(typeof(PropertyFinderPersistentState));
         serializer.Serialize(stream, state);
     });
 }
        public void Save(IEnumerable<PetViewModel> pets)
        {
            var narrowed = pets.Select(x => new { x.Name, x.Antiepidemic });

            var json = JsonConvert.SerializeObject(narrowed);

            _fileStore.WriteFile(_storedFile, json);
        }
Exemplo n.º 13
0
        public Task SaveAsync(OAuthToken token)
        {
            return(Task.Run(delegate
            {
                var json = JsonConvert.SerializeObject(token);

                fileStore.WriteFile(TokenPath, json);
            }));
        }
Exemplo n.º 14
0
        private async Task DownloadSessionsAsync()
        {
            var httpClient = new HttpClient();
            var result     = await httpClient.GetAsync(new Uri(SessionsUrl));

            var sessionData = await result.Content.ReadAsStringAsync();

            _fileStore.WriteFile(SessionsFileName, sessionData);
            Settings.LastSyncTime = DateTime.UtcNow;
        }
        public NoteDataService(IMvxFileStore mvxFileStorage)
        {
            filePath = "noteStorage.json";
            converter = new MvxJsonConverter();

            storage = mvxFileStorage;
            if (!storage.Exists(filePath))
            {
                storage.WriteFile(filePath, converter.SerializeObject(Enumerable.Empty<Note>()));
            }
        }
Exemplo n.º 16
0
 private void Save()
 {
     try
     {
         string fileContent = JsonConvert.SerializeObject(m_Data);
         m_FileStore.WriteFile(Path.Combine(m_PlatformInfo.BaseDirectory, m_FileName), fileContent);
     }
     catch (Exception ex)
     {
         MvxTrace.Error(ex.StackTrace);
     }
 }
Exemplo n.º 17
0
 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);
     }
 }
Exemplo n.º 18
0
        public string SaveImageToFile(byte[] pictureBytes)
        {
            if (pictureBytes == null)
            {
                return(null);
            }

            var randomFileName = "Image" + Guid.NewGuid().ToString("N") + ".jpg";

            _fileStore.EnsureFolderExists("Images");
            var path = _fileStore.PathCombine("Images", randomFileName);

            _fileStore.WriteFile(path, pictureBytes);
            return(path);
        }
Exemplo n.º 19
0
        private string GenerateImagePath()
        {
            if (PictureBytes == null)
            {
                return(null);
            }

            var randomFileName = "Image" + Guid.NewGuid().ToString("N") + ".jpg";

            _fileStore.EnsureFolderExists("Images");
            var path = _fileStore.PathCombine("Images", randomFileName);

            _fileStore.WriteFile(path, PictureBytes);
            return(path);
        }
Exemplo n.º 20
0
        public void AddBookToLibrary(Book mybook)
        {
            try
            {
                FillLibrary();

                if (_myLibrary == null)
                {
                    _myLibrary = new List <Book>();
                    _myLibrary.Add(mybook);
                }
                else
                {
                    if (CheckInLibrary(mybook))
                    {
                        _myLibrary.Remove(mybook);
                        if (CheckInLibrary(mybook))
                        {
                            List <Book> l = _myLibrary;
                            _myLibrary = new List <Book>();
                            foreach (Book b in l)
                            {
                                if (b.id != mybook.id)
                                {
                                    _myLibrary.Add(b);
                                }
                            }
                        }
                    }
                    else
                    {
                        _myLibrary.Add(mybook);
                    }
                }

                if (!_fileStore.FolderExists("MyBookApp"))
                {
                    _fileStore.EnsureFolderExists("MyBookApp");
                }
                _fileStore.WriteFile("MyBookApp/Library", JsonConvert.SerializeObject(_myLibrary));
            }
            catch (Exception e)
            {
                throw e;
            }
        }
        //Save naar file
        public static void SaveToFile(string Togglevalue)
        {
            try
            {
                if (!_fileStore.FolderExists(_folderName))
                {
                    _fileStore.EnsureFolderExists(_folderName);
                }

                // Tekst = Togglevalue;

                _fileStore.WriteFile(_folderName + "/" + _fileName, Togglevalue);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        private void SaveToFile()
        {
            string _folderName = "NewJob";
            string _fileName   = "Location";

            try
            {
                if (!_fileStore.FolderExists(_folderName))
                {
                    _fileStore.EnsureFolderExists(_folderName);
                }
                var json = JsonConvert.SerializeObject(Location);
                _fileStore.WriteFile(_folderName + "/" + _fileName, json);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Exemplo n.º 23
0
        /// <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());
            }
        }
Exemplo n.º 24
0
        /// <summary>
        /// Gets the filepath to a locally cached copy of an online image.
        /// </summary>
        /// <param name="imageUrl">Http/https URL of the required image resource.</param>
        /// <returns>Local filepath for the cached image, or null if the online resource was not found.</returns>
        public async Task <string> GetCachedIamgePathAsync(string imageUrl)
        {
            var localPath = imageUrl.Replace("https://", "");

            localPath = localPath.Replace("http://", "");
            localPath = localPath.Replace('/', '_');

            try
            {
                if (_fileStore.Exists(localPath))
                {
                    return(_fileStore.NativePath(localPath));
                }
            }
            catch (Exception)
            {
                // this is OK, an exception may be thrown here if the file wasn't found.
            }

            try
            {
                using (var httpClient = new HttpClient())
                {
                    var response = await httpClient.GetAsync(imageUrl);

                    if (response.IsSuccessStatusCode)
                    {
                        var bytes = await response.Content.ReadAsByteArrayAsync();

                        _fileStore.WriteFile(localPath, bytes);
                    }
                }
            }
            catch (Exception ex)
            {
                // TODO: handle http exceptions
            }

            return(_fileStore.NativePath(localPath));
        }
Exemplo n.º 25
0
        /// <summary>
        ///     Restores an existing backup from the backupservice.
        /// </summary>
        public async Task RestoreBackup()
        {
            if (!connectivity.IsConnected)
            {
                return;
            }

            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");
            }

            await dbFactory.Init();

            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");
            }
        }
Exemplo n.º 27
0
        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;
            }
        }
Exemplo n.º 28
0
 public void Save(string name, IEnumerable <byte> bytes)
 {
     _store.WriteFile(name, bytes);
 }
 private void WriteFile(T setting)
 {
     _fileStore.WriteFile(_filePath, JsonConvert.SerializeObject(setting));
 }
Exemplo n.º 30
0
 /// <summary>
 /// Saves the data to the file system.
 /// </summary>
 /// <param name="feedbackData">Data that should be saved</param>
 public void SaveData(FeedbackData feedbackData)
 {
     _fileStore.WriteFile(DataFileName, _jsonConverter.SerializeObject(feedbackData));
 }
Exemplo n.º 31
0
 /// <summary>
 /// Save data to file
 /// </summary>
 /// <param name="fileName">File's name</param>
 /// <param name="obj">Data to store</param>
 public void Save(string fileName, object obj)
 {
     _fileStore.WriteFile(fileName, _jsonConverter.Serialize(obj));
 }