private void PublishLaunchApp()
        {
            proximityDevice = Windows.Networking.Proximity.ProximityDevice.GetDefault();

            if (proximityDevice != null)
            {
                // The format of the app launch string is: "<args>\tWindows\t<AppName>".
                // The string is tab or null delimited.

                // The <args> string can be an empty string ("").
                string launchArgs = "user=default";

                // The format of the AppName is: PackageFamilyName!PRAID.
                string praid = "{b8c21b6b-2f16-49f6-9ee9-b3a713c54500}"; // The Application Id value from your package.appxmanifest.

                string appName = Windows.ApplicationModel.Package.Current.Id.FamilyName + "!" + praid;

                string launchAppMessage = launchArgs + "\tWindows\t" + appName;

                var dataWriter = new Windows.Storage.Streams.DataWriter();
                dataWriter.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf16LE;
                dataWriter.WriteString(launchAppMessage);
                var launchAppPubId =
                proximityDevice.PublishBinaryMessage(
                    "LaunchApp:WriteTag", dataWriter.DetachBuffer());
            }
        }
예제 #2
0
        public static async Task OutputSensorDataAsync()
        {
            // ファイルの作成 すでに存在する場合は置き換える
            Windows.Storage.StorageFolder documentsLibrary = KnownFolders.DocumentsLibrary;
            Windows.Storage.StorageFile   file             = await documentsLibrary.CreateFileAsync(sensorDataFileName, Windows.Storage.CreationCollisionOption.ReplaceExisting);

            // ファイルへの書き込み
            var stream = await file.OpenAsync(Windows.Storage.FileAccessMode.ReadWrite);

            using (var outputStream = stream.GetOutputStreamAt(0))
            {
                using (var dataWriter = new Windows.Storage.Streams.DataWriter(outputStream))
                {
                    dataWriter.WriteString("valueX valueY valueZ time\n");

                    if (Sensor_Values_Record_Time_List != null)
                    {
                        for (int i = 0; i < Sensor_Values_Record_Time_List.Count; i++)
                        {
                            dataWriter.WriteString($"{Math.Round(Sensor_ValueX_List[i], 3)} {Math.Round(Sensor_ValueY_List[i], 3)} {Math.Round(Sensor_ValueZ_List[i], 3)} {Math.Round(Sensor_Values_Record_Time_List[i], 2)}\n");
                        }
                    }

                    await dataWriter.StoreAsync();

                    await outputStream.FlushAsync();
                }
            }
            stream.Dispose(); // Or use the stream variable (see previous code snippet) with a using statement as well.
        }
예제 #3
0
        public static async Task OutputTrialDataAsync()
        {
            // ファイルの作成 すでに存在する場合は置き換える
            StorageFolder documentsLibrary = KnownFolders.DocumentsLibrary;
            StorageFile   file             = await documentsLibrary.CreateFileAsync(trialDataFileName, Windows.Storage.CreationCollisionOption.ReplaceExisting);

            // ファイルへの書き込み
            var stream = await file.OpenAsync(FileAccessMode.ReadWrite);

            using (var outputStream = stream.GetOutputStreamAt(0))
            {
                using (var dataWriter = new Windows.Storage.Streams.DataWriter(outputStream))
                {
                    dataWriter.WriteString("trial initLeftAngle initRightAngle respLeftAngle respRightAngle time\n");

                    if (Resp_Time_List != null)
                    {
                        for (int i = 0; i < Resp_Time_List.Count; i++)
                        {
                            dataWriter.WriteString($"{i} {Math.Round(InitLeftLineAngle[i],1)} {Math.Round(InitRightLineAngle[i], 1)} {Math.Round(RespLeftLineAngle[i], 1)} {Math.Round(RespRightLineAngle[i], 1)} {Math.Round(Resp_Time_List[i], 2)}\n");
                        }
                    }

                    await dataWriter.StoreAsync();

                    await outputStream.FlushAsync();
                }
            }
            stream.Dispose(); // Or use the stream variable (see previous code snippet) with a using statement as well.
        }
예제 #4
0
        //
        /// <summary>
        /// Accept a List<Move> and dump them into a CSV file
        /// </summary>
        /// <param name="moveList">a list of moves</param>
        public async void SaveGame(List <Move> moveList)
        {
            FileSavePicker fileSavePicker = new FileSavePicker();

            fileSavePicker.DefaultFileExtension = ".csv";
            fileSavePicker.FileTypeChoices.Add("game data", new List <string>()
            {
                ".csv"
            });
            StorageFile targetFile = await fileSavePicker.PickSaveFileAsync();

            if (targetFile != null)
            {
                var stream = await targetFile.OpenAsync(Windows.Storage.FileAccessMode.ReadWrite);

                using (var outputStream = stream.GetOutputStreamAt(0))
                {
                    using (var dataWriter = new Windows.Storage.Streams.DataWriter(outputStream))
                    {
                        // The first number determines how many moves should be read in the future loading
                        // I use this trick because I haven't found a way to empty a file
                        dataWriter.WriteString(moveList.Count.ToString() + System.Environment.NewLine);
                        foreach (Move move in moveList)
                        {
                            dataWriter.WriteString(move.ToString() + System.Environment.NewLine);
                        }
                        await dataWriter.StoreAsync();

                        await outputStream.FlushAsync();
                    }
                }
                stream.Dispose();
            }
        }
예제 #5
0
파일: Log.cs 프로젝트: BSalita/Woundify
        public static void Write(string message, [CallerFilePath] string sourceFilePath = "", [CallerMemberName] string memberName = "", [CallerLineNumber] int sourceLineNum = 0)
        {
            string messageFormatted = string.Format("{0}.{1}({2}):{3}", System.IO.Path.GetFileNameWithoutExtension(sourceFilePath), memberName, sourceLineNum, message);

            Trace.Write(messageFormatted);
            if (logFile != null)
#if WINDOWS_UWP
            { logFile.WriteString(messageFormatted); }
#else
            { logFile.Write(messageFormatted); }
#endif
        }
        private async void btnRndFile_Click(object sender, RoutedEventArgs e)
        {
            Random        rnd = new Random(DateTime.Now.Millisecond);
            double        output;
            StorageFolder storagefold = KnownFolders.MusicLibrary;
            StorageFile   randomFile  = await storagefold.CreateFileAsync("EEGRnd.txt", CreationCollisionOption.ReplaceExisting);

            var Stream = await randomFile.OpenAsync(FileAccessMode.ReadWrite);

            using (var outEEGStream = Stream.GetOutputStreamAt(0))
            {
                using (var outEEG = new Windows.Storage.Streams.DataWriter(outEEGStream))
                {
                    // create file
                    int count = 0;
                    int step  = 0;
                    for (int index = 0; index < 512; index++)
                    {
                        count++;
                        for (int channel = 0; channel <= 15; channel++)
                        {
                            output  = rnd.Next(-10, 9);
                            output += rnd.NextDouble();
                            if (count > 15)
                            {
                                count = 0;
                                step++;
                            }
                            if (step == 20)
                            {
                                step = 0;
                            }
                            if (channel < 15)
                            {
                                outEEG.WriteString(string.Format("{0:0.0000}, ", output));
                            }
                            else
                            {
                                outEEG.WriteString(string.Format("{0:0.0000}", output));
                            }
                        }
                    }
                    await outEEG.StoreAsync();

                    await outEEGStream.FlushAsync();
                }
            }
            Stream.Dispose();
        }
예제 #7
0
        public async void SavePresets()
        {
            String json_str = Serial.JsonHelper.ToJson(m_Presets, m_Presets.GetType());
            var    picker   = new Windows.Storage.Pickers.FileSavePicker();

            picker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.DocumentsLibrary;
            // Dropdown of file types the user can save the file as
            picker.FileTypeChoices.Add("JSON", new List <string>()
            {
                ".json"
            });
            // Default file name if the user does not type one in or select a file to replace
            picker.SuggestedFileName = "GenCodePreset";
            var t_storagefile = await picker.PickSaveFileAsync();

            if (t_storagefile == null)
            {
                return;
            }
            using (StorageStreamTransaction transaction = await t_storagefile.OpenTransactedWriteAsync())
            {
                using (Windows.Storage.Streams.DataWriter dataWriter = new Windows.Storage.Streams.DataWriter(transaction.Stream))
                {
                    dataWriter.WriteString(json_str);
                    transaction.Stream.Size = await dataWriter.StoreAsync();

                    await transaction.Stream.FlushAsync();

                    await transaction.CommitAsync();
                }
            }
        }
예제 #8
0
        public static async void Stringify()
        {
            JsonObject jsonObject = new JsonObject();

            if (Player.CurrentlyPlayingFile != null && !string.IsNullOrEmpty(Player.CurrentlyPlayingFile.Path))
            {
                jsonObject[pathKey] = JsonValue.CreateStringValue(Player.CurrentlyPlayingFile.Path);
                jsonObject[posKey]  = JsonValue.CreateNumberValue(Player.Position);
            }
            jsonObject[shuffleKey] = JsonValue.CreateBooleanValue(ShellVM.Shuffle);
            jsonObject[repeatKey]  = JsonValue.CreateBooleanValue(ShellVM.Repeat);
            jsonObject[volKey]     = JsonValue.CreateNumberValue(Player.Volume);
            StorageFile file = await ApplicationData.Current.TemporaryFolder.CreateFileAsync("lastplaying.mc", CreationCollisionOption.ReplaceExisting);

            using (var stream = await file.OpenAsync(Windows.Storage.FileAccessMode.ReadWrite))
            {
                using (var outputStream = stream.GetOutputStreamAt(0))
                {
                    using (var dataWriter = new Windows.Storage.Streams.DataWriter(outputStream))
                    {
                        dataWriter.WriteString(jsonObject.Stringify());
                        await dataWriter.StoreAsync();

                        await outputStream.FlushAsync();
                    }
                }
            }
        }
예제 #9
0
        private void PublishLaunchApp()
        {
            proximityDevice = Windows.Networking.Proximity.ProximityDevice.GetDefault();

            if (proximityDevice != null)
            {
                // The format of the app launch string is: "<args>\tWindows\t<AppName>".
                // The string is tab or null delimited.

                // The <args> string must have at least one character.
                string launchArgs = "user=default";

                // The format of the AppName is: PackageFamilyName!PRAID.
                string praid = "MyAppId"; // The Application Id value from your package.appxmanifest.

                string appName = Windows.ApplicationModel.Package.Current.Id.FamilyName + "!" + praid;

                string launchAppMessage = launchArgs + "\tWindows\t" + appName;

                var dataWriter = new Windows.Storage.Streams.DataWriter();
                dataWriter.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf16LE;
                dataWriter.WriteString(launchAppMessage);
                var launchAppPubId =
                    proximityDevice.PublishBinaryMessage(
                        "LaunchApp:WriteTag", dataWriter.DetachBuffer());
            }
        }
예제 #10
0
        private async void FileWrite_UsingStream(Windows.Storage.StorageFolder storageFolder)
        {
            //Windows.Storage.StorageFolder storageFolder =
            //    Windows.Storage.ApplicationData.Current.LocalFolder;
            //Windows.Storage.StorageFolder storageFolder =
            //    Windows.ApplicationModel.Package.Current.InstalledLocation;
            try
            {
                Windows.Storage.StorageFile storage = await storageFolder.GetFileAsync("StreamWrite.txt");

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

                // outputStream 가져옴
                using (var outputStream = stream.GetOutputStreamAt(0))
                {
                    using (var dataWriter = new Windows.Storage.Streams.DataWriter(outputStream))
                    {
                        dataWriter.WriteString("StreamWriteTest");
                        await dataWriter.StoreAsync();
                    }
                    await outputStream.FlushAsync();
                }

                stream.Dispose();
            }
            catch
            {
            }
        }
예제 #11
0
        /// <summary>
        ///  動作ログを出力する.
        /// </summary>
        /// <param name="taskInstance"></param>
        /// <returns></returns>
        async Task WriteLogAsync(IBackgroundTaskInstance taskInstance, SetLockscreenResult result)
        {
            var log = String.Format("{0}: {1} / {2}, {3}{4}",
                                    DateTimeOffset.Now,
                                    taskInstance.Task.Name,
                                    taskInstance.Task.TaskId,
                                    result,
                                    Environment.NewLine);

            System.Diagnostics.Debug.WriteLine(log);

            var logfile = await Windows.Storage.ApplicationData.Current.LocalFolder.CreateFileAsync("bgtask.log", Windows.Storage.CreationCollisionOption.OpenIfExists);

            if (logfile != null)
            {
                System.Diagnostics.Debug.WriteLine(logfile.Path);
                using (var strm = await logfile.OpenAsync(Windows.Storage.FileAccessMode.ReadWrite))
                {
                    strm.Seek(strm.Size);
                    using (var dw = new Windows.Storage.Streams.DataWriter(strm))
                    {
                        dw.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf16LE;
                        dw.WriteString(log);
                        await dw.StoreAsync();

                        await dw.FlushAsync();
                    }
                }
            }
        }
예제 #12
0
        private void PublishLaunchApp(ProximityDevice proximityDevice)
        {
            //var proximityDevice = Windows.Networking.Proximity.ProximityDevice.GetDefault();

            if (proximityDevice != null)
            {
                                // The format of the app launch string is:
                                // <args>\tWindows\t<AppFamilyBasedName>\tWindowsPhone\t<AppGUID>
                                // The string is tab delimited.

                                // The <args> string must have at least one character.
                                string launchArgs = "user=default";


                                                      // The format of the AppFamilyBasedName is: PackageFamilyName!PRAID.
                                string praid = "App"; // The Application Id value from your package.appxmanifest.
                                string appFamilyBasedName = Windows.ApplicationModel.Package.Current.Id.FamilyName + "!" + praid;


                // GUID is PhoneProductId value from you package.appxmanifest
                // NOTE: The GUID will change after you associate app to the app store
                // Consider using windows.applicationmodel.store.currentapp.appid after the app is associated to the store.
                string appGuid = "{55d006ef-be06-4019-bc6d-ec38f28a5304}";

                string launchAppMessage = launchArgs +
                                          "\tWindows\t" + appFamilyBasedName +
                                          "\tWindowsPhone\t" + appGuid;

                var dataWriter = new Windows.Storage.Streams.DataWriter();
                dataWriter.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf16LE;
                dataWriter.WriteString(launchAppMessage);
                var launchAppPubId = proximityDevice.PublishBinaryMessage("LaunchApp:WriteTag", dataWriter.DetachBuffer());
            }
        }
예제 #13
0
        public async Task<bool> WritePlaylistFile(Playlist play)
        {
            try
            {

                StorageFolder storageFolder = ApplicationData.Current.LocalFolder;
                StorageFolder playlistsFolder = await storageFolder.CreateFolderAsync("Playlists", CreationCollisionOption.OpenIfExists);
                StorageFile playlist = await playlistsFolder.CreateFileAsync(play.PlaylistName + ".m3u",
                        CreationCollisionOption.ReplaceExisting);


                var stream = await playlist.OpenAsync(Windows.Storage.FileAccessMode.ReadWrite);
                using (var outputStream = stream.GetOutputStreamAt(0))
                {
                    using (var dataWriter = new Windows.Storage.Streams.DataWriter(outputStream))
                    {
                        dataWriter.WriteString(await PrepareM3uFile(play));
                        await dataWriter.StoreAsync();
                        await outputStream.FlushAsync();
                    }
                }
                stream.Dispose();
                return true;
            }
            catch
            {
                return false;
            }
        }
예제 #14
0
        private async void C_BUTTON_GENCODE_ENTITY_Click(object sender,RoutedEventArgs e)
        {
            String res = m_Elements.GenFunctions();

            var picker = new Windows.Storage.Pickers.FileSavePicker();

            picker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.DocumentsLibrary;
            // Dropdown of file types the user can save the file as
            picker.FileTypeChoices.Add("cs",new List <string>()
            {
                ".cs"
            });
            // Default file name if the user does not type one in or select a file to replace
            picker.SuggestedFileName = "gencode";
            var t_storagefile = await picker.PickSaveFileAsync();

            if (t_storagefile == null)
            {
                return;
            }
            using (StorageStreamTransaction transaction = await t_storagefile.OpenTransactedWriteAsync())
            {
                using (Windows.Storage.Streams.DataWriter dataWriter = new Windows.Storage.Streams.DataWriter(transaction.Stream))
                {
                    dataWriter.WriteString(res);
                    transaction.Stream.Size = await dataWriter.StoreAsync();

                    await transaction.Stream.FlushAsync();

                    await transaction.CommitAsync();
                }
            }
        }
        private async void Write_to_text_file_stream_Click(object sender, RoutedEventArgs e)
        {
            // Get the sample file
            Windows.Storage.StorageFolder storageFolder =
                Windows.Storage.ApplicationData.Current.LocalFolder;
            Windows.Storage.StorageFile sampleFile =
                await storageFolder.GetFileAsync("sample.txt");

            // Open the file
            var stream = await sampleFile.OpenAsync(Windows.Storage.FileAccessMode.ReadWrite);

            // Get an output stream
            using (var outputStream = stream.GetOutputStreamAt(0))
            {
                // Write to the output stream
                using (var dataWriter = new Windows.Storage.Streams.DataWriter(outputStream))
                {
                    dataWriter.WriteString("DataWriter has methods to write to various types, such as DataTimeOffset.");

                    // Save the stream
                    await dataWriter.StoreAsync();

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

            // Test sample file
            Access_sample_file();
        }
예제 #16
0
        internal async void CustomerWriteToFile(string filename, List <Customer> InputList)
        {
            //Hakee tiedoston kirjoitettavaksi. Kirjoittaa tiedostoon C:/users/USER/AppData.....
            var file = await folder.CreateFileAsync(filename, CreationCollisionOption.OpenIfExists);

            var stream = await file.OpenAsync(FileAccessMode.ReadWrite);

            Type tyyppi         = InputList.GetType();
            int  attributeCount = 0;

            foreach (PropertyInfo property in tyyppi.GetProperties())
            {
                attributeCount += property.GetCustomAttributes(false).Count();
            }


            using (var outputStream = stream.GetOutputStreamAt(0))
            {
                using (var datawriter = new Windows.Storage.Streams.DataWriter(outputStream))
                {
                    datawriter.WriteString("Testi");
                    await datawriter.StoreAsync();
                }
            }

            stream.Dispose();
        }
예제 #17
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.
        }
예제 #18
0
        private async void Archive(String hourData)
        {
            try
            {
                //string tr = DateTime.Now.Ticks.ToString() + ".txt";
                string tr = DateTime.Now.Ticks.ToString() + ".txt";
                //StorageFolder storageFolder = ApplicationData.Current.LocalFolder;
                StorageFolder storageFolder = ApplicationData.Current.TemporaryFolder;
                StorageFile   sampleFile    = await storageFolder.CreateFileAsync(tr, CreationCollisionOption.ReplaceExisting);

                var stream = await sampleFile.OpenAsync(FileAccessMode.ReadWrite);

                using (var outputStream = stream.GetOutputStreamAt(0))
                {
                    // We'll add more code here in the next step.
                    using (var dataWriter = new Windows.Storage.Streams.DataWriter(outputStream))
                    {
                        dataWriter.WriteString(hourData);
                        await dataWriter.StoreAsync();

                        await outputStream.FlushAsync();
                    }
                }
                stream.Dispose();
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine("Archive: " + ex);
            }
        }
예제 #19
0
        public async Task <Settings> WriteSettingsAsync(Settings settings)
        {
            var         localFolder = ApplicationData.Current.LocalFolder;
            StorageFile file        = await localFolder.CreateFileAsync(SettingsName, CreationCollisionOption.ReplaceExisting);

            //await FileIO.WriteBufferAsync(file, buffer);

            var formatter = new DataContractSerializer(typeof(Settings));
            var stream    = await file.OpenAsync(FileAccessMode.ReadWrite);

            using (var outputStream = stream.GetOutputStreamAt(0))
            {
                using (var dataWriter = new Windows.Storage.Streams.DataWriter(outputStream))
                {
                    dataWriter.WriteString(settings.FileSystemDirectory);
                    dataWriter.WriteBoolean(settings.IsFileSystemEnabled);
                    await dataWriter.StoreAsync();

                    await outputStream.FlushAsync();
                }
            }

            //formatter.WriteObject(outStream, settings);

            Debug.WriteLine("SavedSettings");
            return(settings);
        }
        public async void Send(string message)
        {
            if (_websocket != null && messageWriter != null)
            {
                try {
                    message = "\"" + message + "\"";
                    messageWriter.WriteString(message);
                    await messageWriter.StoreAsync();

                    //System.Diagnostics.Debug.WriteLine(":: send: " + message);
                } catch {/*
                          * var ev = OnError;
                          * if (ev != null) {
                          * Task.Factory.StartNew(() => ev(new OrtcNotConnectedException("Unable to write to socket.")));
                          * }*/
                }

                /*
                 * using (var writer = new Windows.Storage.Streams.DataWriter(_websocket.OutputStream)) {
                 *  writer.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf8;
                 *  writer.WriteString(message);
                 *  writer.StoreAsync();
                 *  //await writer.FlushAsync();
                 *  System.Diagnostics.Debug.WriteLine(":: send: " + message);
                 * }
                 */
            }
        }
예제 #21
0
        /// <summary>
        /// This is the click handler for the 'Copy Strings' button.  Here we will parse the
        /// strings contained in the ElementsToWrite text block, write them to a stream using
        /// DataWriter, retrieve them using DataReader, and output the results in the
        /// ElementsRead text block.
        /// </summary>
        /// <param name="sender">Contains information about the button that fired the event.</param>
        /// <param name="e">Contains state information and event data associated with a routed event.</param>
        private async void TransferData(object sender, RoutedEventArgs e)
        {
            // Initialize the in-memory stream where data will be stored.
            using (var stream = new Windows.Storage.Streams.InMemoryRandomAccessStream())
            {
                // Create the data writer object backed by the in-memory stream.
                using (var dataWriter = new Windows.Storage.Streams.DataWriter(stream))
                {
                    dataWriter.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf8;
                    dataWriter.ByteOrder       = Windows.Storage.Streams.ByteOrder.LittleEndian;

                    // Write each element separately.
                    foreach (string inputElement in inputElements)
                    {
                        uint inputElementSize = dataWriter.MeasureString(inputElement);
                        dataWriter.WriteUInt32(inputElementSize);
                        dataWriter.WriteString(inputElement);
                    }

                    // Send the contents of the writer to the backing stream.
                    await dataWriter.StoreAsync();

                    // For the in-memory stream implementation we are using, the flushAsync call is superfluous,
                    // but other types of streams may require it.
                    await dataWriter.FlushAsync();

                    // In order to prolong the lifetime of the stream, detach it from the DataWriter so that it
                    // will not be closed when Dispose() is called on dataWriter. Were we to fail to detach the
                    // stream, the call to dataWriter.Dispose() would close the underlying stream, preventing
                    // its subsequent use by the DataReader below.
                    dataWriter.DetachStream();
                }

                // Create the input stream at position 0 so that the stream can be read from the beginning.
                stream.Seek(0);
                using (var dataReader = new Windows.Storage.Streams.DataReader(stream))
                {
                    // The encoding and byte order need to match the settings of the writer we previously used.
                    dataReader.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf8;
                    dataReader.ByteOrder       = Windows.Storage.Streams.ByteOrder.LittleEndian;

                    // Once we have written the contents successfully we load the stream.
                    await dataReader.LoadAsync((uint)stream.Size);

                    var receivedStrings = "";

                    // Keep reading until we consume the complete stream.
                    while (dataReader.UnconsumedBufferLength > 0)
                    {
                        // Note that the call to readString requires a length of "code units" to read. This
                        // is the reason each string is preceded by its length when "on the wire".
                        uint bytesToRead = dataReader.ReadUInt32();
                        receivedStrings += dataReader.ReadString(bytesToRead) + "\n";
                    }

                    // Populate the ElementsRead text block with the items we read from the stream.
                    ElementsRead.Text = receivedStrings;
                }
            }
        }
        /// <summary>
        /// This is the click handler for the 'Copy Strings' button.  Here we will parse the
        /// strings contained in the ElementsToWrite text block, write them to a stream using
        /// DataWriter, retrieve them using DataReader, and output the results in the
        /// ElementsRead text block.
        /// </summary>
        /// <param name="sender">Contains information about the button that fired the event.</param>
        /// <param name="e">Contains state information and event data associated with a routed event.</param>
        private async void TransferData(object sender, RoutedEventArgs e)
        {
            // Initialize the in-memory stream where data will be stored.
            using (var stream = new Windows.Storage.Streams.InMemoryRandomAccessStream())
            {
                // Create the data writer object backed by the in-memory stream.
                using (var dataWriter = new Windows.Storage.Streams.DataWriter(stream))
                {
                    dataWriter.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf8;
                    dataWriter.ByteOrder = Windows.Storage.Streams.ByteOrder.LittleEndian;

                    // Write each element separately.
                    foreach (string inputElement in inputElements)
                    {
                        uint inputElementSize = dataWriter.MeasureString(inputElement);
                        dataWriter.WriteUInt32(inputElementSize);
                        dataWriter.WriteString(inputElement);
                    }

                    // Send the contents of the writer to the backing stream.
                    await dataWriter.StoreAsync();

                    // For the in-memory stream implementation we are using, the flushAsync call is superfluous,
                    // but other types of streams may require it.
                    await dataWriter.FlushAsync();

                    // In order to prolong the lifetime of the stream, detach it from the DataWriter so that it 
                    // will not be closed when Dispose() is called on dataWriter. Were we to fail to detach the 
                    // stream, the call to dataWriter.Dispose() would close the underlying stream, preventing 
                    // its subsequent use by the DataReader below.
                    dataWriter.DetachStream();
                }

                // Create the input stream at position 0 so that the stream can be read from the beginning.
                stream.Seek(0);
                using (var dataReader = new Windows.Storage.Streams.DataReader(stream))
                {
                    // The encoding and byte order need to match the settings of the writer we previously used.
                    dataReader.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf8;
                    dataReader.ByteOrder = Windows.Storage.Streams.ByteOrder.LittleEndian;

                    // Once we have written the contents successfully we load the stream.
                    await dataReader.LoadAsync((uint)stream.Size);

                    var receivedStrings = "";

                    // Keep reading until we consume the complete stream.
                    while (dataReader.UnconsumedBufferLength > 0)
                    {
                        // Note that the call to readString requires a length of "code units" to read. This
                        // is the reason each string is preceded by its length when "on the wire".
                        uint bytesToRead = dataReader.ReadUInt32();
                        receivedStrings += dataReader.ReadString(bytesToRead) + "\n";
                    }

                    // Populate the ElementsRead text block with the items we read from the stream.
                    ElementsRead.Text = receivedStrings;
                }
            }
        }
예제 #23
0
        private async void AddToIndex_Click(object sender, RoutedEventArgs e)
        {
            if (ItemKeyInput.Text == "")
            {
                rootPage.NotifyUser("You must add an item key to insert an item into the index.", NotifyType.ErrorMessage);
            }
            else
            {
                // Write the content property to a stream
                var contentStream = new Windows.Storage.Streams.InMemoryRandomAccessStream();
                var contentWriter = new Windows.Storage.Streams.DataWriter(contentStream);
                contentWriter.WriteString(ContentInput.Text);
                await contentWriter.StoreAsync();

                contentStream.Seek(0);

                // Get the name, keywords, and comment properties, and assign a language to them if provided
                object itemNameValue = NameInput.Text;
                object keywordsValue = KeywordsInput.Text;
                object commentValue  = CommentInput.Text;
                if (LanguageInput.Text != "")
                {
                    var itemNameValueAndLanguage = new Windows.Storage.Search.ValueAndLanguage();
                    itemNameValueAndLanguage.Language = LanguageInput.Text;
                    itemNameValueAndLanguage.Value    = itemNameValue;
                    itemNameValue = itemNameValueAndLanguage;
                    var keywordsValueAndLanguage = new Windows.Storage.Search.ValueAndLanguage();
                    keywordsValueAndLanguage.Language = LanguageInput.Text;
                    keywordsValueAndLanguage.Value    = keywordsValue;
                    keywordsValue = keywordsValueAndLanguage;
                    var commentValueAndLanguage = new Windows.Storage.Search.ValueAndLanguage();
                    commentValueAndLanguage.Language = LanguageInput.Text;
                    commentValueAndLanguage.Value    = commentValue;
                    commentValue = commentValueAndLanguage;
                }

                // Create the item to add to the indexer
                var content = new Windows.Storage.Search.IndexableContent();
                content.Id = ItemKeyInput.Text;
                content.Properties.Add(Windows.Storage.SystemProperties.ItemNameDisplay, itemNameValue);
                content.Properties.Add(Windows.Storage.SystemProperties.Keywords, keywordsValue);
                content.Properties.Add(Windows.Storage.SystemProperties.Comment, commentValue);
                content.Stream            = contentStream;
                content.StreamContentType = "text/plain";

                // Add the item to the indexer
                Helpers.OnIndexerOperationBegin();
                var indexer = Windows.Storage.Search.ContentIndexer.GetIndexer();
                await indexer.AddAsync(content);

                Helpers.OnIndexerOperationComplete(indexer);

                // Retrieve the item from the indexer and output its properties
                var retrievedProperties = await indexer.RetrievePropertiesAsync(ItemKeyInput.Text, content.Properties.Keys);

                rootPage.NotifyUser(Helpers.CreateItemString(ItemKeyInput.Text, content.Properties.Keys, retrievedProperties), NotifyType.StatusMessage);
            }
        }
        private async void AddToIndex_Click(object sender, RoutedEventArgs e)
        {
            if (ItemKeyInput.Text == "")
            {
                rootPage.NotifyUser("You must add an item key to insert an item into the index.", NotifyType.ErrorMessage);
            }
            else
            {
                // Write the content property to a stream
                var contentStream = new Windows.Storage.Streams.InMemoryRandomAccessStream();
                var contentWriter = new Windows.Storage.Streams.DataWriter(contentStream);
                contentWriter.WriteString(ContentInput.Text);
                await contentWriter.StoreAsync();
                contentStream.Seek(0);

                // Get the name, keywords, and comment properties, and assign a language to them if provided
                object itemNameValue = NameInput.Text;
                object keywordsValue = KeywordsInput.Text;
                object commentValue = CommentInput.Text;
                if (LanguageInput.Text != "")
                {
                    var itemNameValueAndLanguage = new Windows.Storage.Search.ValueAndLanguage();
                    itemNameValueAndLanguage.Language = LanguageInput.Text;
                    itemNameValueAndLanguage.Value = itemNameValue;
                    itemNameValue = itemNameValueAndLanguage;
                    var keywordsValueAndLanguage = new Windows.Storage.Search.ValueAndLanguage();
                    keywordsValueAndLanguage.Language = LanguageInput.Text;
                    keywordsValueAndLanguage.Value = keywordsValue;
                    keywordsValue = keywordsValueAndLanguage;
                    var commentValueAndLanguage = new Windows.Storage.Search.ValueAndLanguage();
                    commentValueAndLanguage.Language = LanguageInput.Text;
                    commentValueAndLanguage.Value = commentValue;
                    commentValue = commentValueAndLanguage;
                }

                // Create the item to add to the indexer
                var content = new Windows.Storage.Search.IndexableContent();
                content.Id = ItemKeyInput.Text;
                content.Properties.Add(Windows.Storage.SystemProperties.ItemNameDisplay, itemNameValue);
                content.Properties.Add(Windows.Storage.SystemProperties.Keywords, keywordsValue);
                content.Properties.Add(Windows.Storage.SystemProperties.Comment, commentValue);
                content.Stream = contentStream;
                content.StreamContentType = "text/plain";

                // Add the item to the indexer
                Helpers.OnIndexerOperationBegin();
                var indexer = Windows.Storage.Search.ContentIndexer.GetIndexer();
                await indexer.AddAsync(content);
                Helpers.OnIndexerOperationComplete(indexer);

                // Retrieve the item from the indexer and output its properties
                var retrievedProperties = await indexer.RetrievePropertiesAsync(ItemKeyInput.Text, content.Properties.Keys);
                rootPage.NotifyUser(Helpers.CreateItemString(ItemKeyInput.Text, content.Properties.Keys, retrievedProperties), NotifyType.StatusMessage);
            }
        }
예제 #25
0
        public async void rubbish()
        {
            //string line = "\r\n";
            string usingstr = string.Format("using System;{0}using System.Collections.Generic;{0}using System.Linq;{0}using System.Text;{0}using System.Threading.Tasks;{0}namespace rubbish{1}", line, left);
            //string classstr = ranstr();
            int           count;
            StringBuilder str = new StringBuilder();

            for (count = 0; count < 100; count++)
            {
                junk.Add(ranstr() + count.ToString());
            }
            str.Append(usingstr);
            str.Append(constructor());
            for (int i = 10; i < junk.Count; i++)
            {
                element.Add(lajicontent(junk[i]));
            }
            element.Add(content1());
            element.Add(content2());
            for (int i = 0; i < element.Count;)
            {
                count = ran.Next() % element.Count;
                str.Append(element[count]);
                element.RemoveAt(count);
            }
            for (int i = 10; i < junk.Count; i++)
            {
                //temp = string.Format("{0}(o);{1}" , junk[i] , line);
                //content.Append(temp);
                str.Append(string.Format("{0}private bool _{1}_bool;{2}", space, junk[i], line));
            }
            for (int i = 10; i < junk.Count; i++)
            {
                str.Append(string.Format("{0}private int _{1}_int;{2}", space, junk[i], line));
            }
            str.Append("}\r\n}");
            StorageFile file = await ApplicationData.Current.LocalFolder.CreateFileAsync(junk[0] + ".cs", CreationCollisionOption.ReplaceExisting);

            using (StorageStreamTransaction transaction = await file.OpenTransactedWriteAsync())
            {
                using (Windows.Storage.Streams.DataWriter dataWriter = new Windows.Storage.Streams.DataWriter(transaction.Stream))
                {
                    dataWriter.WriteString(str.ToString());
                    transaction.Stream.Size = await dataWriter.StoreAsync();

                    await transaction.CommitAsync();
                }
            }

            junk.Clear();
            str.Clear();
            _reminder.Append(file.Path);
            OnPropertyChanged("reminder");
        }
예제 #26
0
 private Windows.Storage.Streams.IBuffer GetBufferFromString(String str)
 {
     using (Windows.Storage.Streams.InMemoryRandomAccessStream memoryStream = new Windows.Storage.Streams.InMemoryRandomAccessStream())
     {
         using (Windows.Storage.Streams.DataWriter dataWriter = new Windows.Storage.Streams.DataWriter(memoryStream))
         {
             dataWriter.WriteString(str);
             return(dataWriter.DetachBuffer());
         }
     }
 }
예제 #27
0
        /// <summary>
        /// This is the click handler for the 'scenario3BtnBuffer' button.  You would replace this with your own handler
        /// if you have a button or buttons on this page.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void Scenario3BtnBuffer_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                // Get load settings
                var loadSettings = new Windows.Data.Xml.Dom.XmlLoadSettings();
                if (true == scenario3RB1.IsChecked)
                {
                    loadSettings.ProhibitDtd      = true;   // DTD is prohibited
                    loadSettings.ResolveExternals = false;  // Disable the resolve to external definitions such as external DTD
                }
                else if (true == scenario3RB2.IsChecked)
                {
                    loadSettings.ProhibitDtd      = false;  // DTD is not prohibited
                    loadSettings.ResolveExternals = false;  // Disable the resolve to external definitions such as external DTD
                }
                else if (true == scenario3RB3.IsChecked)
                {
                    loadSettings.ProhibitDtd      = false;  // DTD is not prohibited
                    loadSettings.ResolveExternals = true;   // Enable the resolve to external definitions such as external DTD
                }

                String xml;

                scenario3OriginalData.Document.GetText(Windows.UI.Text.TextGetOptions.None, out xml);

                // Set external dtd file path
                if (loadSettings.ResolveExternals == true && loadSettings.ProhibitDtd == false)
                {
                    Windows.Storage.StorageFolder storageFolder = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFolderAsync("loadExternaldtd");

                    String dtdPath = storageFolder.Path + "\\dtd.txt";
                    xml = xml.Replace("dtd.txt", dtdPath);
                }

                var dataWriter = new Windows.Storage.Streams.DataWriter();

                dataWriter.WriteString(xml);

                Windows.Storage.Streams.IBuffer ibuffer = dataWriter.DetachBuffer();

                var doc = new Windows.Data.Xml.Dom.XmlDocument();

                doc.LoadXmlFromBuffer(ibuffer, loadSettings);

                Scenario.RichEditBoxSetMsg(scenario3Result, doc.GetXml(), true);
            }
            catch (Exception)
            {
                // After loadSettings.ProhibitDtd is set to true, the exception is expected as the sample XML contains DTD
                Scenario.RichEditBoxSetError(scenario3Result, "Error: DTD is prohibited");
            }
        }
예제 #28
0
        public async void StartReceiveAsync()
        {
            isRun = true;
            while(isRun)
            {
                if(!isReceive)
                {
                    System.Diagnostics.Debug.WriteLine("Start Receive");
                    udpSocket = new Windows.Networking.Sockets.DatagramSocket();
                    udpSocket.MessageReceived += UdpSocket_MessageReceived;

                    Windows.Networking.HostName hostName = null;
                    IReadOnlyList<Windows.Networking.HostName> networkinfo = Windows.Networking.Connectivity.NetworkInformation.GetHostNames();
                    foreach (Windows.Networking.HostName h in networkinfo)
                    {
                        if (h.IPInformation != null)
                        {
                            Windows.Networking.Connectivity.IPInformation ipinfo = h.IPInformation;
                            if (h.RawName == IPAddr)
                            {
                                hostName = h;
                                break;
                            }
                        }
                    }
                    if (hostName != null)
                        await udpSocket.BindEndpointAsync(hostName, Port);
                    else
                        await udpSocket.BindServiceNameAsync(Port);
                    outstm = await udpSocket.GetOutputStreamAsync(new Windows.Networking.HostName("255.255.255.255"), "49002");
                    await outstm.FlushAsync();
                    Windows.Storage.Streams.DataWriter dw = new Windows.Storage.Streams.DataWriter(outstm);
                    dw.WriteString("Start Receive");
                    await dw.StoreAsync();
                    isReceive = true;
                }
                else
                {
                    if(CurrentStat.GPSStatus !=null & CurrentStat.ATTStatus != null)
                    {
                        if (onXPlaneStatReceived != null)
                            onXPlaneStatReceived.Invoke(this, CurrentStat);
                    }
                    System.Diagnostics.Debug.WriteLine("Try To Sleep");
                    isReceive = false;
                    await udpSocket.CancelIOAsync();
                    udpSocket.MessageReceived -= UdpSocket_MessageReceived;
                    udpSocket.Dispose();
                    udpSocket = null;
                }
                await Task.Delay(waitSeconds*1000);
            }
        }
예제 #29
0
        public static async void Stringify()
        {
            JsonObject jsonObject = new JsonObject();

            if (Player.CurrentlyPlayingFile != null && !string.IsNullOrEmpty(Player.CurrentlyPlayingFile.Path))
            {
                jsonObject[pathKey] = JsonValue.CreateStringValue(Player.CurrentlyPlayingFile.Path);
                jsonObject[posKey]  = JsonValue.CreateNumberValue(Player.Position);
            }

            jsonObject[shuffleKey]    = JsonValue.CreateBooleanValue(ShellVM.Shuffle);
            jsonObject[repeatKey]     = JsonValue.CreateStringValue(ShellVM.Repeat);
            jsonObject[volKey]        = JsonValue.CreateNumberValue(Player.Volume);
            jsonObject[isplaybarKey]  = JsonValue.CreateBooleanValue(ShellVM.IsPlayBarVisible);
            jsonObject[sortKey]       = JsonValue.CreateStringValue(LibVM.Sort);
            jsonObject[timeclosedKey] = JsonValue.CreateStringValue(DateTimeOffset.Now.ToString("yyyy-MM-dd HH:mm:ss"));
            if (SettingsVM.LibraryFoldersCollection.Any())
            {
                JsonArray array = new JsonArray();
                foreach (var folder in SettingsVM.LibraryFoldersCollection)
                {
                    array.Add(JsonValue.CreateStringValue(folder.Path));
                }
                jsonObject[foldersKey] = array;
            }
            try
            {
                StorageFile file = await ApplicationData.Current.TemporaryFolder.CreateFileAsync("lastplaying.mc", CreationCollisionOption.ReplaceExisting);

                using (var stream = await file.OpenAsync(Windows.Storage.FileAccessMode.ReadWrite))
                {
                    using (var outputStream = stream.GetOutputStreamAt(0))
                    {
                        using (var dataWriter = new Windows.Storage.Streams.DataWriter(outputStream))
                        {
                            dataWriter.WriteString(jsonObject.Stringify());
                            await dataWriter.StoreAsync();

                            await outputStream.FlushAsync();
                        }
                    }
                }
            }
            catch (UnauthorizedAccessException ex)
            {
                await NotificationManager.ShowAsync("Error while saving player state!");

                await Task.Delay(5000);

                await NotificationManager.ShowAsync("Nothing Baking!");
            }
        }
예제 #30
0
        public void Chat()
        {
            var DataReader = new Windows.Storage.Streams.DataReader(client.InputStream);

            byte[] getByte = new byte[5000];
            DataReader.ReadBytes(getByte);
            Encoding code       = Encoding.GetEncoding("UTF-8");
            string   RemoteData = code.GetString(getByte, 0, getByte.Length);

            Messages.Add(new Message("Your Friend", DateTime.Now, RemoteData, false));
            var DataWriter = new Windows.Storage.Streams.DataWriter(client.OutputStream);

            DataWriter.WriteString("test\n");
            Messages.Add(new Message("You", DateTime.Now, textBox.Text, true));
        }
 public async void saveFile(string content)
 {
     Windows.Storage.StorageFolder storageFolder = Windows.Storage.ApplicationData.Current.LocalFolder;
     Windows.Storage.StorageFile dataFile = await storageFolder.CreateFileAsync("db.txt", Windows.Storage.CreationCollisionOption.ReplaceExisting);
     var stream = await dataFile.OpenAsync(Windows.Storage.FileAccessMode.ReadWrite);
     using (var outputStream = stream.GetOutputStreamAt(0))
     {
         using (var dataWriter = new Windows.Storage.Streams.DataWriter(outputStream))
         {
             dataWriter.WriteString(content);
             await dataWriter.StoreAsync();
             await outputStream.FlushAsync();
         }
     }
     stream.Dispose();
 }
예제 #32
0
        private async Task WriteFileAsync(string filename, string content)
        {
            var folder = ApplicationData.Current.GetPublisherCacheFolder("SharedFolder");
            var file   = await folder.CreateFileAsync(filename, Windows.Storage.CreationCollisionOption.ReplaceExisting);

            var fs = await file.OpenAsync(Windows.Storage.FileAccessMode.ReadWrite);

            var outStream  = fs.GetOutputStreamAt(0);
            var dataWriter = new Windows.Storage.Streams.DataWriter(outStream);

            dataWriter.WriteString(content);
            await dataWriter.StoreAsync();

            dataWriter.DetachStream();
            await outStream.FlushAsync();
        }
예제 #33
0
        /// <summary>
        /// 스트림으로 파일 작성하기
        /// </summary>
        /// <param name="storage"></param>
        /// <param name="data"></param>
        /// <returns></returns>
        private async Task <bool> FileWrite_UsingStream(StorageFile storage, List <string> data)
        {
            var stream = await storage.OpenAsync(Windows.Storage.FileAccessMode.ReadWrite);

            // outputStream 가져옴
            using (var outputStream = stream.GetOutputStreamAt(0))
            {
                using (var dataWriter = new Windows.Storage.Streams.DataWriter(outputStream))
                {
                    dataWriter.WriteString("StreamWriteTest");
                    await dataWriter.StoreAsync();
                }
                await outputStream.FlushAsync();
            }

            stream.Dispose();
            return(true);
        }
    public async void WriteData(string data)
    {
        StorageFile file = await KnownFolders.PicturesLibrary.CreateFileAsync(filename, CreationCollisionOption.OpenIfExists);

        using (var stream = await file.OpenAsync(FileAccessMode.ReadWrite))
        {
            using (var outputStream = stream.GetOutputStreamAt(stream.Size))
            {
                using (var dataWriter = new Windows.Storage.Streams.DataWriter(outputStream))
                {
                    dataWriter.WriteString(data);

                    await dataWriter.StoreAsync();
                }
                await outputStream.FlushAsync();
            }
        }
    }
예제 #35
0
        public static async void WriteFile(string filename, string contents)
        {
            var localFolder = Windows.Storage.ApplicationData.Current.LocalFolder;
            var folder      = await localFolder.CreateFolderAsync("DataCache", Windows.Storage.CreationCollisionOption.OpenIfExists);

            var file = await folder.CreateFileAsync(filename, Windows.Storage.CreationCollisionOption.ReplaceExisting);

            var fs = await file.OpenAsync(Windows.Storage.FileAccessMode.ReadWrite);

            var outStream  = fs.GetOutputStreamAt(0);
            var dataWriter = new Windows.Storage.Streams.DataWriter(outStream);

            dataWriter.WriteString(contents);
            await dataWriter.StoreAsync();

            dataWriter.DetachStream();
            await outStream.FlushAsync();
        }
예제 #36
0
        private async Task<int> send_command_async (string command, bool use_send_characteristic = true)
        {
            if (ganglion_device == null)
            {
                return (int) CustomExitCodes.GANGLION_IS_NOT_OPEN_ERROR;
            }
            if (send_characteristic == null)
            {
                return (int) CustomExitCodes.SEND_CHARACTERISTIC_NOT_FOUND_ERROR;
            }

            var writer = new Windows.Storage.Streams.DataWriter ();
            writer.WriteString (command);
            try
            {
                GattWriteResult result = null;
                if (use_send_characteristic)
                {
                    result = await send_characteristic.WriteValueWithResultAsync (writer.DetachBuffer ()).AsTask ().TimeoutAfter (timeout);
                }
                else
                {
                    result = await disconnect_characteristic.WriteValueWithResultAsync (writer.DetachBuffer ()).AsTask ().TimeoutAfter (timeout);
                }
                if (result.Status == GattCommunicationStatus.Success)
                {
                    return (int) CustomExitCodes.STATUS_OK;
                }
                else
                {
                    return (int) CustomExitCodes.STOP_ERROR;
                }
            }
            catch (TimeoutException e)
            {
                return (int) CustomExitCodes.TIMEOUT_ERROR;
            }
            catch (Exception e)
            {
                return (int) CustomExitCodes.GENERAL_ERROR;
            }
            return (int) CustomExitCodes.STATUS_OK;
        }
예제 #37
0
        private async Task WriteFileAsync(string filename, string content)
		{
			var folder = ApplicationData.Current.GetPublisherCacheFolder("SharedFolder");
			var file = await folder.CreateFileAsync(filename, Windows.Storage.CreationCollisionOption.ReplaceExisting);
			var fs = await file.OpenAsync(Windows.Storage.FileAccessMode.ReadWrite);
			var outStream = fs.GetOutputStreamAt(0);
			var dataWriter = new Windows.Storage.Streams.DataWriter(outStream);
			dataWriter.WriteString(content);
			await dataWriter.StoreAsync();
			dataWriter.DetachStream();
			await outStream.FlushAsync();
		}
예제 #38
0
		private async void DownloadCardData()
		{
			string filename = "cards.txt";
			Windows.Storage.StorageFolder storageFolder = Windows.Storage.ApplicationData.Current.LocalFolder;
			Windows.Storage.StorageFile file = await storageFolder.CreateFileAsync(filename, Windows.Storage.CreationCollisionOption.ReplaceExisting);
			
			file = await storageFolder.GetFileAsync(filename);
			var stream = await file.OpenAsync(Windows.Storage.FileAccessMode.ReadWrite);
			using (var outputStream = stream.GetOutputStreamAt(0))
			{
				using (var dataWriter = new Windows.Storage.Streams.DataWriter(outputStream))
				{
					dataWriter.WriteString("6014EAD5\nCDDCEED5");
					await dataWriter.StoreAsync();
					await outputStream.FlushAsync();
				}
			}
			stream.Dispose();
			LoadCardData();
		}
예제 #39
0
 private Windows.Storage.Streams.IBuffer GetBufferFromString(String str)
 {
     using (Windows.Storage.Streams.InMemoryRandomAccessStream memoryStream = new Windows.Storage.Streams.InMemoryRandomAccessStream())
     {
         using (Windows.Storage.Streams.DataWriter dataWriter = new Windows.Storage.Streams.DataWriter(memoryStream))
         {
             dataWriter.WriteString(str);
             return dataWriter.DetachBuffer();
         }
     }
 }
        /// <summary>
        /// This is the click handler for the 'scenario3BtnBuffer' button.  You would replace this with your own handler
        /// if you have a button or buttons on this page.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void Scenario3BtnBuffer_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                // Get load settings
                var loadSettings = new Windows.Data.Xml.Dom.XmlLoadSettings();
                if (true == scenario3RB1.IsChecked)
                {
                    loadSettings.ProhibitDtd = true;        // DTD is prohibited
                    loadSettings.ResolveExternals = false;  // Disable the resolve to external definitions such as external DTD
                }
                else if (true == scenario3RB2.IsChecked)
                {
                    loadSettings.ProhibitDtd = false;       // DTD is not prohibited
                    loadSettings.ResolveExternals = false;  // Disable the resolve to external definitions such as external DTD
                }
                else if (true == scenario3RB3.IsChecked)
                {
                    loadSettings.ProhibitDtd = false;       // DTD is not prohibited
                    loadSettings.ResolveExternals = true;   // Enable the resolve to external definitions such as external DTD
                }

                String xml;

                scenario3OriginalData.Document.GetText(Windows.UI.Text.TextGetOptions.None, out xml);

                // Set external dtd file path
                if (loadSettings.ResolveExternals == true && loadSettings.ProhibitDtd == false)
                {
                    Windows.Storage.StorageFolder storageFolder = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFolderAsync("loadExternaldtd");
                    String dtdPath = storageFolder.Path + "\\dtd.txt";
                    xml = xml.Replace("dtd.txt", dtdPath);
                }

                var dataWriter = new Windows.Storage.Streams.DataWriter();

                dataWriter.WriteString(xml);

                Windows.Storage.Streams.IBuffer ibuffer = dataWriter.DetachBuffer();

                var doc = new Windows.Data.Xml.Dom.XmlDocument();

                doc.LoadXmlFromBuffer(ibuffer, loadSettings);

                Scenario.RichEditBoxSetMsg(scenario3Result, doc.GetXml(), true);
            }
            catch (Exception)
            {
                // After loadSettings.ProhibitDtd is set to true, the exception is expected as the sample XML contains DTD
                Scenario.RichEditBoxSetError(scenario3Result, "Error: DTD is prohibited");
            }
        }
예제 #41
0
        // Handles PeerFinder_AdvertiseButton click
        void PeerFinder_StartAdvertising(object sender, RoutedEventArgs e)
        {
            // If PeerFinder is started, stop it, so that new properties
            // selected by the user (Role/DiscoveryData) can be updated.
            PeerFinder_StopAdvertising(sender, e);

            rootPage.NotifyUser("", NotifyType.ErrorMessage);
            if (!_peerFinderStarted)
            {
                // attach the callback handler (there can only be one PeerConnectProgress handler).
                PeerFinder.TriggeredConnectionStateChanged += new TypedEventHandler<object, TriggeredConnectionStateChangedEventArgs>(TriggeredConnectionStateChangedEventHandler);
                // attach the incoming connection request event handler
                PeerFinder.ConnectionRequested += new TypedEventHandler<object, ConnectionRequestedEventArgs>(PeerConnectionRequested);

                // Set the PeerFinder.Role property
                switch (PeerFinder_SelectRole.SelectionBoxItem.ToString())
                {
                    case "Peer":
                        PeerFinder.Role = PeerRole.Peer;
                        break;
                    case "Host":
                        PeerFinder.Role = PeerRole.Host;
                        break;
                    case "Client":
                        PeerFinder.Role = PeerRole.Client;
                        break;
                }

                // Set DiscoveryData property if the user entered some text
                if ((PeerFinder_DiscoveryData.Text.Length > 0) && (PeerFinder_DiscoveryData.Text != "What's happening today?"))
                {
                    using (var discoveryDataWriter = new Windows.Storage.Streams.DataWriter(new Windows.Storage.Streams.InMemoryRandomAccessStream()))
                    {
                        discoveryDataWriter.WriteString(PeerFinder_DiscoveryData.Text);
                        PeerFinder.DiscoveryData = discoveryDataWriter.DetachBuffer();
                    }
                }

                // start listening for proximate peers
                PeerFinder.Start();
                _peerFinderStarted = true;
                PeerFinder_StopAdvertiseButton.Visibility = Visibility.Visible;
                PeerFinder_ConnectButton.Visibility = Visibility.Visible;

                if (_browseConnectSupported && _triggeredConnectSupported)
                {
                    rootPage.NotifyUser("Click Browse for Peers button or tap another device to connect to a peer.", NotifyType.StatusMessage);
                    PeerFinder_BrowseGrid.Visibility = Visibility.Visible;
                }
                else if (_triggeredConnectSupported)
                {
                    rootPage.NotifyUser("Tap another device to connect to a peer.", NotifyType.StatusMessage);
                }
                else if (_browseConnectSupported)
                {
                    rootPage.NotifyUser("Click Browse for Peers button.", NotifyType.StatusMessage);
                    PeerFinder_BrowseGrid.Visibility = Visibility.Visible;
                }
            }
        }
 public void Chat()
 {
     var DataReader = new Windows.Storage.Streams.DataReader(client.InputStream);
     byte[] getByte = new byte[5000];
     DataReader.ReadBytes(getByte);
     Encoding code = Encoding.GetEncoding("UTF-8");
     string RemoteData = code.GetString(getByte, 0, getByte.Length);
     Messages.Add(new Message("Your Friend", DateTime.Now, RemoteData, false));
     var DataWriter = new Windows.Storage.Streams.DataWriter(client.OutputStream);
     DataWriter.WriteString("test\n");
     Messages.Add(new Message("You", DateTime.Now, textBox.Text, true));
 }
		public async void SaveData() {
			var fileList = await ApplicationData.Current.LocalFolder.GetFilesAsync();
			System.IO.MemoryStream ms = new System.IO.MemoryStream();
			var scratchFile = await ApplicationData.Current.LocalFolder.CreateFileAsync(localScratchFileName, CreationCollisionOption.ReplaceExisting);
			using (var storageTransaction = await scratchFile.OpenTransactedWriteAsync()) {
				using (var dw = new Windows.Storage.Streams.DataWriter(storageTransaction.Stream)) {
					dw.WriteInt32(Items.Count);
					for (int x = 0; x < Items.Count; x++) {
						TrackItem item = Items[x];
						dw.WriteDateTime(item.Start);
						dw.WriteDateTime(item.End.Value);
						dw.WriteInt32(item.Topic.Length);
						dw.WriteString(item.Topic);
					}
					if (CurrentItem == null) {
						dw.WriteBoolean(false);
					} else {
						dw.WriteBoolean(true);
						dw.WriteDateTime(CurrentItem.Start);
						dw.WriteInt32(CurrentItem.Topic.Length);
						dw.WriteString(CurrentItem.Topic);
					}
					storageTransaction.Stream.Size = await dw.StoreAsync();
					await storageTransaction.CommitAsync();
				}
			}
			await scratchFile.RenameAsync(localFileName, NameCollisionOption.ReplaceExisting);
		}