private void WriteStringTableTo(UtfHeader header, Stream bufferStream) { bufferStream.Seek(header.StringTableOffset, SeekOrigin.Begin); bufferStream.WriteBytes(TableNameBytesCache); var row0 = Rows[0]; foreach (var fieldImage in row0) { bufferStream.WriteBytes(fieldImage.NameBytesCache); } foreach (var fieldImage in row0) { if ((fieldImage.Storage == ColumnStorage.Constant || fieldImage.Storage == ColumnStorage.Constant2) && fieldImage.Type == ColumnType.String) { bufferStream.WriteBytes(fieldImage.StringValueBytesCache); } } foreach (var row in Rows) { foreach (var fieldImage in row) { if (fieldImage.Type == ColumnType.String && fieldImage.Storage == ColumnStorage.PerRow) { bufferStream.WriteBytes(fieldImage.StringValueBytesCache); } } } }
public async Task <int> StreamJson(Stream stream, DbDataReader reader, CancellationToken token) { var count = 0; var ordinal = reader.FieldCount == 1 ? 0 : reader.GetOrdinal("data"); await stream.WriteBytes(ManagedConnectionExtensions.LeftBracket, token).ConfigureAwait(false); if (await reader.ReadAsync(token).ConfigureAwait(false)) { _statistics.TotalResults = await reader.GetFieldValueAsync <int>(_countIndex, token).ConfigureAwait(false); count++; var source = await reader.As <NpgsqlDataReader>().GetStreamAsync(ordinal, token).ConfigureAwait(false); await source.CopyStreamSkippingSOHAsync(stream, token).ConfigureAwait(false); } while (await reader.ReadAsync(token).ConfigureAwait(false)) { count++; await stream.WriteBytes(ManagedConnectionExtensions.Comma, token).ConfigureAwait(false); var source = await reader.As <NpgsqlDataReader>().GetStreamAsync(ordinal, token).ConfigureAwait(false); await source.CopyStreamSkippingSOHAsync(stream, token).ConfigureAwait(false); } await stream.WriteBytes(ManagedConnectionExtensions.RightBracket, token).ConfigureAwait(false); return(count); }
internal static async Task StreamMany(this IManagedConnection connection, NpgsqlCommand command, Stream stream, CancellationToken token) { using (var reader = (NpgsqlDataReader)await connection.ExecuteReaderAsync(command, token)) { var ordinal = reader.FieldCount == 1 ? 0 : reader.GetOrdinal("data"); await stream.WriteBytes(LeftBracket, token); if (await reader.ReadAsync(token)) { var source = await reader.GetStreamAsync(ordinal, token); await source.CopyStreamSkippingSOHAsync(stream, token); } while (await reader.ReadAsync(token)) { await stream.WriteBytes(Comma, token); var source = await reader.GetStreamAsync(ordinal, token); await source.CopyStreamSkippingSOHAsync(stream, token); } await stream.WriteBytes(RightBracket, token); } }
internal void Write(Stream stream) { stream.WriteUInt32(BitHelper.ConvertEndian(Length)); //4 bytes. stream.WriteBytes(Encoding.ASCII.GetBytes(ChunkType)); //4 bytes. stream.WriteBytes(ChunkData); //XX bytes. stream.WriteUInt32(BitHelper.ConvertEndian(CrcHelper.Calculate(stream.PeekBytes(stream.Position - (Length + 4), (int)Length + 4)))); //CRC, 4 bytes. }
protected override void SaveToStream(Stream stream) { if (Version==0 && (_CreationTime > uint.MaxValue || _ModificationTime > uint.MaxValue || Duration > uint.MaxValue)) Version = 1; base.SaveToStream(stream); if (Version == 1) { stream.WriteBEUInt64(_CreationTime); stream.WriteBEUInt64(_ModificationTime); stream.WriteBEUInt32(TimeScale); stream.WriteBEUInt64(Duration); } else // if(Version == 0) { stream.WriteBEUInt32(checked((uint)_CreationTime)); stream.WriteBEUInt32(checked((uint)_ModificationTime)); stream.WriteBEUInt32(TimeScale); stream.WriteBEUInt32(checked((uint)Duration)); } stream.WriteBEInt32(_Rate); stream.WriteBEInt16(_Volume); stream.WriteBytes(Reserved); for (int i = 0; i < 9; i++) stream.WriteBEInt32(Matrix[i]); stream.WriteBytes(PreDefined); stream.WriteBEUInt32(NextTrackID); }
/// <summary>发出请求</summary> /// <param name="ms"></param> /// <param name="cmd"></param> /// <param name="args"></param> /// <returns></returns> protected virtual void GetRequest(Stream ms, String cmd, Packet[] args) { // *<number of arguments>\r\n$<number of bytes of argument 1>\r\n<argument data>\r\n // *1\r\n$4\r\nINFO\r\n var log = Log == null || Log == Logger.Null ? null : Pool.StringBuilder.Get(); log?.Append(cmd); /* * 一颗玲珑心 * 九天下凡尘 * 翩翩起菲舞 * 霜摧砺石开 */ // 区分有参数和无参数 if (args == null || args.Length == 0) { //var str = "*1\r\n${0}\r\n{1}\r\n".F(cmd.Length, cmd); ms.WriteBytes(GetHeaderBytes(cmd, 0)); } else { //var str = "*{2}\r\n${0}\r\n{1}\r\n".F(cmd.Length, cmd, 1 + args.Length); ms.WriteBytes(GetHeaderBytes(cmd, args.Length)); foreach (var item in args) { var size = item.Total; var sizes = size.ToString().GetBytes(); var len = 1 + sizes.Length + NewLine.Length * 2 + size; if (log != null) { if (size <= 32) { log.AppendFormat(" {0}", item.ToStr()); } else { log.AppendFormat(" [{0}]", size); } } //str = "${0}\r\n".F(item.Length); //ms.Write(str.GetBytes()); ms.WriteByte((Byte)'$'); ms.WriteBytes(sizes); ms.WriteBytes(NewLine); //ms.Write(item); item.CopyTo(ms); ms.WriteBytes(NewLine); } } if (log != null) { WriteLog(log.Put(true)); } }
public static void Write(Stream output, Party instance, Endian endian) { output.WriteBytes(instance.Unknown0000Bytes); output.WriteBytes(instance.NameBytes); ArrayHelper.ForEach(instance.Units, e => Unit.Write(output, e, endian), UnitCount); int itemQuantityIndex = 0; if (instance.ItemQuantities != null) { if (instance.ItemQuantities.Length > ItemQuantityCount) { throw new InvalidOperationException("too many item quantities to write"); } var itemQuantityCount = Math.Min(instance.ItemQuantities.Length, ItemQuantityCount); output.Write(instance.ItemQuantities, 0, itemQuantityCount); itemQuantityIndex += itemQuantityCount; } if (itemQuantityIndex < ItemQuantityCount) { output.Write(DummyItemQuantities, 0, ItemQuantityCount - itemQuantityIndex); } ArrayHelper.ForEach(instance.CursedWeapons, e => CursedWeapon.Write(output, e), CursedWeaponCount); output.WriteValueU32(instance.Unknown2CB8, endian); output.WriteValueU32(instance.Unknown2CBC, endian); }
private async Task <bool> ConcatenateFragmentsIntoAsync(Stream dest) { while (true) { var frame = await WebSocketFrame.ReadAsync(_stream, true).ConfigureAwait(false); if (frame.IsFinal) { /* FINAL */ // CONT if (frame.IsContinuation) { dest.WriteBytes(frame.PayloadData.ApplicationData); break; } // PING if (frame.IsPing) { processPingFrame(frame); continue; } // PONG if (frame.IsPong) { processPongFrame(frame); continue; } // CLOSE if (frame.IsClose) { return(await ProcessCloseFrameAsync(frame).ConfigureAwait(false)); } } else { /* MORE */ // CONT if (frame.IsContinuation) { dest.WriteBytes(frame.PayloadData.ApplicationData); continue; } } // ? return(await ProcessUnsupportedFrameAsync( frame, CloseStatusCode.IncorrectData, "An incorrect data has been received while receiving fragmented data.").ConfigureAwait(false)); } return(true); }
internal static void WriteString(Stream stream, [NotNull] String o) { if (o == null) { throw new ArgumentNullException("o"); } byte[] bytes = Encoding.Unicode.GetBytes(o); stream.WriteBytes(BitConverter.GetBytes(bytes.Length)); stream.WriteBytes(bytes); }
protected override void SaveToStream(Stream stream) { base.SaveToStream(stream); stream.WriteBytes(MajorBrand.GetBytes()); stream.WriteBEUInt32(MinorVersion); foreach (FourCC compatibleBrand in CompatibleBrands) { stream.WriteBytes(compatibleBrand.GetBytes()); } }
protected override void SaveToStream(Stream stream) { base.SaveToStream(stream); stream.WriteBytes(MajorBrand.GetBytes()); stream.WriteBEUInt32(MinorVersion); foreach (FourCC compatibleBrand in _CompatibleBrands) { stream.WriteBytes(compatibleBrand.GetBytes()); } }
public static void Write(Stream output, ArchiveFileEntry instance, Endian endian) { ushort nameLength, archiveLength; byte[] nameBytes, archiveBytes; if (instance.Name == null) { nameBytes = null; nameLength = 0; } else { nameBytes = Encoding.UTF8.GetBytes(instance.Name); if (nameBytes.Length > ushort.MaxValue) { throw new InvalidOperationException(); } nameLength = (ushort)nameBytes.Length; } if (instance.Archive == null) { archiveBytes = null; archiveLength = 0; } else { archiveBytes = Encoding.UTF8.GetBytes(instance.Archive); if (archiveBytes.Length > ushort.MaxValue) { throw new InvalidOperationException(); } archiveLength = (ushort)archiveBytes.Length; } output.WriteValueU16(nameLength, endian); output.WriteValueU32(instance.Hash, endian); output.WriteValueU32(instance.CompressedSize, endian); output.WriteValueU32(instance.UncompressedSize, endian); output.WriteValueU32(instance.Offset, endian); output.WriteValueU16(archiveLength, endian); if (archiveBytes != null) { output.WriteBytes(archiveBytes); } if (nameBytes != null) { output.WriteBytes(nameBytes); } }
public bool SaveToStream(Stream str) { if (str != null) { // version byte str.WriteByte(0); str.WriteLong(ID); str.WriteShort((short)EntityType); str.WriteShort((short)CacheMode); if (CIID.HasValue) { byte[] ciid = CIID.Value.ToByteArray(); str.WriteByte((byte)ciid.Length); str.WriteBytes(ciid); } else { str.WriteByte(0); } if ((Key != null) && (Key.Length > 0)) { str.WriteShort((short)Key.Length); str.WriteBytes(Key); } else { str.WriteByte(0); } if (!String.IsNullOrEmpty(dataFile)) { byte[] dfb = StringHelper.GetBytes(dataFile); str.WriteShort((short)dfb.Length); str.WriteBytes(dfb); } else { str.WriteByte(0); } return(true); } return(false); }
public override void WriteToStream(Stream outputStream) { outputStream .WriteBytes((Byte)ASCIIBytes.p) .WriteInt32(4 + password.Length) .WriteBytes(password); }
public override void Close(NpgsqlConnector context) { NpgsqlEventLog.LogMethodEnter(LogLevel.Debug, CLASSNAME, "Close"); Stream stream = context.Stream; try { stream .WriteBytes((byte)FrontEndMessageCode.Termination) .WriteInt32(4) .Flush(); } catch { //Error writting termination message to stream, nothing we can do. } try { stream.Close(); } catch { } context.Stream = null; ChangeState(context, NpgsqlClosedState.Instance); }
public void Serialize(ushort version, Stream output, Endian endian) { output.WriteValueU32(Unk01, endian); output.WriteValueU64(FileHash, endian); output.WriteValueU32(Unk02); output.WriteBytes(Data); }
public void Serialize(Stream output) { output.WriteValueF32(this.X); output.WriteValueF32(this.Y); output.WriteValueF32(this.Z); output.WriteBytes(this.Data); }
public override void WriteToStream(Stream outputStream) { NpgsqlEventLog.LogMethodEnter(LogLevel.Debug, CLASSNAME, "WriteToStream"); switch (protocolVersion) { case ProtocolVersion.Version2: // Write the size of the packet. // 4 + (passwordlength + 1) -> Int32 + NULL terminated string. // output_stream.Write(BitConverter.GetBytes(IPAddress.HostToNetworkOrder(4 + (password.Length + 1))), 0, 4); outputStream .WriteInt32(4 + password.Length + 1) .WriteBytesNullTerminated(password); break; case ProtocolVersion.Version3: outputStream .WriteBytes((Byte)ASCIIBytes.p) .WriteInt32(4 + password.Length + 1) .WriteBytesNullTerminated(password); break; } }
private void AbandonShip() { //field size will always be smaller than message size //but if we fall out of sync with the stream due to an error then we will probably hit //such a situation soon as bytes from elsewhere in the stream get interpreted as a size. //so if we see this happens, we know we've lost the stream - our best option is to just give up on it, //and have the connector recovered later. try { Stream .WriteBytes((byte)FrontEndMessageCode.Termination) .WriteInt32(4) .Flush(); } catch { } try { Stream.Close(); } catch { } throw new DataException(); }
public override void WriteToStream(Stream outputStream) { outputStream .WriteBytes((byte)FrontEndMessageCode.Describe) .WriteInt32(_messageLength) .WriteBytes((byte)_whatToDescribe) .WriteBytesNullTerminated(_bPortalName); }
public override void WriteToStream(Stream outputStream) { NpgsqlEventLog.LogMethodEnter(LogLevel.Debug, CLASSNAME, "WriteToStream"); outputStream .WriteBytes((Byte)ASCIIBytes.p) .WriteInt32(4 + password.Length) .WriteBytes(password); }
private static void WriteBeginRequest(Stream Stream) { Stream.WriteBytes(new byte[] { 1, // Version (byte)Fastcgi.PacketType.FCGI_BEGIN_REQUEST, // Type 0, 1, // RequestId 0, 8, // Content Length 0, // Padding Length 0, // Reserved 1, 2, 3, 4, 5, 6, 7, 8, // Data }); }
public static void Encode(Image image, Stream stream) { stream.WriteString(image.Header); stream.WriteBytes(image.LogicalScreenDescriptor.ToBytes()); if (image.LogicalScreenDescriptor.GlobalColorTableFlag) { stream.WriteBytes(image.GlobalColorTable); } foreach (var applicationExtension in image.ApplictionExtensions) { stream.WriteBytes(applicationExtension.ToBytes()); } foreach (var commentExtension in image.CommentExtensions) { stream.WriteBytes(commentExtension.ToBytes()); } WriteFrames(image.Frames, stream); }
private static void WriteFrames(IEnumerable<ImageFrame> frames, Stream stream) { foreach (var frame in frames) { var frameBytes = new List<byte>(); if (frame.GraphicControlExtension != null) { frameBytes.AddRange(frame.GraphicControlExtension.ToBytes()); } frame.ImageDescriptor.SortFlag = false; frame.ImageDescriptor.InterlaceFlag = false; frameBytes.AddRange(frame.ImageDescriptor.ToBytes()); if (frame.ImageDescriptor.LocalColorTableFlag) { frameBytes.AddRange(frame.LocalColorTable); } stream.WriteBytes(frameBytes.ToArray()); var transparentColorIndex = -1; if (frame.GraphicControlExtension != null && frame.GraphicControlExtension.TransparentColorFlag) { transparentColorIndex = frame.GraphicControlExtension.TransparentColorIndex; } var imageData = GetImageData(frame.Bitmap, frame.LocalColorTable, transparentColorIndex); var lzwEncoder = new LzwEncoder(imageData, (byte) frame.ColorDepth); lzwEncoder.Encode(stream); stream.WriteByte(Const.BlockTerminator); } stream.WriteByte(Const.EndIntroducer); }
/// <summary> /// /// </summary> /// <param name="IplData"></param> /// <param name="OutputStream"></param> /// <param name="ToMemoryAddress"></param> /// <returns></returns> public static IplInfo DecryptIplToMemory(byte[] IplData, Stream OutputStream, bool ToMemoryAddress = true) { var buffer = new byte[0x1000]; var IplInfo = default(IplInfo); //ArrayUtils.HexDump(IplData); fixed (byte* IplPtr = IplData) fixed (byte* bufferPtr = buffer) { for (int n = 0; n < IplData.Length; n += 0x1000) { var Ptr = IplPtr + n; var Header = *(Kirk.AES128CMACHeader*)Ptr; //Console.WriteLine(Header.DataSize); var Kirk = new Kirk(); Kirk.kirk_init(); Kirk.kirk_CMD1(bufferPtr, Ptr, 0x1000, do_check: false); var IplBlock = *(IplBlock*)bufferPtr; //Console.WriteLine(IplBlock.ToStringDefault()); if (ToMemoryAddress) { OutputStream.Position = IplBlock.LoadAddress; Console.WriteLine("IplBlock.LoadAddress: 0x{0:X8}", IplBlock.LoadAddress); } OutputStream.WriteBytes(PointerUtils.PointerToByteArray(&IplBlock.BlockData, (int)IplBlock.BlockSize)); if (IplBlock.EntryFunction != 0) { IplInfo.EntryFunction = IplBlock.EntryFunction; } } } return IplInfo; }
protected override void SaveToStream(Stream stream) { base.SaveToStream(stream); stream.WriteBytes(Format.GetBytes()); }
public void Serialize(Stream output) { var endian = this.Endian; const uint headerSize = 32; output.WriteValueU32(0x42424947, endian); output.WriteValueU32(this.Version, endian); var keys = new List<string>() {""}; int maxValueLength = 0; var blob = new StringBuilder(); foreach (var file in this.Files) { keys.Add(file.Name); foreach (var section in file.Sections) { keys.Add(section.Key); foreach (var value in section.Value) { keys.Add(value.Key); foreach (var item in value.Value) { if (item.Value != null) { blob.Append(item.Value + '\0'); maxValueLength = Math.Max(maxValueLength, item.Value.Length); } } } } } var huffmanEncoder = new Huffman.Encoder(); huffmanEncoder.Build(blob.ToString()); keys = keys.Distinct().OrderBy(k => k.HashCrc32()).ToList(); int maxKeyLength = keys.Max(k => k.Length); uint stringTableSize; using (var data = new MemoryStream()) { data.Position = 4; data.WriteValueS32(keys.Count, endian); data.Position = 4 + 4 + (8 * keys.Count); var offsets = new List<KeyValuePair<uint, uint>>(); foreach (var key in keys) { var offset = (uint)data.Position; data.WriteValueU16((ushort)key.Length, endian); data.WriteString(key, Encoding.UTF8); offsets.Add(new KeyValuePair<uint, uint>(key.HashCrc32(), offset)); } data.Position = 8; foreach (var kv in offsets) { data.WriteValueU32(kv.Key, endian); data.WriteValueU32(kv.Value - 8, endian); } data.Position = 0; data.WriteValueU32((uint)data.Length, endian); data.Position = 0; stringTableSize = (uint)data.Length; output.Seek(headerSize, SeekOrigin.Begin); output.WriteFromStream(data, data.Length); } uint huffmanSize; using (var data = new MemoryStream()) { var pairs = huffmanEncoder.GetPairs(); data.WriteValueU16((ushort)pairs.Length, endian); foreach (var pair in pairs) { data.WriteValueS32(pair.Left, endian); data.WriteValueS32(pair.Right, endian); } data.Position = 0; huffmanSize = (uint)data.Length; output.Seek(headerSize + stringTableSize, SeekOrigin.Begin); output.WriteFromStream(data, data.Length); } var bits = new BitArray(huffmanEncoder.TotalBits); var bitOffset = 0; uint indexSize; using (var index = new MemoryStream()) { var fileDataOffset = 2 + (this.Files.Count * 6); var files = new List<KeyValuePair<ushort, int>>(); foreach (var file in this.Files.OrderBy(f => keys.IndexOf(f.Name))) { files.Add(new KeyValuePair<ushort, int>( (ushort)keys.IndexOf(file.Name), fileDataOffset)); var sectionDataOffset = 2 + (file.Sections.Count * 6); var sections = new List<KeyValuePair<ushort, int>>(); foreach (var section in file.Sections.OrderBy(s => keys.IndexOf(s.Key))) { sections.Add(new KeyValuePair<ushort, int>( (ushort)keys.IndexOf(section.Key), sectionDataOffset)); var valueDataOffset = 2 + (section.Value.Count * 6); var values = new List<KeyValuePair<ushort, int>>(); foreach (var value in section.Value.OrderBy(v => keys.IndexOf(v.Key))) { index.Position = fileDataOffset + sectionDataOffset + valueDataOffset; values.Add(new KeyValuePair<ushort, int>( (ushort)keys.IndexOf(value.Key), valueDataOffset)); index.WriteValueU16((ushort)value.Value.Count, endian); valueDataOffset += 2; foreach (var item in value.Value) { if (item.Type == 1) { index.WriteValueS32((1 << 29) | bitOffset, endian); } else if (item.Type == 0 || item.Type == 2 || item.Type == 3 || item.Type == 4) { index.WriteValueS32((item.Type << 29) | bitOffset, endian); bitOffset += huffmanEncoder.Encode((item.Value ?? "") + '\0', bits, bitOffset); } valueDataOffset += 4; } } index.Position = fileDataOffset + sectionDataOffset; index.WriteValueU16((ushort)values.Count, endian); sectionDataOffset += 2; foreach (var value in values) { index.WriteValueU16(value.Key, endian); index.WriteValueS32(value.Value, endian); sectionDataOffset += 6; } sectionDataOffset += valueDataOffset; } index.Position = fileDataOffset; index.WriteValueU16((ushort)sections.Count, endian); fileDataOffset += 2; foreach (var section in sections) { index.WriteValueU16(section.Key, endian); index.WriteValueS32(section.Value, endian); fileDataOffset += 6; } fileDataOffset += sectionDataOffset; } index.Position = 0; index.WriteValueU16((ushort)files.Count, endian); foreach (var file in files) { index.WriteValueU16(file.Key, endian); index.WriteValueS32(file.Value, endian); } index.Position = 0; indexSize = (uint)index.Length; output.Seek(headerSize + stringTableSize + huffmanSize, SeekOrigin.Begin); output.WriteFromStream(index, index.Length); } output.Seek(headerSize + stringTableSize + huffmanSize + indexSize, SeekOrigin.Begin); output.WriteValueS32(bits.Length, endian); var bytes = new byte[(bits.Length - 1) / 8 + 1]; bits.CopyTo(bytes, 0); output.WriteBytes(bytes); output.Seek(8, SeekOrigin.Begin); output.WriteValueS32(maxKeyLength, endian); output.WriteValueS32(maxValueLength, endian); output.WriteValueU32(stringTableSize, endian); output.WriteValueU32(huffmanSize, endian); output.WriteValueU32(indexSize, endian); output.WriteValueS32(bytes.Length, endian); output.Seek(0, SeekOrigin.Begin); output.WriteValueU32(0x666D726D, endian); }
/// <summary> /// Append a region of a source command text to an output command, performing parameter token /// substitutions. /// </summary> /// <param name="dest">Stream to which to append output.</param> /// <param name="src">Command text.</param> /// <param name="begin">Starting index within src.</param> /// <param name="length">Length of region to be processed.</param> /// <param name="prepare"></param> /// <param name="forExtendedQuery"></param> private void AppendCommandReplacingParameterValues(Stream dest, string src, int begin, int length, bool prepare, bool forExtendedQuery) { char lastChar = '\0'; TokenType currTokenType = TokenType.None; char paramMarker = '\0'; int currTokenBeg = begin; int currTokenLen = 0; Dictionary<NpgsqlParameter, int> paramOrdinalMap = null; if (prepare) { paramOrdinalMap = new Dictionary<NpgsqlParameter, int>(); for (int i = 0 ; i < parameters.Count ; i++) { paramOrdinalMap[parameters[i]] = i + 1; } } for (int currCharOfs = begin ; currCharOfs < begin + length ; currCharOfs++) { char ch = src[currCharOfs]; // goto label for character re-evaluation: ProcessCharacter: switch (currTokenType) { case TokenType.None : switch (ch) { case '\'': if (currTokenLen > 0) { dest.WriteString(src.Substring(currTokenBeg, currTokenLen)); } currTokenType = TokenType.Quoted; currTokenBeg = currCharOfs; currTokenLen = 1; break; case ':': { dest.WriteString(src.Substring(currTokenBeg, currTokenLen)); } currTokenType = TokenType.Colon; currTokenBeg = currCharOfs; currTokenLen = 1; break; case '@': { dest.WriteString(src.Substring(currTokenBeg, currTokenLen)); } currTokenType = TokenType.Param; currTokenBeg = currCharOfs + 1; currTokenLen = 0; paramMarker = '@'; break; default: currTokenLen++; break; } break; case TokenType.Param : if (IsParamNameChar(ch)) { currTokenLen++; } else { if (currTokenLen == 0) { dest.WriteBytes((byte)ASCIIBytes.Colon); } else { string paramName = src.Substring(currTokenBeg, currTokenLen); NpgsqlParameter parameter; bool wroteParam = false; if (parameters.TryGetValue(paramName, out parameter)) { if ( (parameter.Direction == ParameterDirection.Input) || (parameter.Direction == ParameterDirection.InputOutput) ) { if (prepare) { AppendParameterPlaceHolder(dest, parameter, paramOrdinalMap[parameter]); } else { AppendParameterValue(dest, parameter); } } wroteParam = true; } if (! wroteParam) { dest.WriteString("{0}{1}", paramMarker, paramName); } } currTokenType = TokenType.None; currTokenBeg = currCharOfs; currTokenLen = 0; // Re-evaluate this character goto ProcessCharacter; } break; case TokenType.Quoted : switch (ch) { case '\'': currTokenLen++; break; default: if (currTokenLen > 1 && lastChar == '\'') { dest.WriteString(src.Substring(currTokenBeg, currTokenLen)); currTokenType = TokenType.None; currTokenBeg = currCharOfs; currTokenLen = 0; // Re-evaluate this character goto ProcessCharacter; } else { currTokenLen++; } break; } break; case TokenType.Colon : switch (ch) { case ':': currTokenLen++; break; default: if (currTokenLen == 1) { currTokenType = TokenType.Param; currTokenBeg = currCharOfs; currTokenLen = 0; paramMarker = ':'; } else { dest.WriteString(src.Substring(currTokenBeg, currTokenLen)); currTokenType = TokenType.None; currTokenBeg = currCharOfs; currTokenLen = 0; } // Re-evaluate this character goto ProcessCharacter; } break; } lastChar = ch; } switch (currTokenType) { case TokenType.Param : if (currTokenLen == 0) { dest.WriteBytes((byte)ASCIIBytes.Colon); } else { string paramName = src.Substring(currTokenBeg, currTokenLen); NpgsqlParameter parameter; bool wroteParam = false; if (parameters.TryGetValue(paramName, out parameter)) { if ( (parameter.Direction == ParameterDirection.Input) || (parameter.Direction == ParameterDirection.InputOutput) ) { if (prepare) { AppendParameterPlaceHolder(dest, parameter, paramOrdinalMap[parameter]); } else { AppendParameterValue(dest, parameter); } } wroteParam = true; } if (! wroteParam) { dest.WriteString("{0}{1}", paramMarker, paramName); } } break; default : if (currTokenLen > 0) { dest.WriteString(src.Substring(currTokenBeg, currTokenLen)); } break; } }
public void Serialize(Stream output) { var saveGame = this.SaveGame; byte[] innerUncompressedBytes; using (var innerUncompressedData = new MemoryStream()) { saveGame.Compose(); try { ProtoBuf.Serializer.Serialize(innerUncompressedData, saveGame); } finally { saveGame.Decompose(); } innerUncompressedData.Position = 0; innerUncompressedBytes = innerUncompressedData.ReadBytes((uint)innerUncompressedData.Length); } byte[] innerCompressedBytes; using (var innerCompressedData = new MemoryStream()) { var endian = this.Endian; innerCompressedData.WriteValueS32(0, Endian.Big); innerCompressedData.WriteString("WSG"); innerCompressedData.WriteValueU32(2, endian); innerCompressedData.WriteValueU32(CRC32.Hash(innerUncompressedBytes, 0, innerUncompressedBytes.Length), endian); // crc32 innerCompressedData.WriteValueS32(innerUncompressedBytes.Length, endian); var encoder = new Huffman.Encoder(); encoder.Build(innerUncompressedBytes); innerCompressedData.WriteBytes(encoder.Encode(innerUncompressedBytes)); innerCompressedData.Position = 0; innerCompressedData.WriteValueU32((uint)(innerCompressedData.Length - 4), Endian.Big); innerCompressedData.Position = 0; innerCompressedBytes = innerCompressedData.ReadBytes((uint)innerCompressedData.Length); } byte[] compressedBytes; if (innerCompressedBytes.Length <= BlockSize) { compressedBytes = new byte[innerCompressedBytes.Length + (innerCompressedBytes.Length / 16) + 64 + 3]; var actualCompressedSize = compressedBytes.Length; var result = LZO.Compress(innerCompressedBytes, 0, innerCompressedBytes.Length, compressedBytes, 0, ref actualCompressedSize); if (result != LZO.ErrorCode.Success) { throw new SaveCorruptionException(string.Format("LZO compression failure ({0})", result)); } Array.Resize(ref compressedBytes, actualCompressedSize); } else { int innerCompressedOffset = 0; int innerCompressedSizeLeft = innerCompressedBytes.Length; using (var blockData = new MemoryStream()) { var blockCount = (innerCompressedSizeLeft + BlockSize) / BlockSize; blockData.WriteValueS32(blockCount, Endian.Big); blockData.Position = 4 + (blockCount * 8); var blockInfos = new List<Tuple<uint, uint>>(); while (innerCompressedSizeLeft > 0) { var blockUncompressedSize = Math.Min(BlockSize, innerCompressedSizeLeft); compressedBytes = new byte[blockUncompressedSize + (blockUncompressedSize / 16) + 64 + 3]; var actualCompressedSize = compressedBytes.Length; var result = LZO.Compress(innerCompressedBytes, innerCompressedOffset, blockUncompressedSize, compressedBytes, 0, ref actualCompressedSize); if (result != LZO.ErrorCode.Success) { throw new SaveCorruptionException(string.Format("LZO compression failure ({0})", result)); } blockData.Write(compressedBytes, 0, actualCompressedSize); blockInfos.Add(new Tuple<uint, uint>((uint)actualCompressedSize, BlockSize)); innerCompressedOffset += blockUncompressedSize; innerCompressedSizeLeft -= blockUncompressedSize; } blockData.Position = 4; foreach (var blockInfo in blockInfos) { blockData.WriteValueU32(blockInfo.Item1, Endian.Big); blockData.WriteValueU32(blockInfo.Item2, Endian.Big); } blockData.Position = 0; compressedBytes = blockData.ReadBytes((uint)blockData.Length); } } byte[] uncompressedBytes; using (var uncompressedData = new MemoryStream()) { uncompressedData.WriteValueS32(innerCompressedBytes.Length, Endian.Big); uncompressedData.WriteBytes(compressedBytes); uncompressedData.Position = 0; uncompressedBytes = uncompressedData.ReadBytes((uint)uncompressedData.Length); } byte[] computedHash; using (var sha1 = new System.Security.Cryptography.SHA1Managed()) { computedHash = sha1.ComputeHash(uncompressedBytes); } output.WriteBytes(computedHash); output.WriteBytes(uncompressedBytes); }
public override void WriteToStream(Stream outputStream) { if (_messageLength == 0) { _messageLength = 4 + // Message length (32 bits) _bPortalName.Length + 1 + // Portal name + null terminator _bPreparedStatementName.Length + 1 + // Statement name + null terminator 2 + // Parameter format code array length (16 bits) _parameterFormatCodes.Length * 2 + // Parameter format code array (16 bits per code) 2; // Parameter va;ue array length (16 bits) if (_parameterValues != null) { for (int i = 0; i < _parameterValues.Length; i++) { _messageLength += 4; // Parameter value length (32 bits) if (_parameterValues[i] != null) { _messageLength += _parameterValues[i].Length; // Parameter value } } } _messageLength += 2 + // Result format code array length (16 bits) _resultFormatCodes.Length * 2; // Result format code array (16 bits per code) } outputStream .WriteBytes((byte)FrontEndMessageCode.Bind) .WriteInt32(_messageLength) .WriteBytesNullTerminated(_bPortalName) .WriteBytesNullTerminated(_bPreparedStatementName) .WriteInt16((Int16)_parameterFormatCodes.Length); foreach (short code in _parameterFormatCodes) { outputStream.WriteInt16(code); } if (_parameterValues != null) { outputStream.WriteInt16((Int16)_parameterValues.Length); for (int i = 0 ; i < _parameterValues.Length ; i++) { Byte[] parameterValue = _parameterValues[i]; if (parameterValue == null) { outputStream.WriteInt32(-1); } else { outputStream .WriteInt32(parameterValue.Length) .WriteBytes(parameterValue); } } } else { outputStream.WriteInt16(0); } outputStream.WriteInt16((Int16)_resultFormatCodes.Length); foreach (short code in _resultFormatCodes) { outputStream.WriteInt16(code); } }
public override void WriteToStream(Stream outputStream) { outputStream.WriteBytes(pgCommandBytes); }
private bool concatenateFragments(Stream dest) { Func<WsFrame, bool> processContinuation = contFrame => { if (!contFrame.IsContinuation) return false; dest.WriteBytes (contFrame.PayloadData.ApplicationData); return true; }; while (true) { var frame = _stream.ReadFrame (); if (processAbnormal (frame)) return false; if (!frame.IsFinal) { // MORE & CONT if (processContinuation (frame)) continue; } else { // FINAL & CONT if (processContinuation (frame)) break; // FINAL & PING if (processPing (frame)) continue; // FINAL & PONG if (processPong (frame)) continue; // FINAL & CLOSE if (processClose (frame)) return false; } // ? processIncorrectFrame (); return false; } return true; }
public override void Pack(Stream stream) { stream.WriteBytes(Encoding.ASCII.GetBytes(Reason)); }
private bool concatenateFragmentsInto(Stream destination) { while (true) { var frame = WebSocketFrame.Read (_stream, false); var msg = checkIfValidReceivedFrame (frame); if (msg != null) return processUnsupportedFrame (frame, CloseStatusCode.ProtocolError, msg); frame.Unmask (); if (frame.IsFinal) { /* FINAL */ // CONT if (frame.IsContinuation) { destination.WriteBytes (frame.PayloadData.ApplicationData); break; } // PING if (frame.IsPing) { processPingFrame (frame); continue; } // PONG if (frame.IsPong) { processPongFrame (frame); continue; } // CLOSE if (frame.IsClose) return processCloseFrame (frame); } else { /* MORE */ // CONT if (frame.IsContinuation) { destination.WriteBytes (frame.PayloadData.ApplicationData); continue; } } // ? return processUnsupportedFrame ( frame, CloseStatusCode.UnsupportedData, "Unsupported data has been received while receiving the fragmented data."); } return true; }
private void EncodeBits(Stream stream, BitEncoder bitEncoder, int suffix) { bitEncoder.Add(suffix); bitEncoder.Add(this.endCode); bitEncoder.End(); if (bitEncoder.Length > 255) { var leftBuffer = new byte[bitEncoder.Length - 255]; bitEncoder.CopyTo(255, leftBuffer, 0, leftBuffer.Length); bitEncoder.Clear(); bitEncoder.AddRange(leftBuffer); stream.WriteByte((byte) leftBuffer.Length); stream.WriteBytes(leftBuffer); } else { stream.WriteByte((byte) (bitEncoder.Length)); stream.WriteBytes(bitEncoder.ToArray()); bitEncoder.Clear(); } }
public override void Pack(Stream stream) { stream.WriteInt32(Time); stream.WriteBoolean(DayTime); stream.WriteInt8(MoonPhase); stream.WriteBoolean(BloodMoon); stream.WriteInt32(MaxTilesX); stream.WriteInt32(MaxTilesY); stream.WriteInt32(SpawnX); stream.WriteInt32(SpawnY); stream.WriteInt32(WorldSurface); stream.WriteInt32(RockLayer); stream.WriteInt32(WorldID); stream.WriteInt8((byte) WorldFlags); stream.WriteBytes(Encoding.UTF8.GetBytes(WorldName)); }
public override void WriteToStream(Stream outputStream) { outputStream .WriteBytes(_messageData) .Flush(); }
private void AppendParameterValue(Stream dest, NpgsqlParameter parameter) { byte[] serialised = parameter.TypeInfo.ConvertToBackend(parameter.NpgsqlValue, false, Connector.NativeToBackendTypeConverterOptions); // Add parentheses wrapping parameter value before the type cast to avoid problems with Int16.MinValue, Int32.MinValue and Int64.MinValue // See bug #1010543 // Check if this parenthesis can be collapsed with the previous one about the array support. This way, we could use // only one pair of parentheses for the two purposes instead of two pairs. dest .WriteBytes((byte)ASCIIBytes.ParenLeft) .WriteBytes((byte)ASCIIBytes.ParenLeft) .WriteBytes(serialised) .WriteBytes((byte)ASCIIBytes.ParenRight); if (parameter.UseCast) { dest.WriteString("::{0}", parameter.TypeInfo.CastName); if (parameter.TypeInfo.UseSize && (parameter.Size > 0)) { dest.WriteString("({0})", parameter.Size); } } dest.WriteBytes((byte)ASCIIBytes.ParenRight); }
private void AppendParameterPlaceHolder(Stream dest, NpgsqlParameter parameter, int paramNumber) { string parameterSize = ""; dest.WriteBytes((byte)ASCIIBytes.ParenLeft); if (parameter.TypeInfo.UseSize && (parameter.Size > 0)) { parameterSize = string.Format("({0})", parameter.Size); } if (parameter.UseCast) { dest.WriteString("${0}::{1}{2}", paramNumber, parameter.TypeInfo.CastName, parameterSize); } else { dest.WriteString("${0}{1}", paramNumber, parameterSize); } dest.WriteBytes((byte)ASCIIBytes.ParenRight); }
public override void WriteToStream(Stream outputStream) { if (NpgsqlEventLog.Level >= LogLevel.Debug) { // Log the string being sent. // If (this) was constructed with a byte[], then commandText has to be // initialized before the first Log call. if (commandText == null) { commandText = BackendEncoding.UTF8Encoding.GetString(commandBytes); commandBytes = null; } PGUtil.LogStringWritten(commandText); } outputStream.WriteBytes(pgCommandBytes); }
private bool concatenateFragmentsInto(Stream dest) { while (true) { var frame = _stream.ReadFrame (); if (frame.IsFinal) { // FINAL // CONT if (frame.IsContinuation) { dest.WriteBytes (frame.PayloadData.ApplicationData); break; } // PING if (frame.IsPing) { acceptPingFrame (frame); continue; } // PONG if (frame.IsPong) { acceptPongFrame (frame); continue; } // CLOSE if (frame.IsClose) return acceptCloseFrame (frame); } else { // MORE // CONT if (frame.IsContinuation) { dest.WriteBytes (frame.PayloadData.ApplicationData); continue; } } // ? return acceptUnsupportedFrame ( frame, CloseStatusCode.IncorrectData, "An incorrect data has been received while receiving fragmented data."); } return true; }
public override void Pack(Stream stream) { stream.WriteInt32(Time); stream.WriteBoolean(DayTime); stream.WriteInt8(MoonPhase); stream.WriteBoolean(BloodMoon); stream.WriteBoolean(Eclipse); stream.WriteInt32(MaxTilesX); stream.WriteInt32(MaxTilesY); stream.WriteInt32(SpawnX); stream.WriteInt32(SpawnY); stream.WriteInt32(WorldSurface); stream.WriteInt32(RockLayer); stream.WriteInt32(WorldID); stream.WriteByte(MoonType); stream.WriteInt32(TreeX0); stream.WriteInt32(TreeX1); stream.WriteInt32(TreeX2); stream.WriteByte(TreeStyle0); stream.WriteByte(TreeStyle1); stream.WriteByte(TreeStyle2); stream.WriteByte(TreeStyle3); stream.WriteInt32(CaveBackX0); stream.WriteInt32(CaveBackX1); stream.WriteInt32(CaveBackX2); stream.WriteByte(CaveBackStyle0); stream.WriteByte(CaveBackStyle1); stream.WriteByte(CaveBackStyle2); stream.WriteByte(CaveBackStyle3); stream.WriteByte(SetBG0); stream.WriteByte(SetBG1); stream.WriteByte(SetBG2); stream.WriteByte(SetBG3); stream.WriteByte(SetBG4); stream.WriteByte(SetBG5); stream.WriteByte(SetBG6); stream.WriteByte(SetBG7); stream.WriteByte(IceBackStyle); stream.WriteByte(JungleBackStyle); stream.WriteByte(HellBackStyle); stream.WriteSingle(WindSpeed); stream.WriteByte(NumberOfClouds); stream.WriteInt8((byte)BossFlags); stream.WriteInt8((byte)BossFlags2); stream.WriteSingle(Rain); stream.WriteBytes(Encoding.UTF8.GetBytes(WorldName)); }
private bool concatenateFragmentsInto(Stream dest) { while (true) { var frame = _stream.ReadFrame (); // MORE & CONT if (!frame.IsFinal && frame.IsContinuation) { dest.WriteBytes (frame.PayloadData.ApplicationData); continue; } // FINAL & CONT if (frame.IsFinal && frame.IsContinuation) { dest.WriteBytes (frame.PayloadData.ApplicationData); break; } // FINAL & PING if (frame.IsFinal && frame.IsPing) { processPingFrame (frame); continue; } // FINAL & PONG if (frame.IsFinal && frame.IsPong) { processPongFrame (); continue; } // FINAL & CLOSE if (frame.IsFinal && frame.IsClose) return processCloseFrame (frame); // ? return processUnsupportedFrame (frame, CloseStatusCode.INCORRECT_DATA, null); } return true; }
public void Pack(Stream stream) { stream.WriteInt8(Field6); stream.WriteInt16(Field7); stream.WriteInt32(Field8); stream.WriteBytes(Field9); stream.WriteString(Field10); }