Exemplo n.º 1
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();
            }
        }
Exemplo n.º 2
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();
                }
            }
        }
Exemplo n.º 3
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
            {
            }
        }
Exemplo n.º 4
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();
                    }
                }
            }
        }
Exemplo n.º 5
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;
            }
        }
        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);
                 * }
                 */
            }
        }
Exemplo n.º 7
0
        public void     Stop()
        {
            this.behaviour.StopCoroutine(this.pingCoroutine);

            for (int i = 0; i < this.BroadcastEndPoint.Length; i++)
#if NETFX_CORE
            {
                var action = this.Client.GetOutputStreamAsync(new Windows.Networking.HostName("127.0.0.1"), this.BroadcastEndPoint[i].Port.ToString());
                //var action = this.Client.GetOutputStreamAsync(this.Client.Information.LocalAddress, this.BroadcastEndPoint[i].Port.ToString());
                action.AsTask().Wait();
                var outputStream = action.GetResults();
                var writer       = new Windows.Storage.Streams.DataWriter(outputStream);
                writer.WriteBytes(AutoDetectUDPClient.UDPEndMessage);
                writer.StoreAsync().AsTask().Wait();
            }
#else
            { this.Client.Send(AutoDetectUDPClient.UDPEndMessage, AutoDetectUDPClient.UDPEndMessage.Length, this.BroadcastEndPoint[i]); }
#endif

#if NETFX_CORE
            this.Client.Dispose();
#else
            this.Client.Close();
#endif
        }
Exemplo n.º 8
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);
        }
Exemplo n.º 9
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);
            }
        }
Exemplo n.º 10
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.
        }
Exemplo n.º 11
0
        private async void _baseWebView_ScriptNotify(object sender, NotifyEventArgs e)
        {
            try
            {
                var bmp        = new BitmapImage();
                var base64     = e.Value.Substring(e.Value.IndexOf(",") + 1);
                var imageBytes = Convert.FromBase64String(base64);

#if WINDOWS_APP || WINDOWS_PHONE_APP
                using (var ms = new Windows.Storage.Streams.InMemoryRandomAccessStream())
                {
                    using (var writer = new Windows.Storage.Streams.DataWriter(ms.GetOutputStreamAt(0)))
                    {
                        writer.WriteBytes(imageBytes);
                        await writer.StoreAsync();
                    }

                    bmp.SetSource(ms);
                }
#elif WINDOWS_PHONE
                using (var ms = new System.IO.MemoryStream(imageBytes))
                {
                    ms.Position = 0;
                    bmp.SetSource(ms);
                }
#endif

                imageBytes      = null;
                _img.Source     = bmp;
                _img.Visibility = Visibility.Visible;
            }
            catch { }
        }
Exemplo n.º 12
0
        private IEnumerator     AsyncSendPing()
        {
#if !NETFX_CORE
            AsyncCallback callback = new AsyncCallback(this.SendPresence);
#endif
            WaitForSeconds wait = new WaitForSeconds(this.pingInterval);

            while (true)
            {
                for (int i = 0; i < this.BroadcastEndPoint.Length; i++)
#if NETFX_CORE
                {
                    var action = this.Client.GetOutputStreamAsync(new Windows.Networking.HostName("127.0.0.1"), this.BroadcastEndPoint[i].Port.ToString());
                    //var action = this.Client.GetOutputStreamAsync(this.Client.Information.LocalAddress, this.BroadcastEndPoint[i].Port.ToString());
                    action.AsTask().Wait();
                    var outputStream = action.GetResults();
                    var writer       = new Windows.Storage.Streams.DataWriter(outputStream);
                    writer.WriteBytes(AutoDetectUDPClient.UDPPingMessage);
                    writer.StoreAsync().AsTask().Wait();
                }
#else
                { this.Client.BeginSend(this.pingContent, this.pingContent.Length, this.BroadcastEndPoint[i], callback, null); }
#endif

                yield return(wait);
            }
        }
Exemplo n.º 13
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();
        }
Exemplo n.º 14
0
        public static async Task <UwpSoftwareBitmap> ConvertFrom(BitmapFrame sourceBitmap)
        {
            // BitmapFrameをBMP形式のバイト配列に変換
            byte[] bitmapBytes;
            var    encoder = new BmpBitmapEncoder(); // .NET用のエンコーダーを使う

            encoder.Frames.Add(sourceBitmap);
            using (var memoryStream = new MemoryStream())
            {
                encoder.Save(memoryStream);
                bitmapBytes = memoryStream.ToArray();
            }

            // バイト配列をUWPのIRandomAccessStreamに変換
            using (var randomAccessStream = new UwpInMemoryRandomAccessStream())
            {
                using (var outputStream = randomAccessStream.GetOutputStreamAt(0))
                    using (var writer = new UwpDataWriter(outputStream))
                    {
                        writer.WriteBytes(bitmapBytes);
                        await writer.StoreAsync();

                        await outputStream.FlushAsync();
                    }

                // IRandomAccessStreamをSoftwareBitmapに変換
                // (UWP APIのデコーダー)
                var decoder = await UwpBitmapDecoder.CreateAsync(randomAccessStream);

                var softwareBitmap
                    = await decoder.GetSoftwareBitmapAsync(UwpBitmapPixelFormat.Bgra8, UwpBitmapAlphaMode.Premultiplied);

                return(softwareBitmap);
            }
        }
Exemplo n.º 15
0
        /// <summary>
        /// Gửi một gói tin đi
        /// </summary>
        /// <param name="data">gói tin cần gửi</param>
        /// <returns>true nếu gửi thành công, false nếu thất bại</returns>
        public async Task <bool> SendAsync(byte[] data)
        {
            // Monitor.Enter(nstreamlock);
            try
            {
                byte[] senddata = new byte[data.Length + sizeof(int)];
                // đưa độ dài của data về dạng bytes rồi copy vào send
                Buffer.BlockCopy(BitConverter.GetBytes(data.Length), 0, senddata, 0, sizeof(int));

                // copy dữ liệu còn lại vào send
                Buffer.BlockCopy(data, 0, senddata, sizeof(int), data.Length);

                writer.WriteBytes(senddata);
                await writer.StoreAsync();

                // Monitor.Exit(nstreamlock);
                return(true);
            }
            catch
            {
                Disconnect();
                //  Monitor.Exit(nstreamlock);
                return(false);
            }
        }
        /// <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>
            /// Writes a specified number of bytes to the serial port using data from a buffer.
            /// </summary>
            /// <param name="buffer">The byte array that contains the data to write to the port.</param>
            /// <param name="offset">The zero-based byte offset in the buffer parameter at which to begin copying bytes to the port.</param>
            /// <param name="count">The number of bytes to write.</param>
            /// <remarks>
            /// ArgumentException: offset plus count is greater than the length of the buffer.
            /// </remarks>
            public Windows.Foundation.IAsyncAction Write(
                Windows.Storage.Streams.IBuffer buffer,
                uint offset,
                uint count
                )
            {
                var outputStream = this.cdcData.BulkOutPipes[0].OutputStream;
                var writer       = new Windows.Storage.Streams.DataWriter(outputStream);

                return(Task.Run(async() =>
                {
                    // Overflow check.
                    if ((int)buffer.Length < (offset + count))
                    {
                        throw new System.ArgumentException("Capacity of buffer is not enough.");
                    }

                    writer.WriteBuffer(buffer, offset, count);

                    var written = await writer.StoreAsync();

                    return;
                }
                                ).AsAsyncAction());
            }
Exemplo n.º 18
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;
                }
            }
        }
Exemplo n.º 19
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();
                    }
                }
            }
        }
Exemplo n.º 20
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.
        }
Exemplo n.º 21
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.
        }
        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();
        }
Exemplo n.º 23
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();
                }
            }
        }
Exemplo n.º 24
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);
            }
        }
Exemplo n.º 26
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");
        }
Exemplo n.º 27
0
        public async Task SendData(byte[] data)
        {
            Task <UInt32> storeAsyncTask;

            // Load the text from the sendText input text box to the dataWriter object
            dataWriteObject.WriteBytes(data);

            // Launch an async task to complete the write operation
            storeAsyncTask = dataWriteObject.StoreAsync().AsTask();

            UInt32 bytesWritten = await storeAsyncTask;
        }
Exemplo n.º 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);
            }
        }
Exemplo n.º 29
0
        /// <summary>
        /// Restores the applications data using a backup from the current user's OneDrive.
        /// <para>Note: Application requires restart after restoring data</para>
        /// </summary>
        /// <param name="itemId">Unique item identifier within a DriveItem (i.e., a folder/file facet).</param>
        /// <param name="filename">Name of the datafile.</param>
        /// <returns></returns>
        public async Task RestoreFileAsync(string itemId, string dataFilename)
        {
            try
            {
                // Local storage folder
                Windows.Storage.StorageFolder storageFolder =
                    Windows.Storage.ApplicationData.Current.LocalFolder;

                // Our local ktdatabase.db file
                Windows.Storage.StorageFile originalDataFile =
                    await storageFolder.GetFileAsync(dataFilename);

                // Stream for the backed up data file
                var backedUpFileStream = await GraphClient.Me.Drive.Items[itemId]
                                         .ItemWithPath(dataFilename)
                                         .Content
                                         .Request()
                                         .GetAsync();

                // Backed up file
                var backedUpFile = await storageFolder.CreateFileAsync("temp", CreationCollisionOption.ReplaceExisting);

                var newStream = await backedUpFile.OpenAsync(Windows.Storage.FileAccessMode.ReadWrite);

                // Write data to new file
                using (var outputStream = newStream.GetOutputStreamAt(0))
                {
                    using (var dataWriter = new Windows.Storage.Streams.DataWriter(outputStream))
                    {
                        var buffer = backedUpFileStream.ToByteArray();
                        dataWriter.WriteBytes(buffer);

                        await dataWriter.StoreAsync();

                        await outputStream.FlushAsync();
                    }
                }

                // Copy and replace local file
                await backedUpFile.CopyAsync(storageFolder, dataFilename, NameCollisionOption.ReplaceExisting);
            }

            catch (ServiceException ex)
            {
                if (ex.StatusCode == HttpStatusCode.Forbidden)
                {
                    Console.WriteLine($"Access Denied: {ex.Message}");
                }

                Console.WriteLine($"Service Exception, Error uploading file to signed-in users one drive: {ex.Message}");
                // return null;
            }
        }
Exemplo n.º 30
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!");
            }
        }
        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();
        }
        private BitmapImage GetBitmap(byte[] bytes)
        {
            var bmp = new BitmapImage();

              using (var stream = new Windows.Storage.Streams.InMemoryRandomAccessStream())
              {
            using (var writer = new Windows.Storage.Streams.DataWriter(stream.GetOutputStreamAt(0)))
            {
              writer.WriteBytes(bytes);
              writer.StoreAsync().GetResults();
              bmp.SetSource(stream);
            }
              }
              return bmp;
        }
Exemplo n.º 33
0
        private static Windows.UI.Xaml.Media.Imaging.BitmapImage GetBitmap(byte[] bytes)
        {
            var bmp = new Windows.UI.Xaml.Media.Imaging.BitmapImage();

            using (var stream = new Windows.Storage.Streams.InMemoryRandomAccessStream())
            {
                using (var writer = new Windows.Storage.Streams.DataWriter(stream.GetOutputStreamAt(0)))
                {
                    writer.WriteBytes(bytes);
                    writer.StoreAsync().GetResults();
                    bmp.SetSource(stream);
                }
            }
            return(bmp);
        }
Exemplo n.º 34
0
		/// <summary>
		/// Writes an array of Session objects to local storage.
		/// </summary>
		/// <param name="sessions">The Session objects to write. This is an array to force it to be a fixed collection by the time it gets here.</param>
		/// <returns>A task that can be awaited until the storage completes.</returns>
		public static async Task SerializeLocalSessions(Session[] sessions) {
			var fileList = await ApplicationData.Current.LocalFolder.GetFilesAsync();
			var scratchFile = await ApplicationData.Current.LocalFolder.CreateFileAsync(localScratchSessionsFileName, CreationCollisionOption.ReplaceExisting);
			using (var storageTransaction = await scratchFile.OpenTransactedWriteAsync()) {
				using (var dw = new Windows.Storage.Streams.DataWriter(storageTransaction.Stream)) {
					dw.WriteInt32(sessions.Length);
					for (int x = 0; x < sessions.Length; x++) {
						sessions[x].WriteSession(dw);
					}
					storageTransaction.Stream.Size = await dw.StoreAsync();
					await storageTransaction.CommitAsync();
				}
			}
			await scratchFile.RenameAsync(localSessionsFileName, NameCollisionOption.ReplaceExisting);
		}
Exemplo n.º 35
0
        private async System.Threading.Tasks.Task SendMessage(string message)
        {
            using (var stream = await socket.GetOutputStreamAsync(new Windows.Networking.HostName(externalIP), externalPort))
            {
                using (var writer = new Windows.Storage.Streams.DataWriter(stream))
                {
                    var data = Encoding.UTF8.GetBytes(message);

                    writer.WriteBytes(data);
                    await writer.StoreAsync();

                    Debug.Log("Sent: " + message);
                }
            }
        }
 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();
 }
Exemplo n.º 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();
        }
Exemplo n.º 38
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();
		}
Exemplo n.º 39
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();
		}
Exemplo n.º 40
0
        private async void SaveDocument(IPlotModel model, String newDocument)
        {
            if (model == null)
            {
                var msg = new MessageDialog("График не создан, рассчитайте распределение", "Ошибка сохранения");
                await msg.ShowAsync();
                return;
            }

            var savePicker = new Windows.Storage.Pickers.FileSavePicker
            {
                SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.PicturesLibrary
            };
            savePicker.FileTypeChoices.Add("PDF Document", new List<string>() { ".pdf" });
            savePicker.SuggestedFileName = newDocument;
            StorageFile file = await savePicker.PickSaveFileAsync();
            if (file != null)
            {
                CachedFileManager.DeferUpdates(file);
                var stream = await file.OpenAsync(FileAccessMode.ReadWrite);

                using (var outputStream = stream.GetOutputStreamAt(0))
                {
                    using (var dataWriter = new Windows.Storage.Streams.DataWriter(outputStream))
                    {
                        using (var memoryStream = new MemoryStream())
                        {
                            var pdf = new PdfExporter();
                            PdfExporter.Export(model, memoryStream, 1000, 400);
                            var bt = memoryStream.ToArray();
                            dataWriter.WriteBytes(bt);
                            await dataWriter.StoreAsync();
                            await outputStream.FlushAsync();
                        }
                    }
                }
                var status = await CachedFileManager.CompleteUpdatesAsync(file);
                if (status == FileUpdateStatus.Complete)
                {
                    var msg = new MessageDialog("По пути " + file.Path, "Файл сохранен");
                    await msg.ShowAsync();
                }
                else
                {
                    var msg = new MessageDialog("Произошла ошибка сохранения");
                    await msg.ShowAsync();
                }
            }
        }
Exemplo n.º 41
0
        private BitmapSource ReadDeviceIndependantBitmap(BinaryReader wmfReader, uint dibSize, out int width, out int height)
        {
            #if NETFX_CORE
            var bmp = new BitmapImage();
            var memStream = new Windows.Storage.Streams.InMemoryRandomAccessStream();
            var dibBytes = wmfReader.ReadBytes((int)dibSize);
            // int imageBytesOffset = 14;

            //System.Runtime.InteropServices.GCHandle pinnedDib = System.Runtime.InteropServices.GCHandle.Alloc(dibBytes, System.Runtime.InteropServices.GCHandleType.Pinned);

            //if (dibBytes[3] == 0x0C)
            //{
            //    imageBytesOffset += 12;
            //}
            //else
            //{
            //    var infoHeader = (BITMAPINFOHEADER)System.Runtime.InteropServices.Marshal.PtrToStructure(pinnedDib.AddrOfPinnedObject(), typeof(BITMAPINFOHEADER));

            //    imageBytesOffset += (int)infoHeader.biSize;

            //    switch ((BitCount)infoHeader.biBitCount)
            //    {
            //        case BitCount.BI_BITCOUNT_1:
            //            // 1 bit - Two colors
            //            imageBytesOffset += 4 * (colorUsed == 0 ? 2 : Math.Min(colorUsed, 2));
            //            break;

            //        case BitCount.BI_BITCOUNT_2:
            //            // 4 bit - 16 colors
            //            imageBytesOffset += 4 * (colorUsed == 0 ? 16 : Math.Min(colorUsed, 16));
            //            break;

            //        case BitCount.BI_BITCOUNT_3:
            //            // 8 bit - 256 colors
            //            imageBytesOffset += 4 * (colorUsed == 0 ? 256 : Math.Min(colorUsed, 256));
            //            break;
            //    }

            //    if ((Compression)infoHeader.biCompression == Compression.BI_BITFIELDS)
            //    {
            //        imageBytesOffset += 12;
            //    }
            //}

            //pinnedDib.Free();

            using (Windows.Storage.Streams.DataWriter writer = new Windows.Storage.Streams.DataWriter(memStream.GetOutputStreamAt(0)))
            {
                writer.WriteBytes(new byte[] { 66, 77 }); // BM
                writer.WriteUInt32(dibSize + 14);
                writer.WriteBytes(new byte[] { 0, 0, 0, 0 }); // Reserved
                writer.WriteUInt32((UInt32)0);

                writer.WriteBytes(dibBytes);
                var t = writer.StoreAsync();
                t.GetResults();
            }

            // bmp.ImageFailed += bmp_ImageFailed;
            // bmp.ImageOpened += bmp_ImageOpened;
            bmp.SetSource(memStream);
            width = bmp.PixelWidth;
            height = bmp.PixelHeight;
            return bmp;
            #else
            var bmp = new BitmapImage();
            var memStream = new MemoryStream();
            var dibBytes = wmfReader.ReadBytes((int)dibSize);

            BinaryWriter writer = new BinaryWriter(memStream);
            writer.Write(new byte[] { 66, 77 }); // BM
            writer.Write(dibSize + 14);
            writer.Write(new byte[] { 0, 0, 0, 0 }); // Reserved
            writer.Write((UInt32)0);

            writer.Write(dibBytes);
            writer.Flush();

            memStream.Position = 0;
            try
            {
                bmp.BeginInit();
                bmp.StreamSource = memStream;
                bmp.EndInit();
                width = bmp.PixelWidth;
                height = bmp.PixelHeight;

                return bmp;
            }
            catch
            {
                // Bad image;
                width = 0;
                height = 0;

                return null;
            }
            #endif
        }
Exemplo n.º 42
0
            /// <summary>
            /// Writes a specified number of bytes to the serial port using data from a buffer.
            /// </summary>
            /// <param name="buffer">The byte array that contains the data to write to the port.</param>
            /// <param name="offset">The zero-based byte offset in the buffer parameter at which to begin copying bytes to the port.</param>
            /// <param name="count">The number of bytes to write.</param>
            /// <remarks>
            /// ArgumentException: offset plus count is greater than the length of the buffer.
            /// </remarks>
            public Windows.Foundation.IAsyncAction Write(
                Windows.Storage.Streams.IBuffer buffer,
                uint offset,
                uint count
            )
            {
                var outputStream = this.cdcData.BulkOutPipes[0].OutputStream;
                var writer = new Windows.Storage.Streams.DataWriter(outputStream);

                return Task.Run(async () =>
                {
                    // Overflow check.
                    if ((int)buffer.Length < (offset + count))
                    {
                        throw new System.ArgumentException("Capacity of buffer is not enough.");
                    }

                    writer.WriteBuffer(buffer, offset, count);

                    var written = await writer.StoreAsync();

                    return;
                }
                ).AsAsyncAction();
            }
		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);
		}