private static async Task <string> ReadCRLFLineAsync(Stream stream, Encoding encoding, CancellationToken ctsToken = default) { var bab = new ByteArrayBuilder(); while (true) { int ch = await stream.ReadByteAsync(ctsToken).ConfigureAwait(false); if (ch == -1) { break; } if (ch == '\r') { var ch2 = await stream.ReadByteAsync(ctsToken).ConfigureAwait(false); if (ch2 == '\n') { return(bab.ToString(encoding)); } bab.Append(new byte[] { (byte)ch, (byte)ch2 }); continue; } bab.Append((byte)ch); } return(bab.Length > 0 ? bab.ToString(encoding) : throw new FormatException("There's no CRLF.")); }
public static byte[] BuildReadScreenResponse(ScreenContent ScreenContent) { var ra = new ByteArrayBuilder(); // data stream header. { var buf = DataStreamHeader.Build(50, TerminalOpcode.ReadScreen, 0, 0); ra.Append(buf); } // screen regeneration buffer. each byte on the screen. { var buf = ScreenContent.GetRegenerationBuffer(); ra.Append(buf); } // update length of response data stream. { var wk = new ByteArrayBuilder(); wk.AppendBigEndianShort((short)ra.Length); ra.CopyToBuffer(wk.ToByteArray(), 0); } // IAC EOR { ra.Append(EOR_Command.Build()); } return(ra.ToByteArray()); }
private static async Task <string> ReadCRLFLineAsync(Stream stream, Encoding encoding, CancellationToken ctsToken = default) { var bab = new ByteArrayBuilder(); while (true) { int ch = await stream.ReadByteAsync(ctsToken); if (ch == -1) { break; } if (ch == '\r') { var ch2 = await stream.ReadByteAsync(ctsToken); if (ch2 == '\n') { return(bab.ToString(encoding)); } bab.Append(new byte[] { (byte)ch, (byte)ch2 }); continue; } bab.Append((byte)ch); } if (bab.Length > 0) { return(bab.ToString(encoding)); } return(null); }
/// <summary> /// search for all the Find byte[] patterns and replace with Replace byte[] /// contents. /// </summary> /// <param name="Input"></param> /// <param name="Find"></param> /// <param name="Replace"></param> /// <returns></returns> public static byte[] ReplaceAll(this byte[] Input, byte[] Find, byte[] Replace) { int bx = 0; int inputLength = Input.Length; ByteArrayBuilder ba = new ByteArrayBuilder(inputLength + 100); // loop until all bytes of the Input array while (bx < inputLength) { var fx = Input.IndexOf(bx, Find); if (fx >= 0) { var lx = fx - bx; // length of bytes before the found pattern. ba.Append(Input, bx, lx); // copy the Replace pattern to the result array. ba.Append(Replace); // advance in the input array. bx = fx + Find.Length; } // find pattern not found. Copy remaining bytes to result array. else { int remLx = inputLength - bx; ba.Append(Input, bx, remLx); bx += remLx; } } // return the return(ba.ToByteArray()); }
private void ContinueBuildHash(ByteArrayBuilder byteArrayBuilder, string line) { if (string.IsNullOrWhiteSpace(line)) { byteArrayBuilder.Append(0); } else { if (DigestRandomIndex.HasValue) { int index = DigestRandomIndex == -1 || DigestRandomIndex >= line.Length // Last char. ? line.Length - 1 : DigestRandomIndex.Value; var c = line[index]; var b = (byte)c; byteArrayBuilder.Append(b); } else { var b = Encoding.ASCII.GetBytes(line); byteArrayBuilder.Append(b); } } }
private void HanlderModbusBaseRead(MasterReadDataBase masterReadData) { byte _readOrderCmd = 0x00; if (masterReadData is ReadCoilsData) { _readOrderCmd = (byte)ModbusBaseOrderCmd.ReadCoilStatus; } else if (masterReadData is ReadDiscreteInputData) { _readOrderCmd = (byte)ModbusBaseOrderCmd.ReadInputStatus; } else if (masterReadData is ReadHoldingRegistersData) { _readOrderCmd = (byte)ModbusBaseOrderCmd.ReadHoldingRegister; } else if (masterReadData is ReadInputRegisters) { _readOrderCmd = (byte)ModbusBaseOrderCmd.ReadInputRegister; } if (_readOrderCmd != 0x00) { using (ByteArrayBuilder builder = new ByteArrayBuilder()) { builder.Append(masterReadData.SlaveID); //高位在前 builder.Append(_readOrderCmd); //功能码 builder.Append(ByteHelper.ToBytes(masterReadData.Address, true)); //高位在前 builder.Append(ByteHelper.ToBytes(masterReadData.Quantity, true)); //数量 ModBusAppData = builder.ToArray(); } } }
public override byte[] ToBytes() { if (this.RawBytes != null) { return(this.RawBytes); } else { var ba = new ByteArrayBuilder(); if (this.AttrByte != null) { ba.Append(this.AttrByte.Value); } if (this.TextBytes != null) { ba.Append(this.TextBytes); } else if (this.DisplayText != null) { ba.Append(this.DisplayText.ToEbcdicBytes()); } return(ba.ToByteArray()); } }
public byte[] GetBytes() { var bytes = _byteArrayBuilder.GetBytes(); var outBytes = new ByteArrayBuilder(); byte currentByte = 0; var currentBit = 7; for (int i = 0; i < _byteArrayBuilder.Length; i++) { currentByte |= (byte)(bytes[i] << currentBit); currentBit--; if (currentBit < 0) { outBytes.Append(currentByte); currentByte = 0; currentBit = 7; } } if (currentBit < 7) { outBytes.Append(currentByte); } return(outBytes.GetBytes()); }
public virtual byte[] ToBytes( ) { var ba = new ByteArrayBuilder(); ba.Append(0x04); ba.Append((byte)this.CmdCode); return(ba.ToByteArray()); }
public override byte[] ToBytes() { var ba = new ByteArrayBuilder(); var buf = base.ToBytes(); ba.Append(buf); ba.Append(this.ControlChars); return(ba.ToByteArray()); }
public static Tuple <int, byte[], TelnetLogList> ProcessTelnetCommand( TelnetCommand TelnetCmd, NegotiateSettings NegotiateSettings, bool doLog = false) { TelnetLogList logList = null; if (doLog == true) { logList = new TelnetLogList(); } int cx = 0; var writeStream = new ByteArrayBuilder(); // write to the run log. if (logList != null) { logList.AddItem(Direction.Read, TelnetCmd.ToString()); } if (TelnetCmd.CmdCode == Enums.CommandCode.DO) { var replyStmt = TelnetCmd.BuildReply(NegotiateSettings); writeStream.Append(replyStmt.ToBytes()); } else if (TelnetCmd is NewEnvironCommand) { var envStmt = TelnetCmd as NewEnvironCommand; cx = ProcessNewEnvironStatement(envStmt, writeStream, NegotiateSettings); } else if (TelnetCmd is TerminalTypeCommand) { var ttStmt = TelnetCmd as TerminalTypeCommand; cx = ProcessTerminalTypeStatement(ttStmt, writeStream, NegotiateSettings); } else if ((TelnetCmd is EndOfRecordStatement) || (TelnetCmd is TransmitBinaryCommand)) { if (TelnetCmd.CmdCode == Enums.CommandCode.DO) { var replyStmt = TelnetCmd.BuildReply(NegotiateSettings); writeStream.Append(replyStmt.ToBytes()); if ((replyStmt.CmdCode == Enums.CommandCode.DO) && (replyStmt.Subject.IsEqual(TelnetSubject.TRANSMIT_BINARY))) { } } else if (TelnetCmd.CmdCode == Enums.CommandCode.WILL) { var replyStmt = TelnetCmd.BuildDoReply(); writeStream.Append(replyStmt.ToBytes()); } } return(new Tuple <int, byte[], TelnetLogList>(cx, writeStream.ToByteArray(), logList)); }
public override byte[] ToBytes() { var ba = new ByteArrayBuilder(); var buf = base.ToBytes(); ba.Append(buf); ba.Append(this.RequestByte); return(ba.ToByteArray()); }
public byte[] ToArray() { using (ByteArrayBuilder builder = new ByteArrayBuilder()) { builder.Append(CRCCaluData); byte[] _crcValue = ByteHelper.ToBytes(CRCBuilder.Calu16MODBUS(CRCCaluData), false); builder.Append(_crcValue); return(builder.ToArray()); } }
/// <summary> /// build a byte array containing a SBA order. /// </summary> /// <param name="RowNum"></param> /// <param name="ColNum"></param> /// <returns></returns> public static byte[] Build(OneRowCol RowCol) { var ba = new ByteArrayBuilder(); ba.Append((byte)WtdOrder.SetBufferAddress); ba.Append(RowCol.RowNum); ba.Append(RowCol.ColNum); return(ba.ToByteArray()); }
/// <summary> /// build a byte array containing an InsertCursor order. /// </summary> /// <param name="RowNum"></param> /// <param name="ColNum"></param> /// <returns></returns> public static byte[] Build(OneRowCol RowCol) { var ba = new ByteArrayBuilder(); ba.Append((byte)WtdOrder.InsertCursor); ba.Append(RowCol.RowNum); ba.Append(RowCol.ColNum); return(ba.ToByteArray()); }
public static byte[] Build(OneRowCol RowCol, AidKey AidKey) { var ba = new ByteArrayBuilder(); ba.Append((byte)RowCol.RowNum); ba.Append((byte)RowCol.ColNum); ba.Append((byte)AidKey); return(ba.ToByteArray()); }
/* Image Commands */ public byte[] SetImageDensity(bool isHiDPI) { ByteArrayBuilder builder = new ByteArrayBuilder(); byte dpiSetting = isHiDPI ? (byte)0x33 : (byte)0x32; // TODO: is this right?? byte[] baseCommand = new byte[] { 0x30, 0x31, dpiSetting, dpiSetting }; builder.Append(GetImageHeader(baseCommand.Length)); builder.Append(baseCommand); return(builder.ToArray()); }
public byte[] WriteImageFromBuffer() { // Print image that's already buffered. ByteArrayBuilder response = new ByteArrayBuilder(); byte[] printCommandBytes = new byte[] { 0x30, 0x32 }; response.Append(GetImageHeader(printCommandBytes.Length)); response.Append(printCommandBytes); return(response.ToArray()); }
public override byte[] ToBytes() { var ba = new ByteArrayBuilder(); ba.Append((byte)this.OrderCode.Value); ba.Append(this.RowAddress); ba.Append(this.ColumnAddress); ba.Append(this.RepeatTextByte); return(ba.ToByteArray()); }
public override byte[] ToBytes() { var ba = new ByteArrayBuilder(); ba.Append((byte)this.OrderCode.Value); ba.AppendBigEndianShort(this.MajorLength); ba.Append(this.ClassByte); ba.Append(this.TypeByte); return(ba.ToByteArray()); }
public byte[] ToArray() { using (ByteArrayBuilder builder = new ByteArrayBuilder()) { builder.Append(ModbusHeader.TransactionIdentifier); builder.Append(ModbusHeader.ProtocolIdentifier); builder.Append(ByteHelper.ToBytes((ushort)ModBusAppData.Length)); builder.Append(ModBusAppData); ModbusHeader.IncreaseTranIdentifier(); return(builder.ToArray()); } }
private static int ProcessNewEnvironStatement( NewEnvironCommand Stmt, ByteArrayBuilder WriteStream, NegotiateSettings NegotiateSettings) { int sendStmtCx = 0; // got the stmt with the SEND parm. Send back the NEW_ENVIRON stmt with the IS parm. if ((Stmt.SubOption != null) && (Stmt.SubOption.Value == TelnetOptionParm.SEND)) { var neSend = new NewEnvironCommand(Enums.CommandCode.SB, TelnetOptionParm.IS); foreach (var newEnv in NegotiateSettings.SendNewEnvironList) { var optnVar = newEnv.ToOptionVariable(NegotiateSettings.SbsValuesDict); neSend.AddOptionVar(optnVar); } int xx = 25; if (xx == 26) { neSend.AddOptionVar(EnvironVarCode.VAR, "USER", "SRICHTER"); neSend.AddOptionVar(EnvironVarCode.VAR, "DEVNAME", "STEVE25"); // reply to newEnviron IBMRSEED stmt SEND statement. if (Stmt.ContainsUserVar_IBMRSEED() == true) { byte[] clientSeed = new byte[8] { 0x55, 0x56, 0x59, 0x5a, 0x5b, 0x5c, 0x4c, 0x48 }; string passWord = "******"; string userName = "******"; var serverSeed = Stmt.IBMRSEED_SeedValue(); var substitutionPassword = CipherCommon.EncryptPassword(passWord, userName, serverSeed, clientSeed); neSend.AddOptionVar(EnvironVarCode.USERVAR, "IBMRSEED", clientSeed); neSend.AddOptionVar(EnvironVarCode.USERVAR, "IBMSUBSPW", substitutionPassword); } } WriteStream.Append(neSend.ToBytes()); // send the SE command immed after NEW-ENVIRON { var ts = new TelnetCommand(Enums.CommandCode.SE); WriteStream.Append(ts.ToBytes()); } } return(sendStmtCx); }
public static byte[] Build(byte ControlChar1, byte ControlChar2, byte[] OrderBytes) { var ba = new ByteArrayBuilder(); { var buf = WorkstationCommandBase.ToBytes(WorkstationCode.WTD); ba.Append(buf); } ba.Append(ControlChar1); ba.Append(ControlChar2); ba.Append(OrderBytes); return(ba.ToByteArray()); }
async Task <bool> ReadLineAsync(ByteArrayBuilder builder, bool doAsync, CancellationToken cancellationToken) { CheckDisposed(); if (inputIndex == inputEnd) { await ReadAheadAsync(doAsync, cancellationToken).ConfigureAwait(false); } unsafe { fixed(byte *inbuf = input) { byte *start, inptr, inend; int offset = inputIndex; int count; start = inbuf + inputIndex; inend = inbuf + inputEnd; *inend = (byte)'\n'; inptr = start; // FIXME: use SIMD to optimize this while (*inptr != (byte)'\n') { inptr++; } inputIndex = (int)(inptr - inbuf); count = (int)(inptr - start); if (inptr == inend) { builder.Append(input, offset, count); midline = true; return(false); } // consume the '\n' midline = false; inputIndex++; count++; builder.Append(input, offset, count); return(true); } } }
public static async Task <byte[]> ReadStartStopAsync(this SerialPort port, byte startbyte, byte stopbyte, CancellationToken token = default, int timeoutms = 0) { CancellationTokenSource linkedCTS = null; CancellationTokenSource timeoutCTS = null; try { CancellationToken internalToken = token; timeoutCTS = new CancellationTokenSource(timeoutms); if (timeoutms > 0) { linkedCTS = CancellationTokenSource.CreateLinkedTokenSource(timeoutCTS.Token, token); internalToken = linkedCTS.Token; } //number of total received data bytes int received = 0; var buffer = new ByteArrayBuilder(); bool startByteFound = false; byte[] tempBuffer = new byte[1]; while (!token.IsCancellationRequested) { received = await port.BaseStream.ReadAsync(tempBuffer, 0, 1, internalToken); if (!startByteFound) { if (tempBuffer[0] == startbyte) { startByteFound = true; buffer.Append(startbyte); } continue; } else { buffer.Append(tempBuffer[0]); if (tempBuffer[0] == stopbyte) { break; } } } return(buffer.ToArray()); } finally { linkedCTS?.Dispose(); timeoutCTS?.Dispose(); } }
public override byte[] ToBytes() { if (this.OrderBytes != null) { return(this.OrderBytes); } else { var ba = new ByteArrayBuilder(); ba.Append((byte)this.OrderCode.Value); ba.Append(this.RowNum); ba.Append(this.ColNum); return(ba.ToByteArray()); } }
public override byte[] ToBytes() { var ba = new ByteArrayBuilder(); ba.Append((byte)this.OrderCode.Value); ba.Append(this.FFW_Bytes); if (this.FCW_Bytes != null) { ba.Append(this.FCW_Bytes); } ba.Append(this.AttrByte); ba.AppendBigEndianShort(this.LL_Length); return(ba.ToByteArray()); }
void AppendString(FormatOptions options, bool allowAtom, ByteArrayBuilder builder, string value) { byte[] buf; switch (GetStringType(Engine, value, allowAtom)) { case ImapStringType.Literal: var literal = Encoding.UTF8.GetBytes(value); var plus = CanUseNonSynchronizedLiteral(Engine, literal.Length); var length = literal.Length.ToString(CultureInfo.InvariantCulture); buf = Encoding.ASCII.GetBytes(length); builder.Append((byte)'{'); builder.Append(buf, 0, buf.Length); if (plus) { builder.Append((byte)'+'); } builder.Append((byte)'}'); builder.Append((byte)'\r'); builder.Append((byte)'\n'); if (plus) { builder.Append(literal, 0, literal.Length); } else { parts.Add(new ImapCommandPart(builder.ToArray(), new ImapLiteral(options, literal))); builder.Clear(); } break; case ImapStringType.QString: buf = Encoding.UTF8.GetBytes(MimeUtils.Quote(value)); builder.Append(buf, 0, buf.Length); break; case ImapStringType.Atom: buf = Encoding.UTF8.GetBytes(value); builder.Append(buf, 0, buf.Length); break; case ImapStringType.Nil: builder.Append(Nil, 0, Nil.Length); break; } }
public static async Task <string> ReadStartLineAsync(Stream stream, CancellationToken ctsToken = default) { // https://tools.ietf.org/html/rfc7230#section-3 // A recipient MUST parse an HTTP message as a sequence of octets in an // encoding that is a superset of US-ASCII[USASCII]. // Read until the first CRLF // the CRLF is part of the startLine // https://tools.ietf.org/html/rfc7230#section-3.5 // Although the line terminator for the start-line and header fields is // the sequence CRLF, a recipient MAY recognize a single LF as a line // terminator and ignore any preceding CR. var bab = new ByteArrayBuilder(); int read = 0; while (read >= 0) { read = await stream.ReadByteAsync(ctsToken).ConfigureAwait(false); bab.Append((byte)read); if (LF == (byte)read) { break; } } var startLine = bab.ToString(Encoding.ASCII); if (string.IsNullOrEmpty(startLine)) { throw new FormatException($"{nameof(startLine)} cannot be null or empty."); } return(startLine); }
protected override byte[] BodyToBytes() { ByteArrayBuilder ab = new ByteArrayBuilder(); if (this.SubOption != null) { ab.Append(this.SubOption.Value.ToByte()); } foreach (var optn in this.OptionList) { ab.Append(optn.ToBytes()); } return(ab.ToByteArray()); }