コード例 #1
0
        public void Test_StorageFileHelper_IsFilePathValid_WithIllegalCharacters()
        {
            string filepath = "my>folder|my<file\t.txt";

            bool result = StorageFileHelper.IsFilePathValid(filepath);

            Assert.IsFalse(result);
        }
コード例 #2
0
        public async Task Test_StorageFileHelper_Bytes_PackagedFile()
        {
            byte[] loadedBytes = await StorageFileHelper.ReadBytesFromPackagedFileAsync(PackagedFilePath);

            string loadedText = Encoding.Unicode.GetString(loadedBytes);

            StringAssert.Contains(loadedText, Sampletext);
        }
コード例 #3
0
        public void Test_StorageFileHelper_IsFilePathValid_WithCorrectFilePath()
        {
            string filepath = "my_folder/my_file.txt";

            bool result = StorageFileHelper.IsFilePathValid(filepath);

            Assert.IsTrue(result);
        }
コード例 #4
0
        public void Test_StorageFileHelper_IsFileNameValid_WithIllegalCharacters()
        {
            string filename = "my|file.txt";

            bool result = StorageFileHelper.IsFileNameValid(filename);

            Assert.IsFalse(result);
        }
コード例 #5
0
        public void Test_StorageFileHelper_IsFileNameValid_WithCorrectFileName()
        {
            string filename = "my_file.txt";

            bool result = StorageFileHelper.IsFileNameValid(filename);

            Assert.IsTrue(result);
        }
コード例 #6
0
        public async Task Test_StorageFileHelper_Bytes_PackagedFile()
        {
            byte[] loadedBytes = await StorageFileHelper.ReadBytesFromPackagedFileAsync(PACKAGEDFILEPATH);

            string loadedText = Encoding.Unicode.GetString(loadedBytes);

            StringAssert.Contains(loadedText, SAMPLETEXT);
        }
コード例 #7
0
        /// <summary>
        /// Save object inside file.
        /// There is no limitation to use this method (refers to <see cref="Save{T}(string, T)"/> method for simple objects).
        /// </summary>
        /// <typeparam name="T">Type of object saved</typeparam>
        /// <param name="filePath">Path to the file that will contain the object</param>
        /// <param name="value">Object to save</param>
        /// <returns>Waiting task until completion</returns>
        public async Task SaveFileAsync <T>(string filePath, T value)
        {
            if (Folder == null)
            {
                Folder = await GetDataSaveFolder();
            }

            await StorageFileHelper.WriteTextToFileAsync(Folder, JsonConvert.SerializeObject(value), filePath, CreationCollisionOption.ReplaceExisting);
        }
コード例 #8
0
        /// <summary>
        /// Retrieve object from file.
        /// </summary>
        /// <typeparam name="T">Type of object retrieved</typeparam>
        /// <param name="filePath">Path to the file that contains the object</param>
        /// <param name="default">Default value of the object</param>
        /// <returns>Waiting task until completion with the object in the file</returns>
        public async Task <T> ReadFileAsync <T>(string filePath, T @default = default(T))
        {
            if (Folder == null)
            {
                Folder = await GetDataSaveFolder();
            }

            string value = await StorageFileHelper.ReadTextFromFileAsync(Folder, filePath);

            return((value != null) ? JsonConvert.DeserializeObject <T>(value) : @default);
        }
コード例 #9
0
        public async Task Test_StorageFileHelper_Text_KnownFolder()
        {
            var storageFile = await StorageFileHelper.WriteTextToKnownFolderFileAsync(KnownFolderId.PicturesLibrary, Sampletext, Filename);

            Assert.IsNotNull(storageFile);

            string loadedText = await StorageFileHelper.ReadTextFromKnownFoldersFileAsync(KnownFolderId.PicturesLibrary, Filename);

            Assert.AreEqual(Sampletext, loadedText);

            await storageFile.DeleteAsync(StorageDeleteOption.Default);
        }
コード例 #10
0
        public async Task Test_StorageFileHelper_Text_LocalCacheFolder()
        {
            var storageFile = await StorageFileHelper.WriteTextToLocalCacheFileAsync(Sampletext, Filename);

            Assert.IsNotNull(storageFile);

            string loadedText = await StorageFileHelper.ReadTextFromLocalCacheFileAsync(Filename);

            Assert.AreEqual(Sampletext, loadedText);

            await storageFile.DeleteAsync(StorageDeleteOption.Default);
        }
コード例 #11
0
        public async Task Test_StorageFileHelper_Text_LocalFolder()
        {
            var storageFile = await StorageFileHelper.WriteTextToLocalFileAsync(SAMPLETEXT, FILENAME);

            Assert.IsNotNull(storageFile);

            string loadedText = await StorageFileHelper.ReadTextFromLocalFileAsync(FILENAME);

            Assert.AreEqual(SAMPLETEXT, loadedText);

            await storageFile.DeleteAsync(StorageDeleteOption.Default);
        }
コード例 #12
0
        public async Task Test_StorageFileHelper_Text_StorageFolder()
        {
            var folder      = ApplicationData.Current.LocalFolder;
            var storageFile = await StorageFileHelper.WriteTextToFileAsync(folder, Sampletext, Filename);

            Assert.IsNotNull(storageFile);

            var loadedText = await StorageFileHelper.ReadTextFromFileAsync(folder, Filename);

            Assert.AreEqual(Sampletext, loadedText);

            await storageFile.DeleteAsync(StorageDeleteOption.Default);
        }
コード例 #13
0
        public async static Task <string> Get_HomeInfo()
        {
            StorageFolder localFolder = Windows.Storage.ApplicationData.Current.LocalFolder;

            if (await localFolder.FileExistsAsync("HomeInfo.json"))
            {
                return(await StorageFileHelper.ReadTextFromLocalFileAsync("HomeInfo.json"));
            }
            else
            {
                return("");
            }
            // Load some text from a file named appFilename.txt in the local folder
        }
コード例 #14
0
        public async Task Test_StorageFileHelper_Bytes_LocalCacheFolder()
        {
            byte[] unicodeBytes = Encoding.Unicode.GetBytes(Sampletext);

            var storageFile = await StorageFileHelper.WriteBytesToLocalCacheFileAsync(unicodeBytes, Filename);

            Assert.IsNotNull(storageFile);

            byte[] loadedBytes = await StorageFileHelper.ReadBytesFromLocalCacheFileAsync(Filename);

            string loadedText = Encoding.Unicode.GetString(loadedBytes);

            Assert.AreEqual(Sampletext, loadedText);

            await storageFile.DeleteAsync(StorageDeleteOption.Default);
        }
コード例 #15
0
        public async Task Test_StorageFileHelper_Bytes_KnownFolder()
        {
            byte[] unicodeBytes = Encoding.Unicode.GetBytes(Sampletext);

            var storageFile = await StorageFileHelper.WriteBytesToKnownFolderFileAsync(KnownFolderId.PicturesLibrary, unicodeBytes, Filename);

            Assert.IsNotNull(storageFile);

            byte[] loadedBytes = await StorageFileHelper.ReadBytesFromKnownFoldersFileAsync(KnownFolderId.PicturesLibrary, Filename);

            string loadedText = Encoding.Unicode.GetString(loadedBytes);

            Assert.AreEqual(Sampletext, loadedText);

            await storageFile.DeleteAsync(StorageDeleteOption.Default);
        }
コード例 #16
0
        protected override async void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);

            CustomizeTitleBar();

            var viewModel = (MainShellViewModel)DataContext;
            var localFolder = ApplicationData.Current.LocalFolder;

            if (await localFolder.FileExistsAsync(MainShellViewModel.UserInfoLocalStorageKey))
            {
                viewModel.UserInfo = JsonConvert.DeserializeObject<UserInfo>(await StorageFileHelper.ReadTextFromLocalFileAsync(MainShellViewModel.UserInfoLocalStorageKey));
                viewModel.IsAuthenticated = viewModel.UserInfo != null;
            }

            viewModel.NavigateTo(typeof(HomeViewModel));
        }
コード例 #17
0
        public async Task Test_StorageFileHelper_Bytes_StorageFolder()
        {
            byte[] unicodeBytes = Encoding.Unicode.GetBytes(SAMPLETEXT);

            var folder      = ApplicationData.Current.LocalFolder;
            var storageFile = await StorageFileHelper.WriteBytesToFileAsync(folder, unicodeBytes, FILENAME);

            Assert.IsNotNull(storageFile);

            byte[] loadedBytes = await StorageFileHelper.ReadBytesFromFileAsync(folder, FILENAME);

            string loadedText = Encoding.Unicode.GetString(loadedBytes);

            Assert.AreEqual(SAMPLETEXT, loadedText);

            await storageFile.DeleteAsync(StorageDeleteOption.Default);
        }
コード例 #18
0
 void FromDraft(DraftModel model)
 {
     Clean();
     Text               = model.Status.Replace("\n", "\r");
     IsSensitive        = model.Sensitive;
     ContentWarningText = model.SpoilerText;
     if (!string.IsNullOrEmpty(model.SpoilerText))
     {
         ContentWarning.IsChecked = true;
     }
     SelectedVisibilityIndex = TootVisibilityList.VisibilityList.FindIndex(v => v.VisibilityCode == model.Visibility);
     if (model.Medias != null && model.Medias.Any())
     {
         model.Medias.ForEach(async item => await AddMediaData(await StorageFileHelper.ReadBytesFromLocalFileAsync(item.SavedFile)));
     }
     _draftId = model.Id;
 }
コード例 #19
0
ファイル: Data.cs プロジェクト: sebastiandittrich/SchulApp
        public static async void Save <T>(List <T> list, string filename)
        {
            var helper = new LocalObjectStorageHelper();

            if (list.Count != 0)
            {
                await helper.SaveFileAsync(filename, list);
            }
            else
            {
                if (await StorageFileHelper.FileExistsAsync(ApplicationData.Current.LocalFolder, filename))
                {
                    StorageFile file = await ApplicationData.Current.LocalFolder.GetFileAsync(filename);

                    await file.DeleteAsync();
                }
            }
        }
コード例 #20
0
        public async Task Test_StreamHelper_LocalCacheFolder()
        {
            Assert.IsFalse(await StreamHelper.IsLocalCacheFileExistsAsync(Filename));

            var storageFile = await StorageFileHelper.WriteTextToLocalCacheFileAsync(SampleText, Filename);

            Assert.IsNotNull(storageFile);

            Assert.IsTrue(await StreamHelper.IsLocalCacheFileExistsAsync(Filename));

            using (var stream = await StreamHelper.GetLocalCacheFileStreamAsync(Filename))
            {
                var loadedText = await stream.ReadTextAsync(Encoding.UTF8);

                StringAssert.Contains(loadedText, SampleText);
            }

            await storageFile.DeleteAsync(StorageDeleteOption.Default);
        }
コード例 #21
0
        public async Task Test_StreamHelper_KnownFolder()
        {
            var folder = KnownFolderId.PicturesLibrary;

            Assert.IsFalse(await StreamHelper.IsKnownFolderFileExistsAsync(folder, Filename));

            var storageFile = await StorageFileHelper.WriteTextToKnownFolderFileAsync(folder, SampleText, Filename);

            Assert.IsNotNull(storageFile);

            Assert.IsTrue(await StreamHelper.IsKnownFolderFileExistsAsync(folder, Filename));

            using (var stream = await StreamHelper.GetKnowFoldersFileStreamAsync(folder, Filename))
            {
                var loadedText = await stream.ReadTextAsync(Encoding.UTF8);

                StringAssert.Contains(loadedText, SampleText);
            }

            await storageFile.DeleteAsync(StorageDeleteOption.Default);
        }
コード例 #22
0
ファイル: GankService.cs プロジェクト: jango2015/gank.uwp
        //static StorageFileHelper _storageHelper = new StorageFileHelper();
        public static async Task <DayResult> GetDayResult(DateTime date, bool useCache)
        {
            var url = $"http://gank.io/api/day/{ date.Year }/{ date.Month }/{ date.Day }";// dayUrl(date.Year, date.Month, date.Day);

            string key  = $"DayResult{date.ToString("yyyyMMdd")}";
            string json = string.Empty;

            if (useCache && await ApplicationData.Current.LocalCacheFolder.FileExistsAsync(key))
            {
                json = await StorageFileHelper.ReadTextFromLocalCacheFileAsync(key);
            }
            else
            {
                json = await Utils.GetJsonAsync(url);

                await StorageFileHelper.WriteTextToLocalCacheFileAsync(json, key);
            }
            var res = Utils.Deserialize <DayResultRoot>(json);

            return(res.error ? null : res.results);
        }
コード例 #23
0
        public static async void LoadKeysAsync()
        {
            // https://docs.microsoft.com/de-de/windows/uwp/get-started/fileio-learning-track
            // aktueller Ordner
            StorageFolder storageFolder = ApplicationData.Current.LocalFolder;
            // LocalState
            bool result = await StorageFileHelper.FileExistsAsync(storageFolder, fileNameOfKeys, false).ConfigureAwait(true);

            if (result == true)
            {
                StorageFile file = await storageFolder.GetFileAsync(fileNameOfKeys);

                var keys = await FileIO.ReadLinesAsync(file);

                if (keys.Count > 0)
                {
                    Default.DropBoxAppToken = keys[0];
                }
                if (keys.Count > 1)
                {
                    Default.OpenWeatherMapKey = keys[1];
                }
                if (keys.Count > 2)
                {
                    Default.NewsAPIKey = keys[2];
                }
                if (keys.Count > 3)
                {
                    Default.MapsAPIKey = keys[3];
                }
                if (keys.Count > 4)
                {
                    Default.ApplicationId = keys[4];
                }
                if (keys.Count > 5)
                {
                    Default.NetKey = keys[5];
                }
            }
        }
        public async Task Test_InfiniteCanvas_LoadsFile(string file)
        {
            var taskSource = new TaskCompletionSource <object>();
            await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(
                CoreDispatcherPriority.Normal, async() =>
            {
                try
                {
                    string json = await StorageFileHelper.ReadTextFromPackagedFileAsync(file);

                    InfiniteCanvasVirtualDrawingSurface.LoadJson(json).Should().NotBeEmpty();

                    taskSource.SetResult(null);
                }
                catch (Exception e)
                {
                    taskSource.SetException(e);
                }
            });

            await taskSource.Task;
        }
コード例 #25
0
ファイル: AppData.cs プロジェクト: bramborman/Pandafrog
        public static async Task LoadAsync()
        {
#if DEBUG
            if (Current != null)
            {
                throw new Exception("You're not doing it right ;)");
            }
#endif

            var loadObjectAsyncResult = await StorageFileHelper.LoadObjectAsync <AppData>(FILE_NAME, ApplicationData.Current.LocalFolder);

            Current = loadObjectAsyncResult.Object;
            Current.ShowLoadingError = !loadObjectAsyncResult.Success;

            Current.PropertyChanged += async(sender, e) =>
            {
                if (e.PropertyName != nameof(ShowAbout) && e.PropertyName != nameof(ShowMobile))
                {
                    await Current.SaveAsync();
                }
            };
        }
コード例 #26
0
#pragma warning disable SA1009 // Doesn't like ValueTuples.
        public async Task <(string contents, string path)> GetDocumentationAsync()
#pragma warning restore SA1009 // Doesn't like ValueTuples.
        {
            if (!string.IsNullOrWhiteSpace(_cachedDocumentation))
            {
                return(_cachedDocumentation, _cachedPath);
            }

            var filepath  = string.Empty;
            var filename  = string.Empty;
            var localPath = string.Empty;

            var docRegex = new Regex("^" + _repoOnlineRoot + "(?<branch>.+?)/docs/(?<file>.+)");
            var docMatch = docRegex.Match(DocumentationUrl);

            if (docMatch.Success)
            {
                filepath  = docMatch.Groups["file"].Value;
                filename  = Path.GetFileName(filepath);
                localPath = $"ms-appx:///docs/{Path.GetDirectoryName(filepath)}/";
            }

#if !DEBUG // use the docs repo in release mode
            string modifiedDocumentationUrl = $"{_docsOnlineRoot}master/docs/{filepath}";

            _cachedPath = modifiedDocumentationUrl.Replace(filename, string.Empty);

            // Read from Cache if available.
            try
            {
                _cachedDocumentation = await StorageFileHelper.ReadTextFromLocalCacheFileAsync(filename);
            }
            catch (Exception)
            {
            }

            // Grab from docs repo if not.
            if (string.IsNullOrWhiteSpace(_cachedDocumentation))
            {
                try
                {
                    using (var request = new HttpRequestMessage(HttpMethod.Get, new Uri(modifiedDocumentationUrl)))
                    {
                        using (var response = await client.SendAsync(request).ConfigureAwait(false))
                        {
                            if (response.IsSuccessStatusCode)
                            {
                                var result = await response.Content.ReadAsStringAsync();

                                _cachedDocumentation = ProcessDocs(result);

                                if (!string.IsNullOrWhiteSpace(_cachedDocumentation))
                                {
                                    await StorageFileHelper.WriteTextToLocalCacheFileAsync(_cachedDocumentation, filename);
                                }
                            }
                        }
                    }
                }
                catch (Exception)
                {
                }
            }
#endif

            // Grab the local copy in Debug mode, allowing you to preview changes made.
            if (string.IsNullOrWhiteSpace(_cachedDocumentation))
            {
                try
                {
                    using (var localDocsStream = await StreamHelper.GetPackagedFileStreamAsync($"docs/{filepath}"))
                    {
                        var result = await localDocsStream.ReadTextAsync();

                        _cachedDocumentation = ProcessDocs(result);
                        _cachedPath          = localPath;
                    }
                }
                catch (Exception)
                {
                }
            }

            return(_cachedDocumentation, _cachedPath);
        }
コード例 #27
0
        public async Task Test_StorageFileHelper_Text_PackagedFile()
        {
            string loadedText = await StorageFileHelper.ReadTextFromPackagedFileAsync(PACKAGEDFILEPATH);

            StringAssert.Contains(loadedText, SAMPLETEXT);
        }
コード例 #28
0
        public async Task Test_StorageFileHelper_Text_PackagedFile()
        {
            string loadedText = await StorageFileHelper.ReadTextFromPackagedFileAsync(PackagedFilePath);

            StringAssert.Contains(loadedText, Sampletext);
        }
コード例 #29
0
ファイル: AppData.cs プロジェクト: bramborman/Pandafrog
 public Task SaveAsync()
 {
     return(StorageFileHelper.SaveObjectAsync(this, FILE_NAME, ApplicationData.Current.LocalFolder));
 }
コード例 #30
0
        public async Task <string> GetDocumentationAsync()
        {
            if (!string.IsNullOrWhiteSpace(_cachedDocumentation))
            {
                return(_cachedDocumentation);
            }

            var filepath = string.Empty;
            var filename = string.Empty;
            var branch   = "master";

            var docRegex = new Regex("^" + _docsOnlineRoot + "(?<branch>.+?)/docs/(?<file>.+)");
            var docMatch = docRegex.Match(DocumentationUrl);

            if (docMatch.Success)
            {
                branch   = docMatch.Groups["branch"].Value;
                filepath = docMatch.Groups["file"].Value;
                filename = Path.GetFileName(filepath);
            }

            string modifiedDocumentationUrl = DocumentationUrl;

#if !DEBUG // only use the master branch for release mode
            modifiedDocumentationUrl = $"{_docsOnlineRoot}master/docs/{filepath}";
#endif

            try
            {
                using (var request = new HttpRequestMessage(HttpMethod.Get, new Uri(modifiedDocumentationUrl)))
                {
                    using (var response = await client.SendAsync(request).ConfigureAwait(false))
                    {
                        if (response.IsSuccessStatusCode)
                        {
                            var result = await response.Content.ReadAsStringAsync();

                            _cachedDocumentation = ProcessDocs(result);

                            if (!string.IsNullOrWhiteSpace(_cachedDocumentation))
                            {
                                await StorageFileHelper.WriteTextToLocalCacheFileAsync(_cachedDocumentation, filename);
                            }
                        }
                    }
                }
            }
            catch (Exception)
            {
            }

#if !DEBUG // don't cache for debugging perpuses so it always gets the latests
            if (string.IsNullOrWhiteSpace(_cachedDocumentation))
            {
                try
                {
                    _cachedDocumentation = await StorageFileHelper.ReadTextFromLocalCacheFileAsync(filename);
                }
                catch (Exception)
                {
                }
            }
#endif

            if (string.IsNullOrWhiteSpace(_cachedDocumentation))
            {
                try
                {
                    using (var localDocsStream = await StreamHelper.GetPackagedFileStreamAsync($"docs/{filepath}"))
                    {
                        var result = await localDocsStream.ReadTextAsync();

                        _cachedDocumentation = ProcessDocs(result);
                    }
                }
                catch (Exception)
                {
                }
            }

            return(_cachedDocumentation);
        }