private void PublishLaunchApp() { proximityDevice = Windows.Networking.Proximity.ProximityDevice.GetDefault(); if (proximityDevice != null) { // The format of the app launch string is: "<args>\tWindows\t<AppName>". // The string is tab or null delimited. // The <args> string can be an empty string (""). string launchArgs = "user=default"; // The format of the AppName is: PackageFamilyName!PRAID. string praid = "{b8c21b6b-2f16-49f6-9ee9-b3a713c54500}"; // The Application Id value from your package.appxmanifest. string appName = Windows.ApplicationModel.Package.Current.Id.FamilyName + "!" + praid; string launchAppMessage = launchArgs + "\tWindows\t" + appName; var dataWriter = new Windows.Storage.Streams.DataWriter(); dataWriter.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf16LE; dataWriter.WriteString(launchAppMessage); var launchAppPubId = proximityDevice.PublishBinaryMessage( "LaunchApp:WriteTag", dataWriter.DetachBuffer()); } }
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; } }
/// <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; } } }
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); } }
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); } }
/// <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); }
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; }
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(); }
private void radioButtonDataFormat_Checked(object sender, RoutedEventArgs e) { if (sender.Equals(this.radioButtonAscii)) { var binary = this.textBoxReadBulkInLogger.Text; var separator = new String[1]; separator[0] = " "; var byteArray = binary.Split(separator, StringSplitOptions.None); // Binary to Unicode. uint strlen = 0; var writer = new Windows.Storage.Streams.DataWriter(); writer.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf8; foreach (var onebyte in byteArray) { if (onebyte.Length < 2) { continue; } writer.WriteByte(byte.Parse(onebyte, System.Globalization.NumberStyles.HexNumber)); strlen++; } var reader = Windows.Storage.Streams.DataReader.FromBuffer(writer.DetachBuffer()); this.textBoxReadBulkInLogger.Text = reader.ReadString(strlen); } else if (sender.Equals(this.radioButtonBinary)) { var ascii = this.textBoxReadBulkInLogger.Text; // Unicode to ASCII. var chars = ascii.ToCharArray(0, ascii.Length); var writer = new Windows.Storage.Streams.DataWriter(); writer.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf8; foreach (var onechar in chars) { writer.WriteByte((byte)onechar); } var str = Util.BinaryBufferToBinaryString(writer.DetachBuffer()); this.textBoxReadBulkInLogger.Text = str; } }
public void toggleAllDigitalPinsV2(bool setPinsHigh) { //a DataWriter object uses an IBuffer as its backing storage //we'll write our data to this object and detach the buffer to invoke sendSysex() Windows.Storage.Streams.DataWriter writer = new Windows.Storage.Streams.DataWriter(); //we're defining our own command, so we're free to encode it how we want. //let's send a '1' if we want the pins HIGH, and a 0 for LOW writer.WriteByte((byte)(setPinsHigh ? 1 : 0)); //invoke the sendSysex command with ALL_PINS_COMMAND and our data payload as an IBuffer //firmata.@lock(); firmata.sendSysex(ALL_PINS_COMMAND, writer.DetachBuffer()); //firmata.@unlock(); }
/// <summary> /// Publish and subscribe a dealcards -message. /// </summary> public void DealCards() { state = ProtoState.DealCard; if (IsMaster()) { opponentsCards = App.CardModel.SuffleCards(); Message msg = new Message(Message.TypeEnum.EDealCards); msg.CardIds = opponentsCards; // Construct and serialize a dealcards -message. MemoryStream mstream = _nfcMessage.SerializeMessage(msg); var dataWriter = new Windows.Storage.Streams.DataWriter(); dataWriter.WriteBytes(mstream.GetBuffer()); // Publish the message _publishedMsgId = _proximityDevice.PublishBinaryMessage("Windows.CarTrumps", dataWriter.DetachBuffer(), NfcWriteCallback); } else { // subscribe for a reply _subscribedMsgId = _proximityDevice.SubscribeForMessage("Windows.CarTrumps", NfcMessageReceived); } }
/// <summary> /// SET_LINE_CODING CDC request. /// </summary> /// <param name="index">Interface index.</param> /// <param name="dteRate">Data terminal rate, in bits per second.</param> /// <param name="charFormat">Stop bits.</param> /// <param name="parityType">Parity.</param> /// <param name="dataBits">Data bits.</param> /// <returns> /// The result of Task contains a length of bytes actually sent to the serial port. /// </returns> private Task<uint> SetLineCoding( uint index, uint dteRate, byte charFormat, byte parityType, byte dataBits ) { // SetLineCoding var writer = new Windows.Storage.Streams.DataWriter(); writer.ByteOrder = Windows.Storage.Streams.ByteOrder.LittleEndian; writer.WriteUInt32(dteRate); writer.WriteByte(charFormat); writer.WriteByte(parityType); writer.WriteByte(dataBits); var buffer = writer.DetachBuffer(); var requestType = new UsbControlRequestType(); requestType.AsByte = RequestType.Set; return UsbControlRequestForSet( index, requestType, RequestCode.SetLineCoding, 0, buffer); }
public void Chat() { var DataReader = new Windows.Storage.Streams.DataReader(client.InputStream); byte[] getByte = new byte[5000]; DataReader.ReadBytes(getByte); Encoding code = Encoding.GetEncoding("UTF-8"); string RemoteData = code.GetString(getByte, 0, getByte.Length); Messages.Add(new Message("Your Friend", DateTime.Now, RemoteData, false)); var DataWriter = new Windows.Storage.Streams.DataWriter(client.OutputStream); DataWriter.WriteString("test\n"); Messages.Add(new Message("You", DateTime.Now, textBox.Text, true)); }
// Handles PeerFinder_AdvertiseButton click void PeerFinder_StartAdvertising(object sender, RoutedEventArgs e) { // If PeerFinder is started, stop it, so that new properties // selected by the user (Role/DiscoveryData) can be updated. PeerFinder_StopAdvertising(sender, e); rootPage.NotifyUser("", NotifyType.ErrorMessage); if (!_peerFinderStarted) { // attach the callback handler (there can only be one PeerConnectProgress handler). PeerFinder.TriggeredConnectionStateChanged += new TypedEventHandler<object, TriggeredConnectionStateChangedEventArgs>(TriggeredConnectionStateChangedEventHandler); // attach the incoming connection request event handler PeerFinder.ConnectionRequested += new TypedEventHandler<object, ConnectionRequestedEventArgs>(PeerConnectionRequested); // Set the PeerFinder.Role property switch (PeerFinder_SelectRole.SelectionBoxItem.ToString()) { case "Peer": PeerFinder.Role = PeerRole.Peer; break; case "Host": PeerFinder.Role = PeerRole.Host; break; case "Client": PeerFinder.Role = PeerRole.Client; break; } // Set DiscoveryData property if the user entered some text if ((PeerFinder_DiscoveryData.Text.Length > 0) && (PeerFinder_DiscoveryData.Text != "What's happening today?")) { using (var discoveryDataWriter = new Windows.Storage.Streams.DataWriter(new Windows.Storage.Streams.InMemoryRandomAccessStream())) { discoveryDataWriter.WriteString(PeerFinder_DiscoveryData.Text); PeerFinder.DiscoveryData = discoveryDataWriter.DetachBuffer(); } } // start listening for proximate peers PeerFinder.Start(); _peerFinderStarted = true; PeerFinder_StopAdvertiseButton.Visibility = Visibility.Visible; PeerFinder_ConnectButton.Visibility = Visibility.Visible; if (_browseConnectSupported && _triggeredConnectSupported) { rootPage.NotifyUser("Click Browse for Peers button or tap another device to connect to a peer.", NotifyType.StatusMessage); PeerFinder_BrowseGrid.Visibility = Visibility.Visible; } else if (_triggeredConnectSupported) { rootPage.NotifyUser("Tap another device to connect to a peer.", NotifyType.StatusMessage); } else if (_browseConnectSupported) { rootPage.NotifyUser("Click Browse for Peers button.", NotifyType.StatusMessage); PeerFinder_BrowseGrid.Visibility = Visibility.Visible; } } }
// Click event for "Advertise" button. void AdvertiseForPeers(object sender, RoutedEventArgs e) { if (!started) { Windows.Networking.Proximity.PeerFinder.DisplayName = DisplayNameTextBox.Text; if ((Windows.Networking.Proximity.PeerFinder.SupportedDiscoveryTypes & Windows.Networking.Proximity.PeerDiscoveryTypes.Triggered) == Windows.Networking.Proximity.PeerDiscoveryTypes.Triggered) { Windows.Networking.Proximity.PeerFinder.TriggeredConnectionStateChanged += TriggeredConnectionStateChanged; WriteMessageText("You can tap to connect a peer device that is " + "also advertising for a connection.\n"); } else { WriteMessageText("Tap to connect is not supported.\n"); } if ((Windows.Networking.Proximity.PeerFinder.SupportedDiscoveryTypes & Windows.Networking.Proximity.PeerDiscoveryTypes.Browse) != Windows.Networking.Proximity.PeerDiscoveryTypes.Browse) { WriteMessageText("Peer discovery using Wi-Fi Direct is not supported.\n"); } // Set the peer role selected by the user. if (launchedByTap) { Windows.Networking.Proximity.PeerFinder.Role = appRole; } else { switch (GetRoleFromUser()) { case "Peer": Windows.Networking.Proximity.PeerFinder.Role = Windows.Networking.Proximity.PeerRole.Peer; break; case "Host": Windows.Networking.Proximity.PeerFinder.Role = Windows.Networking.Proximity.PeerRole.Host; break; case "Client": Windows.Networking.Proximity.PeerFinder.Role = Windows.Networking.Proximity.PeerRole.Client; break; } } // Set discoveryData property with user supplied text. var discData = GetDiscoveryDataFromUser(); var writer = new Windows.Storage.Streams.DataWriter( new Windows.Storage.Streams.InMemoryRandomAccessStream()); writer.WriteString(discData); Windows.Networking.Proximity.PeerFinder.DiscoveryData = writer.DetachBuffer(); Windows.Networking.Proximity.PeerFinder.Start(); started = true; } }
private async void AppBarSave_Click(object sender, RoutedEventArgs e) { var savePicker = new FileSavePicker(); savePicker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary; savePicker.FileTypeChoices.Add("Excel CSV", new List <string>() { ".csv" }); // Default file name if the user does not type one in or select a file to replace savePicker.SuggestedFileName = "New Document"; StorageFile file = await savePicker.PickSaveFileAsync(); if (file == null) { return; } try { CachedFileManager.DeferUpdates(file); using (var stream = await file.OpenAsync(FileAccessMode.ReadWrite)) { var dw = new Windows.Storage.Streams.DataWriter(stream); foreach (var p in this.Cache) { dw.WriteString(p.Text + ", " + p.CreateDate.ToString() + "\r\n"); } await dw.StoreAsync(); await stream.FlushAsync(); } FileUpdateStatus status = await CachedFileManager.CompleteUpdatesAsync(file); string message = "Save the data to " + file.Name + " successfully."; if (status != FileUpdateStatus.Complete) { message = "File " + file.Name + " couldn't be saved."; } var dialog = new MessageDialog(message); dialog.Commands.Add(new UICommand("OK") { Id = 0 }); await dialog.ShowAsync(); } catch (Exception ex) { await App.Logger.Write(ex.Message); } }
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(); } } }
private async Task SaveAsCSV(List <AEDATEvent> data, StorageFile saveFile, bool includeCords, bool onOffType, bool pixelNumber) { if (saveFile == null) { return; } Windows.Storage.Provider.FileUpdateStatus status = await CachedFileManager.CompleteUpdatesAsync(saveFile); if (status == Windows.Storage.Provider.FileUpdateStatus.Complete) { var stream = await saveFile.OpenAsync(FileAccessMode.ReadWrite); using (var outputStream = stream.GetOutputStreamAt(0)) { using (var dataWriter = new Windows.Storage.Streams.DataWriter(outputStream)) { Func <bool, string> formatOnOff; Func <int, int, string> formatCoords; // Determine which columns are included in the CSV if (includeCords) { if (pixelNumber) { dataWriter.WriteString("On/Off,PixelNumber,Timestamp\n"); formatCoords = (x, y) => ((currentCamera.cameraX * (y - 1)) + (x - 1)).ToString() + ","; } else { dataWriter.WriteString("On/Off,X,Y,Timestamp\n"); formatCoords = (x, y) => x.ToString() + "," + y.ToString() + ","; } } else { dataWriter.WriteString("On/Off,Timestamp\n"); formatCoords = (x, y) => ""; } // Determine if events are represented by booleans or integers if (!onOffType) { formatOnOff = b => b.ToString() + ","; } else { formatOnOff = b => b == true ? "1," : "-1,"; } // Write to the CSV file foreach (AEDATEvent item in data) { dataWriter.WriteString(formatOnOff(item.onOff) + formatCoords(item.x, item.y) + item.time + "\n"); } await dataWriter.StoreAsync(); await outputStream.FlushAsync(); } } stream.Dispose(); } }
private async void C_SAVE_BUTTON_Click(object sender, RoutedEventArgs e) { Model.TrickerStarNodeViewSerialize s = new Model.TrickerStarNodeViewSerialize(); var nodes = C_MAIN_NODE_VIEW.TS_GetNodes(); foreach (String nodename in nodes) { s.Nodes.Add(C_MAIN_NODE_VIEW.TS_GetNode(nodename)); s.Codes.Add( new Model.TrickerStarFunctionNodeCodeModel() { Code = m_NodeCode[nodename] as String, NodeName = nodename } ); } var lines = C_MAIN_NODE_VIEW.TS_GetLines(); foreach (String linename in lines) { s.Lines.Add(C_MAIN_NODE_VIEW.TS_GetLine(linename)); } foreach (var group in m_GroupList) { s.Groups.Add(group); } foreach (String node_name in m_NodeGroup.Keys) { Model.TrickerStarNodeGroupModel g = (Model.TrickerStarNodeGroupModel)m_NodeGroup[node_name]; s.NodeGroups.Add(new TrickerStarNodeGroupModel() { NodeName = node_name, GroupName = g.GroupName, GroupTitle = g.GroupTitle }); } String json_str = Model.JsonHelper.ToJson(s, s.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 = "NewDocument"; 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(); } } }
private Windows.Storage.Streams.IBuffer GetBufferFromBytes(byte[] str) { using (Windows.Storage.Streams.InMemoryRandomAccessStream memoryStream = new Windows.Storage.Streams.InMemoryRandomAccessStream()) { using (Windows.Storage.Streams.DataWriter dataWriter = new Windows.Storage.Streams.DataWriter(memoryStream)) { dataWriter.WriteBytes(str); return dataWriter.DetachBuffer(); } } }
/// <summary> /// This is the click handler for the 'scenario3BtnBuffer' button. You would replace this with your own handler /// if you have a button or buttons on this page. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private async void Scenario3BtnBuffer_Click(object sender, RoutedEventArgs e) { try { // Get load settings var loadSettings = new Windows.Data.Xml.Dom.XmlLoadSettings(); if (true == scenario3RB1.IsChecked) { loadSettings.ProhibitDtd = true; // DTD is prohibited loadSettings.ResolveExternals = false; // Disable the resolve to external definitions such as external DTD } else if (true == scenario3RB2.IsChecked) { loadSettings.ProhibitDtd = false; // DTD is not prohibited loadSettings.ResolveExternals = false; // Disable the resolve to external definitions such as external DTD } else if (true == scenario3RB3.IsChecked) { loadSettings.ProhibitDtd = false; // DTD is not prohibited loadSettings.ResolveExternals = true; // Enable the resolve to external definitions such as external DTD } String xml; scenario3OriginalData.Document.GetText(Windows.UI.Text.TextGetOptions.None, out xml); // Set external dtd file path if (loadSettings.ResolveExternals == true && loadSettings.ProhibitDtd == false) { Windows.Storage.StorageFolder storageFolder = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFolderAsync("loadExternaldtd"); String dtdPath = storageFolder.Path + "\\dtd.txt"; xml = xml.Replace("dtd.txt", dtdPath); } var dataWriter = new Windows.Storage.Streams.DataWriter(); dataWriter.WriteString(xml); Windows.Storage.Streams.IBuffer ibuffer = dataWriter.DetachBuffer(); var doc = new Windows.Data.Xml.Dom.XmlDocument(); doc.LoadXmlFromBuffer(ibuffer, loadSettings); Scenario.RichEditBoxSetMsg(scenario3Result, doc.GetXml(), true); } catch (Exception) { // After loadSettings.ProhibitDtd is set to true, the exception is expected as the sample XML contains DTD Scenario.RichEditBoxSetError(scenario3Result, "Error: DTD is prohibited"); } }
private void buttonWriteBulkOut_Click(object sender, RoutedEventArgs e) { if (this.SerialPortInfo != null) { var dataToWrite = this.textBoxDataToWrite.Text; var dispatcher = this.Dispatcher; ((Action)(async () => { await dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, new Windows.UI.Core.DispatchedHandler(async () => { // Unicode to ASCII. var encoder = System.Text.Encoding.UTF8.GetEncoder(); var utf8bytes = new byte[dataToWrite.Length]; int bytesUsed, charsUsed; bool completed; encoder.Convert(dataToWrite.ToCharArray(), 0, dataToWrite.Length, utf8bytes, 0, utf8bytes.Length, true, out bytesUsed, out charsUsed, out completed); var writer = new Windows.Storage.Streams.DataWriter(); writer.WriteBytes(utf8bytes); var isChecked = checkBoxSendNullTerminateCharToBulkOut.IsChecked; if (isChecked.HasValue && isChecked.Value == true) { writer.WriteByte(0x00); // NUL } var buffer = writer.DetachBuffer(); await this.SerialPortInfo.Port.Write(buffer, 0, buffer.Length); var temp = this.textBoxWriteLog.Text; temp += "Write completed: \"" + dataToWrite + "\" (" + buffer.Length.ToString() + " bytes)\n"; this.textBoxWriteLog.Text = temp; this.textBoxDataToWrite.Text = ""; })); } )).Invoke(); } }
// Handles PeerFinder_AdvertiseButton click void PeerFinder_StartAdvertising(object sender, RoutedEventArgs e) { // If PeerFinder is started, stop it, so that new properties // selected by the user (Role/DiscoveryData) can be updated. PeerFinder_StopAdvertising(sender, e); rootPage.NotifyUser("", NotifyType.ErrorMessage); if (!_peerFinderStarted) { // attach the callback handler (there can only be one PeerConnectProgress handler). PeerFinder.TriggeredConnectionStateChanged += new TypedEventHandler <object, TriggeredConnectionStateChangedEventArgs>(TriggeredConnectionStateChangedEventHandler); // attach the incoming connection request event handler PeerFinder.ConnectionRequested += new TypedEventHandler <object, ConnectionRequestedEventArgs>(PeerConnectionRequested); // Set the PeerFinder.Role property // NOTE: this has no effect on the Phone platform if (PeerFinder_SelectRole.SelectionBoxItem != null) { switch (PeerFinder_SelectRole.SelectionBoxItem.ToString()) { case "Peer": PeerFinder.Role = PeerRole.Peer; break; case "Host": PeerFinder.Role = PeerRole.Host; break; case "Client": PeerFinder.Role = PeerRole.Client; break; } } // Set DiscoveryData property if the user entered some text // NOTE: this has no effect on the Phone platform if ((PeerFinder_DiscoveryData.Text.Length > 0) && (PeerFinder_DiscoveryData.Text != "What's happening today?")) { using (var discoveryDataWriter = new Windows.Storage.Streams.DataWriter(new Windows.Storage.Streams.InMemoryRandomAccessStream())) { discoveryDataWriter.WriteString(PeerFinder_DiscoveryData.Text); PeerFinder.DiscoveryData = discoveryDataWriter.DetachBuffer(); } } // start listening for proximate peers PeerFinder.Start(); _peerFinderStarted = true; ToggleWatcherControls(true); if (_browseConnectSupported && _triggeredConnectSupported) { rootPage.NotifyUser("Click Start Watching button or tap another device to connect to a peer.", NotifyType.StatusMessage); } else if (_triggeredConnectSupported) { rootPage.NotifyUser("Tap another device to connect to a peer.", NotifyType.StatusMessage); } else if (_browseConnectSupported) { rootPage.NotifyUser("Click Start Watching for peers button.", NotifyType.StatusMessage); } } }
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 }
/// <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; // Parse the input stream and write each element separately. string[] inputElements = ElementsToWrite.Text.Split(';'); 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. using (var inputStream = stream.GetInputStreamAt(0)) { using (var dataReader = new Windows.Storage.Streams.DataReader(inputStream)) { // 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(); }
//private Windows.Storage.Streams.DataWriter writer; public void Connect(string url) { Uri uri = null; string connectionId = Strings.RandomString(8); int serverId = Strings.RandomNumber(1, 1000); try { uri = new Uri(url); } catch (Exception) { throw new OrtcEmptyFieldException(String.Format("Invalid URL: {0}", url)); } string prefix = uri != null && "https".Equals(uri.Scheme) ? "wss" : "ws"; Uri connectionUrl = new Uri(String.Format("{0}://{1}:{2}/broadcast/{3}/{4}/websocket", prefix, uri.DnsSafeHost, uri.Port, serverId, connectionId)); // // NOTE: For wss connections, must have a valid installed certificate // See: http://www.runcode.us/q/c-iphone-push-server // _websocket = new Windows.Networking.Sockets.MessageWebSocket(); _websocket.Control.MessageType = Windows.Networking.Sockets.SocketMessageType.Utf8; _websocket.MessageReceived += _websocket_MessageReceived; _websocket.Closed += _websocket_Closed; _websocket.ConnectAsync(connectionUrl).Completed = new Windows.Foundation.AsyncActionCompletedHandler( (Windows.Foundation.IAsyncAction source, Windows.Foundation.AsyncStatus status) => { //System.Diagnostics.Debug.WriteLine(":: connecting status " + status); if (status == Windows.Foundation.AsyncStatus.Canceled) { _reconnectTimer.ActionDone(false); } else if (status == Windows.Foundation.AsyncStatus.Completed) { //writer = new Windows.Storage.Streams.DataWriter(_websocket.OutputStream); //writer.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf8; messageWriter = new Windows.Storage.Streams.DataWriter(_websocket.OutputStream); var ev = OnOpened; if (ev != null) { Task.Factory.StartNew(() => ev()); } //_reconnectTimer.ActionDone(true); } else if (status == Windows.Foundation.AsyncStatus.Error) { var ev = OnError; if (ev != null) { Task.Factory.StartNew(() => ev(new OrtcNotConnectedException("Websocket has encountered an error."))); } _reconnectTimer.ActionDone(true); } else if (status == Windows.Foundation.AsyncStatus.Started) { } else { //unknown state } }); /* * _websocket = new WebSocket(connectionUrl.AbsoluteUri); * * _websocket.Opened += new EventHandler(websocket_Opened); * _websocket.Error += new EventHandler<SuperSocket.ClientEngine.ErrorEventArgs>(websocket_Error); * _websocket.Closed += new EventHandler(websocket_Closed); * _websocket.MessageReceived += new EventHandler<MessageReceivedEventArgs>(websocket_MessageReceived); * * _websocket.Open(); */ }
/// <summary> /// Publish and subscribe a showcard -message. /// </summary> public void ShowCard() { state = ProtoState.ShowCard; StopAll(); // Construct and serialize a showcard -message. Message msg = new Message(Message.TypeEnum.EShowCard); msg.CardId = (ushort)App.CardModel.ActiveCard.CardId; msg.SelectedCardProperty = App.CardModel.SelectedCardPropertyName; MemoryStream mstream = _nfcMessage.SerializeMessage(msg); var dataWriter = new Windows.Storage.Streams.DataWriter(); dataWriter.WriteBytes(mstream.GetBuffer()); // Publish the message _publishedMsgId = _proximityDevice.PublishBinaryMessage("Windows.CarTrumps", dataWriter.DetachBuffer(), NfcWriteCallback); // and subscribe for a reply _subscribedMsgId = _proximityDevice.SubscribeForMessage("Windows.CarTrumps", NfcMessageReceived); }
/// <summary> /// Sends DHCP reply /// </summary> /// <param name="msgType">Type of DHCP message to send</param> /// <param name="ip">IP for client</param> /// <param name="replyData">Reply options (will be sent if requested)</param> /// <param name="otherForceOptions">Force reply options (will be sent anyway)</param> private async void SendDHCPReply(DhcpMsgType msgType, IPAddress ip, DhcpReplyOptions replyData, Dictionary <DhcpOption, byte[]> otherForceOptions, IEnumerable <DhcpOption> forceOptions) { var replyBuffer = requestData; replyBuffer.op = 2; // Reply replyBuffer.yiaddr = ip.GetAddressBytes(); // Client's IP if (replyData.ServerIpAddress != null) { replyBuffer.siaddr = replyData.ServerIpAddress.GetAddressBytes(); } replyBuffer.options = CreateOptionStruct(msgType, replyData, otherForceOptions, forceOptions); // Options if (!string.IsNullOrEmpty(dhcpServer.ServerName)) { var serverNameBytes = Encoding.ASCII.GetBytes(dhcpServer.ServerName); int len = (serverNameBytes.Length > 63) ? 63 : serverNameBytes.Length; Array.Copy(serverNameBytes, replyBuffer.sname, len); replyBuffer.sname[len] = 0; } //lock (requestSocket) { var DataToSend = BuildDataStructure(replyBuffer); if (DataToSend.Length < 300) { var sendArray = new byte[300]; Array.Copy(DataToSend, 0, sendArray, 0, DataToSend.Length); DataToSend = sendArray; } if ((replyBuffer.giaddr[0] == 0) && (replyBuffer.giaddr[1] == 0) && (replyBuffer.giaddr[2] == 0) && (replyBuffer.giaddr[3] == 0)) { //requestSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, true); //endPoint = new IPEndPoint(dhcpServer.BroadcastAddress, PORT_TO_SEND_TO_CLIENT); //var udp = new UdpClient(); //udp.EnableBroadcast = true; //udp.Send(DataToSend, DataToSend.Length, new IPEndPoint(dhcpServer.BroadcastAddress, 68)); //udp.Close(); var datagramsocket = new Windows.Networking.Sockets.DatagramSocket(); using (var stream = await datagramsocket.GetOutputStreamAsync(new Windows.Networking.HostName(dhcpServer.BroadcastAddress), PORT_TO_SEND_TO_CLIENT.ToString())) { using (var datawriter = new Windows.Storage.Streams.DataWriter(stream)) { datawriter.WriteBytes(DataToSend); await datawriter.StoreAsync(); } } } else { //requestSocket .SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, false); //endPoint = new IPEndPoint(new IPAddress(replyBuffer.giaddr), PORT_TO_SEND_TO_RELAY); //requestSocket.SendTo(DataToSend, endPoint); using (var stream = await requestSocket.GetOutputStreamAsync(new Windows.Networking.HostName(new IPAddress(replyBuffer.giaddr).ToString()), PORT_TO_SEND_TO_RELAY.ToString())) { using (var datawriter = new Windows.Storage.Streams.DataWriter(stream)) { datawriter.WriteBytes(DataToSend); await datawriter.StoreAsync(); } } } } }
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); }
private async void ReadingChanged(object sender, AccelerometerReadingChangedEventArgs e) { DateTime localDate = DateTime.Now; await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async() => { AccelerometerReading reading = e.Reading; txtXAxis.Text = String.Format("{0,5:0.00}", reading.AccelerationX); txtYAxis.Text = String.Format("{0,5:0.00}", reading.AccelerationY); txtZAxis.Text = String.Format("{0,5:0.00}", reading.AccelerationZ); if (numero > 100) { txtXoldAxis.Text = "SAVING:" + numero; numero += 1; if (numero > 1000) { changer = true; numero = 0; } } else { numero += 1; txtXoldAxis.Text = "" + numero; } if (DataChanged == false) { old_x = txtXAxis.Text; old_y = txtYAxis.Text; old_z = txtZAxis.Text; txtXoldAxis.Text = old_x; txtYoldAxis.Text = old_y; txtZoldAxis.Text = old_z; DataChanged = true; } else { old_x = txtXAxis.Text; old_y = txtYAxis.Text; old_z = txtZAxis.Text; DataChanged = true; // print and SAVE DATA string new_line = localDate + "|" + old_x + "|" + old_y + "|" + old_z + "\n"; // WORK WITH FILE storage.txt string DataFile = @"Assets\storage.txt"; Windows.Storage.StorageFolder storageFolder = Windows.ApplicationModel.Package.Current.InstalledLocation; Windows.Storage.StorageFile sampleFile = await storageFolder.GetFileAsync(DataFile); //string oldData = await Windows.Storage.FileIO.ReadTextAsync(sampleFile); var stream = await sampleFile.OpenAsync(Windows.Storage.FileAccessMode.ReadWrite); string new_data; using (var outputStream = stream.GetOutputStreamAt(0)) { using (var dataWriter = new Windows.Storage.Streams.DataWriter(outputStream)) { if (changer == true) { new_data = new_line; dataWriter.WriteString(new_data); await dataWriter.StoreAsync(); await outputStream.FlushAsync(); changer = false; txtData.Text = new_data; } else { } } } stream.Dispose(); } }); }
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(); }
public virtual async System.Threading.Tasks.Task <IServiceResponse> PostAsyncWindowsWeb(Uri uri, byte[] audioBytes, apiArgs) { IServiceResponse response = new IServiceResponse(service); try { // Using HttpClient to grab chunked encoding (partial) responses. using (Windows.Web.Http.HttpClient httpClient = new Windows.Web.Http.HttpClient()) { Log.WriteLine("before requestContent"); Log.WriteLine("after requestContent"); // rate must be specified but doesn't seem to need to be accurate. Windows.Web.Http.IHttpContent requestContent = null; if (Options.options.APIs.preferChunkedEncodedRequests) { // using chunked transfer requests Log.WriteLine("Using chunked encoding"); Windows.Storage.Streams.InMemoryRandomAccessStream contentStream = new Windows.Storage.Streams.InMemoryRandomAccessStream(); // TODO: obsolete to use DataWriter? use await Windows.Storage.FileIO.Write..(file); Windows.Storage.Streams.DataWriter dw = new Windows.Storage.Streams.DataWriter(contentStream); dw.WriteBytes(audioBytes); await dw.StoreAsync(); // GetInputStreamAt(0) forces chunked transfer (sort of undocumented behavior). requestContent = new Windows.Web.Http.HttpStreamContent(contentStream.GetInputStreamAt(0)); } else { requestContent = new Windows.Web.Http.HttpBufferContent(audioBytes.AsBuffer()); } requestContent.Headers.Add("Content-Type", "audio/l16; rate=" + sampleRate.ToString()); // must add header AFTER contents are initialized Log.WriteLine("Before Post: Elapsed milliseconds:" + stopWatch.ElapsedMilliseconds); response.RequestElapsedMilliseconds = stopWatch.ElapsedMilliseconds; using (Windows.Web.Http.HttpResponseMessage hrm = await httpClient.PostAsync(uri, requestContent)) { response.RequestElapsedMilliseconds = stopWatch.ElapsedMilliseconds - response.RequestElapsedMilliseconds; response.StatusCode = (int)hrm.StatusCode; Log.WriteLine("After Post: StatusCode:" + response.StatusCode + " Total milliseconds:" + stopWatch.ElapsedMilliseconds + " Request milliseconds:" + response.RequestElapsedMilliseconds); if (hrm.StatusCode == Windows.Web.Http.HttpStatusCode.Ok) { string responseContents = await hrm.Content.ReadAsStringAsync(); string[] responseJsons = responseContents.Split("\n".ToCharArray(), StringSplitOptions.RemoveEmptyEntries); foreach (string rj in responseJsons) { response.ResponseJson = rj; Newtonsoft.Json.Linq.JToken ResponseBodyToken = Newtonsoft.Json.Linq.JObject.Parse(response.ResponseJson); response.ResponseJsonFormatted = Newtonsoft.Json.JsonConvert.SerializeObject(ResponseBodyToken, new Newtonsoft.Json.JsonSerializerSettings() { Formatting = Newtonsoft.Json.Formatting.Indented }); if (Options.options.debugLevel >= 4) { Log.WriteLine(response.ResponseJsonFormatted); } Newtonsoft.Json.Linq.JToken tokResult = ProcessResponse(ResponseBodyToken); if (tokResult == null || string.IsNullOrEmpty(tokResult.ToString())) { response.ResponseResult = Options.options.Services.APIs.SpeechToText.missingResponse; if (Options.options.debugLevel >= 3) { Log.WriteLine("ResponseResult:" + response.ResponseResult); } } else { response.ResponseResult = tokResult.ToString(); if (Options.options.debugLevel >= 3) { Log.WriteLine("ResponseResult:" + tokResult.Path + ": " + response.ResponseResult); } } } } else { response.ResponseResult = hrm.ReasonPhrase; Log.WriteLine("PostAsync Failed: StatusCode:" + hrm.ReasonPhrase + "(" + response.StatusCode.ToString() + ")"); } } } } catch (Exception ex) { Log.WriteLine("Exception:" + ex.Message); if (ex.InnerException != null) { Log.WriteLine("InnerException:" + ex.InnerException); } } return(response); }
private void buttonLoopbackTest_Click(object sender, RoutedEventArgs e) { // Unicode to ASCII. String textToSend = this.textBoxForLoopback.Text; var encoder = System.Text.Encoding.UTF8.GetEncoder(); var utf8bytes = new byte[textToSend.Length]; int bytesUsed, charsUsed; bool completed; encoder.Convert(textToSend.ToCharArray(), 0, textToSend.Length, utf8bytes, 0, utf8bytes.Length, true, out bytesUsed, out charsUsed, out completed); var writer = new Windows.Storage.Streams.DataWriter(); writer.WriteBytes(utf8bytes); writer.WriteByte(0x00); // NUL var buffer = writer.DetachBuffer(); this.buttonLoopbackTest.IsEnabled = false; this.buttonStopLoopback.IsEnabled = true; SDKTemplate.MainPage.Current.NotifyUser("", SDKTemplate.NotifyType.StatusMessage); var dispatcher = this.Dispatcher; ((Action)(async () => { await dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, new Windows.UI.Core.DispatchedHandler(async () => { // serialport1 to serialport2 var readBuffer = new Windows.Storage.Streams.Buffer(buffer.Length); readBuffer.Length = buffer.Length; var writeTask = this.SerialPortInfo1.Port.Write(buffer, 0, buffer.Length).AsTask(); var readTask = this.Read(this.SerialPortInfo2.Port, readBuffer, Constants.InfiniteTimeout).AsTask(); try { await System.Threading.Tasks.Task.WhenAll(new System.Threading.Tasks.Task[] {writeTask, readTask}); readBuffer.Length = (uint)readTask.Result; } catch (System.OperationCanceledException) { // canceled. SDKTemplate.MainPage.Current.NotifyUser("Canceled", SDKTemplate.NotifyType.ErrorMessage); this.buttonLoopbackTest.IsEnabled = true; this.buttonStopLoopback.IsEnabled = false; return; } finally { this.cancelTokenSrcOpRead = null; writeTask.AsAsyncAction().Cancel(); // just in case. readTask.AsAsyncAction().Cancel(); // just in case. } var isSame = Util.CompareTo(buffer, readBuffer) == 0; String statusMessage = ""; if (isSame) { statusMessage += "CDC device 2 received \"" + textToSend + "\" from CDC device 1. "; } else { statusMessage += "Loopback failed: CDC device 1 to CDC device 2. "; } // serialport2 to serialport1 readBuffer.Length = buffer.Length; writeTask = this.SerialPortInfo2.Port.Write(buffer, 0, buffer.Length).AsTask(); readTask = this.Read(this.SerialPortInfo1.Port, readBuffer, Constants.InfiniteTimeout).AsTask(); try { await System.Threading.Tasks.Task.WhenAll(new System.Threading.Tasks.Task[] { writeTask, readTask }); readBuffer.Length = (uint)readTask.Result; } catch (System.OperationCanceledException) { // canceled. SDKTemplate.MainPage.Current.NotifyUser("Canceled", SDKTemplate.NotifyType.ErrorMessage); this.buttonLoopbackTest.IsEnabled = true; this.buttonStopLoopback.IsEnabled = false; return; } finally { this.cancelTokenSrcOpRead = null; writeTask.AsAsyncAction().Cancel(); // just in case. readTask.AsAsyncAction().Cancel(); // just in case. } isSame = Util.CompareTo(buffer, readBuffer) == 0; if (isSame) { statusMessage += "CDC device 1 received \"" + textToSend + "\" from CDC device 2. "; } else { statusMessage += "Loopback failed: CDC device 2 to CDC device 1. "; } this.buttonLoopbackTest.IsEnabled = true; this.buttonStopLoopback.IsEnabled = false; SDKTemplate.MainPage.Current.NotifyUser(statusMessage, SDKTemplate.NotifyType.StatusMessage); })); } )).Invoke(); }
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(); }
/* socket functions */ public async Task socket_onDataReceived(string message, Windows.Storage.Streams.DataWriter writer) { System.Diagnostics.Debug.WriteLine("received: " + message); if (message.Equals("@welcome@")) { //if the message is from the ScaleHub we don't use DRP, just send back the scale's name. await tcp.Send("TAUIOT@devname=" + PermanentData.Devname, writer); return; } //getting and parsing the messsage DRP msg; try { msg = DRP.deserializeDRP(message); } catch { System.Diagnostics.Debug.WriteLine("non-DRP message received."); return; } /* taking care of illegal messages */ if (msg.DevType == DRPDevType.RBPI) { DRP response = new DRP(DRPDevType.RBPI, "", PermanentData.Serial, PermanentData.Devname, 0, 0, DRPMessageType.ILLEGAL); await tcp.Send(response.ToString(), writer); return; } if (msg.MessageType == DRPMessageType.DATA || msg.MessageType == DRPMessageType.HARDWARE_ERROR || msg.MessageType == DRPMessageType.IN_USE) { DRP response = new DRP(DRPDevType.RBPI, "", PermanentData.Serial, PermanentData.Devname, 0, 0, DRPMessageType.ILLEGAL); await tcp.Send(response.ToString(), writer); return; } /* taking care of SCANNED messages */ if (msg.MessageType == DRPMessageType.SCANNED) { if (uhl == null) { //if there is no uhl, return HARDWARE_ERROR DRP response = new DRP(DRPDevType.RBPI, msg.UserName, PermanentData.Serial, PermanentData.Devname, 0, 0, DRPMessageType.HARDWARE_ERROR); await tcp.Send(response.ToString(), writer); System.Diagnostics.Debug.WriteLine("message sent: " + response.ToString()); return; } TempProfile profile = new TempProfile(msg.UserName, msg.Token, 0); if (uhl.currentServedUser() == null) { //if no user uses the weight uhl.StartUser(profile); try { double w = uhl.getWeight(UserHardwareLinker.WEIGH_AVG); DRP response = new DRP(DRPDevType.RBPI, msg.UserName, PermanentData.Serial, PermanentData.Devname, (float)w, 0, DRPMessageType.DATA); //sending result to client Task sendTask = tcp.Send(response.ToString(), writer); System.Diagnostics.Debug.WriteLine("message sent: " + response.ToString()); //sending to cloud Dictionary <string, string> jsend = new Dictionary <string, string>(); jsend.Add("username", msg.UserName); jsend.Add("weigh", w.ToString()); Task cloudTask = null; if (msg.UserName != null) { string sendToCloud = JsonConvert.SerializeObject(jsend); cloudTask = AzureIoTHub.SendDeviceToCloudMessageAsync(sendToCloud); System.Diagnostics.Debug.WriteLine("Send to cloud with user: "******"!!!!!!!!!!Not sent!"); } await sendTask; uhl.FinishUser(); if (cloudTask != null) { await cloudTask; } return; } catch { DRP response = new DRP(DRPDevType.RBPI, msg.UserName, PermanentData.Serial, PermanentData.Devname, 0, 0, DRPMessageType.HARDWARE_ERROR); await tcp.Send(response.ToString(), writer); System.Diagnostics.Debug.WriteLine("message sent: " + response.ToString()); uhl.FinishUser(); return; } } else { //if somwone already uses the weight DRP response = new DRP(DRPDevType.RBPI, msg.UserName, PermanentData.Serial, PermanentData.Devname, 0, 0, DRPMessageType.IN_USE); await tcp.Send(response.ToString(), writer); System.Diagnostics.Debug.WriteLine("message sent: " + response.ToString()); } } else if (msg.MessageType == DRPMessageType.ILLEGAL) { //never actually happens. DRP response = new DRP(DRPDevType.RBPI, "", PermanentData.Serial, PermanentData.Devname, 0, 0, DRPMessageType.ACK); await tcp.Send(response.ToString(), writer); System.Diagnostics.Debug.WriteLine("message sent: " + response.ToString()); } else { throw new Exception(); } }
/// <summary> /// Сохраняет развертку в локальную папку /// </summary> /// <param name="data"></param> /// <param name="Tail"></param> /// <param name="time"></param> /// <param name="nameFile"></param> /// <returns></returns> public async System.Threading.Tasks.Task saveAsync(int[,] data, int[,] Tail, string time, string nameFile) { string cul = "en-US"; var folderPicker = new Windows.Storage.Pickers.FolderPicker(); folderPicker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.Desktop; folderPicker.FileTypeFilter.Add("*"); Windows.Storage.StorageFolder folder = await folderPicker.PickSingleFolderAsync(); if (folder != null) { // Application now has read/write access to all contents in the picked folder // (including other sub-folder contents) Windows.Storage.AccessCache.StorageApplicationPermissions. FutureAccessList.AddOrReplace("PickedFolderToken", folder); StorageFolder storageFolderRazvertka = await folder.CreateFolderAsync("Развертка", CreationCollisionOption.OpenIfExists); StorageFile sampleFile = await storageFolderRazvertka.CreateFileAsync(nameFile + time + ".txt", CreationCollisionOption.ReplaceExisting); var stream = await sampleFile.OpenAsync(Windows.Storage.FileAccessMode.ReadWrite); using (var outputStream = stream.GetOutputStreamAt(0)) { using (var dataWriter = new Windows.Storage.Streams.DataWriter(outputStream)) { string s = "i" + "\t" + "Ch1" + "\t" + "Ch2" + "\t" + "Ch3" + "\t" + "Ch4" + "\t" + "Ch5" + "\t" + "Ch6" + "\t" + "Ch7" + "\t" + "Ch8" + "\t" + "Ch9" + "\t" + "Ch10" + "\t" + "Ch11" + "\t" + "Ch12" + "\r\n"; for (int i = 0; i < 1024; i++) { s = s + (i + 1).ToString() + "\t"; for (int j = 0; j < 12; j++) { s = s + data[j, i] + "\t"; } if (i < 1023) { s = s + "\r\n"; } else { } } dataWriter.WriteString(s); s = null; await dataWriter.StoreAsync(); await outputStream.FlushAsync(); } } stream.Dispose(); // Or use the stream variable (see previous code snippet) with a using statement as well. if (ClassUserSetUp.TipTail) { // storageFolderRazvertka = await storageFolderRazvertka.CreateFolderAsync("Развертка", CreationCollisionOption.OpenIfExists); sampleFile = await storageFolderRazvertka.CreateFileAsync(nameFile + time + "Хвост" + ".txt", CreationCollisionOption.ReplaceExisting); stream = await sampleFile.OpenAsync(Windows.Storage.FileAccessMode.ReadWrite); using (var outputStream = stream.GetOutputStreamAt(0)) { using (var dataWriter = new Windows.Storage.Streams.DataWriter(outputStream)) { string s = "i" + "\t" + "Ch1" + "\t" + "Ch2" + "\t" + "Ch3" + "\t" + "Ch4" + "\t" + "Ch5" + "\t" + "Ch6" + "\t" + "Ch7" + "\t" + "Ch8" + "\t" + "Ch9" + "\t" + "Ch10" + "\t" + "Ch11" + "\t" + "Ch12" + "\r\n"; for (int i = 0; i < 20000; i++) { s = s + (i + 1).ToString() + "\t"; for (int j = 0; j < 12; j++) { s = s + Tail[j, i] + "\t"; } if (i < 19999) { s = s + "\r\n"; } else { } dataWriter.WriteString(s); s = null; } await dataWriter.StoreAsync(); await outputStream.FlushAsync(); } } stream.Dispose(); } } }