public WriteBuffer ( Windows.Storage.Streams.IBuffer value ) : void | ||
value | Windows.Storage.Streams.IBuffer | |
리턴 | void |
private async Task <WriteableBitmap> LoadWritableBitmap(string path) { var file = await StorageFile.GetFileFromPathAsync(path); var data = await FileIO.ReadBufferAsync(file); var ms = new InMemoryRandomAccessStream(); var dw = new Windows.Storage.Streams.DataWriter(ms); dw.WriteBuffer(data); await dw.StoreAsync(); ms.Seek(0); var bm = new BitmapImage(); await bm.SetSourceAsync(ms); var wb = new WriteableBitmap(bm.PixelWidth, bm.PixelHeight); ms.Seek(0); await wb.SetSourceAsync(ms); return(wb); }
private async void LoginButton_Click(object sender, RoutedEventArgs e) { if (saveLogin) { configSF = await storageFolder.CreateFileAsync("config.txt", Windows.Storage.CreationCollisionOption.ReplaceExisting); var stream = await configSF.OpenAsync(Windows.Storage.FileAccessMode.ReadWrite); using (var outputStream = stream.GetOutputStreamAt(0)) { using (var dataWriter = new Windows.Storage.Streams.DataWriter(outputStream)) { string combo = Username.Text + " " + Password.Password; IBuffer comboB = await SampleDataProtectionStream(strDescriptor, combo, encoding); dataWriter.WriteBuffer(comboB); await dataWriter.StoreAsync(); await outputStream.FlushAsync(); } } stream.Dispose(); } else { configSF = await storageFolder.CreateFileAsync("config.txt", Windows.Storage.CreationCollisionOption.ReplaceExisting); } }
public async void ProccesImage(StorageFile imageFile) { var data = await FileIO.ReadBufferAsync(imageFile); // create a stream from the file var ms = new InMemoryRandomAccessStream(); var dw = new DataWriter(ms); dw.WriteBuffer(data); await dw.StoreAsync(); ms.Seek(0); // find out how big the image is, don't need this if you already know var bm = new BitmapImage(); await bm.SetSourceAsync(ms); // create a writable bitmap of the right size var wb = new WriteableBitmap(bm.PixelWidth, bm.PixelHeight); ms.Seek(0); // load the writable bitpamp from the stream await wb.SetSourceAsync(ms); Bitmap bmp = (Bitmap)wb; //var filter1 = Grayscale.CommonAlgorithms.BT709; //bmp = filter1.Apply(bmp); wb = (WriteableBitmap)bmp; var file = await this.WriteableBitmapToStorageFile(wb, FileFormat.Jpeg); }
private async Task <Windows.Storage.Streams.IRandomAccessStream> toStream(Windows.Storage.Streams.IBuffer ibuffer) { var stream = new Windows.Storage.Streams.InMemoryRandomAccessStream(); var outputStream = stream.GetOutputStreamAt(0); var datawriter = new Windows.Storage.Streams.DataWriter(outputStream); datawriter.WriteBuffer(ibuffer); await datawriter.StoreAsync(); await outputStream.FlushAsync(); return(stream); }
public async void WriteToSocketUsingReader(IBuffer buffer) { using (var dataWriter = new Windows.Storage.Streams.DataWriter(socket.OutputStream)) { dataWriter.ByteOrder = Windows.Storage.Streams.ByteOrder.LittleEndian; dataWriter.WriteUInt32(buffer.Length); dataWriter.WriteBuffer(buffer); await dataWriter.StoreAsync(); await dataWriter.FlushAsync(); dataWriter.DetachStream(); } }
public async void Quadraliteral(StorageFile file, IList<WF.Point> points) { var data = await FileIO.ReadBufferAsync(file); OpencvImageProcess opencv = new OpencvImageProcess(); // create a stream from the file var ms = new InMemoryRandomAccessStream(); var dw = new DataWriter(ms); dw.WriteBuffer(data); await dw.StoreAsync(); ms.Seek(0); // find out how big the image is, don't need this if you already know var bm = new BitmapImage(); await bm.SetSourceAsync(ms); // create a writable bitmap of the right size var wb = new WriteableBitmap(bm.PixelWidth, bm.PixelHeight); ms.Seek(0); // load the writable bitpamp from the stream await wb.SetSourceAsync(ms); Bitmap bmp = (Bitmap)wb; var wb1 = opencv.GetImageCorners(wb); wb1.Invalidate(); //wb.Invalidate(); // define quadrilateral's corners //List<IntPoint> corners = new List<IntPoint>(); //foreach (var point in points) //{ // corners.Add(new IntPoint((int)point.X, (int)point.Y)); //} //// create filter //var filter = // new SimpleQuadrilateralTransformation(corners); //// apply the filter //Bitmap newImage = filter.Apply(bmp); //wb = (WriteableBitmap)newImage; var f = await this.WriteableBitmapToStorageFile(wb1, FileFormat.Jpeg); }
public async Task<string> Decrypt(IBuffer buffProtected, BinaryStringEncoding encoding) { try { // Create a DataProtectionProvider object. DataProtectionProvider Provider = new DataProtectionProvider(); // Create a random access stream to contain the encrypted message. InMemoryRandomAccessStream inputData = new InMemoryRandomAccessStream(); // Create a random access stream to contain the decrypted data. InMemoryRandomAccessStream unprotectedData = new InMemoryRandomAccessStream(); // Retrieve an IOutputStream object and fill it with the input (encrypted) data. IOutputStream outputStream = inputData.GetOutputStreamAt(0); DataWriter writer = new DataWriter(outputStream); writer.WriteBuffer(buffProtected); await writer.StoreAsync(); await outputStream.FlushAsync(); // Retrieve an IInputStream object from which you can read the input (encrypted) data. IInputStream source = inputData.GetInputStreamAt(0); // Retrieve an IOutputStream object and fill it with decrypted data. IOutputStream dest = unprotectedData.GetOutputStreamAt(0); await Provider.UnprotectStreamAsync(source, dest); await dest.FlushAsync(); // Write the decrypted data to an IBuffer object. DataReader reader2 = new DataReader(unprotectedData.GetInputStreamAt(0)); await reader2.LoadAsync((uint)unprotectedData.Size); IBuffer buffUnprotectedData = reader2.ReadBuffer((uint)unprotectedData.Size); // Convert the IBuffer object to a string using the same encoding that was // used previously to conver the plaintext string (before encryption) to an // IBuffer object. String strUnprotected = CryptographicBuffer.ConvertBinaryToString(encoding, buffUnprotectedData); // Return the decrypted data. return strUnprotected; } catch (Exception ex) { App.Telemetry.TrackException(ex); return ""; } }
public async Task<IRandomAccessStream> GetRandomStream() { if (Data == null) { return null; } else { var buffer = this.GetBuffer(); InMemoryRandomAccessStream inStream = new InMemoryRandomAccessStream(); DataWriter datawriter = new DataWriter(inStream.GetOutputStreamAt(0)); datawriter.WriteBuffer(buffer, 0, buffer.Length); await datawriter.StoreAsync(); return inStream; } }
public async Task<IBuffer> Encrypt(string descriptor, string strMsg, BinaryStringEncoding encoding) { // Create a DataProtectionProvider object for the specified descriptor. DataProtectionProvider Provider = new DataProtectionProvider(descriptor); // Convert the input string to a buffer. IBuffer buffMsg = CryptographicBuffer.ConvertStringToBinary(strMsg, encoding); // Create a random access stream to contain the plaintext message. InMemoryRandomAccessStream inputData = new InMemoryRandomAccessStream(); // Create a random access stream to contain the encrypted message. InMemoryRandomAccessStream protectedData = new InMemoryRandomAccessStream(); // Retrieve an IOutputStream object and fill it with the input (plaintext) data. IOutputStream outputStream = inputData.GetOutputStreamAt(0); DataWriter writer = new DataWriter(outputStream); writer.WriteBuffer(buffMsg); await writer.StoreAsync(); await outputStream.FlushAsync(); // Retrieve an IInputStream object from which you can read the input data. IInputStream source = inputData.GetInputStreamAt(0); // Retrieve an IOutputStream object and fill it with encrypted data. IOutputStream dest = protectedData.GetOutputStreamAt(0); await Provider.ProtectStreamAsync(source, dest); await dest.FlushAsync(); //Verify that the protected data does not match the original DataReader reader1 = new DataReader(inputData.GetInputStreamAt(0)); DataReader reader2 = new DataReader(protectedData.GetInputStreamAt(0)); await reader1.LoadAsync((uint)inputData.Size); await reader2.LoadAsync((uint)protectedData.Size); IBuffer buffOriginalData = reader1.ReadBuffer((uint)inputData.Size); IBuffer buffProtectedData = reader2.ReadBuffer((uint)protectedData.Size); if (CryptographicBuffer.Compare(buffOriginalData, buffProtectedData)) { throw new Exception("ProtectStreamAsync returned unprotected data"); } // Return the encrypted data. return buffProtectedData; }
private async Task PlaceIconAsync(string tag, double probability, Rect boundingBox) { if (probability < 0.4) { foreach (var stroke in _sessionStrokes) { _allStrokes.Add(stroke); } } else { var icon = await GetIconFileAsync(tag); if (icon == null) { return; } var bytes = await FileIO.ReadBufferAsync(icon); var ms = new InMemoryRandomAccessStream(); var dw = new Windows.Storage.Streams.DataWriter(ms); dw.WriteBuffer(bytes); await dw.StoreAsync(); ms.Seek(0); var bm = new BitmapImage(); await bm.SetSourceAsync(ms); var wb = new WriteableBitmap(bm.PixelWidth, bm.PixelHeight); ms.Seek(0); await wb.SetSourceAsync(ms); var newBitmap = wb.Resize((int)boundingBox.Width, (int)boundingBox.Height, WriteableBitmapExtensions.Interpolation.Bilinear); var image = new Image(); image.Source = newBitmap; Canvas.SetTop(image, boundingBox.Top); Canvas.SetLeft(image, boundingBox.Left); iconCanvas.Children.Add(image); } }
public async void sendMail(string strSendTo,string strContent , Boolean hasPicture) { HostName hostName = new HostName(hostIP); StreamSocket socket = new StreamSocket(); List<string[]> storeList = new List<string[]>(); try { await socket.ConnectAsync(hostName, port); } catch (Exception exception) { if (SocketError.GetStatus(exception.HResult) == SocketErrorStatus.Unknown) { throw; } } StorageFolder folder = await ApplicationData.Current.LocalFolder.GetFolderAsync("Temp"); StorageFile pic = await folder.GetFileAsync("MyPainter.png"); IBuffer buffer = await FileIO.ReadBufferAsync(pic); DataWriter writer = new DataWriter(socket.OutputStream); writer.WriteUInt32(writer.MeasureString(strSendTo)); writer.WriteString(strSendTo); writer.WriteUInt32(writer.MeasureString(strContent)); writer.WriteString(strContent); if (hasPicture) { writer.WriteUInt32((uint)buffer.Length); writer.WriteBuffer(buffer); } else { writer.WriteUInt32(0); writer.WriteString(""); } await writer.StoreAsync(); writer.DetachStream(); writer.Dispose(); socket.Dispose(); }
private static async Task<StorageFile> SavePhotoAsync(FilteredPhotoModel photo, StorageFile file) { CachedFileManager.DeferUpdates(file); using (var fileStream = await file.OpenAsync(Windows.Storage.FileAccessMode.ReadWrite)) using (var photoStream = await photo.GetFilteredPhotoAsync()) using (var reader = new DataReader(photoStream)) using (var writer = new DataWriter(fileStream)) { await reader.LoadAsync((uint)photoStream.Size); var buffer = reader.ReadBuffer((uint)photoStream.Size); writer.WriteBuffer(buffer); await writer.StoreAsync(); await writer.FlushAsync(); } var status = await CachedFileManager.CompleteUpdatesAsync(file); if (status == Windows.Storage.Provider.FileUpdateStatus.Complete) { return file; } else { return null; } }
public override async void receive_file(String devicename, String add, int not) { try { _httpurl = new Uri(add); _httpprogress = new Progress<HttpProgress>(ProgressHandler); HttpRequestMessage request = new HttpRequestMessage(new HttpMethod("GET"), _httpurl); HttpBaseProtocolFilter filter = new HttpBaseProtocolFilter(); filter.CacheControl.ReadBehavior = HttpCacheReadBehavior.MostRecent; filter.CacheControl.WriteBehavior = HttpCacheWriteBehavior.NoCache; _httpclient = new HttpClient(filter); _cancel_token_source = new CancellationTokenSource(); _cancel_token = _cancel_token_source.Token; scan_network_speed(); _stopwatch.Start(); _httpresponse = await _httpclient.SendRequestAsync(request).AsTask(_cancel_token, _httpprogress); StorageFolder folder = KnownFolders.PicturesLibrary; StorageFile file = await folder.CreateFileAsync(this.filepath, CreationCollisionOption.ReplaceExisting); IRandomAccessStream filestream = await file.OpenAsync(FileAccessMode.ReadWrite); IOutputStream filewriter = filestream.GetOutputStreamAt(0); _datawriter = new DataWriter(filewriter); _timer.Cancel(); _transferspeed /= 1024; _message = format_message(_stopwatch.Elapsed, "Transferspeed", _transferspeed.ToString(), " kB/s"); this.callback.on_transfer_speed_change(_message, this.results); this.main_view.text_to_logs(_message.Replace("\t", " ")); _stopwatch.Stop(); _buffer = await _httpresponse.Content.ReadAsBufferAsync(); _datawriter.WriteBuffer(_buffer); await _datawriter.StoreAsync(); _datawriter.Dispose(); filewriter.Dispose(); filestream.Dispose(); _httpresponse.Content.Dispose(); _httpresponse.Dispose(); _httpclient.Dispose(); _message = format_message(_stopwatch.Elapsed, "File Transfer", "OK", this.filepath); this.callback.on_file_received(_message, this.results); this.main_view.text_to_logs(_message.Replace("\t", " ")); } catch (Exception e) { append_error_tolog(e, _stopwatch.Elapsed, ""); } }
public async Task<bool> DownloadFileAsync(string ftpFile, string localFile, Boolean resume) { CheckLoggedIn(); var response = await ExecuteAsync("TYPE I"); response.CheckReturnCode(200); Debug.WriteLine("Downloading file " + ftpFile + " from " + HostName + "/" + WorkingDirectory, "FtpClient"); if (string.IsNullOrEmpty(localFile)) { localFile = ftpFile; } var tempFile = await ApplicationData.Current.TemporaryFolder.CreateFileAsync(localFile, CreationCollisionOption.OpenIfExists); var tempStream = await tempFile.OpenStreamForWriteAsync(); StreamSocket dataSocket = await OpenSocketForTransferAsync(); ulong resumeOffset = 0; if (resume) { var prop = await tempFile.GetBasicPropertiesAsync(); resumeOffset = prop.Size; if (resumeOffset > 0) { response = await ExecuteAsync("REST " + resumeOffset); if (response.ReturnCode != 350) { resumeOffset = 0; Debug.WriteLine("Resuming not supported:" + response.Message, "FtpClient"); } else { Debug.WriteLine("Resuming at offset " + resumeOffset, "FtpClient"); tempStream.Seek(Convert.ToInt64(resumeOffset), SeekOrigin.Begin); } } } response = await ExecuteAsync("RETR " + ftpFile); response.CheckReturnCode(150, 125); var reader = new DataReader(dataSocket.InputStream); reader.InputStreamOptions = InputStreamOptions.Partial; var writer = new DataWriter(tempStream.AsOutputStream()); DateTime timeout = DateTime.Now.AddSeconds(TimeOut); while (timeout > DateTime.Now) { var count = await reader.LoadAsync(BUFFER_SIZE); var bytes = reader.ReadBuffer(count); writer.WriteBuffer(bytes); await writer.StoreAsync(); if (count < BUFFER_SIZE) { break; } } await tempStream.FlushAsync(); dataSocket.Dispose(); response = await ReadResponseAsync(); response.CheckReturnCode(226, 250); var props = await tempFile.GetBasicPropertiesAsync(); var tempSize = props.Size; var size = await GetFileSizeAsync(ftpFile); if (tempSize != size) return false; var destFile = await ApplicationData.Current.LocalFolder.CreateFileAsync(localFile, CreationCollisionOption.ReplaceExisting); var destStream = await destFile.OpenStreamForWriteAsync(); tempStream.Seek(0, SeekOrigin.Begin); await tempStream.CopyToAsync(destStream); await destStream.FlushAsync(); await tempFile.DeleteAsync(StorageDeleteOption.PermanentDelete); return true; }
private async Task<StorageFile> RotateImage(int rotation, IStorageFile file) { var data = await FileIO.ReadBufferAsync(file); var ms = new InMemoryRandomAccessStream(); var dw = new DataWriter(ms); dw.WriteBuffer(data); await dw.StoreAsync(); ms.Seek(0); var bm = new BitmapImage(); await bm.SetSourceAsync(ms); var wb = new WriteableBitmap(bm.PixelHeight, bm.PixelWidth); ms.Seek(0); await wb.SetSourceAsync(ms); var rotated = wb.Rotate(rotation); var result = await this.SaveCroppedImage(rotated); return result; }
private static IBuffer getsdpRecordBlob(string serviceName, string serviceDescriptor) { DataWriter helperWriter = new DataWriter(); DataWriter NameWriter = new DataWriter(); // The length of the UTF-8 encoded string. NameWriter.WriteByte((byte)serviceName.Length); // The UTF-8 encoded string. NameWriter.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf8; NameWriter.WriteString(serviceName); // UINT16 (0x09) value = 0x0100 [ServiceName] helperWriter.WriteByte(0x09); helperWriter.WriteByte(0x01); helperWriter.WriteByte(0x00); IBuffer serviceNameBuf = NameWriter.DetachBuffer(); helperWriter.WriteByte(0x25); //TextString(0x25) helperWriter.WriteByte((byte)serviceNameBuf.Length); helperWriter.WriteBuffer(serviceNameBuf); DataWriter DescriptorWriter = new DataWriter(); // The length of the UTF-8 encoded string. DescriptorWriter.WriteByte((byte)serviceDescriptor.Length); // The UTF-8 encoded string. DescriptorWriter.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf8; DescriptorWriter.WriteString(serviceDescriptor); // UINT16 (0x09) value = 0x0101 [ServiceDescription] helperWriter.WriteByte(0x09); helperWriter.WriteByte(0x01); helperWriter.WriteByte(0x01); IBuffer descriptorBuf = DescriptorWriter.DetachBuffer(); helperWriter.WriteByte(0x25); //TextString(0x25) helperWriter.WriteByte((byte)descriptorBuf.Length); helperWriter.WriteBuffer(descriptorBuf); DataWriter SdpRecordWriter = new DataWriter(); SdpRecordWriter.WriteByte(0x35); IBuffer dataBuf = helperWriter.DetachBuffer(); SdpRecordWriter.WriteByte((byte)dataBuf.Length); SdpRecordWriter.WriteBuffer(dataBuf); return SdpRecordWriter.DetachBuffer(); }
private async Task<StorageFile> SaveTemporaryPhotoAsync(FilteredPhotoModel photo) { var filename = Application.Current.Resources["PhotoSaveTemporaryFilename"] as string; var folder = ApplicationData.Current.TemporaryFolder; var task = folder.CreateFileAsync(filename, Windows.Storage.CreationCollisionOption.ReplaceExisting).AsTask(); task.Wait(); var file = task.Result; CachedFileManager.DeferUpdates(file); using (var fileStream = await file.OpenAsync(Windows.Storage.FileAccessMode.ReadWrite)) using (var photoStream = await photo.GetFilteredPhotoAsync()) using (var reader = new DataReader(photoStream)) using (var writer = new DataWriter(fileStream)) { await reader.LoadAsync((uint)photoStream.Size); var buffer = reader.ReadBuffer((uint)photoStream.Size); writer.WriteBuffer(buffer); await writer.StoreAsync(); await writer.FlushAsync(); } var status = await CachedFileManager.CompleteUpdatesAsync(file); if (status == Windows.Storage.Provider.FileUpdateStatus.Complete) { return file; } else { return null; } }
public override async void send_file(String devicename, String bluid, int not) { try { _stopwatch.Start(); PeerFinder.AllowBluetooth = true; PeerFinder.AlternateIdentities["Bluetooth:SDP"] = "{" + bluid + "}"; var peers = await PeerFinder.FindAllPeersAsync(); foreach (var p in peers) { if (p.DisplayName.Equals(devicename)) { _peer_info = p; break; } } _bluetooth_client = new StreamSocket(); if (_peer_info.ServiceName.Equals("")) { await _bluetooth_client.ConnectAsync(_peer_info.HostName, "{" + bluid + "}"); } else { await _bluetooth_client.ConnectAsync(_peer_info.HostName, _peer_info.ServiceName); } StorageFolder folder = KnownFolders.PicturesLibrary; StorageFile file = await folder.GetFileAsync(this.filepath); IRandomAccessStreamWithContentType filestream = await file.OpenReadAsync(); _length = (uint)filestream.Size; _ibuffer = new Windows.Storage.Streams.Buffer(_length); _datareader = new DataReader(filestream); await _datareader.LoadAsync(_length); _ibuffer = _datareader.ReadBuffer(_length); _datawriter = new DataWriter(_bluetooth_client.OutputStream); _datawriter.WriteBuffer(_ibuffer); await _datawriter.StoreAsync(); filestream.Dispose(); _datareader.Dispose(); _datawriter.Dispose(); _datareader = new DataReader(_bluetooth_client.InputStream); _datareader.InputStreamOptions = InputStreamOptions.Partial; scan_received_acks(); while (true) { uint count = await _datareader.LoadAsync(4); byte[] ack = new byte[count]; _datareader.ReadBytes(ack); _counter_all_acks += BitConverter.ToInt32(ack, 0); if ((uint)_counter_all_acks == _length) break; } _datareader.Dispose(); _bluetooth_client.Dispose(); _message = format_message(_stopwatch.Elapsed, "File Transfer", "OK", this.filepath); this.callback.on_file_received(_message, this.results); this.main_view.text_to_logs(_message.Replace("\t", " ")); _ack_timer.Cancel(); _stopwatch.Stop(); } catch (Exception e) { append_error_tolog(e, _stopwatch.Elapsed, devicename); } }
/// <summary> /// Function to format provisioning package into chunk data with a NfcProvHeader prefix. /// </summary> /// <param name="content">IBuffer to the provisioning package content.</param> /// <param name="device">ProximityDevice instance passed in the messageHandler.</param> /// <param name="messageHandler">Delegate handler to consume the chunk data.</param> private static async Task ConvertToNfcMessageAsync(IBuffer content, ProximityDevice device, Func<ProximityDevice, IBuffer, CancellationToken, Task> messageHandlerAsync, CancellationToken ct) { var maxMessageSize = device.MaxMessageBytes; var headerSize = GetNfcProvHeaderSize(); uint chunkSize = maxMessageSize - (uint)headerSize; // Calculate the chunk count needed for this transfer. uint chunks = content.Length / chunkSize; if ((content.Length % chunkSize) > 0) { ++chunks; } // Loop and compose the payload per chunk data. for (uint posToRead = 0; posToRead < content.Length; posToRead += chunkSize) { var dataWriter = new DataWriter(); var header = new NfcProvHeader(); header.version = NFC_PROV_MESSAGE_CURRENT_VERSION; // Currently the supported version is 0x00. header.leading = NFC_PROV_MESSAGE_LEADING_BYTE; // The leading byte should be always 0xFF. header.index = (byte)(posToRead / chunkSize); // To specify which chunk to this message. header.total = (byte)chunks; // To specify the total message count for this transfer. int bufferSizeToAlloc = (int)maxMessageSize; if (header.total == (header.index + 1)) { bufferSizeToAlloc = headerSize + (int)(content.Length - posToRead); } // Write the prefix first and the chunk data of the provisioning package. dataWriter.WriteBytes(GetBytes(header)); dataWriter.WriteBuffer(content, posToRead, (uint)(bufferSizeToAlloc - headerSize)); // Invoke the delegate handler to handle the NFC message. await messageHandlerAsync(device, dataWriter.DetachBuffer(), ct); } }
/// <summary> /// this is used when the user selects save to file /// </summary> /// <remarks> /// to implement this, we will need to create and instance of the save file picker /// then write the output stream into a file /// </remarks> /// <param name="sender"></param> /// <param name="e"></param> private async void BtnSaveToFile_Click(object sender, RoutedEventArgs e) { string text = this.tbData.Text; // select the file to save this data to FileSavePicker savePicker = new FileSavePicker(); savePicker.DefaultFileExtension = ".wav"; // this is the only type available savePicker.FileTypeChoices.Add("Audio file", new List<string>() { ".wav" }); StorageFile file = await savePicker.PickSaveFileAsync(); if (file != null) { this.btnSaveToFile.IsEnabled = false; // create the data stream SpeechSynthesisStream synthesisStream; try { synthesisStream = await this.synthesizer.SynthesizeSsmlToStreamAsync(text); } catch (Exception) { synthesisStream = null; this.btnSaveToFile.IsEnabled = true; } if (synthesisStream == null) { MessageDialog dialog = new MessageDialog("unable to synthesize text"); await dialog.ShowAsync(); return; } // open the output stream Windows.Storage.Streams.Buffer buffer = new Windows.Storage.Streams.Buffer(4096); IRandomAccessStream writeStream = (IRandomAccessStream)await file.OpenAsync(FileAccessMode.ReadWrite); IOutputStream outputStream = writeStream.GetOutputStreamAt(0); DataWriter dataWriter = new DataWriter(outputStream); // copy the stream data into the file while (synthesisStream.Position < synthesisStream.Size) { await synthesisStream.ReadAsync(buffer, 4096, InputStreamOptions.None); dataWriter.WriteBuffer(buffer); } // close the data file streams dataWriter.StoreAsync().AsTask().Wait(); outputStream.FlushAsync().AsTask().Wait(); this.btnSaveToFile.IsEnabled = true; } }
public async void SampleDataProtectionStream(String descriptor) { EncryptDecryptText.Text += "*** Sample Stream Data Protection for " + descriptor + " ***\n"; IBuffer data = CryptographicBuffer.GenerateRandom(10000); DataReader reader1, reader2; IBuffer buff1, buff2; DataProtectionProvider Provider = new DataProtectionProvider(descriptor); InMemoryRandomAccessStream originalData = new InMemoryRandomAccessStream(); //Populate the new memory stream IOutputStream outputStream = originalData.GetOutputStreamAt(0); DataWriter writer = new DataWriter(outputStream); writer.WriteBuffer(data); await writer.StoreAsync(); await outputStream.FlushAsync(); //open new memory stream for read IInputStream source = originalData.GetInputStreamAt(0); //Open the output memory stream InMemoryRandomAccessStream protectedData = new InMemoryRandomAccessStream(); IOutputStream dest = protectedData.GetOutputStreamAt(0); // Protect await Provider.ProtectStreamAsync(source, dest); //Flush the output if (await dest.FlushAsync()) EncryptDecryptText.Text += " Protected output was successfully flushed\n"; //Verify the protected data does not match the original reader1 = new DataReader(originalData.GetInputStreamAt(0)); reader2 = new DataReader(protectedData.GetInputStreamAt(0)); await reader1.LoadAsync((uint)originalData.Size); await reader2.LoadAsync((uint)protectedData.Size); EncryptDecryptText.Text += " Size of original stream: " + originalData.Size + "\n"; EncryptDecryptText.Text += " Size of protected stream: " + protectedData.Size + "\n"; if (originalData.Size == protectedData.Size) { buff1 = reader1.ReadBuffer((uint)originalData.Size); buff2 = reader2.ReadBuffer((uint)protectedData.Size); if (CryptographicBuffer.Compare(buff1, buff2)) { EncryptDecryptText.Text += "ProtectStreamAsync returned unprotected data"; return; } } EncryptDecryptText.Text += " Stream Compare completed. Streams did not match.\n"; source = protectedData.GetInputStreamAt(0); InMemoryRandomAccessStream unprotectedData = new InMemoryRandomAccessStream(); dest = unprotectedData.GetOutputStreamAt(0); // Unprotect DataProtectionProvider Provider2 = new DataProtectionProvider(); await Provider2.UnprotectStreamAsync(source, dest); if (await dest.FlushAsync()) EncryptDecryptText.Text += " Unprotected output was successfully flushed\n"; //Verify the unprotected data does match the original reader1 = new DataReader(originalData.GetInputStreamAt(0)); reader2 = new DataReader(unprotectedData.GetInputStreamAt(0)); await reader1.LoadAsync((uint)originalData.Size); await reader2.LoadAsync((uint)unprotectedData.Size); EncryptDecryptText.Text += " Size of original stream: " + originalData.Size + "\n"; EncryptDecryptText.Text += " Size of unprotected stream: " + unprotectedData.Size + "\n"; buff1 = reader1.ReadBuffer((uint)originalData.Size); buff2 = reader2.ReadBuffer((uint)unprotectedData.Size); if (!CryptographicBuffer.Compare(buff1, buff2)) { EncryptDecryptText.Text += "UnrotectStreamAsync did not return expected data"; return; } EncryptDecryptText.Text += "*** Done!\n"; }
private async Task<IRandomAccessStream> GetThumbnailStreamAsync() { #if DEBUG System.Diagnostics.Debug.WriteLine("GetThumbnailStreamAsync invoked " + this.GetHashCode()); #endif var maximumSide = (int)Windows.UI.Xaml.Application.Current.Resources["ThumbnailSide"]; var orientation = await GetPhotoOrientationAsync(); var orientationValue = orientation.HasValue ? orientation.Value : PhotoOrientation.Unspecified; #if WINDOWS_PHONE_APP // TODO Getting platform thumbnails is currently broken in the WP8.1 preview SDK, // thus generating thumbnails from the large original photos. Change to platform // thumbnails again when platform is live & fine. var size = await GetPhotoResolutionAsync(); using (var stream = await GetPhotoAsync()) { return await ResizeStreamAsync(stream, new Size(maximumSide, maximumSide), orientationValue); } #else using (var stream = await _file.GetThumbnailAsync(Windows.Storage.FileProperties.ThumbnailMode.PicturesView)) { if (stream.ContentType == "image/jpeg") { if (stream.OriginalWidth <= maximumSide || stream.OriginalHeight <= maximumSide) { using (var memoryStream = new InMemoryRandomAccessStream()) { using (var reader = new DataReader(stream)) using (var writer = new DataWriter(memoryStream)) { await reader.LoadAsync((uint)stream.Size); var buffer = reader.ReadBuffer((uint)stream.Size); writer.WriteBuffer(buffer); await writer.StoreAsync(); await writer.FlushAsync(); return memoryStream.CloneStream(); } } } else { return await ResizeStreamAsync(stream, new Size(maximumSide, maximumSide), orientationValue); } } else { using (var preview = await GetPreviewAsync()) { return await ResizeStreamAsync(preview, new Size(maximumSide, maximumSide), orientationValue); } } } #endif }
public async Task UsingDataWriter() { var inMem = new InMemoryRandomAccessStream(); var datawriter = new DataWriter(inMem); var starterBytes = CryptographicBuffer.GenerateRandom(32).AsBytes(); var mStream = CryptographicBuffer.GenerateRandom(1024 * 1024).AsBytes(); MemoryStream outStream = new System.IO.MemoryStream(); var tinyStream = ConfigureStream(outStream, PwCompressionAlgorithm.GZip, true); await tinyStream.WriteAsync(starterBytes, 0, starterBytes.Length); await tinyStream.WriteAsync(mStream, 0, mStream.Length); tinyStream.Dispose(); byte[] bb = outStream.ToArray(); var source = bb.AsBuffer(); var aesKey = CryptographicBuffer.GenerateRandom(32); var iv = CryptographicBuffer.GenerateRandom(16); var encrypted = EncryptDatabase(source, aesKey, iv); CollectionAssert.AreNotEqual(mStream, encrypted.AsBytes()); datawriter.WriteBuffer(encrypted); await datawriter.StoreAsync(); datawriter.DetachStream(); datawriter.Dispose(); var i = inMem.GetInputStreamAt(0); var datareader = new DataReader(i); datareader.ByteOrder = ByteOrder.LittleEndian; await datareader.LoadAsync((uint)inMem.Size); var fromStrea = datareader.ReadBuffer(datareader.UnconsumedBufferLength); var decryped = DecryptDatabase(fromStrea, aesKey, iv); Stream bigStream = ConfigureStream(new MemoryStream(decryped.AsBytes()), PwCompressionAlgorithm.GZip, false); System.IO.MemoryStream bigStreamOut = new System.IO.MemoryStream(); bigStream.CopyTo(bigStreamOut); var buffer1 = CryptographicBuffer.CreateFromByteArray(bigStreamOut.ToArray()); var reader = DataReader.FromBuffer(buffer1); var x = reader.ReadBuffer(32).AsBytes(); CollectionAssert.AreEqual(starterBytes, x); }
private async Task SendResponseAsync(StreamSocket socket, HttpResponseMessage response) { if (socket == null) return; _logger.Trace("Pipeline => HttpServer.SendResponseAsync"); try { if (response == null) { string errorPage = HtmlFactory.HttpResponse("utf-8", "Not Found", "Opps, page not found"); response.Content = new HttpStringContent(errorPage, UnicodeEncoding.Utf8, "text/html"); response.StatusCode = HttpStatusCode.NotFound; response.ReasonPhrase = "Not Found"; response.Headers.Add("Connection", "close"); } //if (response.Content == null) // response.Content = new HttpStringContent(string.Empty); //ulong contentLength = await response.Content.BufferAllAsync(); //if (contentLength == 0) // return; using (DataWriter outputWriter = new DataWriter(socket.OutputStream)) { string htmlVersion; switch (response.Version) { case HttpVersion.Http10: htmlVersion = "HTTP/1.0"; break; case HttpVersion.Http20: htmlVersion = "HTTP/2.0"; break; default: htmlVersion = "HTTP/1.1"; break; } outputWriter.UnicodeEncoding = UnicodeEncoding.Utf8; outputWriter.WriteString(string.Format("{0} {1} {2}\r\n", htmlVersion, (int)response.StatusCode, response.StatusCode)); foreach (var item in response.Headers) { outputWriter.WriteString(string.Format("{0}: {1}\r\n", item.Key, item.Value)); } foreach (var item in response.Content.Headers) { outputWriter.WriteString(string.Format("{0}: {1}\r\n", item.Key, item.Value)); } //string ret = "Set-Cookie: {0}={1}; Path={2}; Expires={3};\r\n"; outputWriter.WriteString("\r\n"); var bodyContent = await response.Content.ReadAsBufferAsync(); outputWriter.WriteBuffer(bodyContent); await outputWriter.StoreAsync(); //await outputWriter.FlushAsync(); } } catch (Exception ex) { _logger.Error("Http request failed with error: {0}", ex.Message, ex); } finally { if (socket != null) socket.Dispose(); _logger.Debug("Connection from {0}:{1} to {2}:{3} was closed", socket.Information.RemoteHostName.DisplayName, socket.Information.RemotePort, socket.Information.LocalAddress.DisplayName, socket.Information.LocalPort); } }
private async Task<BitmapImage> doDecode(ImageLoaderQueueItem item, IBuffer buffer) { if (buffer != null) { try { InMemoryRandomAccessStream stream = new InMemoryRandomAccessStream(); DataWriter datawriter = new DataWriter(stream.GetOutputStreamAt(0)); datawriter.WriteBuffer(buffer, 0, buffer.Length); await datawriter.StoreAsync(); BitmapImage image = new BitmapImage(); image.SetSource(stream); return image; } catch { } } return null; }
private async Task<string> CreateSpeechSynthesisFile(TTSMessage item) { string filename = String.Format("{0}.wav", Guid.NewGuid()); try { // get system voice that matches the gender var voice = (from v in voices where v.Gender == (Windows.Media.SpeechSynthesis.VoiceGender)item.VoiceGender.VoiceGenderId select v).FirstOrDefault<VoiceInformation>(); synthesizer.Voice = voice; // create the data stream SpeechSynthesisStream synthesisStream; try { synthesisStream = await synthesizer.SynthesizeTextToStreamAsync(item.Message); } catch (Exception ex) { ri.SendException("Unable to synthesize text", ex); synthesisStream = null; return string.Empty; } ri.SendMessage("Creating file '{0}'", filename); StorageFolder folder = await StorageFolder.GetFolderFromPathAsync("C:\\temp\\TTS"); //Windows.Storage.KnownFolders.DocumentsLibrary;// Windows.Storage.ApplicationData.Current.LocalFolder; var option = CreationCollisionOption.ReplaceExisting; StorageFile file = await folder.CreateFileAsync(filename, option); ri.SendMessage("File '{0}' created. Text to speech synthesis has started...", file.Path); // open the output stream Windows.Storage.Streams.Buffer buffer = new Windows.Storage.Streams.Buffer(4096); IRandomAccessStream writeStream = (IRandomAccessStream)await file.OpenAsync(FileAccessMode.ReadWrite); IOutputStream outputStream = writeStream.GetOutputStreamAt(0); DataWriter dataWriter = new DataWriter(outputStream); // copy the stream data into the file while (synthesisStream.Position < synthesisStream.Size) { await synthesisStream.ReadAsync(buffer, 4096, InputStreamOptions.None); dataWriter.WriteBuffer(buffer); } // close the data file streams dataWriter.StoreAsync().AsTask().Wait(); outputStream.FlushAsync().AsTask().Wait(); ri.SendMessage("Text to speech synthesis completed for file '{0}'", file.Name); } catch (Exception e) { ri.SendException(e); return String.Empty; } return filename; }
public Task<byte[]> GetImage() { var tsk = new TaskCompletionSource<byte[]>(); RunInUI(async () => { var file = await oPicker.PickSingleFileAsync(); if (file == null) { tsk.SetResult(null); return; } CachedFileManager.DeferUpdates(file); var memStream = new InMemoryRandomAccessStream(); using (var writer = new DataWriter(memStream.GetOutputStreamAt(0))) { var buf = await FileIO.ReadBufferAsync(file); writer.WriteBuffer(buf, 0, buf.Length); await writer.StoreAsync(); } BitmapDecoder decoder = await BitmapDecoder.CreateAsync(memStream); var ret = await decoder.GetPixelDataAsync(BitmapPixelFormat.Rgba8, BitmapAlphaMode.Premultiplied, nullTransform, ExifOrientationMode.IgnoreExifOrientation, ColorManagementMode.DoNotColorManage); tsk.SetResult(ret.DetachPixelData()); await CachedFileManager.CompleteUpdatesAsync(file); }); return tsk.Task; }
public static async Task<bool> TryWriteBufferAsync(this StorageFile storageFile, IBuffer buffer, uint start, uint count) { try { using (StorageStreamTransaction transaction = await storageFile.OpenTransactedWriteAsync()) { using (DataWriter dataWriter = new DataWriter(transaction.Stream)) { dataWriter.WriteBuffer(buffer, start, count); transaction.Stream.Size = await dataWriter.StoreAsync(); await transaction.CommitAsync(); return true; } } } catch { return false; } }