Пример #1
0
        private async void LoginButton_Click(object sender, RoutedEventArgs e)
        {
            if (saveLogin)
            {
                configSF = await storageFolder.CreateFileAsync("config.txt", Windows.Storage.CreationCollisionOption.ReplaceExisting);

                var stream = await configSF.OpenAsync(Windows.Storage.FileAccessMode.ReadWrite);

                using (var outputStream = stream.GetOutputStreamAt(0))
                {
                    using (var dataWriter = new Windows.Storage.Streams.DataWriter(outputStream))
                    {
                        string  combo  = Username.Text + " " + Password.Password;
                        IBuffer comboB = await SampleDataProtectionStream(strDescriptor, combo, encoding);

                        dataWriter.WriteBuffer(comboB);
                        await dataWriter.StoreAsync();

                        await outputStream.FlushAsync();
                    }
                }
                stream.Dispose();
            }
            else
            {
                configSF = await storageFolder.CreateFileAsync("config.txt", Windows.Storage.CreationCollisionOption.ReplaceExisting);
            }
        }
Пример #2
0
        public async Task SetUpFile()
        {
            storageFolder = Windows.Storage.ApplicationData.Current.LocalFolder;
            try
            {
                BrightnessFile = await storageFolder.GetFileAsync(FileNames.BrightnessfileName);
            }
            catch (FileNotFoundException e)
            {
                BrightnessFile = await storageFolder.CreateFileAsync(FileNames.BrightnessfileName);
            }

            try
            {
                TemperatureFile = await storageFolder.GetFileAsync(FileNames.TemperaturefileName);
            }
            catch (FileNotFoundException e)
            {
                TemperatureFile = await storageFolder.CreateFileAsync(FileNames.TemperaturefileName);
            }

            try
            {
                O2File = await storageFolder.GetFileAsync(FileNames.O2fileName);

                Debug.WriteLine("Old O2 Files are used");
            }
            catch (FileNotFoundException e)
            {
                O2File = await storageFolder.CreateFileAsync(FileNames.O2fileName);

                Debug.WriteLine("New O2 Files were created");
            }

            try
            {
                TwitterFile = await storageFolder.GetFileAsync(FileNames.SettingsfileName);

                Debug.WriteLine("Old settings Files are used");
            }
            catch (FileNotFoundException e)
            {
                TwitterFile = await storageFolder.CreateFileAsync(FileNames.SettingsfileName);

                Debug.WriteLine("New settings Files are used");
            }

            Brightnessresult = await Windows.Storage.FileIO.ReadLinesAsync(BrightnessFile);

            Temperatureresult = await Windows.Storage.FileIO.ReadLinesAsync(TemperatureFile);

            O2result = await Windows.Storage.FileIO.ReadLinesAsync(file : O2File);

            Twitterresult = await Windows.Storage.FileIO.ReadLinesAsync(TwitterFile);

            BrightnessList  = new List <string>();
            TemperatureList = new List <string>();
            O2List          = new List <string>();
        }
Пример #3
0
        /// <summary>
        /// Creates a new file with the specified name in the current folder.
        /// </summary>
        /// <param name="desiredName">The name of the new file to create in the current folder.</param>
        /// <returns>When this method completes, it returns a StorageFile that represents the new file.</returns>
        public Task <StorageFile> CreateFileAsync(string desiredName)
        {
#if WINDOWS_UWP || WINDOWS_APP || WINDOWS_PHONE_APP || WINDOWS_PHONE
            return(Task.Run <StorageFile>(async() =>
            {
                var f = await _folder.CreateFileAsync(desiredName);
                return f == null ? null : f;
            }));
#else
            return(CreateFileAsync(desiredName, CreationCollisionOption.FailIfExists));
#endif
        }
Пример #4
0
        public static async System.Threading.Tasks.Task <int> SynSpeechWriteToFileAsync(string text, string fileName)
        {
            using (Windows.Media.SpeechSynthesis.SpeechSynthesizer synth = new Windows.Media.SpeechSynthesis.SpeechSynthesizer())
            {
                try
                {
                    using (Windows.Media.SpeechSynthesis.SpeechSynthesisStream synthStream = await synth.SynthesizeTextToStreamAsyncServiceAsync(text, apiArgs)) // doesn't handle special characters such as quotes
                    {
                        // TODO: obsolete to use DataReader? use await Windows.Storage.FileIO.Read...(file);
                        using (Windows.Storage.Streams.DataReader reader = new Windows.Storage.Streams.DataReader(synthStream))
                        {
                            await reader.LoadAsync((uint)synthStream.Size);

                            Windows.Storage.Streams.IBuffer buffer     = reader.ReadBuffer((uint)synthStream.Size);
                            Windows.Storage.StorageFolder   tempFolder = await Windows.Storage.StorageFolder.GetFolderFromPathAsync(Options.options.tempFolderPath);

                            Windows.Storage.StorageFile srcFile = await tempFolder.CreateFileAsync(Options.options.audio.speechSynthesisFileName, Windows.Storage.CreationCollisionOption.ReplaceExisting);

                            await Windows.Storage.FileIO.WriteBufferAsync(srcFile, buffer);

                            Windows.Storage.FileProperties.MusicProperties musicProperties = await srcFile.Properties.GetMusicPropertiesAsync();

                            Log.WriteLine("Bitrate:" + musicProperties.Bitrate);

                            Windows.Media.MediaProperties.MediaEncodingProfile profile    = Windows.Media.MediaProperties.MediaEncodingProfile.CreateWav(Windows.Media.MediaProperties.AudioEncodingQuality.Low);
                            Windows.Media.Transcoding.MediaTranscoder          transcoder = new Windows.Media.Transcoding.MediaTranscoder();
                            Windows.Storage.StorageFile destFile = await tempFolder.CreateFileAsync(fileName, Windows.Storage.CreationCollisionOption.ReplaceExisting);

                            Windows.Media.Transcoding.PrepareTranscodeResult result = await transcoder.PrepareFileTranscodeAsync(srcFile, destFile, profile);

                            if (result.CanTranscode)
                            {
                                await result.TranscodeAsync();
                            }
                            else
                            {
                                Log.WriteLine("can't transcode file:" + result.FailureReason.ToString());
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
            }
            return(0);
        }
Пример #5
0
        async void enableWedge(bool bEnable)
        {
            try
            {
                //add <uap:Capability Name="documentsLibrary" /> to manifest
                //Note: You must add File Type Associations to your app manifest that declare specific file types that your app can access in this location.

                // Open/create the subfolder where the profile is stored.
                Windows.Storage.StorageFolder storageFolder  = Windows.Storage.KnownFolders.DocumentsLibrary;
                Windows.Storage.StorageFolder profilesFolder = await storageFolder.CreateFolderAsync("Profile", Windows.Storage.CreationCollisionOption.OpenIfExists);

                // Open/create the profile file.
                Windows.Storage.StorageFile profileFile = await profilesFolder.CreateFileAsync("HoneywellDecoderSettingsV2.Exm", Windows.Storage.CreationCollisionOption.ReplaceExisting);

                if (bEnable)
                {
                    // Write the profile to the file.
                    await Windows.Storage.FileIO.WriteLinesAsync(profileFile, WedgeEnable);
                }
                else
                {
                    await Windows.Storage.FileIO.WriteLinesAsync(profileFile, WedgeDisable);
                }
            }catch (Exception ex)
            {
                Class1.doLog("Exception in enableWedge: " + ex.Message);
            }
            // Delay to allow time for new profile(s) to be processed.
            await System.Threading.Tasks.Task.Delay(50);
        }
Пример #6
0
        public static async Task <bool> DeleteFileAsync(string fileName)
        {
            try
            {
                Windows.Storage.StorageFolder storageFolder =
                    Windows.Storage.ApplicationData.Current.LocalFolder;
                if (storageFolder == null)
                {
                    return(false);
                }
                Windows.Storage.StorageFile userFile =
                    await storageFolder.CreateFileAsync(fileName,
                                                        Windows.Storage.CreationCollisionOption.ReplaceExisting);

                if (userFile == null)
                {
                    return(false);
                }
            }

            catch
            {
                return(false);
            }
            return(true);
        }
Пример #7
0
        /// <summary>
        /// Reads from a JSON file by filename and returns the result T.
        /// </summary>
        /// <typeparam name="T">The type of object that is being stored in the file</typeparam>
        /// <returns>The object T</returns>
        public async Task <T> ReadFromFile <T>()
        {
            // Locate the folder which this UWP application can read from and write to.
            Windows.Storage.StorageFolder storageFolder = Windows.Storage.ApplicationData.Current.LocalFolder;

            // Initiate a file variable.
            Windows.Storage.StorageFile file;
            try
            {
                // if the file exists, the file variable will be set to that.
                file = await storageFolder.GetFileAsync(_fileName);
            }
            catch (FileNotFoundException fnfe)
            {
                // if the file does not exist, an exception will be thrown, but we will make sure the file will be created.
                file = await storageFolder.CreateFileAsync(_fileName);
            }
            catch (Exception ex)
            {
                // if this exception occurs, this means we do not have handled the an exception and we want the program to crash.
                throw ex;
            }

            var text = await Windows.Storage.FileIO.ReadTextAsync(file);

            T obj = JsonConvert.DeserializeObject <T>(text);

            return(obj);
        }
Пример #8
0
        /// <summary>
        /// Save Text into File
        /// </summary>
        public static bool SaveStringIntoFile(string fileName, string content)
        {
            bool result = false;

            try
            {
                // Create sample file; replace if exists.
                Windows.Storage.StorageFolder storageFolder =
                    Windows.Storage.ApplicationData.Current.LocalFolder;
                Windows.Storage.StorageFile SaveFile = Task.Run(async() => {
                    return(await storageFolder.CreateFileAsync(fileName + ".xml",
                                                               Windows.Storage.CreationCollisionOption.ReplaceExisting));
                }).Result;

                Task.Run(async() => {
                    await Windows.Storage.FileIO.WriteTextAsync(SaveFile, content);
                }).Wait();
                result = true;
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine("Exception while saving into file: " + ex.Message);
            }
            return(result);
        }
Пример #9
0
        private async void Button_Click_2(object sender, RoutedEventArgs e)
        {
            Windows.Storage.StorageFolder storageFolder = Windows.Storage.ApplicationData.Current.LocalFolder;
            try
            {
                /*singlton.api.Authorize(new ApiAuthParams()
                 * {
                 *  Login = singlton.login,
                 *  Password = singlton.password,
                 *  ApplicationId = singlton.appId,
                 *  Settings = Settings.All
                 * });*/
                Windows.Storage.StorageFile sampleFile = await storageFolder.GetFileAsync("pass.txt");

                await Windows.Storage.FileIO.WriteTextAsync(sampleFile, passwordTB.Password + "\n" + loginTB.Text);

                await CoreApplication.RequestRestartAsync("-fastInit -level 1 -foo");
            }
            catch (FileNotFoundException)
            {
                Windows.Storage.StorageFile sampleFile = await storageFolder.CreateFileAsync("pass.txt", Windows.Storage.CreationCollisionOption.ReplaceExisting);

                await Windows.Storage.FileIO.WriteTextAsync(sampleFile, passwordTB.Password + "\n" + loginTB.Text);

                Process.GetCurrentProcess().Close();
            }
            catch (Exception ex)
            {
                answTextBlock.Text = ex.Message;
            }
        }
        public async virtual void SaveToFile(string fileName, Windows.Storage.StorageFolder folder)
        {
            var _option = Windows.Storage.CreationCollisionOption.ReplaceExisting;
            var _file   = await folder.CreateFileAsync(fileName, _option);

            await Windows.Storage.FileIO.WriteTextAsync(_file, Serialize());
        }
Пример #11
0
        /// <summary>
        /// Prints selected account transaction history to a file.
        /// </summary>
        /// <param name="account"></param>
        public async void PrintTransactionsHistory(Account account)
        {
            try
            {
                Windows.Storage.StorageFolder storageFolder =
                    Windows.Storage.ApplicationData.Current.LocalFolder;
                Windows.Storage.StorageFile sampleFile =
                    await storageFolder.CreateFileAsync($"TransactionHistory - {account.AccountID}.txt",
                                                        Windows.Storage.CreationCollisionOption.ReplaceExisting);

                string result = $"AccountID: {account.AccountID} || Remaining balance: {account.Balance} SEK " +
                                $"|| {account.GetType().Name} ({account.Interest*100}%) \n ";

                foreach (var transaction in account.Transactions)
                {
                    result += $"\n{transaction.Time}\t" +
                              $"{transaction.TransactionType}: \t" +
                              $"Amount: {transaction.Amount} SEK \t " +
                              $"Remaining balance: {transaction.NewBalance} SEK \n";
                }

                await Windows.Storage.FileIO.WriteTextAsync(sampleFile, result);
            }
            catch (Exception) { }
        }
        public async void HttpDownloadFile(Windows.Storage.StorageFolder folder, string name)
        {
            String url = "http://music.163.com/song/media/outer/url?id=" + tb.Text;
            // 设置参数
            HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
            //发送请求并获取相应回应数据
            HttpWebResponse response = request.GetResponse() as HttpWebResponse;
            //直到request.GetResponse()程序才开始向目标网页发送Post请求
            Stream responseStream = response.GetResponseStream();

            //创建本地文件写入流
            try
            {
                Windows.Storage.StorageFile f = await folder.CreateFileAsync(name + ".mp3", Windows.Storage.CreationCollisionOption.ReplaceExisting);

                Stream stream = await f.OpenStreamForWriteAsync();

                byte[] bArr = new byte[1024];
                int    size = responseStream.Read(bArr, 0, (int)bArr.Length);
                while (size > 0)
                {
                    stream.Write(bArr, 0, size);
                    size = responseStream.Read(bArr, 0, (int)bArr.Length);
                }
                stream.Close();
                responseStream.Close();
                ShowMessageBox("下载成功", "已存储" + name + ".mp3" + "至" + folder.Path);
            }
            catch (Exception e)
            {
                ShowMessageBox("拒绝访问", e.Message);
            }
        }
Пример #13
0
        async Task<bool> DownloadDb()
        {
            try
            {
                ServiceReference1.IService1 s = new ServiceReference1.Service1Client();
                // Create sample file; replace if exists.
                Windows.Storage.StorageFolder storageFolder =
                    Windows.Storage.ApplicationData.Current.LocalFolder;

                byte[] db = await s.RetrieveFileAsync("");

                var file = await storageFolder.CreateFileAsync("SQLITEV3.sqlite", Windows.Storage.CreationCollisionOption.ReplaceExisting);

                using (var item = await file.OpenStreamForWriteAsync())
                {
                    item.Write(db, 0, db.Length);
                }

                return true;
            }
            catch (Exception ex)
            {
                return false;
                throw;
            }



        }
Пример #14
0
        private async void CheckExistmap()
        {
#if UNITY_WSA && !UNITY_EDITOR
            Windows.Storage.StorageFolder storageFolder = Windows.Storage.ApplicationData.Current.LocalFolder;
            Windows.Storage.StorageFile   file          = await storageFolder.CreateFileAsync(gameDataFileName,
                                                                                              Windows.Storage.CreationCollisionOption.OpenIfExists);

            string filePath = file.Path;
#else
            string filePath = Path.Combine(Application.streamingAssetsPath, gameDataFileName);
#endif

            //string filePath = Path.Combine(Application.streamingAssetsPath, gameDataFileName);

            if (File.Exists(filePath))
            {
                // Read the json from the file into a string
                string dataAsJson = File.ReadAllText(filePath);
                // Pass the json to JsonUtility, and tell it to create a GameData object from it

                JObject obj = JObject.Parse(dataAsJson);
                // Retrieve the allRoundData property of loadedData
                reloadmapname = obj["loadedmap"].ToString();
                if (reloadmapname != mapName)
                {
                    _NeedReloadMap = true;
                }
            }
            else
            {
                Debug.LogError("Cannot load task data!");
            }
        }
Пример #15
0
 // create or open local file
 private async void CreateOrOpenFile()
 {
     Windows.Storage.StorageFolder storageFolder =
         Windows.Storage.ApplicationData.Current.LocalFolder;
     sampleFile =
         await storageFolder.CreateFileAsync("sample.txt", Windows.Storage.CreationCollisionOption.OpenIfExists);
 }
Пример #16
0
        public static async Task saveAsync(DeskQuote quote)
        {
            // Create sample file; replace if exists.
            Windows.Storage.StorageFolder storageFolder = Windows.Storage.ApplicationData.Current.LocalFolder;
            Windows.Storage.StorageFile   writeFile     = await storageFolder.CreateFileAsync("sample text", Windows.Storage.CreationCollisionOption.ReplaceExisting);

            Windows.Storage.StorageFile readFile = await storageFolder.GetFileAsync(Convert.ToString(quote));


            /*
             * // Make a container for our saved desks
             * List<DeskQuote> quotes = new List<DeskQuote>();
             *
             * // If a save file already exists, read from and append to it
             * if (File.Exists(SaveFilePath))
             * {
             * // Load all saves
             * string savedQuotes = File.ReadAllText(SaveFilePath);
             *
             * // Deserialize the saved list of desks
             * quotes = JsonConvert.DeserializeObject<List<DeskQuote>>(savedQuotes);
             * }
             *
             * // Add the current desk to the (possibly empty) list of desks
             * quotes.Add(quote);
             *
             * // JSONify
             * string JSONDesks = JsonConvert.SerializeObject(quotes);
             *
             * // Save our JSON
             * File.WriteAllText(SaveFilePath, JSONDesks);
             */
        }
Пример #17
0
 private void SaveTokenToLocalStorage(string token)
 {
     Windows.Storage.StorageFolder storageFolder = Windows.Storage.ApplicationData.Current.LocalFolder;
     Windows.Storage.StorageFile   sampleFile    = storageFolder.CreateFileAsync("sample.txt",
                                                                                 Windows.Storage.CreationCollisionOption.ReplaceExisting).GetAwaiter().GetResult();
     Windows.Storage.FileIO.WriteTextAsync(sampleFile, token).GetAwaiter().GetResult();
 }
Пример #18
0
        public async void StopTimer_Tick(Object sender, object e)
        {
            DateTimeOffset time = DateTimeOffset.Now;

            timer.Stop();
            TimeSpan span = startTime - lastTime;

            Windows.Storage.StorageFolder storageFolder = Windows.Storage.ApplicationData.Current.LocalFolder;
            Windows.Storage.StorageFile   ticketsFile   = await storageFolder.CreateFileAsync("timelog.txt", Windows.Storage.CreationCollisionOption.OpenIfExists);

            //Use stream to write to the file
            var stream = await ticketsFile.OpenAsync(Windows.Storage.FileAccessMode.ReadWrite);

            using (var outputStream = stream.GetOutputStreamAt(stream.Size))
            {
                using (var dataWriter = new Windows.Storage.Streams.DataWriter(outputStream))
                {
                    dataWriter.WriteString("Time: " + span + "\n");
                    await dataWriter.StoreAsync();

                    await outputStream.FlushAsync();
                }
            }
            stream.Dispose();         // Or use the stream variable (see previous code snippet) with a using statement as well.



            string path = @"c:\temp\MyTest.txt";
            // This text is added only once to the file.
        }
Пример #19
0
        public async void DeletePastScoring_Click(object sender, RoutedEventArgs e)
        {
            Windows.Storage.StorageFolder storageFolder = Windows.Storage.ApplicationData.Current.LocalFolder;
            Windows.Storage.StorageFile   scoreFile     = await storageFolder.CreateFileAsync("score.txt", Windows.Storage.CreationCollisionOption.ReplaceExisting);

            await Windows.Storage.FileIO.WriteTextAsync(scoreFile, "");
        }
Пример #20
0
        async void Finish_Click(object sender, RoutedEventArgs e)
        {
            if (FirstName.Text == "" || LastName.Text == "" || Address.Text == "" || PhoneNumber.Text == "")
            {
                ErrorMessage.Text = "ERROR: PLEASE FILL IN ALL BOXES";
            }
            else
            {
                employee.FoundEmployee.FirstName  = FirstName.Text;
                employee.FoundEmployee.LastName   = LastName.Text;
                employee.FoundEmployee.Address    = Address.Text;
                employee.FoundEmployee.CellNumber = PhoneNumber.Text;
                Dictionary <string, Employee> tempEmployee = new Dictionary <string, Employee>
                {
                    { employee.FoundEmployee.EmailAddress, employee.FoundEmployee }
                };
                string[] employees = new string[1] {
                    employee.FoundEmployee.EmailAddress
                };
                string tempJson       = $"{{ \"employees\": [], "; //"\"{employee.FoundEmployee.EmailAddress}\"], ";
                string employeeString = JsonConvert.SerializeObject(tempEmployee, Formatting.Indented);
                employeeString = employeeString.Remove(0, 1);
                string json = $"{tempJson} {employeeString}";

                employeeFile = await storageFolder.CreateFileAsync("testEmployeeFileWrite.json", Windows.Storage.CreationCollisionOption.OpenIfExists);

                await Windows.Storage.FileIO.WriteTextAsync(employeeFile, json);//employeeString);

                this.Frame.Navigate(typeof(PayrollSystem), employee);
            }
        }
Пример #21
0
        private async void BtnSave_Click(object sender, RoutedEventArgs e)
        {
            const string FILE_NAME = "save.txt";

            Windows.Storage.StorageFolder storageFolder = Windows.Storage.ApplicationData.Current.LocalFolder;
            Windows.Storage.StorageFile   storageFile   =
                await storageFolder.CreateFileAsync(FILE_NAME,
                                                    Windows.Storage.CreationCollisionOption.OpenIfExists);

            await Windows.Storage.FileIO.WriteTextAsync(storageFile, txtBoxSave.Text);

            // 파일 저장 완료 상태 설정
            Windows.Storage.Provider.FileUpdateStatus status =
                await Windows.Storage.CachedFileManager.CompleteUpdatesAsync(storageFile);

            if (status == Windows.Storage.Provider.FileUpdateStatus.Complete)
            {
                txtSaveResult.Text = "저장 완료!";
            }
            else
            {
                txtSaveResult.Text = "저장 실패...";
            }
            FlyoutBase.ShowAttachedFlyout((FrameworkElement)sender);
        }
Пример #22
0
 private void WriteTextToFile(string filename, string info)
 {
     Windows.Storage.StorageFolder storageFolder = Windows.Storage.ApplicationData.Current.LocalFolder;
     Windows.Storage.StorageFile   sampleFile    = storageFolder.CreateFileAsync(filename,
                                                                                 Windows.Storage.CreationCollisionOption.ReplaceExisting).GetAwaiter().GetResult();
     Windows.Storage.FileIO.WriteTextAsync(sampleFile, info).GetAwaiter().GetResult();
 }
Пример #23
0
        /// <summary>
        /// Restore Text from File
        /// </summary>
        public static string RestoreStringFromFile(string fileName)
        {
            string result = string.Empty;

            try
            {
                // Create sample file; replace if exists.
                Windows.Storage.StorageFolder storageFolder = Windows.Storage.ApplicationData.Current.LocalFolder;
                Windows.Storage.StorageFile   RestoreFile   = Task.Run(async() => {
                    return(await storageFolder.CreateFileAsync(fileName + ".xml",
                                                               Windows.Storage.CreationCollisionOption.OpenIfExists));
                }).Result;
                if (RestoreFile != null)
                {
                    result = Task.Run(async() => {
                        return(await Windows.Storage.FileIO.ReadTextAsync(RestoreFile));
                    }).Result;
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine("Exception while restoring from file: " + ex.Message);
            }
            return(result);
        }
Пример #24
0
        /// <summary>
        /// Create a report based on the inspections passed as a parameter
        /// </summary>
        /// <param name="inspections"></param>
        public async void DrawReport(List <Inspection> inspections)
        {
            // Create an empty string builder to make the report string
            var builder = new StringBuilder();

            // Loop through the inspections passed in as parameter
            // to build the string for the report
            foreach (var item in inspections) // Loop through all strings
            {
                builder.AppendLine("Inspection-ID: " + item.ID);
                builder.AppendLine("Inspection Date: " + item.Inspection_Date);
                builder.AppendLine("Inspection Note: " + item.Inspection_Note);
                builder.AppendLine("Sculpture-ID: " + item.Sculpture_ID);
                builder.AppendLine("\n");
            }

            var result = builder.ToString();

            // Open the folder:
            Windows.Storage.StorageFolder storageFolder = Windows.Storage.ApplicationData.Current.LocalFolder;
            // Create the file:
            Windows.Storage.StorageFile sampleFile = await storageFolder.CreateFileAsync("Report.txt", Windows.Storage.CreationCollisionOption.ReplaceExisting);

            // Save the file:
            await Windows.Storage.FileIO.WriteTextAsync(sampleFile, result, UnicodeEncoding.Utf8);

            MessageDialog dialog = new MessageDialog("A report has been saved to your harddrive.");
            await dialog.ShowAsync();
        }
Пример #25
0
        private async void AppBarButton_Click_2(object sender, RoutedEventArgs e)
        {
            try
            {
                var folderPicker = new Windows.Storage.Pickers.FolderPicker();
                folderPicker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.Desktop;
                folderPicker.FileTypeFilter.Add("*");

                Windows.Storage.StorageFolder folder = await folderPicker.PickSingleFolderAsync();

                if (folder != null)
                {
                    Windows.Storage.StorageFile sampleFile = await folder.CreateFileAsync("ReportBluetooth.txt", Windows.Storage.CreationCollisionOption.GenerateUniqueName);

                    await Windows.Storage.FileIO.WriteTextAsync(sampleFile, terminalText.Text);
                }
                else
                {
                    await new MessageDialog("Operation cancelled.").ShowAsync();
                }
            }
            catch (Exception ex)
            {
                await new MessageDialog(ex.Message).ShowAsync();
            }
        }
Пример #26
0
        internal static void CreateAndSerializeRuleSet()
        {
            RuleSet ruleSet = new RuleSet
            {
                Name             = "MyRuleSet",
                ChainingBehavior = RuleChainingBehavior.Full
            };

            ruleSet.Rules.Add(Rule_set_literals());
            ruleSet.Rules.Add(Rule_with_equals_condition_and_setter_action());
            ruleSet.Rules.Add(Rule_with_array_indexer_condition_and_setter_action());
            ruleSet.Rules.Add(Rule_with_method_condition());
            ruleSet.Rules.Add(Rule_with_multiple_conditions());
            ruleSet.Rules.Add(Rule_with_static_method_action());
            ruleSet.Rules.Add(Rule_with_reference_method_action());
            ruleSet.Rules.Add(Rule_with_Cast_object_expression_in_then_action());
            ruleSet.Rules.Add(Rule_with_simple_CodeObjectCreateExpression_calling_a_constructor_in_then_action());
            ruleSet.Rules.Add(Rule_with_list_initialization());
            ruleSet.Rules.Add(Rule_with_child_and_granchild_reference());
            ruleSet.Rules.Add(Rule_with_generic_object_initialization());
            ruleSet.Rules.Add(Rule_with_generic_list_initialization());
            ruleSet.Rules.Add(Rule_call_method_in_static_generic_class());
            ruleSet.Rules.Add(Rule_set_state_WITHOUT_update_action());
            ruleSet.Rules.Add(Rule_get_state_WITHOUT_AlwaysTrue_property_for_reevaluation());
            ruleSet.Rules.Add(Rule_set_state_WITH_update_action_set_targeting_AlwaysTrue_property());
            ruleSet.Rules.Add(Rule_get_state_WITH_AlwaysTrue_property_to_reevaluate_update_action());

            string rulesSetString = SerializeRules(ruleSet);

            RuleValidation ruleValidation = GetValidation(ruleSet, typeof(Sample.FlowEntity));

            Windows.Storage.StorageFolder roamingFolder = Windows.Storage.ApplicationData.Current.RoamingFolder;
            Windows.Storage.StorageFile   file          = Task.Run(async() => await roamingFolder.CreateFileAsync("FlowEntity.Uwp.module", Windows.Storage.CreationCollisionOption.ReplaceExisting)).Result;
            Task.Run(async() => await Windows.Storage.FileIO.WriteTextAsync(file, rulesSetString, Windows.Storage.Streams.UnicodeEncoding.Utf16LE)).Wait();
        }
Пример #27
0
        /// <summary>
        /// Writes T to a file by the initial filename as JSON.
        /// </summary>
        /// <typeparam name="T">The object type to store</typeparam>
        /// <param name="data">The actual object to store in the file</param>
        public async void WriteToFile <T>(T data)
        {
            // Convert data to JSON object (https://www.w3schools.com/whatis/whatis_json.asp)
            string jsonContent = JsonConvert.SerializeObject(data, Formatting.None);

            // Locate the folder which this UWP application can read from and write to.
            Windows.Storage.StorageFolder storageFolder = Windows.Storage.ApplicationData.Current.LocalFolder;

            // Initiate a file variable.
            Windows.Storage.StorageFile file;
            try
            {
                // if the file exists, the file variable will be set to that.
                file = await storageFolder.GetFileAsync(_fileName);
            }
            catch (FileNotFoundException fnfe)
            {
                // if the file does not exist, an exception will be thrown, but we will make sure the file will be created.
                file = await storageFolder.CreateFileAsync(_fileName);
            }
            catch (Exception ex)
            {
                // if this exception occurs, this means we do not have handled the an exception and we want the program to crash.
                throw ex;
            }

            // Now, write the JSON object to the actual file.
            await Windows.Storage.FileIO.WriteTextAsync(file, jsonContent, Windows.Storage.Streams.UnicodeEncoding.Utf8);
        }
Пример #28
0
 public void logout()
 {
     Windows.Storage.StorageFolder storageFolder = Windows.Storage.ApplicationData.Current.LocalFolder;
     Windows.Storage.StorageFile   sampleFile    = storageFolder.CreateFileAsync("ez.txt",
                                                                                 Windows.Storage.CreationCollisionOption.ReplaceExisting).GetAwaiter().GetResult();
     Windows.Storage.FileIO.WriteTextAsync(sampleFile, "").GetAwaiter().GetResult();
 }
Пример #29
0
        public MemberRegister GetInformation(string token)

        {
            Windows.Storage.StorageFolder storageFolder = Windows.Storage.ApplicationData.Current.LocalFolder;

            Windows.Storage.StorageFile sampleFile = storageFolder.CreateFileAsync("sample.txt",

                                                                                   Windows.Storage.CreationCollisionOption.ReplaceExisting).GetAwaiter().GetResult();

            Windows.Storage.FileIO.ReadTextAsync(sampleFile).GetAwaiter().GetResult();
            Debug.WriteLine(token);

            HttpClient client = new HttpClient();

            client.DefaultRequestHeaders.Add("Authorization", "Basic " + token);

            var responseContent = client.GetAsync(ApiUrl.GET_INFORMATION_URL).Result.Content.ReadAsStringAsync().Result;

            Debug.WriteLine("Response: " + responseContent);

            var resMember = JsonConvert.DeserializeObject <MemberRegister>(responseContent);


            return(resMember);
        }
Пример #30
0
        public async void WriteLogEntry(string LogEntryMessage)
        {
            Windows.Storage.StorageFolder storageFolder = Windows.Storage.ApplicationData.Current.LocalFolder;
            Windows.Storage.StorageFile   LogFile       = await storageFolder.CreateFileAsync("logfile.txt", Windows.Storage.CreationCollisionOption.OpenIfExists);

            await Windows.Storage.FileIO.AppendTextAsync(LogFile, DateTime.Now.ToString() + "\t" + LogEntryMessage + Environment.NewLine);
        }