public DomainParticipantTransportSource(DomainParticipant participant, string senderTopic, string receiverTopic) { _participant = participant; var senderTopicQos = new TopicQos(); participant.get_default_topic_qos(senderTopicQos); var receiverTopicQos = new TopicQos(); participant.get_default_topic_qos(receiverTopicQos); _sender = participant.create_topic(senderTopic, BytesTypeSupport.TYPENAME, senderTopicQos, null, StatusMask.STATUS_MASK_NONE); _receiver = participant.create_topic(receiverTopic, BytesTypeSupport.TYPENAME, receiverTopicQos, null, StatusMask.STATUS_MASK_NONE); var writerQos = new DataWriterQos(); //writerQos.publish_mode.kind = PublishModeQosPolicyKind.ASYNCHRONOUS_PUBLISH_MODE_QOS; writerQos.publish_mode.flow_controller_name = FlowController.FIXED_RATE_FLOW_CONTROLLER_NAME; participant.get_default_datawriter_qos(writerQos); var readerQos = new DataReaderQos(); participant.get_default_datareader_qos(readerQos); _writer = participant.create_datawriter(_sender, writerQos, null, StatusMask.STATUS_MASK_NONE); _reader = participant.create_datareader(_receiver, readerQos, this, StatusMask.STATUS_MASK_ALL); }
public static void IndexUimfFile(string uimfFileLocation) { bool indexed = false; using (var uimfReader = new DataReader(uimfFileLocation)) { if (uimfReader.DoesContainBinCentricData()) { indexed = true; Console.WriteLine("Bin centric data found in dataset {0}.", uimfFileLocation); } else { Console.WriteLine("No bin centric data found for file {0}.", uimfFileLocation); } uimfReader.Dispose(); } if (!indexed) { Console.WriteLine("Creating bin centric data for {0}.", uimfFileLocation); using (DataWriter dataWriter = new DataWriter(uimfFileLocation)) { dataWriter.CreateBinCentricTables(); dataWriter.Dispose(); } } }
protected override void SaveBody(IDataWriter writer, IMessage msg) { using (GZipStream compStream = new GZipStream((Stream)writer, CompressionMode.Compress)) { DataWriter dw = new DataWriter(compStream, writer.LittleEndian); base.SaveBody(dw, msg); } }
// Write a datakey to a stream public void ToWriter(DataWriter writer, DataKey root, Logger logger) { logger.LogInfo("Writing to stream"); // Write Data node back to stream // Will throw MissingDataNodeException if it does not exist byte[] data = root["data"].ToArray().Reverse().ToArray(); writer.Write(data); }
public virtual void Write(string name, long dataSizeInBytes, string userName, string groupName, int mode, DateTime lastModificationTime, WriteDataDelegate writeDelegate) { var writer = new DataWriter(OutStream,dataSizeInBytes); WriteHeader(name, lastModificationTime, dataSizeInBytes, userName, groupName, mode); while(writer.CanWrite) { writeDelegate(writer); } AlignTo512(dataSizeInBytes, false); }
public async void SendMotorCommand(Boolean on, int tilt, int forward, int turn, int up, float scale) { var characteristics = _service.GetCharacteristics(RollingSpiderCharacteristicUuids.Parrot_PowerMotors); var characteristic = characteristics[0]; var writer = new DataWriter(); try { writer.WriteByte(2); writer.WriteByte((byte)_motorCounter); writer.WriteByte(2); writer.WriteByte(0); writer.WriteByte(2); writer.WriteByte(0); if (on) { writer.WriteByte(1); } else { writer.WriteByte(0); } // is byte casting necessary??? writer.WriteByte((byte)(tilt & 0xFF)); writer.WriteByte((byte)(forward & 0xFF)); writer.WriteByte((byte)(turn & 0xFF)); writer.WriteByte((byte)(up & 0xFF)); //writer.WriteDouble(scale); // well, but I need different endian :( await characteristic.WriteValueAsync(writer.DetachBuffer()); } catch (IOException e) { Debug.WriteLine(e); } //var gattTransaction = new GattReliableWriteTransaction(); //gattTransaction.WriteValue(characteristic, writer.DetachBuffer()); //var status = await gattTransaction.CommitAsync(); //switch (status) //{ // case GattCommunicationStatus.Success: // AddLogAction("Writing to your device OK !"); // break; // case GattCommunicationStatus.Unreachable: // AddLogAction("Writing to your device Failed !"); // break; //} }
protected override void SaveBody(IDataWriter writer, IMessage msg) { using (TripleDESCryptoServiceProvider tdsAlg = new TripleDESCryptoServiceProvider()) { tdsAlg.Key = mKey; tdsAlg.IV = mIV; ICryptoTransform encryptor = tdsAlg.CreateEncryptor(tdsAlg.Key, tdsAlg.IV); using (CryptoStream csEncrypt = new CryptoStream((Stream)writer, encryptor, CryptoStreamMode.Write)) { DataWriter dw = new DataWriter(csEncrypt, writer.LittleEndian); base.SaveBody(dw, msg); csEncrypt.FlushFinalBlock(); } } }
public SaturationDetector(string uimfFileLocation) { _uimfReader = new DataReader(uimfFileLocation); _smoother = new SavitzkyGolaySmoother(9, 2); _peakDetector = new ChromPeakDetector(0.0001, 0.0001); _theoreticalFeatureGenerator = new JoshTheorFeatureGenerator(); if (!_uimfReader.DoesContainBinCentricData()) { DataWriter dataWriter = new DataWriter(uimfFileLocation); dataWriter.CreateBinCentricTables(); } IterativeTFFParameters msFeatureFinderParameters = new IterativeTFFParameters { MinimumRelIntensityForForPeakInclusion = 0.0000000001, PeakDetectorMinimumPeakBR = 0, PeakDetectorPeakBR = 5.00000000000002, PeakBRStep = 0.25, PeakDetectorSigNoiseRatioThreshold = 0.00000000001, ToleranceInPPM = 50 }; _msFeatureFinder = new IterativeTFF(msFeatureFinderParameters); }
private void WriteHeaders(DataWriter writer) { string writeHeader = OnWriteHeader(); // null indicates that a response has no headers if (writeHeader != null) { WriteLine(writer, writeHeader); foreach (KeyDataPair<string> pair in Headers) { if (!FilterHeader(pair.Name, pair.Value)) { WriteLine(writer, String.Format("{0}: {1}", pair.Name, pair.Value)); } } // If this is the one and only chunk with content-length then send new length header if (!ChunkedEncoding && FinalChunk && CanSendBody()) { WriteLine(writer, String.Format("Content-Length: {0}", GetBody().Length)); } WriteLine(writer, String.Empty); } }
public async Task ReadFromServer(DataReader reader, DataWriter writer) { // set the DataReader to only wait for available data reader.InputStreamOptions = InputStreamOptions.Partial; if (!IsAuthed) { AttemptAuth(); } else { try { await reader.LoadAsync(socketReceiveBufferSize); while (reader.UnconsumedBufferLength > 0) { bool breakLoop = false; byte readChar; do { if (reader.UnconsumedBufferLength > 0) { readChar = reader.ReadByte(); } else { breakLoop = true; break; } } while (!dataStreamLineReader.Add(readChar)); if (breakLoop) { return; } // Read next line from data stream. var line = dataStreamLineReader.SafeFlushLine(); if (line == null) { break; } if (line.Length == 0) { continue; } await HandleLine(line); } } catch (Exception e) { AddError("Error with connection: " + e.Message); AddError(e.StackTrace); ReadOrWriteFailed = true; IsConnected = false; if (server != null) { DisconnectAsync(attemptReconnect: Config.GetBoolean(Config.AutoReconnect)); } return; } } }
/// <summary>Saves the content to the specified writer.</summary> /// <param name="writer">The writer.</param> protected override void SaveContentTo(DataWriter writer) { writer.Write(Horizontal); writer.Write(Vertical); }
// 导出课程表具体实现 private async void exportCourseTable(string xnd, string xq) { try { string json = @"{ body:{ dataStores:{}, parameters:{ args: [""" + xq + @""",""" + xnd + @"""], responseParam = ""rs"" } } }"; HttpClient httpClient = new HttpClient(); httpClient.DefaultRequestHeaders.Add("Referer", "http://uems.sysu.edu.cn/jwxt/forward.action?path=/sysu/xk/xskbcx/xskb"); httpClient.DefaultRequestHeaders.Add("render", "export"); var stringContent = new StringContent(json, Encoding.UTF8, "application/json"); HttpResponseMessage httpResponse = await httpClient.PostAsync("http://uems.sysu.edu.cn/jwxt/KcbcxAction/KcbcxAction.action?method=getList", stringContent); httpResponse.EnsureSuccessStatusCode(); var downloadUrl = "http://uems.sysu.edu.cn/jwxt/ExportToExcel.do?method=exportExcel&xq=" + xq + "&xnd=" + xnd; httpClient.DefaultRequestHeaders.Referrer = new Uri("http://uems.sysu.edu.cn/jwxt/forward.action?path=/sysu/xk/xskbcx/xskb"); httpClient.DefaultRequestHeaders.Add("Accept", "image/gif, image/jpeg, image/pjpeg, application/x-ms-application, application/xaml+xml, application/x-ms-xbap, */*"); httpResponse = await httpClient.GetAsync(downloadUrl); httpResponse.EnsureSuccessStatusCode(); InMemoryRandomAccessStream randomAccess = new InMemoryRandomAccessStream(); DataWriter writer = new DataWriter(randomAccess.GetOutputStreamAt(0)); // Write and save the data into the stream writer.WriteBytes(await httpResponse.Content.ReadAsByteArrayAsync()); await writer.StoreAsync(); var savePicker = new FileSavePicker(); savePicker.SuggestedStartLocation = PickerLocationId.Desktop; savePicker.FileTypeChoices.Add("网页", new List <string>() { ".html" }); savePicker.SuggestedFileName = xnd + "-" + xq + ".html"; StorageFile file = await savePicker.PickSaveFileAsync(); if (file != null) { CachedFileManager.DeferUpdates(file); await FileIO.WriteTextAsync(file, table); //store InMemoryRandomAccessStream into a file //using (var fileStream = await file.OpenAsync(FileAccessMode.ReadWrite)) { // await RandomAccessStream.CopyAndCloseAsync(randomAccess.GetInputStreamAt(0), fileStream.GetOutputStreamAt(0)); //} //httpClient.Dispose(); FileUpdateStatus status = await CachedFileManager.CompleteUpdatesAsync(file); if (status == FileUpdateStatus.Complete) { await new MessageDialog("课表导出成功!").ShowAsync(); } else { await new MessageDialog("课表导出失败!").ShowAsync(); } } else { return; } } catch (Exception ex) { Debug.WriteLine(ex.Message); if (ex.Message.Equals("An error occurred while sending the request.")) { await new MessageDialog("应用无法联网,请检查您的网络设置").ShowAsync(); } } }
public virtual void Write(DataWriter writer) { writer.Write(Id); }
public async void SendCommandTo1StChar(IReadOnlyList<GattCharacteristic> characteristics, byte[] commandToWrite) { var characteristic = characteristics[0]; Debug.WriteLine("Try to write to " + CharacteristicUuidsResolver.GetNameFromUuid(characteristic.Uuid)); try { var writer = new DataWriter(); writer.WriteBytes(commandToWrite); await characteristic.WriteValueAsync(writer.DetachBuffer()); } catch { } }
/// <summary> /// Initializes a new instance of the <see cref="LibraryMatchWorkflow"/> class. /// </summary> /// <param name="uimfFileLocation"> /// The UIMF file location. /// </param> /// <param name="outputDirectory"> /// The output directory. /// </param> /// <param name="resultFileName"> /// The result file name. /// </param> /// <param name="parameters"> /// The parameters. /// </param> public LibraryMatchWorkflow(string uimfFileLocation, string outputDirectory, string resultFileName, LibraryMatchParameters parameters) { this.uimfReader = new DataReader(uimfFileLocation); // Append bin-centric table to the uimf if not present. if (!this.uimfReader.DoesContainBinCentricData()) { DataWriter dataWriter = new DataWriter(uimfFileLocation); dataWriter.CreateBinCentricTables(); } this.Parameters = parameters; this.smoother = new SavitzkyGolaySmoother(parameters.NumPointForSmoothing, 2); this.NumberOfFrames = this.uimfReader.GetGlobalParams().NumFrames; this.NumberOfScans = this.uimfReader.GetFrameParams(1).Scans; this.DatasetName = Path.GetFileNameWithoutExtension(uimfFileLocation); this.Parameters = parameters; this.ResultFileName = resultFileName; if (outputDirectory == string.Empty) { outputDirectory = Directory.GetCurrentDirectory(); } if (!outputDirectory.EndsWith("\\")) { outputDirectory += "\\"; } if (!Directory.Exists(outputDirectory)) { try { Directory.CreateDirectory(outputDirectory); } catch (Exception) { Console.WriteLine("Failed to create directory."); throw; } } this.OutputPath = outputDirectory; Trace.Listeners.Clear(); ConsoleTraceListener consoleTraceListener = new ConsoleTraceListener(false); consoleTraceListener.TraceOutputOptions = TraceOptions.DateTime; string result = this.OutputPath + this.ResultFileName; this.resultFileWriter = File.AppendText(result); TextWriterTraceListener resultFileTraceListener = new TextWriterTraceListener(this.resultFileWriter) { Name = "this.DatasetName" + "_Result", TraceOutputOptions = TraceOptions.ThreadId | TraceOptions.DateTime }; Trace.Listeners.Add(consoleTraceListener); Trace.Listeners.Add(resultFileTraceListener); Trace.AutoFlush = true; }
/// <summary> /// Initializes the singleton application object. This is the first line of authored code /// executed, and as such is the logical equivalent of main() or WinMain(). /// </summary> public Scenario1_Watcher() { this.InitializeComponent(); // Create and initialize a new watcher instance. watcher = new BluetoothLEAdvertisementWatcher(); // Begin of watcher configuration. Configure the advertisement filter to look for the data advertised by the publisher // in Scenario 2 or 4. You need to run Scenario 2 on another Windows platform within proximity of this one for Scenario 1 to // take effect. The APIs shown in this Scenario are designed to operate only if the App is in the foreground. For background // watcher operation, please refer to Scenario 3. // Please comment out this following section (watcher configuration) if you want to remove all filters. By not specifying // any filters, all advertisements received will be notified to the App through the event handler. You should comment out the following // section if you do not have another Windows platform to run Scenario 2 alongside Scenario 1 or if you want to scan for // all LE advertisements around you. // For determining the filter restrictions programatically across APIs, use the following properties: // MinSamplingInterval, MaxSamplingInterval, MinOutOfRangeTimeout, MaxOutOfRangeTimeout // Part 1A: Configuring the advertisement filter to watch for a particular advertisement payload // First, let create a manufacturer data section we wanted to match for. These are the same as the one // created in Scenario 2 and 4. var manufacturerData = new BluetoothLEManufacturerData(); // Then, set the company ID for the manufacturer data. Here we picked an unused value: 0xFFFE manufacturerData.CompanyId = 0xFFFE; // Finally set the data payload within the manufacturer-specific section // Here, use a 16-bit UUID: 0x1234 -> {0x34, 0x12} (little-endian) var writer = new DataWriter(); writer.WriteUInt16(0x1234); // Make sure that the buffer length can fit within an advertisement payload. Otherwise you will get an exception. manufacturerData.Data = writer.DetachBuffer(); // Add the manufacturer data to the advertisement filter on the watcher: watcher.AdvertisementFilter.Advertisement.ManufacturerData.Add(manufacturerData); // Part 1B: Configuring the signal strength filter for proximity scenarios // Configure the signal strength filter to only propagate events when in-range // Please adjust these values if you cannot receive any advertisement // Set the in-range threshold to -70dBm. This means advertisements with RSSI >= -70dBm // will start to be considered "in-range". watcher.SignalStrengthFilter.InRangeThresholdInDBm = -70; // Set the out-of-range threshold to -75dBm (give some buffer). Used in conjunction with OutOfRangeTimeout // to determine when an advertisement is no longer considered "in-range" watcher.SignalStrengthFilter.OutOfRangeThresholdInDBm = -75; // Set the out-of-range timeout to be 2 seconds. Used in conjunction with OutOfRangeThresholdInDBm // to determine when an advertisement is no longer considered "in-range" watcher.SignalStrengthFilter.OutOfRangeTimeout = TimeSpan.FromMilliseconds(2000); // By default, the sampling interval is set to zero, which means there is no sampling and all // the advertisement received is returned in the Received event // End of watcher configuration. There is no need to comment out any code beyond this point. }
private async Task SendMessagesAsync() { try { MessageWebSocket webSocket = new MessageWebSocket(); webSocket.MessageReceived += WebSocket_MessageReceived; webSocket.Closed += WebSocket_Closed; DataWriter messageWriter = new DataWriter(webSocket.OutputStream); await webSocket.ConnectAsync(new Uri(URL)); _connectionState = ConnectionState.CONNECTED; while (_connectionState == ConnectionState.CONNECTED) { _sendEvent.WaitOne(50); Message msg = null; lock (_sendQueue) { if (_sendQueue.Count > 0) { msg = _sendQueue.Dequeue(); } } while (msg != null) { if (msg is TextMessage) { webSocket.Control.MessageType = SocketMessageType.Utf8; messageWriter.WriteString(((TextMessage)msg).Text); await messageWriter.StoreAsync(); } else if (msg is BinaryMessage) { webSocket.Control.MessageType = SocketMessageType.Binary; messageWriter.WriteBytes(((BinaryMessage)msg).Data); await messageWriter.StoreAsync(); } msg = null; lock (_sendQueue) { if (_sendQueue.Count > 0) { msg = _sendQueue.Dequeue(); } } } } webSocket.Close(1000, "Complete"); } catch (System.Exception e) { _connectionState = ConnectionState.DISCONNECTED; Log.Error("WSConnector.SendMessagesAsync()", "Caught WebSocket exception: {0}", e.ToString()); } }
private void btnConvertBCIToPalmtree_Click(object sender, EventArgs e) { // clear the output txtOutput.Text = ""; // try to read the file Data_BCI2000 info = new Data_BCI2000(); double[][] samples = null; bool result = readBCI2000dat(txtInputFile.Text, out info, out samples); // open file dialog to save dat file SaveFileDialog dlgSaveDatFile = new SaveFileDialog(); dlgSaveDatFile.Filter = "Data files (*.dat)|*.dat|Data files (*.src)|*.src|All files (*.*)|*.*"; dlgSaveDatFile.RestoreDirectory = true; // restores current directory to the previously selected directory, potentially beneficial if other code relies on the currently set directory // check if ok has been clicked on the dialog if (dlgSaveDatFile.ShowDialog() != DialogResult.OK) { return; } FileStream dataStream = null; try { // create filestream: create file if it does not exists, allow to write, do not share with other processes and use buffer of 8192 bytes (roughly 1000 samples) dataStream = new FileStream(dlgSaveDatFile.FileName, FileMode.Create, FileAccess.Write, FileShare.None, 8192); } catch (Exception exc) { MessageBox.Show("Unable to create data file at " + dlgSaveDatFile.FileName + " (" + exc.ToString() + ")"); return; } // generate stream names for the header (bci2000 does not have these) string[] streamNames = new string[info.sourceCh]; for (int i = 0; i < streamNames.Length; i++) { streamNames[i] = "Ch" + (i + 1); } // create header DataHeader header = new DataHeader(); header.version = 1; header.code = "dat"; header.columnNames = streamNames; header.numPlaybackStreams = streamNames.Length; header.sampleRate = info.samplingRate; // write header if (dataStream != null) { DataWriter.writeBinaryHeader(dataStream, header); } // write data uint dataSampleCounter = 0; byte[] dataElapsedTimeBinary = BitConverter.GetBytes((1000.0 / header.sampleRate)); for (int i = 0; i < info.numSamples; i++) { // transform variables that will be stored in .dat to binary arrays (except for dataStreamValues array which is copied directly) byte[] dataSampleCounterBinary = BitConverter.GetBytes(dataSampleCounter); // transfer the values for output double[] dataStreamValues = new double[info.sourceCh]; for (int j = 0; j < info.sourceCh; j++) { dataStreamValues[j] = samples[i][j]; } // create new array to hold all bytes int l1 = dataSampleCounterBinary.Length; int l2 = dataElapsedTimeBinary.Length; int l3 = dataStreamValues.Length * sizeof(double); byte[] streamOut = new byte[l1 + l2 + l3]; // blockcopy all bytes to this array Buffer.BlockCopy(dataSampleCounterBinary, 0, streamOut, 0, l1); Buffer.BlockCopy(dataElapsedTimeBinary, 0, streamOut, l1, l2); Buffer.BlockCopy(dataStreamValues, 0, streamOut, l1 + l2, l3); // write data to file if (dataStream != null) { dataStream.Write(streamOut, 0, streamOut.Length); } // increase sample counter dataSampleCounter++; } // set output text txtOutput.Text = "Done"; // clear dataStream.Close(); dataStream = null; }
public async Task <string> Send(string msg, int retryCount = 0) { try { if (_socket == null) { bool bOK = await Connect(); if (!bOK) { string recoMsg = "Failed to reconnect. Cannot retry the Send() of " + msg; FireCommError(recoMsg); return("Failed."); } } string resultMsg = string.Empty; if (retryCount > 4) { string errMsg = $"Failed to re-open the socket after {retryCount} attempts."; FireCommError(errMsg); return(errMsg); } try { if (LoopTaskIsDead()) { //make another receive loop ReceiveLoop(); } } catch (Exception exLoopTask) { FireCommError("Error making ReceiveLoop task: " + exLoopTask.Message); } try { // Launch an async task to complete the write operation var writer = new DataWriter(_socket.OutputStream); //writer.WriteUInt32((uint)msg.Length + 2); writer.WriteString(msg + "\r\n"); var store = await writer.StoreAsync(); //var store = writer.StoreAsync().AsTask(); //dummy response for now writer.DetachStream(); string response = ""; return(response); } catch (Exception ex) { if (ex.Message == "A method was called at an unexpected time. (Exception from HRESULT: 0x8000000E)") { resultMsg = "Bluetooth on the RaspberryPi might need a reboot (" + ex.Message + ")"; } else if (ex.Message == "The object has been closed. (Exception from HRESULT: 0x80000013)") { //call connect and myself again bool bOK = await Connect(); if (bOK) { retryCount++; Send(msg, retryCount); } else { resultMsg = "Failed to reconnect. Cannot retry the Send() of " + msg; } } else { resultMsg = ex.Message; } FireCommError(resultMsg); return(""); } } catch (AggregateException aggEx) { string errMsg = $"Aggregate exception occurred in Send(). " + aggEx.Message; FireCommError(errMsg); return(errMsg); } catch (Exception anyEx) { string errMsg = $"Wide exception occurred in Send(). " + anyEx.Message; FireCommError(errMsg); return(errMsg); } }
public async void Disconnect(string disconnectReason) { string msg = string.Empty; try { if (_listener != null) { _listener.Dispose(); } } catch (Exception ex) { msg += "Disposing _listener: " + ex.Message; } try { if (_socketWriter != null) { try { _socketWriter.DetachStream(); } catch (Exception exDetachWriter) { msg += "Detaching _socketWriter: " + exDetachWriter.Message; } try { _socketWriter.Dispose(); } catch (Exception exDisposeWriter) { msg += "Disposing _socketWriter: " + exDisposeWriter.Message; } _socketWriter = null; } } catch (Exception ex) { msg += "General error Disposing _socketWriter: " + ex.Message; } try { if (_socketReader != null) { try { _socketReader.DetachStream(); } catch (Exception exDetachReader) { msg += "Detaching _socketReader: " + exDetachReader.Message; } try { _socketReader.Dispose(); } catch (Exception exDisposeReader) { msg += "Disposing _socketReader: " + exDisposeReader.Message; } _socketReader = null; } } catch (Exception ex) { msg += "General error Disposing _socketReader: " + ex.Message; } try { if (_socket != null) { try { await _socket.CancelIOAsync(); } catch (Exception exCancelIO) { msg += "Cancelling _socket IO: " + exCancelIO.Message; } _socket.Dispose(); _socket = null; } } catch (Exception ex) { msg += "Disposing _socket: " + ex.Message; } try { if (_service != null) { _service.Dispose(); _service = null; } } catch (Exception ex) { msg += "Disposing _service: " + ex.Message; } FireCommInfoMessage("Disconnected. " + disconnectReason + " " + msg); }
public void Write(DataWriter writer) { writer.Write(this.Value); }
public override DataFrame Read() { try { if (_request == null) { _request = HttpParser.ReadRequestHeader(new DataReader(_stm), false, _logger); } if (_chunks == null) { _chunks = _request.ReadChunks(_config).GetEnumerator(); // If we can't move to the first chunk (headers) there is a serious issue if (!_chunks.MoveNext()) { throw new EndOfStreamException(); } } HttpRequestDataChunk chunk = _chunks.Current; if (!_chunks.MoveNext()) { _request = null; _chunks = null; } MemoryStream stm = new MemoryStream(); DataWriter writer = new DataWriter(stm); chunk.WriteChunk(writer); return new DataFrame(stm.ToArray()); } catch (EndOfStreamException) { return null; } }
public void ToWriter(DataWriter writer, DataKey root, Logger logger) { HTTPDataResponse resp = HTTPDataResponse.FromDataKey(root); resp.ToWriter(writer, logger); }
private void WritePropertyValues(DataWriter writer, bool useAllValueSources) { }
private object DoLen(object target, object[] args) { if (args.Length == 0) { return 0; } Array a = args[0] as Array; string s = args[0] as string; DataReader reader = args[0] as DataReader; IStreamTypeParser parser = args[0] as IStreamTypeParser; if (s != null) { return s.Length; } else if (a != null) { return a.Length; } else if (reader != null) { return reader.DataLeft; } else if (parser != null) { DataWriter writer = new DataWriter(); parser.ToStream(writer, CreateState(target), _logger); return writer.BytesWritten; } return 0; }
public WebMessageSocket() { _socket = GetMessageWebSocket(); _dataWriter = GetDataWriter(); }
public override async void Connect() { if (server == null) { return; } IsAuthed = false; ReadOrWriteFailed = false; if (!ConnCheck.HasInternetAccess) { var autoReconnect = Config.GetBoolean(Config.AutoReconnect); var msg = autoReconnect ? "We'll try to connect once a connection is available." : "Please try again once your connection is restored"; var error = Irc.CreateBasicToast("No connection detected.", msg); error.ExpirationTime = DateTime.Now.AddDays(2); ToastNotificationManager.CreateToastNotifier().Show(error); if (!autoReconnect) { DisconnectAsync(attemptReconnect: autoReconnect); } return; } streamSocket = new StreamSocket(); streamSocket.Control.KeepAlive = true; if (Config.GetBoolean(Config.IgnoreSSL)) { streamSocket.Control.IgnorableServerCertificateErrors.Add(ChainValidationResult.Untrusted); streamSocket.Control.IgnorableServerCertificateErrors.Add(ChainValidationResult.Expired); } dataStreamLineReader = new SafeLineReader(); try { var protectionLevel = server.ssl ? SocketProtectionLevel.Tls12 : SocketProtectionLevel.PlainSocket; Debug.WriteLine("Attempting to connect..."); await streamSocket.ConnectAsync(new Windows.Networking.HostName(server.hostname), server.port.ToString(), protectionLevel); Debug.WriteLine("Connected!"); reader = new DataReader(streamSocket.InputStream); writer = new DataWriter(streamSocket.OutputStream); IsConnected = true; IsReconnecting = false; ConnectionHandler(); } catch (Exception e) { var autoReconnect = Config.GetBoolean(Config.AutoReconnect, true); var msg = autoReconnect ? "Attempting to reconnect..." : "Please try again later."; AddError("Error whilst connecting: " + e.Message + "\n" + msg); AddError(e.StackTrace); AddError("If this error keeps occuring, ensure your connection settings are correct."); DisconnectAsync(attemptReconnect: autoReconnect); Debug.WriteLine(e.Message); Debug.WriteLine(e.StackTrace); } }
/// <summary> /// /// </summary> /// <param name="stm"></param> public override void ToWriter(DataWriter stm) { stm.Write(ToArray()); }
private static int WriteLiterals(DataWriter writer, List <byte> literals) { writer.Write((byte)literals.Count); writer.Write(literals.ToArray()); return(literals.Count + 1); }
public bool AddRegisteredCourses(IEnumerable <RegisteredCourse> courses) { DataWriter.WriterData(courses, nameof(RegisteredCourse)); return(true); }
public override void WritePropertiesData(DataWriter writer, bool writeFlowElements = true) { base.WritePropertiesData(writer, writeFlowElements); }
// Ported from: https://github.com/iltrof/ykcmp private static byte[] Compress(byte[] inputData) { using MemoryStream outputMemoryStream = new MemoryStream(); DataStream outputDataStream = new DataStream(outputMemoryStream); DataWriter writer = new DataWriter(outputDataStream) { DefaultEncoding = Encoding.ASCII, Endianness = EndiannessMode.LittleEndian, }; writer.Write("YKCMP_V1", false); writer.Write(0x04); // unknown writer.Write(0x00); // compressedSize writer.Write(inputData.Length); // uncompressedSize int pos = 0; List <byte> literals = new List <byte>(); int compressedSize = 0x14; while (pos < inputData.Length) { MatchInfo match = FindMatch(inputData, pos); if (match.Size == 0) { if (literals.Count == 0x7F) { int writeCount = WriteLiterals(writer, literals); compressedSize += writeCount; literals.Clear(); } literals.Add(inputData[pos]); pos++; continue; } if (literals.Count > 0) { int writeCount = WriteLiterals(writer, literals); compressedSize += writeCount; literals.Clear(); } if (match.Size <= 0x04 && match.Offset <= 0x10) { int byte1 = (match.Size << 4) + 0x70 + (match.Offset - 1); writer.Write((byte)byte1); compressedSize += 1; } else if (match.Size <= 0x21 && match.Offset <= 0x100) { int byte1 = match.Size + 0xC0 - 2; int byte2 = match.Offset - 1; writer.Write((byte)byte1); writer.Write((byte)byte2); compressedSize += 2; } else { int tmp = match.Size + 0x0E00 - 3; int byte1 = tmp >> 4; int byte2 = ((tmp & 0x0F) << 4) + ((match.Offset - 1) >> 8); int byte3 = match.Offset - 1; writer.Write((byte)byte1); writer.Write((byte)byte2); writer.Write((byte)byte3); compressedSize += 3; } pos += match.Size; } if (literals.Count > 0) { int writeCount = WriteLiterals(writer, literals); compressedSize += writeCount; literals.Clear(); } writer.Stream.Position = 0x0C; writer.Write(compressedSize); return(outputMemoryStream.ToArray()); }
public void ToWriter(DataWriter stm, Logger logger) { if ((Headers != null) && (Body != null)) { stm.Write(OnWriteHeader(logger)); foreach (KeyDataPair<string> header in Headers) { if (!header.Name.Equals("content-length", StringComparison.OrdinalIgnoreCase) && !header.Name.Equals("transfer-encoding", StringComparison.OrdinalIgnoreCase)) { stm.Write(String.Format("{0}: {1}\r\n", header.Name, header.Value)); } } if (!IsRequest || (Body.Length > 0) || !IsGetRequest()) { stm.Write(String.Format("Content-Length: {0}\r\n", Body.Length)); } stm.Write("\r\n"); if (Body.Length > 0) { stm.Write(Body); } } }
public ObexClient(IInputStream inputStream, IOutputStream outputStream) { _reader = new DataReader(inputStream); _writer = new DataWriter(outputStream); }
/// <summary> /// Initializes a new instance of the <see cref="CrossSectionWorkfow"/> class. /// </summary> /// <param name="uimfFileLocation"> /// The uimf file location. /// </param> /// <param name="outputDirectory"> /// The output directory. /// </param> /// <param name="logFileName"> /// The log file name. /// </param> /// <param name="parameters"> /// The parameters. /// </param> public CrossSectionWorkfow(string uimfFileLocation, string outputDirectory, CrossSectionSearchParameters parameters) { this.uimfReader = new DataReader(uimfFileLocation); // Append bin-centric table to the uimf if not present. if (!this.uimfReader.DoesContainBinCentricData()) { DataWriter dataWriter = new DataWriter(uimfFileLocation); dataWriter.CreateBinCentricTables(); } this.Parameters = parameters; this.smoother = new SavitzkyGolaySmoother(parameters.NumPointForSmoothing, 5); this.theoreticalFeatureGenerator = new JoshTheorFeatureGenerator(); this.peakDetector = new ChromPeakDetector(0.0001, 0.0001); this.NumberOfFrames = this.uimfReader.GetGlobalParams().NumFrames; this.NumberOfScans = this.uimfReader.GetFrameParams(1).Scans; this.SampleCollectionDate = this.uimfReader.GetGlobalParams().GetValue(GlobalParamKeyType.DateStarted); this.DatasetName = Path.GetFileNameWithoutExtension(uimfFileLocation); this.OutputPath = outputDirectory; this.DatasetPath = uimfFileLocation; this.Parameters = parameters; if (outputDirectory == string.Empty) { outputDirectory = Directory.GetCurrentDirectory(); } if (!outputDirectory.EndsWith("\\")) { outputDirectory += "\\"; } if (!Directory.Exists(outputDirectory)) { try { Directory.CreateDirectory(outputDirectory); } catch (Exception) { Console.WriteLine("Failed to create directory."); throw; } } this.OutputPath = outputDirectory; }
private static void WriteLine(DataWriter writer, string line) { writer.WriteLine(line, TextLineEnding.CarriageReturnLineFeed); }
private async void getUserDetail() { //This helps get user detail while data is filled out. try { if (!string.IsNullOrEmpty(txtPhoneNumber.Text.Trim())) { if (GuestList != null) { foreach (var item in GuestList) { if (item.GuestPhoneNumber == txtPhoneNumber.Text.Trim()) { //When we find user txbVisitorName.Text = item.GuestName; txbVisitorName.Visibility = Visibility.Visible; string photoString = ""; if (item.GuestPhotoString == null) { #region MyRegion photoString = "/9j/4AAQSkZJRgABAgEASABIAAD/2wBDAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQECAgICAgICAgICAgMDAwMDAwMDAwP/2wBDAQEBAQEBAQEBAQECAgECAgMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwP/wAARCAETARMDAREAAhEBAxEB/8QAHgABAAIDAQEBAQEAAAAAAAAAAAcJBggKBQMEAgH/xABZEAAABgIBA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AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAP//Z"; #endregion } else { photoString = item.GuestPhotoString; } byte[] Bytes = Convert.FromBase64String(photoString); var stream = new InMemoryRandomAccessStream(); //var bytes = Convert.FromBase64String(source); var dataWriter = new DataWriter(stream); dataWriter.WriteBytes(Bytes); await dataWriter.StoreAsync(); stream.Seek(0); var img = new BitmapImage(); img.SetSource(stream); PhotoCopy.Source = img; //txtCheckInCode.Text = item.CheckInCode; if (item.ExtraGuest != null) { GuestColleague = item.ExtraGuest; ConvertJSonToGuestColleague(); stackMainGuest.Visibility = Visibility.Visible; txbCheckOutDisplay.Visibility = Visibility.Visible; txbVisitorStatus.Visibility = Visibility.Visible; } //Send Admin Detail to DB here---- return; } } } else { MessageDialog msg = new MessageDialog("User not Registered. See Guest List", "Alert!"); msg.ShowAsync(); txbVisitorName.Visibility = Visibility.Collapsed; txbVisitorStatus.Visibility = Visibility.Collapsed; return; } } else { MessageDialog msg = new MessageDialog("Enter Guest Phone Number"); txbVisitorName.Visibility = Visibility.Collapsed; txbVisitorStatus.Visibility = Visibility.Collapsed; msg.ShowAsync(); } } catch (Exception ex) { checkInternet(); MessageDialog msg = new MessageDialog(ex.Message + " Void - getUserDetail()"); //msg.ShowAsync(); } }
/// <summary> /// Genericized function to send commands to a Particle device in listening mode /// </summary> /// <param name="setupCommand">The SetupCommand to use</param> /// <param name="data">Any extra data to send with the command</param> /// <returns></returns> private static async Task <string> SendSoftAPCommandAsync(SetupCommand setupCommand, string data = null) { HostName hostname = new HostName("192.168.0.1"); string command; switch (setupCommand) { case SetupCommand.Version: command = "version"; break; case SetupCommand.DeviceId: command = "device-id"; break; case SetupCommand.ScanAP: command = "scan-ap"; break; case SetupCommand.PublicKey: command = "public-key"; break; case SetupCommand.ConfigureAP: command = "configure-ap"; break; case SetupCommand.ConnectAP: command = "connect-ap"; break; case SetupCommand.Set: command = "set"; break; default: return(null); } int dataLength = 0; if (data != null) { dataLength = data.Length; } using (StreamSocket socket = new StreamSocket()) using (DataWriter writer = new DataWriter(socket.OutputStream)) using (DataReader reader = new DataReader(socket.InputStream)) { reader.InputStreamOptions = InputStreamOptions.Partial; try { var socketOperation = socket.ConnectAsync(hostname, "5609"); var cancellationTokenSource = new CancellationTokenSource(); cancellationTokenSource.CancelAfter(5000); Task socketTask = socketOperation.AsTask(cancellationTokenSource.Token); await socketTask; writer.WriteString($"{command}\n{dataLength}\n\n"); if (data != null) { writer.WriteString(data); } string receivedData = ""; await writer.StoreAsync(); uint count = await reader.LoadAsync(2048); if (count > 0) { receivedData = reader.ReadString(count); } if (string.IsNullOrWhiteSpace(receivedData)) { return(null); } return(receivedData); } catch (TaskCanceledException) { } catch (Exception exception) { switch (SocketError.GetStatus(exception.HResult)) { case SocketErrorStatus.HostNotFound: break; default: break; } } return(null); } }
/// <summary> /// Write the check to a data writer /// </summary> /// <param name="writer">The writer to write to</param> public void WriteChunk(DataWriter writer) { if (ChunkNumber == 0) { WriteHeaders(writer); } WriteBody(writer); }
protected override void WritePropertyValues(DataWriter writer) { base.WritePropertyValues(writer); WritePropertyValues(writer, true); }
private void WriteBody(DataWriter writer) { byte[] body = GetBody(); if (ChunkedEncoding) { string chunkLen = String.Format("{0:X}", body.Length); if (!String.IsNullOrEmpty(ChunkExtension)) { chunkLen += ";" + ChunkExtension; } WriteLine(writer, chunkLen); writer.Write(body); WriteLine(writer, String.Empty); if (FinalChunk && body.Length > 0) { WriteLine(writer, "0"); WriteLine(writer, String.Empty); } } else { writer.Write(Body); } }
public override void WritePropertiesData(DataWriter writer) { writer.WriteStartObject(Name); base.WritePropertiesData(writer); if (Status == Core.Process.ProcessStatus.Inactive) { writer.WriteFinishObject(); return; } if (!HasMapping("Service")) { writer.WriteValue("Service", Service, Guid.Empty); } if (!HasMapping("ServiceMethod")) { writer.WriteValue("ServiceMethod", ServiceMethod, null); } if (!HasMapping("ServiceUrl")) { writer.WriteValue("ServiceUrl", ServiceUrl, Guid.Empty); } if (!HasMapping("ServiceMethodParameters")) { writer.WriteValue("ServiceMethodParameters", ServiceMethodParameters, null); } if (!HasMapping("RequestStatus")) { writer.WriteValue("RequestStatus", RequestStatus, 0); } if (Result != null && Result.Schema != null) { if (UseFlowEngineMode) { Result.Write(writer, "Result"); } else { string serializedEntity = Entity.SerializeToJson(Result); writer.WriteValue("Result", serializedEntity, null); } } if (!HasMapping("IsLoggingRequestAndResponce")) { writer.WriteValue("IsLoggingRequestAndResponce", IsLoggingRequestAndResponce, false); } if (!HasMapping("Request")) { writer.WriteValue("Request", Request, null); } if (!HasMapping("Responce")) { writer.WriteValue("Responce", Responce, null); } if (!HasMapping("RequestBodyInternal")) { writer.WriteValue("RequestBodyInternal", RequestBodyInternal, null); } if (!HasMapping("RequestParameters")) { writer.WriteValue("RequestParameters", RequestParameters, null); } writer.WriteFinishObject(); }
public HttpProxyServerAdapter(DataAdapterToStream stm, HttpRequestHeader initialRequest, Logger logger) { _stm = stm; _writer = new DataWriter(_stm); _request = initialRequest; _config = new HttpParserConfig(); _config.StreamBody = true; _logger = logger; Description = stm.Description; }
public async Task ConnectAsync(Uri uri, CancellationToken cancellationToken, ClientWebSocketOptions options) { InterlockedCheckAndUpdateState(WebSocketState.Connecting, s_validConnectStates); CheckValidState(s_validConnectingStates); _messageWebSocket = new MessageWebSocket(); foreach (var header in options.RequestHeaders) { _messageWebSocket.SetRequestHeader((string)header, options.RequestHeaders[(string)header]); } string cookies = options.Cookies == null ? null : options.Cookies.GetCookieHeader(uri); if (!string.IsNullOrEmpty(cookies)) { _messageWebSocket.SetRequestHeader(HeaderNameCookie, cookies); } var websocketControl = _messageWebSocket.Control; foreach (var subProtocol in options.RequestedSubProtocols) { websocketControl.SupportedProtocols.Add(subProtocol); } if (options.ClientCertificates.Count > 0) { if (!MessageWebSocketClientCertificateSupported) { throw new PlatformNotSupportedException(SR.Format(CultureInfo.InvariantCulture, SR.net_WebSockets_UWPClientCertSupportRequiresWindows10GreaterThan1703)); } X509Certificate2 dotNetClientCert = CertificateHelper.GetEligibleClientCertificate(options.ClientCertificates); if (dotNetClientCert != null) { RTCertificate winRtClientCert = await CertificateHelper.ConvertDotNetClientCertToWinRtClientCertAsync(dotNetClientCert).ConfigureAwait(false); if (winRtClientCert == null) { throw new PlatformNotSupportedException(SR.Format( CultureInfo.InvariantCulture, SR.net_WebSockets_UWPClientCertSupportRequiresCertInPersonalCertificateStore)); } websocketControl.ClientCertificate = winRtClientCert; } } // Try to opt into PartialMessage receive mode so that we can hand partial data back to the app as it arrives. // If the MessageWebSocketControl.ReceiveMode API surface is not available, the MessageWebSocket.MessageReceived // event will only get triggered when an entire WebSocket message has been received. This results in large memory // footprint and prevents "streaming" scenarios (e.g., WCF) from working properly. if (MessageWebSocketReceiveModeSupported) { // Always enable partial message receive mode if the WinRT API supports it. _messageWebSocket.Control.ReceiveMode = MessageWebSocketReceiveMode.PartialMessage; } try { _receiveAsyncBufferTcs = new TaskCompletionSource <ArraySegment <byte> >(); _closeWebSocketReceiveResultTcs = new TaskCompletionSource <WebSocketReceiveResult>(); _messageWebSocket.MessageReceived += OnMessageReceived; _messageWebSocket.Closed += OnCloseReceived; await _messageWebSocket.ConnectAsync(uri).AsTask(cancellationToken).ConfigureAwait(false); _subProtocol = _messageWebSocket.Information.Protocol; _messageWriter = new DataWriter(_messageWebSocket.OutputStream); } catch (Exception) { UpdateState(WebSocketState.Closed); throw; } UpdateState(WebSocketState.Open); }
public override void Write(DataWriter writer) { writer.Write(Id); Element.Write(writer); }
public IntakeAirTemperature(DataReader reader, DataWriter writer) : base(reader, writer) { }
/// <summary> /// Initializes a new instance of the <see cref="LcImsPeptideSearchWorkfow"/> class. /// </summary> /// <param name="uimfFileLocation"> /// The uimf file location. /// </param> /// <param name="parameters"> /// The parameters. /// </param> public LcImsPeptideSearchWorkfow(string uimfFileLocation, LcImsPeptideSearchParameters parameters) { this._buildWatershedStopWatch = new Stopwatch(); this._smoothStopwatch = new Stopwatch(); this._featureFindStopWatch = new Stopwatch(); this._featureFindCount = 0; this._pointCount = 0; this._uimfFileLocation = uimfFileLocation; this._uimfReader = new DataReader(uimfFileLocation); // Append bin-centric table to the uimf if not present. if (!this._uimfReader.DoesContainBinCentricData()) { DataWriter dataWriter = new DataWriter(uimfFileLocation); dataWriter.CreateBinCentricTables(); } this._parameters = parameters; this._smoother = new SavitzkyGolaySmoother(parameters.NumPointForSmoothing, 2); this._theoreticalFeatureGenerator = new JoshTheorFeatureGenerator(); this._leftOfMonoPeakLooker = new LeftOfMonoPeakLooker(); this._peakDetector = new ChromPeakDetector(0.0001, 0.0001); this._isotopicPeakFitScoreCalculator = new PeakLeastSquaresFitter(); IterativeTFFParameters msFeatureFinderParameters = new IterativeTFFParameters { MinimumRelIntensityForForPeakInclusion = 0.0001, PeakDetectorMinimumPeakBR = 0.0001, PeakDetectorPeakBR = 5.0002, PeakBRStep = 0.25, PeakDetectorSigNoiseRatioThreshold = 0.0001, ToleranceInPPM = parameters.MassToleranceInPpm }; this._msFeatureFinder = new IterativeTFF(msFeatureFinderParameters); this.NumberOfFrames = this._uimfReader.GetGlobalParams().NumFrames; this.NumberOfScans = this._uimfReader.GetFrameParams(1).Scans; }
/// <summary> /// Write the value to the server /// </summary> public async void WriteValue() { if (!String.IsNullOrEmpty(ValueToWrite)) { IBuffer writeBuffer = null; if (WriteType == WriteTypes.Decimal) { DataWriter writer = new DataWriter(); writer.ByteOrder = ByteOrder.LittleEndian; writer.WriteInt32(Int32.Parse(ValueToWrite)); writeBuffer = writer.DetachBuffer(); } else if (WriteType == WriteTypes.Hex) { try { // pad the value if we've received odd number of bytes if (ValueToWrite.Length % 2 == 1) { writeBuffer = GattConvert.ToIBufferFromHexString("0" + ValueToWrite); } else { writeBuffer = GattConvert.ToIBufferFromHexString(ValueToWrite); } } catch (Exception ex) { MessageDialog dialog = new MessageDialog(ex.Message, "Error"); await dialog.ShowAsync(); return; } } else if (WriteType == WriteTypes.UTF8) { writeBuffer = CryptographicBuffer.ConvertStringToBinary(ValueToWrite, BinaryStringEncoding.Utf8); } try { // BT_Code: Writes the value from the buffer to the characteristic. GattCommunicationStatus result = await Characteristic.Characteristic.WriteValueAsync(writeBuffer); if (result == GattCommunicationStatus.Unreachable) { NotifyUser.Insert(0, "Unable to write data - Device unreachable"); } else if (result == GattCommunicationStatus.ProtocolError) { NotifyUser.Insert(0, "Unable to write data - Protocol error"); } } catch (Exception ex) when((uint)ex.HResult == 0x80650003 || (uint)ex.HResult == 0x80070005) { // E_BLUETOOTH_ATT_WRITE_NOT_PERMITTED or E_ACCESSDENIED // This usually happens when a device reports that it support writing, but it actually doesn't. NotifyUser.Insert(0, "Error writing to characteristic. This usually happens when a device reports that it support writing, but it actually doesn't."); } catch (Exception ex) { MessageDialog dialog = new MessageDialog(ex.Message, "Error"); await dialog.ShowAsync(); } } else { NotifyUser.Insert(0, "No data to write to device"); } }
public void Write(DataWriter writer) { writer.Write((short)Id); writer.Write(Name); DbType.Write(writer); }
public void Write(DataWriter writer) { }
private byte[] ToBytes(object target, object o, bool littleEndian, Encoding encoding) { if (o is byte) { return new byte[1] { (byte)o }; } else if (o is sbyte) { return (byte[])(object)(new sbyte[1] { (sbyte)o }); } else if(o.GetType().IsPrimitive) { MemoryStream stm = new MemoryStream(); DataWriter writer = new DataWriter(stm); writer.WritePrimitive(o, o.GetType(), littleEndian); return stm.ToArray(); } else if (o is byte[]) { return (byte[])o; } else if (o is Array) { MemoryStream stm = new MemoryStream(); foreach (object x in ((Array)o)) { byte[] ba = ToBytes(target, x, littleEndian, encoding); stm.Write(ba, 0, ba.Length); } return stm.ToArray(); } else if (o is IStreamTypeParser) { MemoryStream stm = new MemoryStream(); DataWriter writer = new DataWriter(stm); IStreamTypeParser parser = (IStreamTypeParser)o; parser.ToStream(writer, CreateState(target), _logger); return stm.ToArray(); } else if (o is string) { if(encoding != null) { return encoding.GetBytes((string)o); } else { return BinaryEncoding.Instance.GetBytes((string)o); } } return new byte[0]; }
public void Run() { try { socket = new Windows.Networking.Sockets.StreamSocket(); UpgradeRequest request = null; try { // connect to the eftlServer if (String.Compare("ws", uri.Scheme, StringComparison.CurrentCultureIgnoreCase) == 0) { socket.ConnectAsync(remoteHostName, getPort().ToString(), Windows.Networking.Sockets.SocketProtectionLevel.PlainSocket).AsTask().Wait(5000); } else if (String.Compare("wss", uri.Scheme, StringComparison.CurrentCultureIgnoreCase) == 0) { socket.ConnectAsync(remoteHostName, getPort().ToString(), Windows.Networking.Sockets.SocketProtectionLevel.Ssl).AsTask().Wait(5000); } Windows.Networking.Sockets.SocketProtectionLevel l = socket.Information.ProtectionLevel; Console.WriteLine("ProtectionLevel = " + l); // send HTTP upgrade request request = new UpgradeRequest(uri, protocols); DataWriter writer = new DataWriter(socket.OutputStream); String s = request.toString(); writer.WriteString(s); // Call StoreAsync method to store the data to a backing stream try { writer.StoreAsync().AsTask().Wait(); writer.FlushAsync().AsTask().Wait(); } catch (Exception e) { Console.WriteLine(e.StackTrace); } writer.DetachStream(); } catch (Exception e) { Exception exp = new Exception("failed to connect" + ((e.InnerException != null) ? e.InnerException.Message : "")); notifyError(exp); } byte[] buffer = new byte[32768]; IInputStream inputStream = socket.InputStream; try { inputStream.ReadAsync(buffer.AsBuffer(), (uint)buffer.Length, InputStreamOptions.Partial).AsTask().Wait(); System.IO.Stream stream = new System.IO.MemoryStream(buffer); // read HTTP upgrade response UpgradeResponse response = UpgradeResponse.read(stream); response.validate(request); // get the agreed upon protocol protocol = response.getProtocol(); } catch (Exception e) { notifyError(e); } // notify listener notifyOpen(); // dispatch frames dispatch(); } catch (Exception e) { notifyError(e); } finally { socket.Dispose(); } }
public async void SendCommandToAllChar(IReadOnlyList<GattCharacteristic> characteristics, byte[] commandToWrite) { foreach (var characteristic in characteristics) { Debug.WriteLine("Try to write to " + CharacteristicUuidsResolver.GetNameFromUuid(characteristic.Uuid)); try { var writer = new DataWriter(); writer.WriteBytes(commandToWrite); await characteristic.WriteValueAsync(writer.DetachBuffer()); Debug.WriteLine("Write sucessfull"); } catch { Debug.WriteLine("Write error"); } } }
public BinaryFormat Convert(NodeContainerFormat source) { if (source == null) { throw new ArgumentNullException(nameof(source)); } BinaryFormat binary = new BinaryFormat(); DataWriter writer = new DataWriter(binary.Stream); Encoding utf16 = Encoding.GetEncoding("utf-16"); // header writer.Write("darc", false, Encoding.ASCII); writer.Write((ushort)0xFEFF); writer.Write(0x1C); writer.Write((ushort)0x0100); writer.Write(0x00); // Placeholder for file size writer.Write(0x1C); writer.Write(0x00); // Placeholder for fat size writer.Write(0x00); // Placeholder for data offset // First iteration, get file id and write names DataStream names = new DataStream(); DataWriter nameWriter = new DataWriter(names); Stack <Node> stack = new Stack <Node>(); stack.Push(source.Root); int currentId = 0; while (stack.Any()) { var node = stack.Pop(); var name = node == source.Root ? string.Empty : node.Name; var nameBin = utf16.GetBytes(name + "\0"); nameWriter.Write(nameBin); node.Tags["darc.name"] = nameBin.Length; currentId++; Node t = node; while (t.Parent != null) { t.Parent.Tags["darc.lastId"] = currentId; t = t.Parent; } foreach (var child in node.Children.Reverse()) { stack.Push(child); } } // Write empty FAT writer.WriteTimes(0x00, 0x0C * currentId); names.WriteTo(binary.Stream); names.Dispose(); uint endFatPos = (uint)binary.Stream.Length; writer.WritePadding(0x00, 0x80); // Start writing FAT again binary.Stream.Position = 0x14; writer.Write(endFatPos - 0x1C); writer.Write((uint)binary.Stream.Length); stack.Clear(); stack.Push(source.Root); ushort nameOffset = 0; while (stack.Any()) { var node = stack.Pop(); DataStream fileStream = node.Stream; writer.Write(nameOffset); nameOffset += (ushort)node.Tags["darc.name"]; if (fileStream != null) { writer.Write((ushort)0); writer.Write((uint)binary.Stream.Length); writer.Write((uint)fileStream.Length); // Write file binary.Stream.PushToPosition(0, SeekMode.End); fileStream.WriteTo(binary.Stream); if (stack.Any()) { writer.WritePadding(0x00, 0x80); } binary.Stream.PopPosition(); } else { writer.Write((ushort)0x100); writer.Write(0); writer.Write(node.Tags["darc.lastId"]); } foreach (var child in node.Children.Reverse()) { stack.Push(child); } } // Update file size place holder binary.Stream.Position = 0x0C; writer.Write((uint)binary.Stream.Length); return(binary); }
public override void Write(DataWriter writer) { writer.Write(Id); Key.Write(writer); Value.Write(writer); }
public RPM(DataReader reader, DataWriter writer) : base(reader, writer) { }
public static void WritePoint(DataWriter writer, Point point) { writer.Write(point.X); writer.Write(point.Y); }
protected override async void OnBackgroundActivated(BackgroundActivatedEventArgs args) { base.OnBackgroundActivated(args); IBackgroundTaskInstance taskInstance = args.TaskInstance; var deferral = taskInstance.GetDeferral(); try { if ((taskInstance.TriggerDetails as SocketActivityTriggerDetails)?.Reason == SocketActivityTriggerReason.SocketActivity) { var details = taskInstance.TriggerDetails as SocketActivityTriggerDetails; var socketInformation = details.SocketInformation; switch (details.Reason) { case SocketActivityTriggerReason.SocketActivity: var socket = socketInformation.StreamSocket; DataReader reader = new DataReader(socket.InputStream); //// TODO: the value returned is likely to change (David Born from Spotify): //// " the payload of the message is a bit different than what the earbuds send today //// it needs to contain three separate fields in the future: a cliend-id specific for microsoft headphone integrations //// a brand field(obviously "mircosoft") and a model("surface earbuds" or what the official model name is) //// the whole thing is then tlv encoded " await reader.LoadAsync(12); ShowToast(socketInformation.Id); socket.TransferOwnership(socketInformation.Id); break; case SocketActivityTriggerReason.KeepAliveTimerExpired: // I dont think this should ever be called socket = socketInformation.StreamSocket; DataWriter writer = new DataWriter(socket.OutputStream); writer.WriteBytes(Encoding.UTF8.GetBytes("Keep alive")); await writer.StoreAsync(); writer.DetachStream(); writer.Dispose(); socket.TransferOwnership(socketInformation.Id); break; case SocketActivityTriggerReason.SocketClosed: // nothing doing... // buds have probably been disconnected. Remove them from the list. break; default: break; } } } catch (Exception exception) { ShowToast(exception.Message); } finally { deferral.Complete(); } }
public void HandleConnection() { NetworkStream cStream = this.client.GetStream(); StreamReader reader = new StreamReader(cStream); writer = new DataWriter(cStream); // first we get what version of the protocol // we expect "TVServerXBMC:0-2" String versionInfo = reader.ReadLine(); if (versionInfo == null) return; // version 2 is not backards compatible versionInfo = Uri.UnescapeDataString(versionInfo); if (versionInfo.ToLower().Contains("telnet")) { // human connection writer.setArgumentSeparator("|"); writer.setListSeparator(Environment.NewLine); writer.setHumanEncoders(); //reader side: cmd_sep = ":"; arg_sep = "|"; WriteLine("Protocol Accepted; TVServerXBMC version: " + System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString()); Console.WriteLine("Correct protocol, telnet connection accepted!"); Log.Debug("TVServerXBMC: telnet connection accepted!"); username = "******"; clientType = ClientType.telnet; } else if (Regex.IsMatch(versionInfo,"^TVServerXBMC:0-[0-3]$",RegexOptions.IgnoreCase)) { WriteLine("Protocol-Accept;0-3"); Console.WriteLine("Correct protocol, connection accepted!"); Log.Debug("TVServerXBMC: connection accepted!"); username = "******"; clientType = ClientType.python; } else if (Regex.IsMatch(versionInfo, "^PVRclientXBMC:0-[1]$", RegexOptions.IgnoreCase)) { writer.setArgumentSeparator("|"); //reader side: cmd_sep = ":"; arg_sep = "|"; WriteLine("Protocol-Accept:0|" + System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString()); Console.WriteLine("Correct protocol, connection accepted!"); Log.Debug("TVServerXBMC: connection accepted from XBMC PVR addon"); username = "******" + clientnr; clientType = ClientType.pvrclient; } else { WriteLine("Unexpected Protocol"); client.Close(); Console.WriteLine("Unexpected protocol:" + versionInfo); Log.Debug("TVServerXBMC: Unexpected protocol:" + versionInfo); clientType = ClientType.unknown; return; } me = TVServerConnection.RequestUser(username); ProcessConnection(reader); reader.Dispose(); cStream.Dispose(); }
//--------------------------------------------------------Misc Methods:---------------------------------------------------------------\\ #region --Misc Methods (Public)-- public async Task connectAsync() { switch (state) { case ConnectionState.DISCONNECTED: case ConnectionState.ERROR: setState(ConnectionState.CONNECTING); for (int i = 1; i <= MAX_CONNECTION_TRIES; i++) { try { // Cancel connecting if for example disconnectAsync() got called: if (state != ConnectionState.CONNECTING) { return; } // Setup socket: socket = new StreamSocket(); socket.Control.KeepAlive = true; socket.Control.QualityOfService = SocketQualityOfService.LowLatency; hostName = new HostName(account.serverAddress); // Add all ignored certificate errors: foreach (ChainValidationResult item in account.connectionConfiguration.IGNORED_CERTIFICATE_ERRORS) { socket.Control.IgnorableServerCertificateErrors.Add(item); } // Connect with timeout: if (disableTcpTimeout) { connectingCTS = new CancellationTokenSource(); } else { connectingCTS = new CancellationTokenSource(CONNECTION_TIMEOUT_MS); } await socket.ConnectAsync(hostName, account.port.ToString(), SocketProtectionLevel.PlainSocket).AsTask(connectingCTS.Token); // Setup stream reader and writer: dataWriter = new DataWriter(socket.OutputStream); dataReader = new DataReader(socket.InputStream) { InputStreamOptions = InputStreamOptions.Partial }; // Update account connection info: ConnectionInformation connectionInfo = account.CONNECTION_INFO; connectionInfo.socketInfo = socket?.Information; // Connection successfully established: if (state == ConnectionState.CONNECTING) { setState(ConnectionState.CONNECTED); } return; } catch (TaskCanceledException e) { Logger.Error("[TCPConnection2]: " + i + " try to connect to " + account.serverAddress + " failed:", e); lastConnectionError = new ConnectionError(ConnectionErrorCode.CONNECT_TIMEOUT, e.Message); } catch (Exception e) { onConnectionError(e, i); } } setState(ConnectionState.ERROR, lastConnectionError); break; default: break; } }