private async Task<string> ReadFileAsync(StorageFolder storageFolder, StorageFile storageFile, FileType fileType) { var rootFolder = FileSystem.Current.LocalStorage; var folder = await rootFolder.GetFolderAsync(storageFolder.ToString()); if (folder == null) { return null; } var file = await folder.GetFileAsync(string.Format(@"{0}.{1}", storageFile, fileType)); if (file == null) { return null; } var stream = await file.OpenAsync(FileAccess.Read); if (stream == null) { return null; } using (var streamReader = new StreamReader(stream)) { return streamReader.ReadToEnd(); } }
public FLCPlayer(GraphicsDevice setDevice) { device = setDevice; file = null; flcFile = null; currentFrame = null; }
private string GetScheduleTemplateFile(string[] fileName) { var file = new StorageFile(ResourceManager.Instance.ScheduleSlideTemplatesFolder.RelativePathParts .Merge(new[] { PowerPointManager.Instance.SlideSettings.SlideFolder.ToLower(), "" }) .Merge(fileName)); return file.LocalPath; }
public bool TryGetStorageFile(string path, out IStorageFile storageFile) { FileInfo sourceImagePath; if (!TryFindPhysicalFile(path, out sourceImagePath)) { storageFile = null; return false; } var eTag = m_fileInfoETagCalculator.CalculateETag( sourceImagePath ); storageFile = new StorageFile( sourceImagePath, eTag ); return true; }
private async Task<bool> SaveFileAsync(StorageFolder storageFolder, StorageFile storageFile, FileType fileType, string content) { var rootFolder = FileSystem.Current.LocalStorage; var folder = await rootFolder.CreateFolderAsync(storageFolder.ToString(), CreationCollisionOption.OpenIfExists); if (folder == null) { return false; } var file = await folder.CreateFileAsync(string.Format(@"{0}.{1}", storageFile, fileType), CreationCollisionOption.ReplaceExisting); if (file == null) { return false; } await file.WriteAllTextAsync(content); return true; }
public async Task<bool> Open(StorageFile setFile) { file = setFile; var str = await file.OpenReadAsync(); if (flcFile != null) { flcFile.OnFrameUpdated -= flcFile_OnFrameUpdated; flcFile.OnPlaybackStarted -= flcFile_OnPlaybackStarted; flcFile.OnPlaybackFinished -= flcFile_OnPlaybackFinished; flcFile.Dispose(); flcFile = null; } flcFile = new FLCFile(str.AsStreamForRead()); flcFile.OnFrameUpdated += flcFile_OnFrameUpdated; flcFile.OnPlaybackStarted += flcFile_OnPlaybackStarted; flcFile.OnPlaybackFinished += flcFile_OnPlaybackFinished; flcFile.Open(); return true; }
private bool FileOpened(StorageFile file) { var item = GetTextEditorSetsViewItem(file); return(item != null); }
private async void Display(string _path, List <String> p) { List <ImageSource> pic = new List <ImageSource>(); Boolean _defaultPictures = false; StorageItemThumbnail fileThumbnail; StorageFile _file; IRandomAccessStream _stream; BitmapImage bm; try { if (p.Count() < 4) { if (AlbumRef.Summary.Sample) { _file = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///appdata/" + _path + "/" + p[0])); } else { StorageFolder folder = await ApplicationData.Current.LocalFolder.GetFolderAsync(_path); _file = await folder.GetFileAsync(p[0]); } _stream = await _file.OpenAsync(FileAccessMode.Read); bm = new BitmapImage(); await bm.SetSourceAsync(_stream); pic.Add(bm); } else { for (int idx = 0; idx < 4; idx++) { if (AlbumRef.Summary.Sample) { _file = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///appdata/" + _path + "/" + p[idx])); } else { StorageFolder folder = await ApplicationData.Current.LocalFolder.GetFolderAsync(_path); _file = await folder.GetFileAsync(p[idx]); } _stream = await _file.OpenReadAsync(); bm = new BitmapImage(); await bm.SetSourceAsync(_stream); pic.Add(bm); } } } catch { _defaultPictures = true; } if (_defaultPictures) { pic.Clear(); for (int idx = 0; idx < 4; idx++) { _file = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///Assets/reward_" + idx.ToString() + ".png")); fileThumbnail = await _file.GetThumbnailAsync(ThumbnailMode.SingleItem, 120, ThumbnailOptions.ResizeThumbnail); bm = new BitmapImage(); await bm.SetSourceAsync(fileThumbnail); pic.Add(bm); } } if (p.Count <string>() < 4) { pic_single.Source = pic[0]; pic_single.Visibility = Visibility.Visible; pic0.Visibility = Visibility.Collapsed; pic1.Visibility = Visibility.Collapsed; pic2.Visibility = Visibility.Collapsed; pic3.Visibility = Visibility.Collapsed; } else { pic0.Source = pic[0]; pic1.Source = pic[1]; pic2.Source = pic[2]; pic3.Source = pic[3]; pic_single.Visibility = Visibility.Collapsed; pic0.Visibility = Visibility.Visible; pic1.Visibility = Visibility.Visible; pic2.Visibility = Visibility.Visible; pic3.Visibility = Visibility.Visible; } }
private async void Button_Click(object sender, RoutedEventArgs e) { ProgressRing.IsActive = true; Start.Text = "Music X выполняет первичную настройку. Пожалуйста, подождите..."; ButtonStart.Visibility = Visibility.Collapsed; //создание папки с плейлистами. var localpath = ApplicationData.Current.LocalFolder; if (await localpath.TryGetItemAsync("Playlists") == null) { var pathPlaylists = await localpath.CreateFolderAsync("Playlists"); StaticContent.PlaylistsFolder = pathPlaylists; var filePlaylistId1 = await pathPlaylists.CreateFileAsync("Id1.json"); var filePlaylistId2 = await pathPlaylists.CreateFileAsync("Id2.json"); var playlistLastPlay = new Models.PlaylistFile() { Artist = "Music X", Cover = "ms-appx:///Assets/Images/latest.png", Id = 1, Name = "Слушали недавно", IsLocal = true, TracksFiles = new List <AudioFile>() }; var playlistFavorite = new Models.PlaylistFile() { Artist = "Music X", Cover = "ms-appx:///Assets/Images/favorites.png", Id = 2, Name = "Избранное", IsLocal = true, TracksFiles = new List <AudioFile>() }; var jsonPlaylistId1 = JsonConvert.SerializeObject(playlistLastPlay); var jsonPlaylistId2 = JsonConvert.SerializeObject(playlistFavorite); await FileIO.WriteTextAsync(filePlaylistId1, jsonPlaylistId1); await FileIO.WriteTextAsync(filePlaylistId2, jsonPlaylistId2); } if (await localpath.TryGetItemAsync("Covers") == null) { StaticContent.CoversFolder = await localpath.CreateFolderAsync("Covers"); } if (await localpath.TryGetItemAsync("MusicCollection.json") == null) { var musicFile = await localpath.CreateFileAsync("MusicCollection.json"); var musicString = JsonConvert.SerializeObject(new MusicCollection() { Music = new List <AudioFile>(), DateLastUpdate = "none" }); await FileIO.WriteTextAsync(musicFile, musicString); } if (await localpath.TryGetItemAsync("LastPlay.json") == null) { var lastFile = await localpath.CreateFileAsync("LastPlay.json"); var audio = new AudioFile() { Artist = "", Cover = "ms-appx:///Assets/Images/placeholder.png", DurationMinutes = "00:00", DurationSeconds = 0, Id = -2, InternalId = -2, OwnerId = -2, PlaylistId = 1, SourceString = "ms-appx:///Assets/Audio/song.mp3", Source = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///Assets/Audio/song.mp3")), Title = "Сейчас ничего не воспроизводится" }; var lastplayModel = new LastPlay() { Playlist = null, Track = audio, Volume = 1.0f, }; var jsonLastFile = JsonConvert.SerializeObject(lastplayModel); await FileIO.WriteTextAsync(lastFile, jsonLastFile); } if (await localpath.TryGetItemAsync("ConfigApp.json") == null) { var configFile = await localpath.CreateFileAsync("ConfigApp.json"); var config = new ConfigApp() { FindInDocumentsLibrary = false, FindInMusicLibrary = true, ThemeApp = 0, StreamMusic = true }; var configString = JsonConvert.SerializeObject(config); await FileIO.WriteTextAsync(configFile, configString); StaticContent.Config = config; } var settings = ApplicationData.Current.LocalSettings; settings.Values["themeApp"] = 0; await LikedArtistsService.CreateLikedArtstsFile(); await MusicFilesService.GetMusicLocal(true); var rootFrame = (Frame)Window.Current.Content; rootFrame.Navigate(typeof(Views.MainFrameView), null); }
public TextEditor OpenNewTextEditor( Guid id, string text, StorageFile file, long dateModifiedFileTime, Encoding encoding, LineEnding lineEnding, bool isModified) { //LoggingService.LogInfo("Opening a text editor."); var textEditor = new TextEditor { Id = id, ExtensionProvider = _extensionProvider }; textEditor.Init(new TextFile(text, encoding, lineEnding, dateModifiedFileTime), file, isModified: isModified); textEditor.Loaded += TextEditor_Loaded; textEditor.Unloaded += TextEditor_Unloaded; textEditor.SelectionChanged += TextEditor_SelectionChanged; textEditor.KeyDown += TextEditorKeyDown; textEditor.EditorModificationStateChanged += TextEditor_OnEditorModificationStateChanged; textEditor.ModeChanged += TextEditor_ModeChanged; textEditor.FileModificationStateChanged += (sender, args) => { TextEditorFileModificationStateChanged?.Invoke(this, sender as TextEditor); }; textEditor.LineEndingChanged += (sender, args) => { TextEditorLineEndingChanged?.Invoke(this, sender as TextEditor); }; textEditor.EncodingChanged += (sender, args) => { TextEditorEncodingChanged?.Invoke(this, sender as TextEditor); }; var newItem = new SetsViewItem { Header = file == null ? DefaultNewFileName : file.Name, Content = textEditor, SelectionIndicatorForeground = Application.Current.Resources["SystemControlForegroundAccentBrush"] as SolidColorBrush, Icon = new SymbolIcon(Symbol.Save) { Foreground = Application.Current.Resources["SystemControlForegroundAccentBrush"] as SolidColorBrush, } }; if (newItem.Content == null || newItem.Content is Page) { throw new Exception("Content should not be null and type should not be Page (SetsView does not work well with Page controls)"); } newItem.Icon.Visibility = isModified ? Visibility.Visible : Visibility.Collapsed; newItem.ContextFlyout = new TabContextFlyout(this, textEditor); // Notepads should replace current "Untitled.txt" with open file if it is empty and it is the only tab that has been created. if (GetNumberOfOpenedTextEditors() == 1 && file != null) { var selectedEditor = GetAllTextEditors().First(); if (selectedEditor.EditingFile == null && !selectedEditor.IsModified) { Sets.Items?.Clear(); } } Sets.Items?.Add(newItem); if (GetNumberOfOpenedTextEditors() > 1) { Sets.SelectedItem = newItem; Sets.ScrollToLastSet(); } return(textEditor); }
public async void CutItem_Click(object sender, RoutedEventArgs e) { DataPackage dataPackage = new DataPackage(); dataPackage.RequestedOperation = DataPackageOperation.Move; App.pathsToDeleteAfterPaste.Clear(); List <IStorageItem> items = new List <IStorageItem>(); if (App.CurrentInstance.CurrentPageType == typeof(GenericFileBrowser)) { var CurrentInstance = App.CurrentInstance; if ((CurrentInstance.ContentPage as BaseLayout).SelectedItems.Count != 0) { dataGridRows.Clear(); FindChildren <DataGridRow>(dataGridRows, (CurrentInstance.ContentPage as GenericFileBrowser).AllView); // First, reset DataGrid Rows that may be in "cut" command mode foreach (DataGridRow row in dataGridRows) { if ((CurrentInstance.ContentPage as GenericFileBrowser).AllView.Columns[0].GetCellContent(row).Opacity < 1) { (CurrentInstance.ContentPage as GenericFileBrowser).AllView.Columns[0].GetCellContent(row).Opacity = 1; } } foreach (ListedItem StorItem in (CurrentInstance.ContentPage as BaseLayout).SelectedItems) { IEnumerator allItems = (CurrentInstance.ContentPage as GenericFileBrowser).AllView.ItemsSource.GetEnumerator(); int index = -1; while (allItems.MoveNext()) { index++; var item = allItems.Current; if (item == StorItem) { DataGridRow dataGridRow = dataGridRows[index]; (CurrentInstance.ContentPage as GenericFileBrowser).AllView.Columns[0].GetCellContent(dataGridRow).Opacity = 0.4; } } App.pathsToDeleteAfterPaste.Add(StorItem.FilePath); if (StorItem.FileType != "Folder") { var item = await StorageFile.GetFileFromPathAsync(StorItem.FilePath); items.Add(item); } else { var item = await StorageFolder.GetFolderFromPathAsync(StorItem.FilePath); items.Add(item); } } } } else if (App.CurrentInstance.CurrentPageType == typeof(PhotoAlbum)) { var CurrentInstance = App.CurrentInstance; if ((CurrentInstance.ContentPage as BaseLayout).SelectedItems.Count != 0) { gridViewItems.Clear(); FindChildren <GridViewItem>(gridViewItems, (CurrentInstance.ContentPage as PhotoAlbum).FileList); // First, reset GridView items that may be in "cut" command mode foreach (GridViewItem gridViewItem in gridViewItems) { List <Grid> itemContentGrids = new List <Grid>(); FindChildren <Grid>(itemContentGrids, (CurrentInstance.ContentPage as PhotoAlbum).FileList.ContainerFromItem(gridViewItem.Content)); var imageOfItem = itemContentGrids.Find(x => x.Tag?.ToString() == "ItemImage"); if (imageOfItem.Opacity < 1) { imageOfItem.Opacity = 1; } } foreach (ListedItem StorItem in (CurrentInstance.ContentPage as BaseLayout).SelectedItems) { GridViewItem itemToDimForCut = (GridViewItem)(CurrentInstance.ContentPage as PhotoAlbum).FileList.ContainerFromItem(StorItem); List <Grid> itemContentGrids = new List <Grid>(); FindChildren <Grid>(itemContentGrids, (CurrentInstance.ContentPage as PhotoAlbum).FileList.ContainerFromItem(itemToDimForCut.Content)); var imageOfItem = itemContentGrids.Find(x => x.Tag?.ToString() == "ItemImage"); imageOfItem.Opacity = 0.4; App.pathsToDeleteAfterPaste.Add(StorItem.FilePath); if (StorItem.FileType != "Folder") { var item = await StorageFile.GetFileFromPathAsync(StorItem.FilePath); items.Add(item); } else { var item = await StorageFolder.GetFolderFromPathAsync(StorItem.FilePath); items.Add(item); } } } } IEnumerable <IStorageItem> EnumerableOfItems = items; dataPackage.SetStorageItems(EnumerableOfItems); Clipboard.SetContent(dataPackage); Clipboard.Flush(); }
public async static void readQuickData() { folder = ApplicationData.Current.LocalFolder; Chart = await folder.CreateFileAsync("QuickDiaryCharts.ltr", CreationCollisionOption.OpenIfExists); using (Stream file = await Chart.OpenStreamForReadAsync()) { if (file.Length == 0) { return; } using (StreamReader chartsReader = new StreamReader(file)) { while (!chartsReader.EndOfStream) { int i, j; createTime = new int[3]; string temp = chartsReader.ReadLine(); for (i = 0; temp[i] != ' '; ++i) { ; } emotion = temp.Substring(0, i); while (temp[++i] == ' ') { ; } for (j = 0; temp[i + j] >= '0' && temp[i + j] <= '9'; ++j) { ; } createTime[0] = Int32.Parse(temp.Substring(i, j)); i = i + j; while (temp[++i] == ' ') { ; } for (j = 0; temp[i + j] >= '0' && temp[i + j] <= '9'; ++j) { ; } createTime[1] = Int32.Parse(temp.Substring(i, j)); i = i + j; while (temp[++i] == ' ') { ; } for (j = 0; temp[i + j] >= '0' && temp[i + j] <= '9'; ++j) { ; } createTime[2] = Int32.Parse(temp.Substring(i, j)); i = i + j; while (temp[++i] == ' ') { ; } for (j = 0; i + j < temp.Length; ++j) { ; } content = temp.Substring(i, j); quickDiarys[qcount++] = new QuicDiary(emotion, createTime, content); } } } }
public static async Task <TextFile> ReadFile(string filePath) { StorageFile file = await GetFile(filePath); return(file == null ? null : await ReadFile(file)); }
public async void DeleteItem_Click(object sender, RoutedEventArgs e) { if (App.AppSettings.ShowConfirmDeleteDialog == true) //check if the setting to show a confirmation dialog is on { var dialog = new ConfirmDeleteDialog(); var result = await dialog.ShowAsync(); if (dialog.Result != MyResult.Delete) //delete selected item(s) if the result is yes { return; //return if the result isn't delete } } try { var CurrentInstance = App.CurrentInstance; List <ListedItem> selectedItems = new List <ListedItem>(); foreach (ListedItem selectedItem in (CurrentInstance.ContentPage as BaseLayout).SelectedItems) { selectedItems.Add(selectedItem); } int itemsDeleted = 0; if (selectedItems.Count > 3) { (App.CurrentInstance as ProHome).UpdateProgressFlyout(InteractionOperationType.DeleteItems, itemsDeleted, selectedItems.Count); } foreach (ListedItem storItem in selectedItems) { if (selectedItems.Count > 3) { (App.CurrentInstance as ProHome).UpdateProgressFlyout(InteractionOperationType.DeleteItems, ++itemsDeleted, selectedItems.Count); } try { if (storItem.FileType != "Folder") { var item = await StorageFile.GetFileFromPathAsync(storItem.FilePath); if (App.InteractionViewModel.PermanentlyDelete) { await item.DeleteAsync(StorageDeleteOption.PermanentDelete); } else { await item.DeleteAsync(StorageDeleteOption.Default); } } else { var item = await StorageFolder.GetFolderFromPathAsync(storItem.FilePath); if (App.InteractionViewModel.PermanentlyDelete) { await item.DeleteAsync(StorageDeleteOption.PermanentDelete); } else { await item.DeleteAsync(StorageDeleteOption.Default); } } } catch (FileLoadException) { // try again if (storItem.FileType != "Folder") { var item = await StorageFile.GetFileFromPathAsync(storItem.FilePath); if (App.InteractionViewModel.PermanentlyDelete) { await item.DeleteAsync(StorageDeleteOption.PermanentDelete); } else { await item.DeleteAsync(StorageDeleteOption.Default); } } else { var item = await StorageFolder.GetFolderFromPathAsync(storItem.FilePath); if (App.InteractionViewModel.PermanentlyDelete) { await item.DeleteAsync(StorageDeleteOption.PermanentDelete); } else { await item.DeleteAsync(StorageDeleteOption.Default); } } } CurrentInstance.ViewModel.RemoveFileOrFolder(storItem); } App.CurrentInstance.NavigationToolbar.CanGoForward = false; } catch (UnauthorizedAccessException) { MessageDialog AccessDeniedDialog = new MessageDialog("Access Denied", "Unable to delete this item"); await AccessDeniedDialog.ShowAsync(); } catch (FileNotFoundException) { Debug.WriteLine("Attention: Tried to delete an item that could be found"); } App.InteractionViewModel.PermanentlyDelete = false; //reset PermanentlyDelete flag }
public static async Task <BasicProperties> GetFileProperties(StorageFile file) { return(await file.GetBasicPropertiesAsync()); }
public static bool IsFileReadOnly(StorageFile file) { return((file.Attributes & Windows.Storage.FileAttributes.ReadOnly) != 0); }
private async Task <bool> BackupTextAsync(string text, Encoding encoding, LineEnding lineEnding, StorageFile file) { try { await FileSystemUtility.WriteToFile(LineEndingUtility.ApplyLineEnding(text, lineEnding), encoding, file); return(true); } catch (Exception ex) { LoggingService.LogError($"[SessionManager] Failed to save backup file: {ex.Message}"); return(false); } }
private async Task <ITextEditor> RecoverTextEditorAsync(TextEditorSessionDataV1 editorSessionData) { StorageFile editingFile = null; if (editorSessionData.EditingFileFutureAccessToken != null) { editingFile = await FileSystemUtility.GetFileFromFutureAccessList(editorSessionData.EditingFileFutureAccessToken); } string lastSavedFile = editorSessionData.LastSavedBackupFilePath; string pendingFile = editorSessionData.PendingBackupFilePath; ITextEditor textEditor; if (editingFile == null && lastSavedFile == null && pendingFile == null) { textEditor = null; } else if (editingFile != null && lastSavedFile == null && pendingFile == null) // File without pending changes { textEditor = await _notepadsCore.CreateTextEditor(editorSessionData.Id, editingFile, ignoreFileSizeLimit : true); textEditor.ResetEditorState(editorSessionData.StateMetaData); } else // File with pending changes { string lastSavedText = string.Empty; string pendingText = null; if (lastSavedFile != null) { TextFile lastSavedTextFile = await FileSystemUtility.ReadFile(lastSavedFile, ignoreFileSizeLimit : true, EncodingUtility.GetEncodingByName(editorSessionData.StateMetaData.LastSavedEncoding)); lastSavedText = lastSavedTextFile.Content; } var textFile = new TextFile(lastSavedText, EncodingUtility.GetEncodingByName(editorSessionData.StateMetaData.LastSavedEncoding), LineEndingUtility.GetLineEndingByName(editorSessionData.StateMetaData.LastSavedLineEnding), editorSessionData.StateMetaData.DateModifiedFileTime); textEditor = _notepadsCore.CreateTextEditor( editorSessionData.Id, textFile, editingFile, editorSessionData.StateMetaData.FileNamePlaceholder, editorSessionData.StateMetaData.IsModified); if (pendingFile != null) { TextFile pendingTextFile = await FileSystemUtility.ReadFile(pendingFile, ignoreFileSizeLimit : true, EncodingUtility.GetEncodingByName(editorSessionData.StateMetaData.LastSavedEncoding)); pendingText = pendingTextFile.Content; } textEditor.ResetEditorState(editorSessionData.StateMetaData, pendingText); } return(textEditor); }
public QnUploadImage(StorageFile file) : base(file) { }
/// <summary> /// Cache specific hooks to process items from HTTP response /// </summary> /// <param name="baseFile">storage file</param> /// <param name="initializerKeyValues">key value pairs used when initializing instance of generic type</param> /// <returns>Media source</returns> protected override Task <MediaSource> InitializeTypeAsync(StorageFile baseFile, List <KeyValuePair <string, object> > initializerKeyValues = null) { return(Task.Run(() => MediaSource.CreateFromStorageFile(baseFile))); }
private async Task TranscodeAsync(UpdateFileGenerationStart update) { try { var args = update.Conversion.Substring("transcode#".Length); args = args.Substring(0, args.LastIndexOf('#')); var conversion = JsonConvert.DeserializeObject <VideoConversion>(args); if (conversion.Transcode) { var file = await StorageFile.GetFileFromPathAsync(update.OriginalPath); var temp = await StorageFile.GetFileFromPathAsync(update.DestinationPath); var transcoder = new MediaTranscoder(); var profile = await MediaEncodingProfile.CreateFromFileAsync(file); profile.Video.Width = conversion.Width; profile.Video.Height = conversion.Height; profile.Video.Bitrate = conversion.Bitrate; if (conversion.Mute) { profile.Audio = null; } if (conversion.Transform) { var transform = new VideoTransformEffectDefinition(); transform.Rotation = conversion.Rotation; transform.OutputSize = conversion.OutputSize; transform.Mirror = conversion.Mirror; transform.CropRectangle = conversion.CropRectangle.IsEmpty() ? Rect.Empty : conversion.CropRectangle; transcoder.AddVideoEffect(transform.ActivatableClassId, true, transform.Properties); } var prepare = await transcoder.PrepareFileTranscodeAsync(file, temp, profile); if (prepare.CanTranscode) { var progress = prepare.TranscodeAsync(); progress.Progress = (result, delta) => { _protoService.Send(new SetFileGenerationProgress(update.GenerationId, (int)delta, 100)); }; progress.Completed = (result, delta) => { _protoService.Send(new FinishFileGeneration(update.GenerationId, prepare.FailureReason == TranscodeFailureReason.None ? null : new Error(406, prepare.FailureReason.ToString()))); }; } else { _protoService.Send(new FinishFileGeneration(update.GenerationId, new Error(500, prepare.FailureReason.ToString()))); } } else { await CopyAsync(update); } } catch (Exception ex) { _protoService.Send(new FinishFileGeneration(update.GenerationId, new Error(500, ex.ToString()))); } }
private async void OpenSelectedItems(bool displayApplicationPicker) { try { string selectedItemPath = null; int selectedItemCount; Type sourcePageType = App.CurrentInstance.CurrentPageType; selectedItemCount = (CurrentInstance.ContentPage as BaseLayout).SelectedItems.Count; if (selectedItemCount == 1) { selectedItemPath = (CurrentInstance.ContentPage as BaseLayout).SelectedItems[0].FilePath; } // Access MRU List var mostRecentlyUsed = Windows.Storage.AccessCache.StorageApplicationPermissions.MostRecentlyUsedList; if (selectedItemCount == 1) { var clickedOnItem = (CurrentInstance.ContentPage as BaseLayout).SelectedItems[0]; if (clickedOnItem.FileType == "Folder") { // Add location to MRU List mostRecentlyUsed.Add(await StorageFolder.GetFolderFromPathAsync(selectedItemPath)); CurrentInstance.ViewModel.Universal.WorkingDirectory = selectedItemPath; CurrentInstance.NavigationToolbar.PathControlDisplayText = selectedItemPath; (CurrentInstance.ContentPage as BaseLayout).AssociatedViewModel.EmptyTextState.isVisible = Visibility.Collapsed; App.CurrentInstance.SidebarSelectedItem = App.sideBarItems.FirstOrDefault(x => x.Path != null && x.Path.Equals(selectedItemPath, StringComparison.OrdinalIgnoreCase)); if (App.CurrentInstance.SidebarSelectedItem == null) { App.CurrentInstance.SidebarSelectedItem = App.sideBarItems.FirstOrDefault(x => x.Path != null && x.Path.Equals(Path.GetPathRoot(selectedItemPath), StringComparison.OrdinalIgnoreCase)); } CurrentInstance.ContentFrame.Navigate(sourcePageType, selectedItemPath, new SuppressNavigationTransitionInfo()); } else { // Add location to MRU List mostRecentlyUsed.Add(await StorageFile.GetFileFromPathAsync(clickedOnItem.FilePath)); if (displayApplicationPicker) { StorageFile file = await StorageFile.GetFileFromPathAsync(clickedOnItem.FilePath); var options = new LauncherOptions { DisplayApplicationPicker = true }; await Launcher.LaunchFileAsync(file, options); } else { await InvokeWin32Component(clickedOnItem.FilePath); } } } else if (selectedItemCount > 1) { foreach (ListedItem clickedOnItem in (CurrentInstance.ContentPage as BaseLayout).SelectedItems) { if (clickedOnItem.FileType == "Folder") { instanceTabsView.AddNewTab(typeof(ProHome), clickedOnItem.FilePath); } else { // Add location to MRU List mostRecentlyUsed.Add(await StorageFile.GetFileFromPathAsync(clickedOnItem.FilePath)); if (displayApplicationPicker) { StorageFile file = await StorageFile.GetFileFromPathAsync(clickedOnItem.FilePath); var options = new LauncherOptions { DisplayApplicationPicker = true }; await Launcher.LaunchFileAsync(file, options); } else { await InvokeWin32Component(clickedOnItem.FilePath); } } } } } catch (FileNotFoundException) { MessageDialog dialog = new MessageDialog("The file you are attempting to access may have been moved or deleted.", "File Not Found"); await dialog.ShowAsync(); NavigationActions.Refresh_Click(null, null); } }
private async Task ThumbnailAsync(UpdateFileGenerationStart update) { try { var args = update.Conversion.Substring("thumbnail_transcode#".Length); args = args.Substring(0, args.LastIndexOf('#')); var conversion = JsonConvert.DeserializeObject <VideoConversion>(args); if (conversion.Transcode) { var file = await StorageFile.GetFileFromPathAsync(update.OriginalPath); var temp = await StorageFile.GetFileFromPathAsync(update.DestinationPath); var props = await file.Properties.GetVideoPropertiesAsync(); double originalWidth = props.GetWidth(); double originalHeight = props.GetHeight(); if (!conversion.CropRectangle.IsEmpty()) { file = await ImageHelper.CropAsync(file, conversion.CropRectangle); originalWidth = conversion.CropRectangle.Width; originalHeight = conversion.CropRectangle.Height; } using (var fileStream = await ImageHelper.OpenReadAsync(file)) using (var outputStream = await temp.OpenAsync(FileAccessMode.ReadWrite)) { var decoder = await BitmapDecoder.CreateAsync(fileStream); double ratioX = (double)90 / originalWidth; double ratioY = (double)90 / originalHeight; double ratio = Math.Min(ratioX, ratioY); uint width = (uint)(originalWidth * ratio); uint height = (uint)(originalHeight * ratio); var transform = new BitmapTransform(); transform.ScaledWidth = width; transform.ScaledHeight = height; transform.InterpolationMode = BitmapInterpolationMode.Linear; transform.Flip = conversion.Mirror == MediaMirroringOptions.Horizontal ? BitmapFlip.Horizontal : BitmapFlip.None; var pixelData = await decoder.GetSoftwareBitmapAsync(decoder.BitmapPixelFormat, decoder.BitmapAlphaMode, transform, ExifOrientationMode.RespectExifOrientation, ColorManagementMode.DoNotColorManage); var propertySet = new BitmapPropertySet(); var qualityValue = new BitmapTypedValue(0.77, PropertyType.Single); propertySet.Add("ImageQuality", qualityValue); var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, outputStream); encoder.SetSoftwareBitmap(pixelData); await encoder.FlushAsync(); _protoService.Send(new FinishFileGeneration(update.GenerationId, null)); } } } catch (Exception ex) { _protoService.Send(new FinishFileGeneration(update.GenerationId, new Error(500, ex.ToString()))); } }
public async Task <bool> RenameFileItem(ListedItem item, string oldName, string newName) { if (oldName == newName) { return(true); } if (newName != "") { try { if (item.FileType == "Folder") { var folder = await StorageFolder.GetFolderFromPathAsync(item.FilePath); await folder.RenameAsync(newName, NameCollisionOption.FailIfExists); } else { var file = await StorageFile.GetFileFromPathAsync(item.FilePath); await file.RenameAsync(newName, NameCollisionOption.FailIfExists); } } catch (Exception) { var dialog = new ContentDialog() { Title = "Item already exists", Content = "An item with this name already exists in this folder.", PrimaryButtonText = "Generate new name", SecondaryButtonText = "Replace existing item" }; ContentDialogResult result = await dialog.ShowAsync(); if (result == ContentDialogResult.Primary) { if (item.FileType == "Folder") { var folder = await StorageFolder.GetFolderFromPathAsync(item.FilePath); await folder.RenameAsync(newName, NameCollisionOption.GenerateUniqueName); } else { var file = await StorageFile.GetFileFromPathAsync(item.FilePath); await file.RenameAsync(newName, NameCollisionOption.GenerateUniqueName); } } else if (result == ContentDialogResult.Secondary) { if (item.FileType == "Folder") { var folder = await StorageFolder.GetFolderFromPathAsync(item.FilePath); await folder.RenameAsync(newName, NameCollisionOption.ReplaceExisting); } else { var file = await StorageFile.GetFileFromPathAsync(item.FilePath); await file.RenameAsync(newName, NameCollisionOption.ReplaceExisting); } } } } CurrentInstance.NavigationToolbar.CanGoForward = false; return(true); }
private async Task DownloadAsync(UpdateFileGenerationStart update) { try { if (!Uri.TryCreate(update.OriginalPath, UriKind.Absolute, out Uri result)) { return; } var client = new HttpClient(); client.DefaultRequestHeaders.ExpectContinue = false; var temp = await StorageFile.GetFileFromPathAsync(update.DestinationPath); var request = new HttpRequestMessage(HttpMethod.Get, result); var response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead); var length = int.Parse(response.Content.Headers.GetValues("Content-Length").FirstOrDefault()); _protoService.Send(new SetFileGenerationProgress(update.GenerationId, length, 0)); using (var fs = await temp.OpenAsync(FileAccessMode.ReadWrite)) { using (var stream = await response.Content.ReadAsStreamAsync()) { var inputStream = stream.AsInputStream(); int totalBytesRead = 0; while (true) { // Read from the web. IBuffer buffer = new Windows.Storage.Streams.Buffer(1024); buffer = await inputStream.ReadAsync( buffer, buffer.Capacity, InputStreamOptions.None); if (buffer.Length == 0) { // There is nothing else to read. break; } // Report progress. totalBytesRead += (int)buffer.Length; _protoService.Send(new SetFileGenerationProgress(update.GenerationId, length, totalBytesRead)); // Write to file. await fs.WriteAsync(buffer); } inputStream.Dispose(); fs.Dispose(); } } _protoService.Send(new FinishFileGeneration(update.GenerationId, null)); } catch (Exception ex) { _protoService.Send(new FinishFileGeneration(update.GenerationId, new Error(500, ex.ToString()))); } }
public async void CopyItem_ClickAsync(object sender, RoutedEventArgs e) { DataPackage dataPackage = new DataPackage(); dataPackage.RequestedOperation = DataPackageOperation.Copy; List <IStorageItem> items = new List <IStorageItem>(); if (App.CurrentInstance.CurrentPageType == typeof(GenericFileBrowser)) { var CurrentInstance = App.CurrentInstance; CopySourcePath = CurrentInstance.ViewModel.Universal.WorkingDirectory; if ((CurrentInstance.ContentPage as BaseLayout).SelectedItems.Count != 0) { foreach (ListedItem StorItem in (CurrentInstance.ContentPage as BaseLayout).SelectedItems) { if (StorItem.FileType != "Folder") { var item = await StorageFile.GetFileFromPathAsync(StorItem.FilePath); items.Add(item); } else { var item = await StorageFolder.GetFolderFromPathAsync(StorItem.FilePath); items.Add(item); } } } } else if (App.CurrentInstance.CurrentPageType == typeof(PhotoAlbum)) { CopySourcePath = CurrentInstance.ViewModel.Universal.WorkingDirectory; if ((CurrentInstance.ContentPage as BaseLayout).SelectedItems.Count != 0) { foreach (ListedItem StorItem in (CurrentInstance.ContentPage as BaseLayout).SelectedItems) { if (StorItem.FileType != "Folder") { var item = await StorageFile.GetFileFromPathAsync(StorItem.FilePath); items.Add(item); } else { var item = await StorageFolder.GetFolderFromPathAsync(StorItem.FilePath); items.Add(item); } } } } if (items?.Count > 0) { IEnumerable <IStorageItem> EnumerableOfItems = items; dataPackage.SetStorageItems(EnumerableOfItems); Clipboard.SetContent(dataPackage); Clipboard.Flush(); } }
public StoragePhoto(StorageFile file) : base(file) { }
public static async void readData() { folder = ApplicationData.Current.LocalFolder; Chart = await folder.CreateFileAsync("DiaryCharts.ltr", CreationCollisionOption.OpenIfExists); using (Stream file = await Chart.OpenStreamForReadAsync()) { if (file.Length == 0) { return; } using (StreamReader chartsReader = new StreamReader(file)) { while (!chartsReader.EndOfStream) { int i, j, tagn; string[] tagData; createTime = new int[3]; string temp = chartsReader.ReadLine(); for (i = 0; temp[i] != ' '; ++i) { ; } emotion = temp.Substring(0, i); while (temp[++i] == ' ') { ; } for (j = 0; temp[i + j] >= '0' && temp[i + j] <= '9'; ++j) { ; } createTime[0] = Int32.Parse(temp.Substring(i, j)); i = i + j; while (temp[++i] == ' ') { ; } for (j = 0; temp[i + j] >= '0' && temp[i + j] <= '9'; ++j) { ; } createTime[1] = Int32.Parse(temp.Substring(i, j)); i = i + j; while (temp[++i] == ' ') { ; } for (j = 0; temp[i + j] >= '0' && temp[i + j] <= '9'; ++j) { ; } createTime[2] = Int32.Parse(temp.Substring(i, j)); i = i + j; while (temp[++i] == ' ') { ; } for (j = 0; temp[i + j] >= '0' && temp[i + j] <= '9'; ++j) { ; } background = Int32.Parse(temp.Substring(i, j)); i = i + j; while (temp[++i] == ' ') { ; } for (j = 0; temp[i + j] >= '0' && temp[i + j] <= '9'; ++j) { ; } tagn = Int32.Parse(temp.Substring(i, j)); i = i + j; tagData = new string[tagn]; for (int k = 0; k < tagn; ++k) { while (temp[++i] == ' ') { ; } for (j = 0; temp[i + j] != ' '; ++j) { ; } tagData[k] = temp.Substring(i, j); i += j; } tags = new ArrayList(tagData); while (temp[++i] == ' ') { ; } for (j = 0; i + j < temp.Length; ++j) { ; } fileName = temp.Substring(i, j); Diarys[count++] = new DailyDiary(emotion, createTime, background, tags, fileName); } } } }
private async void LoadVisibleStickers() { var scrollingHost = Stickers.ItemsPanelRoot as ItemsWrapGrid; if (scrollingHost == null) { return; } if (scrollingHost.FirstVisibleIndex < 0) { return; } var lastSet = 0L; for (int i = scrollingHost.FirstVisibleIndex; i <= scrollingHost.LastVisibleIndex; i++) { if (i >= Stickers.Items.Count) { return; } var first = Stickers.Items[i] as ViewModels.Dialogs.StickerViewModel; if (first == null || first.SetId == lastSet) { continue; } lastSet = first.SetId; var fromItem = Stickers.ContainerFromItem(first); if (fromItem == null) { continue; } var header = Stickers.GroupHeaderContainerFromItemContainer(fromItem) as GridViewHeaderItem; if (header == null) { continue; } var group = header.Content as ViewModels.Dialogs.StickerSetViewModel; if (group == null || group.IsLoaded) { continue; } group.IsLoaded = true; Debug.WriteLine("Loading sticker set " + group.Id); var response = await ViewModel.ProtoService.SendAsync(new GetStickerSet(group.Id)); if (response is StickerSet full) { group.Update(full); //group.Stickers.RaiseCollectionChanged(new System.Collections.Specialized.NotifyCollectionChangedEventArgs(System.Collections.Specialized.NotifyCollectionChangedAction.Reset)); int j = 0; foreach (var sticker in group.Stickers) { if (sticker.Thumbnail == null) { continue; } //group.Stickers.RaiseCollectionChanged(new System.Collections.Specialized.NotifyCollectionChangedEventArgs(System.Collections.Specialized.NotifyCollectionChangedAction.Move, sticker, j, j)); //j++; var container = Stickers.ContainerFromItem(sticker) as SelectorItem; if (container == null) { continue; } var content = container.ContentTemplateRoot as Image; var file = sticker.Thumbnail.Photo; if (file.Local.IsDownloadingCompleted) { var temp = await StorageFile.GetFileFromPathAsync(file.Local.Path); var buffer = await FileIO.ReadBufferAsync(temp); content.Source = WebPImage.DecodeFromBuffer(buffer); } else if (file.Local.CanBeDownloaded && !file.Local.IsDownloadingActive) { DownloadFile(file.Id, sticker); } } } } }
private async void Convert_Click(object sender, RoutedEventArgs e) { ConverterTopCommandBar.IsEnabled = false; ConverterBottomCommandBar.IsEnabled = false; this.FileProgressBar.Visibility = Visibility.Visible; this.IsBinary.Visibility = Visibility.Collapsed; this.Depth8_16.Visibility = Visibility.Collapsed; this.FileTypeCombo.Visibility = Visibility.Collapsed; this.MaxPixelValue.Visibility = Visibility.Collapsed; this.ThresholdLevelTxt8.Visibility = Visibility.Collapsed; this.ThresholdLevelTxt16.Visibility = Visibility.Collapsed; this.NameCollisionCombo.Visibility = Visibility.Collapsed; if (outputFolder == null) { await this.ChangeFolder(); } var anymapType = (AnymapType)FileTypeCombo.SelectedIndex; var maxValue = Convert.ToUInt32(MaxPixelValue.Text); var threshold8 = Convert.ToByte(ThresholdLevelTxt8.Text); var threshold16 = Convert.ToUInt16(ThresholdLevelTxt16.Text); var bytesPerColor = Depth8_16.IsOn ? 2u : 1u; var creationCollisionOption = (CreationCollisionOption)NameCollisionCombo.SelectedIndex; var filesNum = InputFilesList.Items.Count; var isBinary = this.IsBinary.IsOn; Parallel.For(0, filesNum, async(i, state) => { using (var stream = await RandomAccessStreamReference.CreateFromFile(files[i]).OpenReadAsync()) { var imageDecoder = await BitmapDecoder.CreateAsync(stream); AnymapProperties properties = new AnymapProperties() { AnymapType = anymapType, Width = imageDecoder.OrientedPixelWidth, Height = imageDecoder.OrientedPixelHeight, MaxValue = maxValue, Threshold8 = threshold8, Threshold16 = threshold16, BytesPerColor = bytesPerColor, StreamPosition = 0, }; try { StorageFile newFile = await outputFolder.CreateFileAsync(outputFiles[i], creationCollisionOption); if (isBinary) { byte[] anymapBytes = await anymapEncoder.EncodeBinary(imageDecoder, properties); await FileIO.WriteBytesAsync(newFile, anymapBytes); } else { await FileIO.WriteTextAsync(newFile, await anymapEncoder.EncodeText(imageDecoder, properties)); } await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { (this.InputFilesList.Items[i] as TextBlock).Visibility = Visibility.Collapsed; (this.OutputFilesList.Items[i] as TextBlock).Visibility = Visibility.Visible; this.FileProgressBar.Value = this.FileProgressBar.Value + 1; }); } catch (Exception ex) { await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { (this.InputFilesList.Items[i] as TextBlock).Visibility = Visibility.Collapsed; this.FileProgressBar.Value = this.FileProgressBar.Value + 1; //ContentDialog convert }); Debug.WriteLine(ex.Message); } } }); }
private string CreatePackageForSend(ReplicationPacket packet, out int last) { int maxc = INTERNALLIMIT; WhatItem what = GetBranchConfig(packet.branchname).what; if (what.PackageItemLimit > 0) maxc = what.PackageItemLimit; string outFolder = _OutboxPath; int packageNumber = packet.lastrecord; int i = packet.lastrecord; string filename = outFolder + _S + packet.branchname + _S + packageNumber.ToString("0000000000") + ".mgdat"; if (i < _docs.RecordCount()) { StorageFile<Guid> package = new StorageFile<Guid>(filename, SF_FORMAT.JSON, true); while (maxc > 0) { var meta = _docs.GetMeta(i); if (meta == null) break; if (meta.isReplicated == false && MatchType(meta.typename, what)) { if (meta.isDeleted == false || what.PropogateHQDeletes) { object obj = _docs.GetObject(i, out meta); package.WriteObject(meta.key, obj); maxc--; } } i++; } package.Shutdown(); packageNumber++; // compress the file using (FileStream read = File.OpenRead(filename)) using (FileStream outp = File.Create(filename + ".gz")) CompressForBackup(read, outp); // delete uncompressed file File.Delete(filename); } last = i; return filename + ".gz"; }
public async Task SaveContentToFileAndUpdateEditorState(TextEditor textEditor, StorageFile file) { await textEditor.SaveContentToFileAndUpdateEditorState(file); TextEditorSaved?.Invoke(this, textEditor); }
private string GetCalendarTemplateFile(string[] fileName) { var file = new StorageFile(ResourceManager.Instance.CalendarSlideTemplatesFolder.RelativePathParts .Merge(fileName)); return file.LocalPath; }
/// <summary> /// Retrieves a SignalServiceAttachment /// </summary> /// <param name="pointer">The <see cref="SignalServiceAttachmentPointer"/> /// received in a <see cref="SignalServiceDataMessage"/></param> /// <param name="destination">The download destination for this attachment.</param> /// <returns>A Stream that streams the plaintext attachment contents.</returns> public Stream retrieveAttachment(SignalServiceAttachmentPointer pointer, StorageFile destination) { throw new NotImplementedException(); return(retrieveAttachment(pointer, destination, null)); }
public StorageVideo(StorageFile file) : base(file) { }
private string CreatePackageForSend() { int maxc = INTERNALLIMIT; if (_clientConfig.what.PackageItemLimit > 0) maxc = _clientConfig.what.PackageItemLimit; string outFolder = _OutboxPath; int packageNumber = _clientConfig.outPackageNumber; int i = _clientConfig.lastCounter; string filename = outFolder + packageNumber.ToString("0000000000") + ".mgdat"; int total = _docs.RecordCount(); if (i < total) { StorageFile<Guid> package = new StorageFile<Guid>(filename, SF_FORMAT.JSON, true); while (maxc > 0 && i < total) { var meta = _docs.GetMeta(i); if (meta == null) break; if (meta.isReplicated == false && MatchType(meta.typename)) { object obj = _docs.GetObject(i, out meta); package.WriteObject(meta.key, obj); maxc--; } i++; } package.Shutdown(); packageNumber++; // compress the file using (FileStream read = File.OpenRead(filename)) using (FileStream outp = File.Create(filename + ".gz")) CompressForBackup(read, outp); // delete uncompressed file File.Delete(filename); _clientConfig.lastCounter = i; _clientConfig.outPackageNumber = packageNumber; SaveConfig(); return filename + ".gz"; } return ""; }
/// <summary> /// Retrieves a SignalServiceAttachment /// </summary> /// <param name="pointer">The <see cref="SignalServiceAttachmentPointer"/> /// received in a <see cref="SignalServiceDataMessage"/></param> /// <param name="destination">The download destination for this attachment.</param> /// <param name="listener">An optional listener (may be null) to receive callbacks on download progress.</param> /// <returns>A Stream that streams the plaintext attachment contents.</returns> public Stream retrieveAttachment(SignalServiceAttachmentPointer pointer, StorageFile destination, ProgressListener listener) { throw new NotImplementedException(); return(new MemoryStream()); }
/// <summary> /// Decode image from a StorageFile and return a VideoFrame /// </summary> /// <param name="file"></param> /// <returns></returns> public static IAsyncOperation <VideoFrame> LoadVideoFrameFromStorageFileAsync(StorageFile file) { return(AsyncInfo.Run(async(token) => { VideoFrame resultFrame = null; SoftwareBitmap softwareBitmap; using (IRandomAccessStream stream = await file.OpenAsync(FileAccessMode.Read)) { // Create the decoder from the stream BitmapDecoder decoder = await BitmapDecoder.CreateAsync(stream); // Get the SoftwareBitmap representation of the file in BGRA8 format softwareBitmap = await decoder.GetSoftwareBitmapAsync(); softwareBitmap = SoftwareBitmap.Convert(softwareBitmap, BitmapPixelFormat.Bgra8, BitmapAlphaMode.Premultiplied); } // Encapsulate the image in the WinML image type (VideoFrame) to be bound and evaluated resultFrame = VideoFrame.CreateWithSoftwareBitmap(softwareBitmap); return resultFrame; })); }
public static async Task <StorageFile> CopyFileToLocalModelFolderAsync(StorageFile file, Guid modelId) { StorageFolder storageFolder = await ApplicationData.Current.LocalFolder.CreateFolderAsync($"FormRecognizer\\{modelId.ToString()}", CreationCollisionOption.OpenIfExists); return(await file?.CopyAsync(storageFolder, file.Name, NameCollisionOption.GenerateUniqueName)); }
public void TestStorageProvider() { // TestAddStorageFile // Act Task<StorageFile> addResult = _storageProvider.AddFileAsync(_userId, _filePath, "application/octet-stream"); addResult.Wait(); // Assert Assert.IsFalse(addResult.IsFaulted); Assert.AreNotEqual(addResult.Result.FileId, new Guid()); Assert.AreEqual(addResult.Result.Users.Count, 0); Assert.AreEqual(addResult.Result.Groups.Count, 0); _fileId = addResult.Result.FileId; // TestExistsStorageFile // Act var existAfterAddResult = _storageProvider.ExistsFileAsync(_filePath); existAfterAddResult.Wait(); // Assert Assert.IsFalse(existAfterAddResult.IsFaulted); Assert.IsTrue(existAfterAddResult.Result); // TestGetStorageFile // Act Task<StorageFile> getAfterAddResult = _storageProvider.GetByIdAsync(_fileId); getAfterAddResult.Wait(); // Assert Assert.IsFalse(getAfterAddResult.IsFaulted); Assert.IsNotNull(getAfterAddResult.Result); Assert.AreNotEqual(getAfterAddResult.Result.FileId, new Guid()); Assert.AreEqual(getAfterAddResult.Result.OwnerUserId, _userId); Assert.AreEqual(getAfterAddResult.Result.Users.Count, 0); Assert.AreEqual(getAfterAddResult.Result.Groups.Count, 0); // TestUpdateStorageFile // Arrange var storageFile = new StorageFile(_fileId, string.Empty, _userId){Users = new List<string> {"vasya"}}; // Act var updateResult = _storageProvider.UpdateAsync(storageFile); updateResult.Wait(); // Assert Assert.IsFalse(updateResult.IsFaulted); // TestGetStorageFileAfterUpdate // Act Task<StorageFile> getAfterUpdateResult = _storageProvider.GetByIdAsync(_fileId); getAfterUpdateResult.Wait(); // Assert Assert.IsFalse(getAfterUpdateResult.IsFaulted); Assert.AreNotEqual(getAfterUpdateResult.Result.FileId, new Guid()); Assert.IsTrue(getAfterUpdateResult.Result.Users.Contains("vasya")); // TestDeleteStorageFile // Arrange storageFile = new StorageFile(_fileId, string.Empty, _userId); // Act var deleteResult = _storageProvider.DeleteAsync(storageFile.FileId, true); deleteResult.Wait(); // Assert Assert.IsFalse(deleteResult.IsFaulted); // TestExistsStorageFileAfterDelete // Act var existsAfterDeleteResult = _storageProvider.ExistsFileAsync(_filePath); existsAfterDeleteResult.Wait(); // Assert Assert.IsFalse(existsAfterDeleteResult.IsFaulted); Assert.IsFalse(existsAfterDeleteResult.Result); // TestGetStorageFileAfterDelete // Act Task<StorageFile> getAfterDeleteResult = _storageProvider.GetByIdAsync(_fileId); getAfterDeleteResult.Wait(); // Assert Assert.IsFalse(getAfterDeleteResult.IsFaulted); Assert.IsNull(getAfterDeleteResult.Result); }
private void CreateStorage() { _storage = new StorageFile<string>(_write, _rec, KeyLength); }