public StoreAsync ( ) : DataWriterStoreOperation | ||
return | DataWriterStoreOperation |
private async void Update() { var writer1 = new BarcodeWriter { Format = BarcodeFormat.QR_CODE, Options = new ZXing.Common.EncodingOptions { Height = 200, Width = 200 }, }; var image = writer1.Write(Text);//Write(text); using (InMemoryRandomAccessStream ms = new InMemoryRandomAccessStream()) { using (DataWriter writer = new DataWriter(ms.GetOutputStreamAt(0))) { writer.WriteBytes(image); await writer.StoreAsync(); } var output = new BitmapImage(); await output.SetSourceAsync(ms); ImageSource = output; } }
private async Task WriteToOutputStreamAsync(byte[] bytes) { if (_socket == null) return; _writer = new DataWriter(_socket.OutputStream); _writer.WriteBytes(bytes); var debugString = UTF8Encoding.UTF8.GetString(bytes, 0, bytes.Length); try { await _writer.StoreAsync(); await _socket.OutputStream.FlushAsync(); _writer.DetachStream(); _writer.Dispose(); } catch (Exception exception) { // If this is an unknown status it means that the error if fatal and retry will likely fail. if (global::Windows.Networking.Sockets.SocketError.GetStatus(exception.HResult) == global::Windows.Networking.Sockets.SocketErrorStatus.Unknown) { // TODO abort any retry attempts on Unity side throw; } } }
protected override async void OnShareTargetActivated(ShareTargetActivatedEventArgs args) { if (args.ShareOperation.Data.Contains(StandardDataFormats.WebLink)) { Uri uri = await args.ShareOperation.Data.GetWebLinkAsync(); if (null != uri) try { using (var socket = new MessageWebSocket()) { socket.Control.MessageType = SocketMessageType.Utf8; await socket.ConnectAsync(new Uri("ws://" + settings["Host"].ToString() + ":" + settings["Port"].ToString())); using (var writer = new DataWriter(socket.OutputStream)) { writer.WriteString(uri.AbsoluteUri); await writer.StoreAsync(); args.ShareOperation.ReportCompleted(); } } } catch { show(); } } }
private async void WriteFile(string s) { Windows.Storage.StorageFolder storageFolder = Windows.Storage.ApplicationData.Current.LocalFolder; Windows.Storage.StorageFile sampleFile = await storageFolder.GetFileAsync("dsp_data.txt"); try { var stream = await sampleFile.OpenAsync(Windows.Storage.FileAccessMode.ReadWrite); using (var outputStream = stream.GetOutputStreamAt(stream.Size)) { using (var dataWriter = new Windows.Storage.Streams.DataWriter(outputStream)) { dataWriter.WriteString(s); await dataWriter.StoreAsync(); await outputStream.FlushAsync(); } } stream.Dispose(); } catch (Exception E) { } }
public static async Task<bool> ConnectAsync() { if (imageComparisonServer != null) return true; try { imageComparisonServer = new StreamSocket(); await imageComparisonServer.ConnectAsync(new HostName(ParadoxImageServerHost), ParadoxImageServerPort.ToString()); // Send initial parameters using (var memoryStream = new MemoryStream()) { var binaryWriter = new BinaryWriter(memoryStream); ImageTestResultConnection.Write(binaryWriter); var dataWriter = new DataWriter(imageComparisonServer.OutputStream); dataWriter.WriteBytes(memoryStream.ToArray()); await dataWriter.StoreAsync(); await dataWriter.FlushAsync(); dataWriter.DetachStream(); } return true; } catch (Exception) { imageComparisonServer = null; return false; } }
public object Convert(object value, Type targetType, object parameter, string language) { if (value != null) { byte[] bytes = (byte[])value; BitmapImage myBitmapImage = new BitmapImage(); if (bytes.Count() > 0) { InMemoryRandomAccessStream stream = new InMemoryRandomAccessStream(); DataWriter writer = new DataWriter(stream.GetOutputStreamAt(0)); writer.WriteBytes(bytes); writer.StoreAsync().GetResults(); myBitmapImage.SetSource(stream); } else { myBitmapImage.UriSource = new Uri("ms-appx:///Assets/firstBackgroundImage.jpg"); } return myBitmapImage; } else { return new BitmapImage(); } }
public async void SendMessage(string msg) { HostName hostName; try { hostName = new HostName("localhost"); } catch (ArgumentException) { return; } StreamSocket socket; try { using (socket = new StreamSocket()) { await socket.ConnectAsync(hostName, port2); //CoreApplication.Properties.Add("connected", null); DataWriter dw = new DataWriter(socket.OutputStream); dw.WriteString(msg); await dw.StoreAsync(); } } catch { //break; } }
public async Task Send(WemosMessage msg) { if (msg != null) { var str = msg.ToDto(); if (!string.IsNullOrEmpty(str)) { try { // GetOutputStreamAsync can be called multiple times on a single DatagramSocket instance to obtain // IOutputStreams pointing to various different remote endpoints. The remote hostname given to // GetOutputStreamAsync can be a unicast, multicast or broadcast address. IOutputStream outputStream = await listenerSocket.GetOutputStreamAsync(new HostName(remoteMulticastAddress), remoteService); DataWriter writer = new DataWriter(outputStream); writer.WriteString(str); await writer.StoreAsync(); } catch (Exception exception) { // If this is an unknown status it means that the error is fatal and retry will likely fail. if (SocketError.GetStatus(exception.HResult) == SocketErrorStatus.Unknown) throw; //rootPage.NotifyUser("Send failed with error: " + exception.Message, NotifyType.ErrorMessage); } } } }
public object Convert(object value, Type targetType, object parameter, string language) { if (value != null && value is byte[]) { //WriteableBitmap bitmap = new WriteableBitmap(100, 100); //System.IO.Stream bitmapStream = null; //bitmapStream = bitmap.PixelBuffer.AsStream(); //bitmapStream.Position = 0; //bitmapStream.Write(value as byte[], 0, (value as byte[]).Length); //bitmapStream.Flush(); InMemoryRandomAccessStream randomAccessStream = new InMemoryRandomAccessStream(); DataWriter writer = new DataWriter(randomAccessStream.GetOutputStreamAt(0)); writer.WriteBytes(value as byte[]); var x = writer.StoreAsync().AsTask().Result; BitmapImage image = new BitmapImage(); image.SetSource(randomAccessStream); return image; } return null; }
private async void OnWrite(Object sender, RoutedEventArgs e) { // 获取本地目录的引用 StorageFolder local = ApplicationData.Current.LocalFolder; // 创建新文件 StorageFile newFIle = await local.CreateFileAsync("demo.dat", CreationCollisionOption.ReplaceExisting); // 打开文件流 using(IRandomAccessStream stream = await newFIle.OpenAsync(FileAccessMode.ReadWrite)) { // 实例化 DataWriter DataWriter dw = new DataWriter(stream); // 设置默认编码格式 dw.UnicodeEncoding = UnicodeEncoding.Utf8; // 写入 bool 值 dw.WriteBoolean(true); // 写入日期值 DateTime dt = new DateTime(2010, 8, 21); dw.WriteDateTime(dt); // 写入字符串 string str = "测试文本"; // 计算字符串长度 uint len = dw.MeasureString(str); // 先写入字符串的长的 dw.WriteUInt32(len); // 再写入字符串 dw.WriteString(str); // 以下方法必须调用 await dw.StoreAsync(); // 解除 DataWriter 与流的关联 dw.DetachStream(); dw.Dispose(); } MessageDialog msgDlg = new MessageDialog("保存成功。"); await msgDlg.ShowAsync(); }
public object Convert(object value, Type targetType, object parameter, string language) { if (!(value is byte[])) { return null; } using (InMemoryRandomAccessStream ms = new InMemoryRandomAccessStream()) { // Writes the image byte array in an InMemoryRandomAccessStream // that is needed to set the source of BitmapImage. using (DataWriter writer = new DataWriter(ms.GetOutputStreamAt(0))) { writer.WriteBytes((byte[])value); // The GetResults here forces to wait until the operation completes // (i.e., it is executed synchronously), so this call can block the UI. writer.StoreAsync().GetResults(); } var image = new BitmapImage(); image.SetSource(ms); return image; } }
public async Task SendAsync(string text) { try { // DataWriter to send message to client var writer = new DataWriter(_socket.OutputStream); //Encrypt message byte[] data = Cryptographic.Encrypt(text, "123"); //Write Lenght message in buffer writer.WriteInt32(data.Length); //Write message in buffer writer.WriteBytes(data); //Send buffer await writer.StoreAsync(); //Clear buffer await writer.FlushAsync(); } catch (Exception e) { InvokeOnError(e.Message); } }
public async static void GetImageSize(this Stream imageStream) { var image = new BitmapImage(); byte[] imageBytes = Convert.FromBase64String(imageStream.ToBase64String()); MemoryStream ms = new MemoryStream(imageBytes, 0, imageBytes.Length); ms.Write(imageBytes, 0, imageBytes.Length); using (InMemoryRandomAccessStream stream = new InMemoryRandomAccessStream()) { using (DataWriter writer = new DataWriter(stream.GetOutputStreamAt(0))) { try { writer.WriteBytes(imageBytes); await writer.StoreAsync(); } catch (Exception) { // ignored } } try { await image.SetSourceAsync(stream); } catch (Exception) { // ignored } } ImageSize = new Size(image.PixelWidth, image.PixelHeight); }
/// <summary> /// Writes a string to a text file. /// </summary> /// <param name="text">The text to write.</param> /// <param name="fileName">Name of the file.</param> /// <param name="folder">The folder.</param> /// <param name="options"> /// The enum value that determines how responds if the fileName is the same /// as the name of an existing file in the current folder. Defaults to ReplaceExisting. /// </param> /// <returns></returns> public static async Task SaveAsync( this string text, string fileName, StorageFolder folder = null, CreationCollisionOption options = CreationCollisionOption.ReplaceExisting) { folder = folder ?? ApplicationData.Current.LocalFolder; var file = await folder.CreateFileAsync( fileName, options); using (var fs = await file.OpenAsync(FileAccessMode.ReadWrite)) { using (var outStream = fs.GetOutputStreamAt(0)) { using (var dataWriter = new DataWriter(outStream)) { if (text != null) dataWriter.WriteString(text); await dataWriter.StoreAsync(); dataWriter.DetachStream(); } await outStream.FlushAsync(); } } }
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); }
public async void PerformPeerDiscovery() { timer.Interval = new TimeSpan(0, 0, 5); timer.Start(); if (socket == null) { socket = new DatagramSocket(); socket.MessageReceived += socket_MessageReceived; try { await socket.BindEndpointAsync(null, "22002"); } catch { // Swallow any already bound exceptions! } } using (var outputStream = await socket.GetOutputStreamAsync(new HostName("230.0.0.1"), "22003")) { using (DataWriter wr = new DataWriter(outputStream)) { wr.WriteString("**BECHARMING DISCOVERY**"); await wr.FlushAsync(); await wr.StoreAsync(); } } }
public static async Task WriteFileAsync(string fileName, byte[] content) { try { var file = await ApplicationData.Current.LocalFolder.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting); using (var fileStream = await file.OpenAsync(FileAccessMode.ReadWrite)) { using (var outputStream = fileStream.GetOutputStreamAt(0)) { using (var dataWriter = new DataWriter(outputStream)) { dataWriter.WriteBytes(content); await dataWriter.StoreAsync(); dataWriter.DetachStream(); } await outputStream.FlushAsync(); } } } catch (Exception exception) { SnazzyDebug.WriteLine(exception); } }
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); }
async void BeginReadCCTV() { IsBeginRead = true; ISExit = false; tblCCTV cctvinfo=null; await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => { cctvinfo = this.DataContext as tblCCTV; }); // client=new HttpClient(); while (!ISExit) { try { Uri uri = new Uri("http://192.192.161.3/" + cctvinfo.REF_CCTV_ID.Trim() + ".jpg?" + rnd.Next(), UriKind.Absolute); using (httpClient = new HttpClient()) { httpClient.Timeout = TimeSpan.FromSeconds(0.5); var contentBytes = await httpClient.GetByteArrayAsync(uri); var ims = new InMemoryRandomAccessStream(); var dataWriter = new DataWriter(ims); dataWriter.WriteBytes(contentBytes); await dataWriter.StoreAsync(); //ims.seak 0 ims.Seek(0 ); await Dispatcher.RunAsync( Windows.UI.Core.CoreDispatcherPriority.Normal,()=> { BitmapImage bitmap = new BitmapImage(); bitmap.SetSource(ims ); this.imgCCTV.Source = bitmap; imginx = (imginx + 1) % 90000; this.RunFrameRate.Text = imginx.ToString(); }); } } catch (Exception ex) { // this.textBlock1.Text = ex.Message; } // BitmapImage img = new BitmapImage(); // img.SetSource(stream); } }
//req: // path file exist // m_words has words private async void saveData(StorageFile file) { //Debug.Assert(path != null); //Debug.Assert(System.IO.File.Exists(path)); Debug.Assert(m_words != null); //StorageFile file = await StorageFile.GetFileFromPathAsync(path); var stream = await file.OpenAsync(Windows.Storage.FileAccessMode.ReadWrite); var outputStream = stream.GetOutputStreamAt(0); var dataWriter = new Windows.Storage.Streams.DataWriter(outputStream); foreach (var w in m_words) { dataWriter.WriteString(w.ToString() + "\r\n"); } await dataWriter.StoreAsync(); await outputStream.FlushAsync(); dataWriter.Dispose(); outputStream.Dispose(); stream.Dispose(); }
async void datagramSocket_MessageReceived(DatagramSocket sender, DatagramSocketMessageReceivedEventArgs args) { i++; DataReader dataReader = args.GetDataReader(); uint length = dataReader.UnconsumedBufferLength; string content = dataReader.ReadString(length); Deployment.Current.Dispatcher.BeginInvoke(() => msgList.Children.Add(new TextBlock { Text = "服务器收到的消息:" + content })); //HostName hostName = new HostName("localhost"); //DatagramSocket datagramSocket = new DatagramSocket(); //IOutputStream outputStream = await datagramSocket.GetOutputStreamAsync(hostName, "22112"); DataWriter writer = new DataWriter(sender.OutputStream); writer.WriteString(content + "|" + i); try { await writer.StoreAsync(); msgList.Children.Add(new TextBlock { Text = "服务器发送的消息:" + content + "|" + i }); } catch (Exception err) { if (SocketError.GetStatus(err.HResult) == SocketErrorStatus.AddressAlreadyInUse) { } } }
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); } }
private async void doShipping(Order order) { try { StorageFile file = await KnownFolders.DocumentsLibrary.CreateFileAsync("dispatch-" + order.OrderID.ToString() + ".txt"); if (file != null) { string dispatchNote = "Order Summary: " + "\r\nOrder ID: " + order.OrderID + "\r\nOrder Total: " + String.Format("{0:C}", order.TotalValue); var stream = await file.OpenAsync(FileAccessMode.ReadWrite); var writeStream = stream.GetOutputStreamAt(0); DataWriter writer = new DataWriter(writeStream); writer.WriteString(dispatchNote); await writer.StoreAsync(); await writeStream.FlushAsync(); writeStream.Dispose(); } else { MessageDialog dlg = new MessageDialog(String.Format("Unable to save to file: {0}", file.DisplayName), "Not saved"); dlg.ShowAsync(); } } catch (Exception ex) { MessageDialog dlg = new MessageDialog(ex.Message, "Exception"); dlg.ShowAsync(); } }
public static async Task <Windows.UI.Xaml.Media.Imaging.BitmapImage> GetBitmapAsync(byte[] data) { if (data is null) { return(null); } var bitmapImage = new Windows.UI.Xaml.Media.Imaging.BitmapImage(); using (var stream = new Windows.Storage.Streams.InMemoryRandomAccessStream()) { using (var writer = new Windows.Storage.Streams.DataWriter(stream)) { writer.WriteBytes(data); await writer.StoreAsync(); await writer.FlushAsync(); writer.DetachStream(); } stream.Seek(0); await bitmapImage.SetSourceAsync(stream); } return(bitmapImage); }
public static async void init(TiSettings settings) { if (!settings.ContainsKey("logToken") || settings["logToken"].Length == 0) { return; } logToken = settings["logToken"]; multicastSocket = new DatagramSocket(); multicastSocket.MessageReceived += multicastSocket_MessageReceived; HostName hostname = new HostName("239.6.6.6"); try { await multicastSocket.BindServiceNameAsync("8666"); multicastSocket.JoinMulticastGroup(hostname); IOutputStream stream = await multicastSocket.GetOutputStreamAsync(hostname, "8666"); DataWriter writer = new DataWriter(stream); writer.WriteString("TI_WP8_LOGGER"); await writer.StoreAsync(); writer.DetachStream(); stream.Dispose(); } catch (Exception ex) { if (SocketError.GetStatus(ex.HResult) == SocketErrorStatus.Unknown) { throw; } Debug.WriteLine(ex.ToString()); } }
public async Task<BitmapImage> Base64ToBitmapImage(string base64String) { BitmapImage img = new BitmapImage(); if (string.IsNullOrEmpty(base64String)) return img; using (var ims = new InMemoryRandomAccessStream()) { byte[] bytes = Convert.FromBase64String(base64String); base64String = ""; using (DataWriter dataWriter = new DataWriter(ims)) { dataWriter.WriteBytes(bytes); bytes = null; await dataWriter.StoreAsync(); ims.Seek(0); await img.SetSourceAsync(ims); //not in RC return img; } } }
public async Task<bool> LocalStorage(string Path,string fileName, byte[] bytes) { try { StorageFolder localFolderStorage = ApplicationData.Current.LocalFolder; var localFolder = await localFolderStorage.CreateFolderAsync(Path, CreationCollisionOption.OpenIfExists); var localFile = await localFolder.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting); using (StorageStreamTransaction transaction = await localFile.OpenTransactedWriteAsync()) { //Stream targetStream = await localFile.OpenStreamForWriteAsync(); //localFolderStorage.OpenStreamForWriteAsync(Path+"\\"+fileName, CreationCollisionOption.OpenIfExists)) DataWriter dataWriter = new DataWriter(transaction.Stream); dataWriter.WriteBytes(bytes); await dataWriter.StoreAsync(); //stream.CopyTo(targetStream); // stream.Dispose(); //targetStream.Close(); } return true; } // Use catch blocks to handle errors catch (Exception err) { return false; } }
/// <summary> /// Gets accurate time using the NTP protocol with default timeout of 45 seconds. /// </summary> /// <param name="timeout">Operation timeout.</param> /// <returns>Network accurate <see cref="DateTime"/> value.</returns> public async Task<DateTime> GetNetworkTimeAsync(TimeSpan timeout) { using (var socket = new DatagramSocket()) using (var ct = new CancellationTokenSource(timeout)) { ct.Token.Register(() => _resultCompletionSource.TrySetCanceled()); socket.MessageReceived += OnSocketMessageReceived; //The UDP port number assigned to NTP is 123 await socket.ConnectAsync(new HostName("pool.ntp.org"), "123"); using (var writer = new DataWriter(socket.OutputStream)) { // NTP message size is 16 bytes of the digest (RFC 2030) var ntpBuffer = new byte[48]; // Setting the Leap Indicator, // Version Number and Mode values // LI = 0 (no warning) // VN = 3 (IPv4 only) // Mode = 3 (Client Mode) ntpBuffer[0] = 0x1B; writer.WriteBytes(ntpBuffer); await writer.StoreAsync(); var result = await _resultCompletionSource.Task; return result; } } }
public override async void Start() { if (_Started) return; _SequenceNumber = 1; try { // Connect to the Drone udpClient = new DatagramSocket(); await udpClient.BindServiceNameAsync(_ServiceName); await udpClient.ConnectAsync(new HostName(DroneClient.Host), _ServiceName); udpWriter = new DataWriter(udpClient.OutputStream); udpWriter.WriteByte(1); await udpWriter.StoreAsync(); _Timer = ThreadPoolTimer.CreatePeriodicTimer(new TimerElapsedHandler(timerElapsedHandler), TimeSpan.FromMilliseconds(25)); _Started = true; } catch (Exception) { Stop(); } }
//public static async Task<bool> FileExist() //{ // try // { // var folders = ApplicationData.Current.LocalFolder; // var file = await folders.GetFileAsync(PersonalDataFileName); // var buildingFile = await folders.GetFileAsync(BuildingDataFileName); // if (file.Path != null) // return false; // else // return true; // } // catch // { // return true; // } //} //public static void SavePersonalDataToJson(AccountInfo accountInfo) //{ // string jsonContents = JsonConvert.SerializeObject(accountInfo); // JObject o = (JObject)JToken.FromObject(accountInfo); //} //public static async void SavePersonalDataToJson(AccountInfo account) //{ // // Serialize our Product class into a string // // Changed to serialze the List // // Get the app data folder and create or replace the file we are storing the JSON in. // StorageFolder localFolder = ApplicationData.Current.LocalFolder; // StorageFile textFile = await localFolder.CreateFileAsync(PersonalDataFileName, CreationCollisionOption.ReplaceExisting); // // Open the file... // string jsonContents = JsonConvert.SerializeObject(account); // using (IRandomAccessStream mysteream = await textFile.OpenAsync(FileAccessMode.ReadWrite)) // { // using (DataWriter textWriter = new DataWriter(mysteream)) // { // textWriter.WriteString(jsonContents); // await textWriter.StoreAsync(); // } // } //} public static async Task <bool> SavePersonalDataToJson(List <AccountInfo> list) { // Serialize our Product class into a string // Changed to serialze the List // Get the app data folder and create or replace the file we are storing the JSON in. if (personalTextFile == null) { personalTextFile = await StorageFolder.CreateFileAsync(PersonalDataFileName, CreationCollisionOption.ReplaceExisting); } // Open the file... string jsonContents = JsonConvert.SerializeObject(UserToUserData(list)); var stream = await personalTextFile.OpenAsync(FileAccessMode.ReadWrite); using (var outputStream = stream.GetOutputStreamAt(0)) { using (var dataWriter = new Windows.Storage.Streams.DataWriter(outputStream)) { dataWriter.WriteString(jsonContents); await dataWriter.StoreAsync(); await outputStream.FlushAsync(); } } stream.Dispose(); return(true); }
//</SnippetVertices> /// <summary> /// Fixes issue in API where textures are not saved correctly /// </summary> /// <param name="modelStream">3dmodel.model data</param> /// <returns></returns> private async Task <IRandomAccessStream> FixTextureContentType(IRandomAccessStream modelStream) { XDocument xmldoc = XDocument.Load(modelStream.AsStreamForRead()); var outputStream = new Windows.Storage.Streams.InMemoryRandomAccessStream(); var writer = new Windows.Storage.Streams.DataWriter(outputStream); writer.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf8; writer.ByteOrder = Windows.Storage.Streams.ByteOrder.LittleEndian; writer.WriteString("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); var text = xmldoc.ToString(); // ensure that content type is set correctly // texture content can be either png or jpg var replacedText = text.Replace("contenttype=\"\"", "contenttype=\"image/png\""); writer.WriteString(replacedText); await writer.StoreAsync(); await writer.FlushAsync(); writer.DetachStream(); return(outputStream); }
private async Task<string> DoCommand(string command) { StringBuilder strBuilder = new StringBuilder(); using (StreamSocket clientSocket = new StreamSocket()) { await clientSocket.ConnectAsync(new HostName("192.168.9.108"), "9001"); using (DataWriter writer = new DataWriter(clientSocket.OutputStream)) { writer.WriteString(command); await writer.StoreAsync(); writer.DetachStream(); } using (DataReader reader = new DataReader(clientSocket.InputStream)) { reader.InputStreamOptions = InputStreamOptions.Partial; await reader.LoadAsync(8192); while (reader.UnconsumedBufferLength > 0) { strBuilder.Append(reader.ReadString(reader.UnconsumedBufferLength)); await reader.LoadAsync(8192); } reader.DetachStream(); } } return (strBuilder.ToString()); }
public async void WriteToSerialPort(string message) { var writer = new DataWriter(_realDevice.OutputStream); writer.WriteString(AddNewLine(message)); await writer.StoreAsync().AsTask(); writer.DetachStream(); }
//private uint sizeOfPixel = 4; private async void createTile(IRandomAccessStream tileStream, Color color) { // Create the data writer object backed by the in-memory stream. using (var dataWriter = new Windows.Storage.Streams.DataWriter(tileStream)) { for (uint y = 0; y < sizeOfMapTile; y++) { for (uint x = 0; x < sizeOfMapTile; x++) { // RGBA dataWriter.WriteByte(color.R); dataWriter.WriteByte(color.G); dataWriter.WriteByte(color.B); dataWriter.WriteByte(color.A); } } // 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(); } }
private async void OnLoadingFile(object sender, GestureEventArgs e) { var city = new City { Name = "Leipzig", State = "Saxony", Country = "Germany", Population = 550000 }; string json = JsonConvert.SerializeObject(city); var cityFile = await ApplicationData.Current .LocalFolder.CreateFileAsync( "leipzig.city", CreationCollisionOption.ReplaceExisting); using (var stream = await cityFile.OpenAsync(FileAccessMode.ReadWrite)) { using (var writer = new DataWriter(stream)) { writer.WriteString(json); await writer.StoreAsync(); } } Launcher.LaunchFileAsync(cityFile); }
public void WriteAllText(string filename, string text, Action completed) { StorageFolder localFolder = ApplicationData.Current.LocalFolder; IAsyncOperation<StorageFile> createOp = localFolder.CreateFileAsync(filename, CreationCollisionOption.ReplaceExisting); createOp.Completed = (asyncInfo1, asyncStatus1) => { IStorageFile storageFile = asyncInfo1.GetResults(); IAsyncOperation<IRandomAccessStream> openOp = storageFile.OpenAsync(FileAccessMode.ReadWrite); openOp.Completed = (asyncInfo2, asyncStatus2) => { IRandomAccessStream stream = asyncInfo2.GetResults(); DataWriter dataWriter = new DataWriter(stream); dataWriter.WriteString(text); DataWriterStoreOperation storeOp = dataWriter.StoreAsync(); storeOp.Completed = (asyncInfo3, asyncStatus3) => { dataWriter.Dispose(); completed(); }; }; }; }
private async void WriteToStreamButton_Click(object sender, RoutedEventArgs e) { try { rootPage.ResetScenarioOutput(OutputTextBlock); StorageFile file = rootPage.sampleFile; if (file != null) { string userContent = InputTextBox.Text; if (!String.IsNullOrEmpty(userContent)) { using (StorageStreamTransaction transaction = await file.OpenTransactedWriteAsync()) { using (DataWriter dataWriter = new DataWriter(transaction.Stream)) { dataWriter.WriteString(userContent); transaction.Stream.Size = await dataWriter.StoreAsync(); // reset stream size to override the file await transaction.CommitAsync(); OutputTextBlock.Text = "The following text was written to '" + file.Name + "' using a stream:" + Environment.NewLine + Environment.NewLine + userContent; } } } else { OutputTextBlock.Text = "The text box is empty, please write something and then click 'Write' again."; } } } catch (FileNotFoundException) { rootPage.NotifyUserFileNotExist(); } }
private async Task Download(string url,StorageFile file,bool cover) { var http = new HttpClient(); byte[] response = { }; string betterUrl = url; if(cover) { var pos = betterUrl.IndexOf(".jpg"); if (pos != -1) betterUrl = betterUrl.Insert(pos, "l"); } //get bytes try { await Task.Run(async () => response = await http.GetByteArrayAsync(betterUrl)); } catch (Exception) { await Task.Run(async () => response = await http.GetByteArrayAsync(url)); } var fs = await file.OpenStreamForWriteAsync(); //get stream var writer = new DataWriter(fs.AsOutputStream()); writer.WriteBytes(response); //write await writer.StoreAsync(); await writer.FlushAsync(); writer.Dispose(); }
private async Task SendMessageUsingMessageWebSocketAsync(string message) { using (var dataWriter = new Windows.Storage.Streams.DataWriter(m_Socket.OutputStream)) { dataWriter.WriteString(message); await dataWriter.StoreAsync(); dataWriter.DetachStream(); } FlowNetworkManager.log("Sending message using MessageWebSocket: " + message); }
private async System.Threading.Tasks.Task _SendUDPMessage(byte[] data) { using (var stream = await socket.GetOutputStreamAsync(new Windows.Networking.HostName(PupilSettings.Instance.connection.pupilRemoteIP), PupilSettings.Instance.connection.pupilRemotePort)) { using (var writer = new Windows.Storage.Streams.DataWriter(stream)) { writer.WriteBytes(data); await writer.StoreAsync(); } } }
private async System.Threading.Tasks.Task _SendUDPMessage(string externalIP, string externalPort, byte[] data) { using (var stream = await socket.GetOutputStreamAsync(new Windows.Networking.HostName(externalIP), externalPort)) { using (var writer = new Windows.Storage.Streams.DataWriter(stream)) { writer.WriteBytes(data); await writer.StoreAsync(); } } }
private async System.Threading.Tasks.Task SendMessage(string message, string ip, int port) { using (var stream = await socket.GetOutputStreamAsync(new Windows.Networking.HostName(ip), port.ToString())) { using (var writer = new Windows.Storage.Streams.DataWriter(stream)) { var data = Encoding.UTF8.GetBytes(message); writer.WriteBytes(data); await writer.StoreAsync(); } } }
private async Task <int> SendAsync(byte[] inbuffer) { using (var writer = new Windows.Storage.Streams.DataWriter(socket.OutputStream)) { writer.WriteBytes(inbuffer); await writer.StoreAsync(); writer.DetachStream(); } // hopefully true... return(inbuffer.Length); }
private async void cutTile(IRandomAccessStream stream, int pixeloffsetX, int pixeloffsetY, int levelOfDetail) { // Create the data writer object backed by the in-memory stream. using (var dataWriter = new Windows.Storage.Streams.DataWriter(stream)) { //dataWriter.dataWriter.ByteOrder = Windows.Storage.Streams.ByteOrder.LittleEndian; for (int y = 0; y < sizeOfMapTile; y++) { for (int x = 0; x < sizeOfMapTile; x++) { double lat, lon = 0.0; Microsoft.MapPoint.TileSystem.PixelXYToLatLong(pixeloffsetX + x, pixeloffsetY + y, levelOfDetail, out lat, out lon); BasicGeoposition point = new BasicGeoposition { Latitude = lat, Longitude = lon }; if (PathCache.pointInPolygon(point.Longitude, point.Latitude)) { // RGBA dataWriter.WriteByte(ColorIn.R); dataWriter.WriteByte(ColorIn.G); dataWriter.WriteByte(ColorIn.B); dataWriter.WriteByte(ColorIn.A); } else { // RGBA dataWriter.WriteByte(ColorOut.R); dataWriter.WriteByte(ColorOut.G); dataWriter.WriteByte(ColorOut.B); dataWriter.WriteByte(ColorOut.A); } } } // 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(); } }
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); }
/// <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 static async Task RestoreFileFromOneDriveAsync(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; } }
/// <summary> /// Send a message to the server. /// This message is specified in the JsonObject message. /// The byteorder of the send message is LittleEndian and the encoding is Utf8. /// </summary> /// <param name="message">The message to be send.</param> /// <returns>A boolean that indicates that the message was succesfully send.</returns> public async Task <bool> SendMessage(JsonObject message) { //Check if the connector is connected. If not, call the Connect() function. if (!isConnected) { await Connect(); } //Write the message to the server. //Code used from https://docs.microsoft.com/en-us/uwp/api/windows.storage.streams.datawriter try { using (var dataWriter = new Windows.Storage.Streams.DataWriter(socket.OutputStream)) { dataWriter.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf8; dataWriter.ByteOrder = Windows.Storage.Streams.ByteOrder.LittleEndian; // Parse the input stream and write each element separately. //Get the string version of the json object. var stringToSend = message.ToString(); //Get the length of the stream, so the server knows how much data was send. uint inputElementSize = dataWriter.MeasureString(stringToSend); dataWriter.WriteUInt32(inputElementSize); dataWriter.WriteString(stringToSend); Debug.WriteLine("Wrote" + stringToSend); Debug.WriteLine("Lenght:" + inputElementSize); // 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(); return(true); } } catch { //TODO on error? throw; } }
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(); } }
// send to external IP and external port private async System.Threading.Tasks.Task SendMessageUDP(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); } } }
/// <summary> /// Send the given data to the server using the established connection public async void SendString(string message) { DatagramSocket socket = new DatagramSocket(); await socket.ConnectAsync(new HostName(ServerIP), ConnectionPort.ToString()); using (var writer = new Windows.Storage.Streams.DataWriter(socket.OutputStream)) { var data = Encoding.UTF8.GetBytes(message); //writer.WriteBytes(data); writer.WriteString(message); await writer.StoreAsync(); //Debug.Log("Sent: " + message); } }
private async void send_data(string dataToSend) { Debug.Log("sending message: " + dataToSend); using (var dataWriter = new Windows.Storage.Streams.DataWriter(streamSocket.OutputStream)){ dataWriter.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf8; dataWriter.ByteOrder = Windows.Storage.Streams.ByteOrder.LittleEndian; dataWriter.WriteString(dataToSend); await dataWriter.StoreAsync(); await dataWriter.FlushAsync(); dataWriter.DetachStream(); } Debug.Log("message sent"); }
/// <summary> /// 指定範囲のキャプチャ画像をSoftwareBitmap型として得る /// </summary> /// <param name="left">キャプチャ範囲の左端端x座標</param> /// <param name="top">キャプチャ範囲の左端端y座標</param> /// <param name="height">キャプチャ範囲の高さ</param> /// <param name="width">キャプチャ範囲の幅</param> /// <returns>指定された範囲のキャプチャ画像</returns> public static async Task <SoftwareBitmap> CaptureAsSoftwareBitmap(int left, int top, int height, int width) { //ビットマップの保持領域を確保 Bitmap partialCapture = new Bitmap(width, height); //描画インターフェイスの設定 Graphics draw = Graphics.FromImage(partialCapture); //画面全体をコピーする draw.CopyFromScreen( left, top, 0, 0, partialCapture.Size ); //解放 draw.Dispose(); MemoryStream memStream = new MemoryStream(); partialCapture.Save(memStream, ImageFormat.Bmp); SoftwareBitmap softwareBitmap; using (var randomAccessStream = new UwpInMemoryRandomAccessStream()) { using (var outputStream = randomAccessStream.GetOutputStreamAt(0)) using (var writer = new UwpDataWriter(outputStream)) { writer.WriteBytes(memStream.ToArray()); await writer.StoreAsync(); await outputStream.FlushAsync(); } // IRandomAccessStreamをSoftwareBitmapに変換 // (ここはUWP APIのデコーダーを使う) var decoder = await UwpBitmapDecoder.CreateAsync(randomAccessStream); softwareBitmap = await decoder.GetSoftwareBitmapAsync(UwpBitmapPixelFormat.Bgra8, UwpBitmapAlphaMode.Premultiplied); } return(softwareBitmap); }
public static async Task WriteFile(string filename, string contents) { var localFolder = Windows.Storage.ApplicationData.Current.LocalFolder; var folder = await localFolder.CreateFolderAsync("DataCache", Windows.Storage.CreationCollisionOption.OpenIfExists); var file = await folder.CreateFileAsync(filename, Windows.Storage.CreationCollisionOption.ReplaceExisting); var fs = await file.OpenAsync(Windows.Storage.FileAccessMode.ReadWrite); fs.Seek(fs.Size); var outStream = fs.GetOutputStreamAt(0); var dataWriter = new Windows.Storage.Streams.DataWriter(outStream); dataWriter.WriteString(contents); await dataWriter.StoreAsync(); dataWriter.DetachStream(); await outStream.FlushAsync(); }
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 static void WriteTextFileAsync(string filename, string content) { var storageFolder = ApplicationData.Current.LocalFolder; var textFile = await storageFolder.CreateFileAsync(filename, CreationCollisionOption.OpenIfExists); var textStream = await textFile.OpenAsync(FileAccessMode.ReadWrite); using (var outputStream = textStream.GetOutputStreamAt(textStream.Size)) { using (var dataWriter = new Windows.Storage.Streams.DataWriter(outputStream)) { dataWriter.WriteString("\n" + content); await dataWriter.StoreAsync(); await outputStream.FlushAsync(); } } textStream.Dispose(); }
// ========================================================================= Class Members =========================================================== // /// <summary> /// Sends message to destination port /// </summary> /// <param name="message">string to send</param> #if NETFX_CORE public async Task Send(string message) { try { using (var stream = await _impl.GetOutputStreamAsync(new Windows.Networking.HostName(destIP), destPortStr)) { using (var writer = new Windows.Storage.Streams.DataWriter(stream)) { var data = Encoding.UTF8.GetBytes(message); writer.WriteBytes(data); await writer.StoreAsync(); } } } catch (Exception e) { Debug.Log(TAG + " SendMessageUDP exception:\n" + e.ToString()); }
private async Task updateImage(Image cameraImage, string url) { // Download the image into memory as a stream System.Net.Http.HttpClient client = new System.Net.Http.HttpClient(); System.Net.Http.HttpResponseMessage imageResponse = await client.GetAsync(url); InMemoryRandomAccessStream randomAccess = new Windows.Storage.Streams.InMemoryRandomAccessStream(); DataWriter writer = new Windows.Storage.Streams.DataWriter(randomAccess.GetOutputStreamAt(0)); writer.WriteBytes(await imageResponse.Content.ReadAsByteArrayAsync()); await writer.StoreAsync(); BitmapImage bit = new BitmapImage(); await bit.SetSourceAsync(randomAccess); cameraImage.Source = bit; }
public async void SaveASync(T Obj, string FileName) { FileName = FileName + ".xml"; try { if (Obj != null) { StorageFile file = null; StorageFolder folder = GetFolder(storageType); file = await folder.CreateFileAsync(FileName, CreationCollisionOption.ReplaceExisting); DataContractJsonSerializer ser = new DataContractJsonSerializer(Obj.GetType()); MemoryStream ms = new MemoryStream(); ser.WriteObject(ms, Obj); var bytes = ms.ToArray(); var contents = UTF8Encoding.UTF8.GetString(bytes, 0, bytes.Length); using (var writeStream = await file.OpenAsync(FileAccessMode.ReadWrite)) { //Stream outStream = Task.Run(() => writeStream.AsStreamForWrite()).Result; //serializer.Serialize(outStream, Obj); using (var outStream = writeStream.GetOutputStreamAt(0)) { using (var dataWriter = new Windows.Storage.Streams.DataWriter(outStream)) { dataWriter.WriteString(contents); await dataWriter.StoreAsync(); dataWriter.DetachStream(); await outStream.FlushAsync(); } } } } } catch (Exception) { throw; } }
private async Task <IRandomAccessStream> FixTextureContentType(IRandomAccessStream modelStream) { XDocument xmldoc = XDocument.Load(modelStream.AsStreamForRead()); var outputStream = new Windows.Storage.Streams.InMemoryRandomAccessStream(); var writer = new Windows.Storage.Streams.DataWriter(outputStream); writer.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf8; writer.ByteOrder = Windows.Storage.Streams.ByteOrder.LittleEndian; var text = xmldoc.ToString(); var replacedText = text.Replace("contenttype=\"\"", "contenttype=\"image/png\""); writer.WriteString(replacedText); await writer.StoreAsync(); await writer.FlushAsync(); writer.DetachStream(); return(outputStream); }
async private Task <int> SaveXMLDoc(XmlDocument xdoc, StorageFile file) { using (var stream = await file.OpenStreamForWriteAsync()) { stream.SetLength(0); } IRandomAccessStream existingFileStream = await file.OpenAsync(Windows.Storage.FileAccessMode.ReadWrite); using (IOutputStream outputStream = existingFileStream.GetOutputStreamAt(0)) { using (DataWriter dataWriter = new Windows.Storage.Streams.DataWriter(outputStream)) { dataWriter.WriteString(CreateXMLStringWithNewlines(ref xdoc)); await dataWriter.StoreAsync(); await outputStream.FlushAsync(); } } existingFileStream.Dispose(); return(0); }