public void StreamMultiPart(Stream stream) { stream.WriteString(_boundary); if (_multipartFormData != null) { foreach (var entry in _multipartFormData) { stream.WriteString(CreateFormBoundaryHeader(entry.Key, entry.Value)); stream.WriteString(_boundary); } } if (_multipartFileData != null) { foreach (var fileData in _multipartFileData) { using (var file = new FileStream(fileData.Filename, FileMode.Open)) { stream.WriteString(CreateFileBoundaryHeader(fileData)); StreamFileContents(file, fileData, stream); stream.WriteString(_boundary); } } } stream.WriteString("--"); }
public virtual bool SaveTo(Stream stream) { stream.Write((uint)KeyValues.Count); foreach (var keyValue in KeyValues) { stream.WriteString(keyValue.Key); stream.WriteString(keyValue.Value); } return true; }
public override void RenderCommand(Stream stream) { if (Blob != null) { stream.WriteString("M 644 "); Blob.RenderMarkReference(stream); stream.WriteString(string.Format(" \"{0}\"", Path)); stream.WriteLineFeed(); } else { stream.WriteLine(string.Format("M 644 inline \"{0}\"", Path)); stream.RenderCommand(Data); } }
public void Serialize(Stream output) { if (this.Version < 1 || this.Version > 2) { throw new InvalidOperationException("unsupported blob version"); } output.WriteValueU32(this.Version); output.WriteValueS32(this.Entries.Count); var nameLength = this.Version == 2 ? 32 : 14; foreach (var entry in this.Entries) { var name = entry.Name; if (name.Length + 1 > nameLength) { throw new InvalidOperationException(); } output.WriteString(name.PadRight(nameLength, '\0')); output.WriteValueU32((uint)entry.Offset); output.WriteValueU32(entry.Size); } }
public void Serialize(Stream dest, Exception value) { if (dest == null) throw new ArgumentNullException("dest"); if (value == null) throw new ArgumentNullException("value"); var type = value.GetType(); int typeAlias = _data.TypeTable.GetAlias(type); var typeSerializable = _data.MessageSerializer.CanSerialize(type); dest.WriteByte((byte)((typeAlias != 0 ? 1 : 0) | (typeSerializable ? 2 : 0))); if (typeAlias != 0) dest.Write32BitEncodedInt(typeAlias); else dest.WriteString(type.FullName); if (typeSerializable) { var lengthMarker = new StreamLengthMarker(dest, true); _data.MessageSerializer.Serialize(dest, value); lengthMarker.WriteLength(true); } }
public void RenderMarkReference(Stream stream) { if (!_HasBeenRendered) throw new InvalidOperationException("A MarkCommand cannot be referenced if it has not been rendered."); var reference = string.Format(":{0}", MarkId); stream.WriteString(reference); }
public override void RenderCommand(Stream stream) { stream.WriteLine(string.Format("reset {0}", Reference)); if (From != null) { stream.WriteString("from "); From.RenderMarkReference(stream); stream.WriteLineFeed(); } }
static void StreamFileContents(Stream file, FileData fileData, Stream requestStream) { var buffer = new byte[8192]; int count; while ((count = file.Read(buffer, 0, buffer.Length)) > 0) { if (fileData.ContentTransferEncoding == HttpContentTransferEncoding.Base64) { string str = Convert.ToBase64String(buffer, 0, count); requestStream.WriteString(str); } else if (fileData.ContentTransferEncoding == HttpContentTransferEncoding.Binary) { requestStream.Write(buffer, 0, count); } } }
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); }
public virtual bool SaveTo(Stream stream) { stream.WriteString(Name); return true; }
public override bool SaveTo(Stream stream) { base.SaveTo(stream); Attribute.SaveTo(stream); stream.WriteString(BaseTypeName); //types uint typeCount = (uint)Types.Count; stream.Write(typeCount); foreach (var baseSirenCustomType in Types) { byte isClass = baseSirenCustomType.Value.IsCustomClass ? (byte)1 : (byte)0; stream.WriteByte(isClass); baseSirenCustomType.Value.SaveTo(stream); } //fields uint filedCount = (uint)FieldNameDict.Count; stream.Write(filedCount); foreach (var sirenField in FieldNameDict) { sirenField.Value.SaveTo(stream); } return true; }
// +--------+--------+--+----------+-----------+-------------+-----------+------------+-------+ // | LEN(4) | CRC(4) |H1| ID (1~6) | AID (1~6) | M_SIG (1~6) | M_LEN (4) | M_DATA (~) | E (~) | // +--------+--------+--+----------+-----------+-------------+-----------+------------+-------+ // H=[ME....TT] T=Type, M=Message?, E=Exception? // ID=RequestId, AID=ActorId, M=Message, E=Exception public void Serialize(Stream stream, object packet) { var p = (Packet)packet; // Jump 8 Bytes for writing Length | Checksum var packetLengthMarker = new StreamLengthMarker(stream, false); stream.Seek(8, SeekOrigin.Current); // Write Packet Header var header = (byte)((byte)(p.Type) | (byte)(p.Message != null ? 0x80 : 0) | (byte)(p.Exception != null ? 0x40 : 0)); stream.WriteByte(header); stream.Write7BitEncodedInt(p.ActorId); stream.Write7BitEncodedInt(p.RequestId); // Write Message if (p.Message != null) { if (p.Type == PacketType.System) { // System message: Always string. stream.WriteString((string)p.Message); } else { // User message: Length, Signature, and Data var messageTypeAlias = _data.TypeTable.GetAlias(p.Message.GetType()); stream.Write7BitEncodedInt(messageTypeAlias); var messageLengthMarker = new StreamLengthMarker(stream, true); _data.MessageSerializer.Serialize(stream, p.Message); messageLengthMarker.WriteLength(true); } } // Write Exception if (p.Exception != null) { _exceptionSerializer.Serialize(stream, p.Exception); } // Write Length packetLengthMarker.WriteLength(false); // Encrypt and Calc Checksum ArraySegment<byte> s0, s1; GetBuffers(stream, (int)packetLengthMarker.StartPosition + 8, packetLengthMarker.Length - 4, out s0, out s1); var ctx = new EncryptContext { Key = _serializeWrapKey }; Encrypt(s0.Array, s0.Offset, s0.Array, s0.Offset, s0.Count, ref ctx); Encrypt(s1.Array, s1.Offset, s1.Array, s1.Offset, s1.Count, ref ctx); if (_serializeWrapKey != 0) { _serializeWrapKey += 1; if (_serializeWrapKey == 0) _serializeWrapKey = 1; } // Write Checksum var hashBytes = BitConverter.GetBytes(ctx.Hash); stream.Write(hashBytes, 0, hashBytes.Length); // End of stream, again. stream.Seek(packetLengthMarker.EndPosition, SeekOrigin.Begin); // Pending WrapKey if (_serializeWrapPendingKey != 0) { _serializeWrapKey = _serializeWrapPendingKey; _serializeWrapPendingKey = 0; } }
public override bool SaveTo(Stream stream) { stream.Write((uint)Mode); stream.WriteString(Dir); return(true); }
public override async Task Encode() { await Stream.WriteString(AvatarName); }
private static void WriteMultipartFormData(Stream stream, string boundary, IEnumerable <KeyValuePair <string, object> > prm) { const int bufferSize = 81920; foreach (var x in prm) { var valueStream = x.Value as Stream; var valueArraySegment = x.Value as ArraySegment <byte>?; var valueBytes = x.Value as IEnumerable <byte>; #if !PCL var valueFile = x.Value as FileInfo; #endif var valueString = x.Value.ToString(); #if WP var valueInputStream = x.Value as Windows.Storage.Streams.IInputStream; if (valueInputStream != null) { valueStream = valueInputStream.AsStreamForRead(); } #endif stream.WriteString("--" + boundary + "\r\n"); if (valueStream != null || valueBytes != null || valueArraySegment != null #if !PCL || valueFile != null #endif ) { stream.WriteString("Content-Type: application/octet-stream\r\n"); } stream.WriteString(string.Format(@"Content-Disposition: form-data; name=""{0}""", x.Key)); #if !PCL if (valueFile != null) { stream.WriteString(string.Format(@"; filename=""{0}""", valueFile.Name.Replace("\n", "%0A").Replace("\r", "%0D").Replace("\"", "%22"))); } else #endif if (valueStream != null || valueBytes != null || valueArraySegment != null) { stream.WriteString(@"; filename=""file"""); } stream.WriteString("\r\n\r\n"); #if !PCL if (valueFile != null) { valueStream = valueFile.OpenRead(); } #endif if (valueStream != null) { var buffer = new byte[bufferSize]; int count; while ((count = valueStream.Read(buffer, 0, bufferSize)) > 0) { stream.Write(buffer, 0, count); } } else if (valueArraySegment != null) { stream.Write(valueArraySegment.Value.Array, valueArraySegment.Value.Offset, valueArraySegment.Value.Count); } else if (valueBytes != null) { var buffer = valueBytes as byte[]; if (buffer != null) { stream.Write(buffer, 0, buffer.Length); } else { buffer = new byte[bufferSize]; var i = 0; foreach (var b in valueBytes) { buffer[i++] = b; if (i == bufferSize) { stream.Write(buffer, 0, bufferSize); i = 0; } } if (i > 0) { stream.Write(buffer, 0, i); } } } else { stream.WriteString(valueString); } #if !PCL if (valueFile != null) { valueStream.Close(); } #endif stream.WriteString("\r\n"); } stream.WriteString("--" + boundary + "--"); }
public static void WriteLine(this Stream stream, string s) { stream.WriteString(s); stream.WriteLineFeed(); }
private static void WriteMultipartFormData(Stream stream, string boundary, IEnumerable <KeyValuePair <string, object> > prm) { prm.ForEach(x => { var valueStream = x.Value as Stream; var valueBytes = x.Value as IEnumerable <byte>; #if !PCL var valueFile = x.Value as FileInfo; #endif var valueString = x.Value.ToString(); #if WP var valueInputStream = x.Value as Windows.Storage.Streams.IInputStream; if (valueInputStream != null) { valueStream = valueInputStream.AsStreamForRead(); } #endif stream.WriteString("--" + boundary + "\r\n"); if (valueStream != null || valueBytes != null #if !PCL || valueFile != null #endif ) { stream.WriteString("Content-Type: application/octet-stream\r\n"); } stream.WriteString(String.Format(@"Content-Disposition: form-data; name=""{0}""", x.Key)); #if !PCL if (valueFile != null) { stream.WriteString(String.Format(@"; filename=""{0}""", valueFile.Name)); } else #endif if (valueStream != null || valueBytes != null) { stream.WriteString(@"; filename=""file"""); } stream.WriteString("\r\n\r\n"); #if !PCL if (valueFile != null) { valueStream = valueFile.OpenRead(); } #endif if (valueStream != null) { while (true) { var buffer = new byte[4096]; var count = valueStream.Read(buffer, 0, buffer.Length); if (count == 0) { break; } stream.Write(buffer, 0, count); } } else if (valueBytes != null) { valueBytes.ForEach(b => stream.WriteByte(b)); } else { stream.WriteString(valueString); } #if !PCL if (valueFile != null) { valueStream.Close(); } #endif stream.WriteString("\r\n"); }); stream.WriteString("--" + boundary + "--"); }
public static void Write(object obj, Stream stream) { stream.WriteString((string)obj); }
public void Write(Stream destination) { destination.WriteInt32(this.Id); destination.WriteInt64(this.Offset); destination.WriteString(this.Metadata); }
public void Write(Stream destination) { destination.WriteString(this.Name); destination.WriteArray(this.Partitions); }
public override void ToStream(Stream s) { s.WriteString(this.ZeroTerminatedStrings, this.Name); }
private void Write(Stream BTKFile) { string Padding = "Hack.io.BTK © Super Hackio Incorporated 2020"; BTKFile.WriteString(Magic); BTKFile.Write(new byte[4] { 0xDD, 0xDD, 0xDD, 0xDD }, 0, 4); BTKFile.Write(new byte[4] { 0x00, 0x00, 0x00, 0x01 }, 0, 4); BTKFile.Write(new byte[16] { 0x53, 0x56, 0x52, 0x31, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF }, 0, 16); BTKFile.WriteString(Magic2); BTKFile.Write(new byte[4] { 0xDD, 0xDD, 0xDD, 0xDD }, 0, 4); BTKFile.WriteByte((byte)Loop); BTKFile.WriteByte((byte)RotationMultiplier); BTKFile.WriteReverse(BitConverter.GetBytes(Time), 0, 2); BTKFile.WriteReverse(BitConverter.GetBytes((ushort)(TextureAnimations.Count * 3)), 0, 2); BTKFile.Write(new byte[2] { 0xDD, 0xDD }, 0, 2); BTKFile.Write(new byte[2] { 0xEE, 0xEE }, 0, 2); BTKFile.Write(new byte[2] { 0xFF, 0xFF }, 0, 2); //Animation Table Offset BTKFile.Write(new byte[4] { 0xDD, 0xDD, 0xDD, 0xDD }, 0, 4); //Remap Table Offset BTKFile.Write(new byte[4] { 0xDD, 0xDD, 0xDD, 0xDD }, 0, 4); //Material ST Offset BTKFile.Write(new byte[4] { 0xDD, 0xDD, 0xDD, 0xDD }, 0, 4); //TexMtxTable Offset BTKFile.Write(new byte[4] { 0xDD, 0xDD, 0xDD, 0xDD }, 0, 4); //Center Table Offset BTKFile.Write(new byte[4] { 0xDD, 0xDD, 0xDD, 0xDD }, 0, 4); //Scale Table Offset BTKFile.Write(new byte[4] { 0xDD, 0xDD, 0xDD, 0xDD }, 0, 4); //Rotation Table Offset BTKFile.Write(new byte[4] { 0xDD, 0xDD, 0xDD, 0xDD }, 0, 4); //Translation Table Offset BTKFile.Write(new byte[4] { 0xDD, 0xDD, 0xDD, 0xDD }, 0, 4); #region Padding //int PadCount = 0; while (BTKFile.Position < 0x80) { BTKFile.WriteByte(0x00); } #endregion long AnimationTableOffset = BTKFile.Position; for (int i = 0; i < TextureAnimations.Count; i++) { BTKFile.WriteReverse(BitConverter.GetBytes((ushort)TextureAnimations[i].ScaleUFrames.Count), 0, 2); BTKFile.WriteReverse(new byte[2], 0, 2); BTKFile.WriteReverse(BitConverter.GetBytes((ushort)(TextureAnimations[i].ScaleUFrames.Any(S => S.IngoingTangent != S.OutgoingTangent) ? 1 : 1)), 0, 2); BTKFile.WriteReverse(BitConverter.GetBytes((ushort)TextureAnimations[i].RotationUFrames.Count), 0, 2); BTKFile.WriteReverse(new byte[2], 0, 2); BTKFile.WriteReverse(BitConverter.GetBytes((ushort)(TextureAnimations[i].RotationUFrames.Any(S => S.IngoingTangent != S.OutgoingTangent) ? 1 : 1)), 0, 2); BTKFile.WriteReverse(BitConverter.GetBytes((ushort)TextureAnimations[i].TranslationUFrames.Count), 0, 2); BTKFile.WriteReverse(new byte[2], 0, 2); BTKFile.WriteReverse(BitConverter.GetBytes((ushort)(TextureAnimations[i].TranslationUFrames.Any(S => S.IngoingTangent != S.OutgoingTangent) ? 1 : 1)), 0, 2); BTKFile.WriteReverse(BitConverter.GetBytes((ushort)TextureAnimations[i].ScaleVFrames.Count), 0, 2); BTKFile.WriteReverse(new byte[2], 0, 2); BTKFile.WriteReverse(BitConverter.GetBytes((ushort)(TextureAnimations[i].ScaleVFrames.Any(S => S.IngoingTangent != S.OutgoingTangent) ? 1 : 1)), 0, 2); BTKFile.WriteReverse(BitConverter.GetBytes((ushort)TextureAnimations[i].RotationVFrames.Count), 0, 2); BTKFile.WriteReverse(new byte[2], 0, 2); BTKFile.WriteReverse(BitConverter.GetBytes((ushort)(TextureAnimations[i].RotationVFrames.Any(S => S.IngoingTangent != S.OutgoingTangent) ? 1 : 1)), 0, 2); BTKFile.WriteReverse(BitConverter.GetBytes((ushort)TextureAnimations[i].TranslationVFrames.Count), 0, 2); BTKFile.WriteReverse(new byte[2], 0, 2); BTKFile.WriteReverse(BitConverter.GetBytes((ushort)(TextureAnimations[i].TranslationVFrames.Any(S => S.IngoingTangent != S.OutgoingTangent) ? 1 : 1)), 0, 2); BTKFile.WriteReverse(BitConverter.GetBytes((ushort)TextureAnimations[i].ScaleWFrames.Count), 0, 2); BTKFile.WriteReverse(new byte[2], 0, 2); BTKFile.WriteReverse(BitConverter.GetBytes((ushort)(TextureAnimations[i].ScaleWFrames.Any(S => S.IngoingTangent != S.OutgoingTangent) ? 1 : 1)), 0, 2); BTKFile.WriteReverse(BitConverter.GetBytes((ushort)TextureAnimations[i].RotationWFrames.Count), 0, 2); BTKFile.WriteReverse(new byte[2], 0, 2); BTKFile.WriteReverse(BitConverter.GetBytes((ushort)(TextureAnimations[i].RotationWFrames.Any(S => S.IngoingTangent != S.OutgoingTangent) ? 1 : 1)), 0, 2); BTKFile.WriteReverse(BitConverter.GetBytes((ushort)TextureAnimations[i].TranslationWFrames.Count), 0, 2); BTKFile.WriteReverse(new byte[2], 0, 2); BTKFile.WriteReverse(BitConverter.GetBytes((ushort)(TextureAnimations[i].TranslationWFrames.Any(S => S.IngoingTangent != S.OutgoingTangent) ? 1 : 1)), 0, 2); } #region Padding int PadCount = 0; while (BTKFile.Position % 4 != 0) { BTKFile.WriteByte((byte)Padding[PadCount++]); } #endregion long RemapTableOffset = BTKFile.Position; List <string> strings = new List <string>(); for (int i = 0; i < TextureAnimations.Count; i++) { BTKFile.WriteReverse(BitConverter.GetBytes(TextureAnimations[i].RemapIndex), 0, 2); strings.Add(TextureAnimations[i].MaterialName); } #region Padding PadCount = 0; while (BTKFile.Position % 4 != 0) { BTKFile.WriteByte((byte)Padding[PadCount++]); } #endregion long StringTableOffset = BTKFile.Position; BTKFile.WriteReverse(BitConverter.GetBytes((ushort)strings.Count), 0, 2); BTKFile.Write(new byte[2] { 0xFF, 0xFF }, 0, 2); ushort stringofffset = (ushort)(4 + (4 * strings.Count)); List <byte> bytestrings = new List <byte>(); byte[] TexMapID = new byte[TextureAnimations.Count]; for (int i = 0; i < TextureAnimations.Count; i++) { BTKFile.WriteReverse(BitConverter.GetBytes(StringToHash(strings[i])), 0, 2); BTKFile.WriteReverse(BitConverter.GetBytes(stringofffset), 0, 2); byte[] currentstring = Encoding.GetEncoding(932).GetBytes(strings[i]); stringofffset += (ushort)(currentstring.Length + 1); bytestrings.AddRange(currentstring); bytestrings.Add(0x00); TexMapID[i] = TextureAnimations[i].MaterialTextureID; } BTKFile.Write(bytestrings.ToArray(), 0, bytestrings.Count); #region Padding PadCount = 0; while (BTKFile.Position % 4 != 0) { BTKFile.WriteByte((byte)Padding[PadCount++]); } #endregion long TexMapIDTableOffset = BTKFile.Position; BTKFile.Write(TexMapID, 0, TexMapID.Length); #region Padding PadCount = 0; while (BTKFile.Position % 4 != 0) { BTKFile.WriteByte((byte)Padding[PadCount++]); } #endregion long CenterTableOffset = BTKFile.Position; for (int i = 0; i < TextureAnimations.Count; i++) { BTKFile.WriteReverse(BitConverter.GetBytes(TextureAnimations[i].Center[0]), 0, 4); BTKFile.WriteReverse(BitConverter.GetBytes(TextureAnimations[i].Center[1]), 0, 4); BTKFile.WriteReverse(BitConverter.GetBytes(TextureAnimations[i].Center[2]), 0, 4); } #region Padding PadCount = 0; while (BTKFile.Position % 4 != 0) { BTKFile.WriteByte((byte)Padding[PadCount++]); } #endregion List <float> ScaleTable = new List <float>(); List <short> RotationTable = new List <short>(); List <float> TranslationTable = new List <float>(); for (int i = 0; i < TextureAnimations.Count; i++) { FindMatch(ref ScaleTable, TextureAnimations[i].ScaleUFrames, 1); FindMatch(ref ScaleTable, TextureAnimations[i].ScaleVFrames, 1); FindMatch(ref ScaleTable, TextureAnimations[i].ScaleWFrames, 1); FindMatch(ref RotationTable, TextureAnimations[i].RotationUFrames, RotationMultiplier); FindMatch(ref RotationTable, TextureAnimations[i].RotationVFrames, RotationMultiplier); FindMatch(ref RotationTable, TextureAnimations[i].RotationWFrames, RotationMultiplier); FindMatch(ref TranslationTable, TextureAnimations[i].TranslationUFrames, 1); FindMatch(ref TranslationTable, TextureAnimations[i].TranslationVFrames, 1); FindMatch(ref TranslationTable, TextureAnimations[i].TranslationWFrames, 1); } long ScaleTableOffset = BTKFile.Position; for (int i = 0; i < ScaleTable.Count; i++) { BTKFile.WriteReverse(BitConverter.GetBytes(ScaleTable[i]), 0, 4); } #region Padding PadCount = 0; while (BTKFile.Position % 4 != 0) { BTKFile.WriteByte((byte)Padding[PadCount++]); } #endregion long RotationTableOffset = BTKFile.Position; for (int i = 0; i < RotationTable.Count; i++) { BTKFile.WriteReverse(BitConverter.GetBytes(RotationTable[i]), 0, 2); } #region Padding PadCount = 0; while (BTKFile.Position % 4 != 0) { BTKFile.WriteByte((byte)Padding[PadCount++]); } #endregion long TranslationTableOffset = BTKFile.Position; for (int i = 0; i < TranslationTable.Count; i++) { BTKFile.WriteReverse(BitConverter.GetBytes(TranslationTable[i]), 0, 4); } #region Padding PadCount = 0; while (BTKFile.Position % 32 != 0) { BTKFile.WriteByte((byte)Padding[PadCount++]); } #endregion BTKFile.Position = 0x08; BTKFile.WriteReverse(BitConverter.GetBytes((uint)BTKFile.Length), 0, 4); BTKFile.Position = 0x24; BTKFile.WriteReverse(BitConverter.GetBytes((uint)(BTKFile.Length - 0x20)), 0, 4); BTKFile.Position = 0x2E; BTKFile.WriteReverse(BitConverter.GetBytes((ushort)ScaleTable.Count), 0, 2); BTKFile.WriteReverse(BitConverter.GetBytes((ushort)RotationTable.Count), 0, 2); BTKFile.WriteReverse(BitConverter.GetBytes((ushort)TranslationTable.Count), 0, 2); BTKFile.WriteReverse(BitConverter.GetBytes((uint)(AnimationTableOffset - 0x20)), 0, 4); BTKFile.WriteReverse(BitConverter.GetBytes((uint)(RemapTableOffset - 0x20)), 0, 4); BTKFile.WriteReverse(BitConverter.GetBytes((uint)(StringTableOffset - 0x20)), 0, 4); BTKFile.WriteReverse(BitConverter.GetBytes((uint)(TexMapIDTableOffset - 0x20)), 0, 4); BTKFile.WriteReverse(BitConverter.GetBytes((uint)(CenterTableOffset - 0x20)), 0, 4); BTKFile.WriteReverse(BitConverter.GetBytes((uint)(ScaleTableOffset - 0x20)), 0, 4); BTKFile.WriteReverse(BitConverter.GetBytes((uint)(RotationTableOffset - 0x20)), 0, 4); BTKFile.WriteReverse(BitConverter.GetBytes((uint)(TranslationTableOffset - 0x20)), 0, 4); BTKFile.Seek(AnimationTableOffset, SeekOrigin.Begin); for (int i = 0; i < TextureAnimations.Count; i++) { BTKFile.Position += 2; BTKFile.WriteReverse(BitConverter.GetBytes(FindMatch(ref ScaleTable, TextureAnimations[i].ScaleUFrames, 1)), 0, 2); BTKFile.Position += 2; BTKFile.Position += 2; BTKFile.WriteReverse(BitConverter.GetBytes(FindMatch(ref RotationTable, TextureAnimations[i].RotationUFrames, RotationMultiplier)), 0, 2); BTKFile.Position += 2; BTKFile.Position += 2; BTKFile.WriteReverse(BitConverter.GetBytes(FindMatch(ref TranslationTable, TextureAnimations[i].TranslationUFrames, 1)), 0, 2); BTKFile.Position += 2; BTKFile.Position += 2; BTKFile.WriteReverse(BitConverter.GetBytes(FindMatch(ref ScaleTable, TextureAnimations[i].ScaleVFrames, 1)), 0, 2); BTKFile.Position += 2; BTKFile.Position += 2; BTKFile.WriteReverse(BitConverter.GetBytes(FindMatch(ref RotationTable, TextureAnimations[i].RotationVFrames, RotationMultiplier)), 0, 2); BTKFile.Position += 2; BTKFile.Position += 2; BTKFile.WriteReverse(BitConverter.GetBytes(FindMatch(ref TranslationTable, TextureAnimations[i].TranslationVFrames, 1)), 0, 2); BTKFile.Position += 2; BTKFile.Position += 2; BTKFile.WriteReverse(BitConverter.GetBytes(FindMatch(ref ScaleTable, TextureAnimations[i].ScaleWFrames, 1)), 0, 2); BTKFile.Position += 2; BTKFile.Position += 2; BTKFile.WriteReverse(BitConverter.GetBytes(FindMatch(ref RotationTable, TextureAnimations[i].RotationWFrames, RotationMultiplier)), 0, 2); BTKFile.Position += 2; BTKFile.Position += 2; BTKFile.WriteReverse(BitConverter.GetBytes(FindMatch(ref TranslationTable, TextureAnimations[i].TranslationWFrames, 1)), 0, 2); BTKFile.Position += 2; } }
public void Write(Stream s) { s.WriteString(Version); }
public virtual bool SaveTo(Stream stream) { stream.WriteString(Name); return(true); }
void AppendParameterValues(Stream dest) { var first = true; for (var i = 0; i < _parameters.Count; i++) { var parameter = _parameters[i]; if (parameter.IsInputDirection) { if (first) { first = false; } else { dest.WriteString(", "); } AppendParameterValue(dest, parameter); } } }
public void Serialize(ushort version, Stream input, Endian endian) { input.WriteValueU64(NameHash, endian); input.WriteStringU16(Name, endian); if (version >= 2) { input.WriteBytes(new byte[10]); input.WriteValueS32(-1); input.WriteValueS32(0); } input.WriteValueU16((ushort)Columns.Count, endian); input.WriteValueU32(Unk1, endian); input.WriteValueU32(Unk2, endian); input.WriteValueU32((uint)(Data.Length / Rows.Count)); input.WriteValueU32((uint)Rows.Count); for (int i = 0; i < Rows.Count; i++) { for (int x = 0; x < Columns.Count; x++) { Column column = Columns[x]; switch (column.Type) { case ColumnType.Boolean: uint value = Convert.ToUInt32(Rows[i].Values[x]); input.WriteValueU32(value); break; case ColumnType.Float32: input.WriteValueF32((float)Rows[i].Values[x]); break; case ColumnType.Signed32: input.WriteValueS32((int)Rows[i].Values[x]); break; case ColumnType.Unsigned32: input.WriteValueU32((uint)Rows[i].Values[x]); break; case ColumnType.Flags32: input.WriteValueU32((uint)Rows[i].Values[x]); break; case ColumnType.Hash64: input.WriteValueU64((ulong)Rows[i].Values[x]); break; case ColumnType.String8: input.WriteString(Rows[i].Values[x].ToString(), 8); break; case ColumnType.String16: input.WriteString(Rows[i].Values[x].ToString(), 16); break; case ColumnType.String32: input.WriteString(Rows[i].Values[x].ToString(), 32, System.Text.Encoding.GetEncoding(1250)); break; case ColumnType.String64: input.WriteString(Rows[i].Values[x].ToString(), 64); break; case ColumnType.Color: string[] colors = (Rows[i].Values[x] as string).Split(new char[1] { ' ' }, StringSplitOptions.RemoveEmptyEntries); input.WriteValueF32(float.Parse(colors[0])); input.WriteValueF32(float.Parse(colors[1])); input.WriteValueF32(float.Parse(colors[2])); break; case ColumnType.Hash64AndString32: string name = (string)Rows[i].Values[x]; ulong hash = FNV64.Hash(name); input.WriteValueU64(hash); input.WriteString(Rows[i].Values[x].ToString(), 32); break; default: throw new FormatException(); break; } } } for (int i = 0; i < Columns.Count; i++) { Columns[i].Serialize(input, endian); } }
private static void WriteMultipartFormData(Stream stream, string boundary, KeyValuePair<string, object>[] prm) { var items = prm.ConvertAll(x => MultipartItem.Create(x.Key, x.Value)); // Start writing foreach(var x in items) { stream.WriteString("--" + boundary + "\r\n"); x.WriteTo(stream); stream.WriteString("\r\n"); } stream.WriteString("--" + boundary + "--"); }
private void ListenWorker_DoWork(object sender, DoWorkEventArgs e) { // setup http listener. if (!HttpListener.IsSupported) { e.Result = "HttpListener is not supported on your OS."; return; } HttpListener http = new HttpListener(); try { http.Prefixes.Add($"http://localhost:{SERVER_PORT}/"); http.Start(); } catch (Exception exc) { e.Result = exc.Message; return; } // make a pseudo random generator. Random rnd = new Random(); rnd.Next(); BackgroundWorker self = sender as BackgroundWorker; int counter = 1; List <IPAddress> blocked = new List <IPAddress>(); List <string> allIPs = new List <string>(); List <int> gennedIDs = new List <int>(); while (true) { // obtain responses and stuff. HttpListenerContext context = http.GetContext(); HttpListenerRequest request = context.Request; HttpListenerResponse response = context.Response; Stream output = response.OutputStream; Stream input = request.InputStream; response.ContentType = "application/x-www-form-urlencoded"; response.ContentEncoding = Encoding.UTF8; response.StatusCode = (int)HttpStatusCode.OK; // if blocked ip is trying again... bool cont = false; foreach (var endpoint in blocked) { if (endpoint.Equals(request.RemoteEndPoint.Address)) { // update the RNG so it gets stronger. rnd.Next(); Console.WriteLine("Blocked IP trying again huh... " + endpoint.ToString()); output.WriteString("status=success&reason=ok"); output.Close(); cont = true; break; } } if (cont) { continue; } switch (request.Url.AbsolutePath) { case "/register": { // get values. var nvc = HttpUtility.ParseQueryString(input.ReadToEnd()); string employeename = nvc["username"]; string ipport = nvc["ipport"]; string iponly = ipport.Substring(0, ipport.IndexOf(':')); bool stop = false; foreach (string ip in allIPs) { if (iponly == ip) { // oh. output.WriteString("status=denied&id=0"); output.Close(); stop = true; Console.WriteLine("Access denied for " + ipport); break; } } if (stop) { continue; } Console.WriteLine("Adding " + iponly); allIPs.Add(iponly); // generate a totally unique random emp id. int id = 0; int bob = 100; do { Console.WriteLine("Generating employee id..."); id = bob + rnd.Next(bob, int.MaxValue / bob); }while (gennedIDs.IndexOf(id) != -1); gennedIDs.Add(id); // construct info struct EmployeeInfo info = new EmployeeInfo(counter, id, employeename, ipport); // return response output.WriteString("status=success&id=" + id.ToString()); // send it to the ProgressChanged method. self.ReportProgress(0, info); counter++; break; } case "/updatetime": { // update the RNG so it gets stronger. rnd.Next(); // lol. Console.WriteLine("Updating time..."); // parse client. string query = input.ReadToEnd(); var nvc = HttpUtility.ParseQueryString(query); if (nvc["time"] == "ABUSE") // abuse detection worked. { blocked.Add(request.RemoteEndPoint.Address); Console.WriteLine("ABUSE DETECTED! " + request.RemoteEndPoint.ToString()); } else { int _newtime = -1, _empid = -1; if (!int.TryParse(nvc["time"], out _newtime)) { output.WriteString("status=failure&reason=InvalidTime"); output.Close(); continue; } else if (!int.TryParse(nvc["employeeid"], out _empid)) { output.WriteString("status=failure&reason=InvalidEmployeeId"); output.Close(); continue; } output.WriteString("status=success&reason=ok"); // construct update struct. UpdateInfo uinfo = new UpdateInfo(_newtime, _empid); // report to UI self.ReportProgress(1, uinfo); } // we're done. output.WriteString("status=success&reason=ok"); break; } case "/leaderboard": { Leaderboard lbret = (Leaderboard)MainListView.Invoke((Func <Leaderboard>) delegate { Leaderboard lb = new Leaderboard { employees = new Employee[MainListView.Items.Count] }; int i = 0; foreach (ListViewItem lvi in MainListView.Items) { if (lvi.SubItems[2].Text == "-1") { continue; } lb.employees[i] = new Employee { id = lvi.Text, best_time = lvi.SubItems[2].Text }; i++; } return(lb); }); string lbstring = JsonConvert.SerializeObject(lbret); byte[] lbrawstring = Encoding.UTF8.GetBytes(lbstring); response.ContentType = "application/json"; response.ContentLength64 = lbrawstring.LongLength; output.WriteString(lbstring); break; } default: { Console.WriteLine("Unsupported method, ignoring..."); break; } } output.Close(); } }
private void WriteDataItems(Stream s, IList <TFString> strings, ExportOptions options) { var written = new Dictionary <int, long>(); var stringOffset = 0x0E03E800; foreach (var tfString in strings) { var indexOffset = Convert.ToInt32(tfString.Section, 16); s.Seek(indexOffset, SeekOrigin.Begin); if (written.ContainsKey(tfString.Offset)) { s.WriteValueS64(written[tfString.Offset], Endianness); } else { var correctedOffset = stringOffset + OUTPUT_BASE; s.WriteValueS64(correctedOffset, Endianness); s.Seek(stringOffset, SeekOrigin.Begin); string str; Encoding enc; bool replaceChars; if (tfString.Original == tfString.Translation) { str = tfString.Original; enc = Encoding; replaceChars = false; } else { str = tfString.Translation; enc = options.SelectedEncoding; replaceChars = options.CharReplacement != 0; } if (!string.IsNullOrEmpty(str)) { if (replaceChars) { str = Utils.ReplaceChars(str, options.CharReplacementList); } str = Yakuza0Project.WritingReplacements(str); s.WriteStringZ(str, enc); stringOffset += str.GetLength(enc) + 1; } else { // Hay que escribir solo el 0 del final s.WriteString("\0"); stringOffset++; } written.Add(tfString.Offset, correctedOffset); } } }
/// <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; int end = begin + length; 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 < end; 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 ':': if (currTokenLen > 0) { dest.WriteString(src.Substring(currTokenBeg, currTokenLen)); } currTokenType = TokenType.Colon; currTokenBeg = currCharOfs; currTokenLen = 1; break; case '<': case '@': if (currTokenLen > 0) { dest.WriteString(src.Substring(currTokenBeg, currTokenLen)); } currTokenType = TokenType.FullTextMatchOp; currTokenBeg = currCharOfs; currTokenLen = 1; break; case '-': if (currTokenLen > 0) { dest.WriteString(src.Substring(currTokenBeg, currTokenLen)); } currTokenType = TokenType.LineCommentBegin; currTokenBeg = currCharOfs; currTokenLen = 1; break; case '/': if (currTokenLen > 0) { dest.WriteString(src.Substring(currTokenBeg, currTokenLen)); } currTokenType = TokenType.BlockCommentBegin; currTokenBeg = currCharOfs; currTokenLen = 1; break; default: currTokenLen++; break; } break; case TokenType.Param: if (IsParamNameChar(ch)) { currTokenLen++; } 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.LineComment: if (ch == '\n') { currTokenType = TokenType.None; } currTokenLen++; break; case TokenType.BlockComment: if (ch == '*') { currTokenType = TokenType.BlockCommentEnd; } currTokenLen++; break; case TokenType.Colon: if (IsParamNameChar(ch)) { // Switch to parameter name token, include this character. currTokenType = TokenType.Param; currTokenBeg = currCharOfs; currTokenLen = 1; paramMarker = ':'; } else { // Demote to the unknown token type and continue. currTokenType = TokenType.None; currTokenLen++; } break; case TokenType.FullTextMatchOp: if (lastChar == '@' && IsParamNameChar(ch)) { // Switch to parameter name token, include this character. currTokenType = TokenType.Param; currTokenBeg = currCharOfs; currTokenLen = 1; paramMarker = '@'; } else { // Demote to the unknown token type. currTokenType = TokenType.None; // Re-evaluate this character goto ProcessCharacter; } break; case TokenType.LineCommentBegin: if (ch == '-') { currTokenType = TokenType.LineComment; currTokenLen++; } else { // Demote to the unknown token type. currTokenType = TokenType.None; // Re-evaluate this character goto ProcessCharacter; } break; case TokenType.BlockCommentBegin: if (ch == '*') { currTokenType = TokenType.BlockComment; currTokenLen++; } else { // Demote to the unknown token type. currTokenType = TokenType.None; // Re-evaluate this character goto ProcessCharacter; } break; case TokenType.BlockCommentEnd: if (ch == '/') { currTokenType = TokenType.None; currTokenLen++; } else { currTokenType = TokenType.BlockComment; currTokenLen++; } break; } lastChar = ch; } switch (currTokenType) { case TokenType.Param: 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; } }
internal override void Write(Stream writer) { writer.WriteString((String)_val); }
public override void Pack(Stream stream) { stream.WriteString(Reason); }
public override async Task Encode() { await Stream.WriteString(Reason); }
/// <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="prepare"></param> /// <param name="allowMultipleStatements"></param> /// <returns>false if the query has multiple statements which are not allowed</returns> private bool AppendCommandReplacingParameterValues(Stream dest, string src, bool prepare, bool allowMultipleStatements) { bool standardConformantStrings = connection != null && connection.Connector != null && connection.Connector.IsInitialized ? connection.UseConformantStrings : true; int currCharOfs = 0; int end = src.Length; char ch = '\0'; char lastChar = '\0'; int dollarTagStart = 0; int dollarTagEnd = 0; int currTokenBeg = 0; int blockCommentLevel = 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; } } if (allowMultipleStatements && parameters.Count == 0) { dest.WriteString(src); return(true); } None: if (currCharOfs >= end) { goto Finish; } lastChar = ch; ch = src[currCharOfs++]; NoneContinue: for (; ; lastChar = ch, ch = src[currCharOfs++]) { switch (ch) { case '/': goto BlockCommentBegin; case '-': goto LineCommentBegin; case '\'': if (standardConformantStrings) { goto Quoted; } else { goto Escaped; } case '$': if (!IsIdentifier(lastChar)) { goto DollarQuotedStart; } else { break; } case '"': goto DoubleQuoted; case ':': if (lastChar != ':') { goto ParamStart; } else { break; } case '@': if (lastChar != '@') { goto ParamStart; } else { break; } case ';': if (!allowMultipleStatements) { goto SemiColon; } else { break; } case 'e': case 'E': if (!IsLetter(lastChar)) { goto EscapedStart; } else { break; } } if (currCharOfs >= end) { goto Finish; } } ParamStart: if (currCharOfs < end) { lastChar = ch; ch = src[currCharOfs]; if (IsParamNameChar(ch)) { if (currCharOfs - 1 > currTokenBeg) { dest.WriteString(src.Substring(currTokenBeg, currCharOfs - 1 - currTokenBeg)); } currTokenBeg = currCharOfs++ - 1; goto Param; } else { currCharOfs++; goto NoneContinue; } } goto Finish; Param: // We have already at least one character of the param name for (; ;) { lastChar = ch; if (currCharOfs >= end || !IsParamNameChar(ch = src[currCharOfs])) { string paramName = src.Substring(currTokenBeg, currCharOfs - currTokenBeg); NpgsqlParameter parameter; 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); } currTokenBeg = currCharOfs; } } if (currCharOfs >= end) { goto Finish; } currCharOfs++; goto NoneContinue; } else { currCharOfs++; } } Quoted: while (currCharOfs < end) { if (src[currCharOfs++] == '\'') { ch = '\0'; goto None; } } goto Finish; DoubleQuoted: while (currCharOfs < end) { if (src[currCharOfs++] == '"') { ch = '\0'; goto None; } } goto Finish; EscapedStart: if (currCharOfs < end) { lastChar = ch; ch = src[currCharOfs++]; if (ch == '\'') { goto Escaped; } goto NoneContinue; } goto Finish; Escaped: while (currCharOfs < end) { ch = src[currCharOfs++]; if (ch == '\'') { goto MaybeConcatenatedEscaped; } if (ch == '\\') { if (currCharOfs >= end) { goto Finish; } currCharOfs++; } } goto Finish; MaybeConcatenatedEscaped: while (currCharOfs < end) { ch = src[currCharOfs++]; if (ch == '\r' || ch == '\n') { goto MaybeConcatenatedEscaped2; } if (ch != ' ' && ch != '\t' && ch != '\f') { lastChar = '\0'; goto NoneContinue; } } goto Finish; MaybeConcatenatedEscaped2: while (currCharOfs < end) { ch = src[currCharOfs++]; if (ch == '\'') { goto Escaped; } if (ch == '-') { if (currCharOfs >= end) { goto Finish; } ch = src[currCharOfs++]; if (ch == '-') { goto MaybeConcatenatedEscapeAfterComment; } lastChar = '\0'; goto NoneContinue; } if (ch != ' ' && ch != '\t' && ch != '\n' & ch != '\r' && ch != '\f') { lastChar = '\0'; goto NoneContinue; } } goto Finish; MaybeConcatenatedEscapeAfterComment: while (currCharOfs < end) { ch = src[currCharOfs++]; if (ch == '\r' || ch == '\n') { goto MaybeConcatenatedEscaped2; } } goto Finish; DollarQuotedStart: if (currCharOfs < end) { ch = src[currCharOfs]; if (ch == '$') { // Empty tag dollarTagStart = dollarTagEnd = currCharOfs; currCharOfs++; goto DollarQuoted; } if (IsIdentifierStart(ch)) { dollarTagStart = currCharOfs; currCharOfs++; goto DollarQuotedInFirstDelim; } lastChar = '$'; currCharOfs++; goto NoneContinue; } goto Finish; DollarQuotedInFirstDelim: while (currCharOfs < end) { lastChar = ch; ch = src[currCharOfs++]; if (ch == '$') { dollarTagEnd = currCharOfs - 1; goto DollarQuoted; } if (!IsDollarTagIdentifier(ch)) { goto NoneContinue; } } goto Finish; DollarQuoted: { string tag = src.Substring(dollarTagStart - 1, dollarTagEnd - dollarTagStart + 2); int pos = src.IndexOf(tag, dollarTagEnd + 1); // Not linear time complexity, but that's probably not a problem, since PostgreSQL backend's isn't either if (pos == -1) { currCharOfs = end; goto Finish; } currCharOfs = pos + dollarTagEnd - dollarTagStart + 2; ch = '\0'; goto None; } LineCommentBegin: if (currCharOfs < end) { ch = src[currCharOfs++]; if (ch == '-') { goto LineComment; } lastChar = '\0'; goto NoneContinue; } goto Finish; LineComment: while (currCharOfs < end) { ch = src[currCharOfs++]; if (ch == '\r' || ch == '\n') { goto None; } } goto Finish; BlockCommentBegin: while (currCharOfs < end) { ch = src[currCharOfs++]; if (ch == '*') { blockCommentLevel++; goto BlockComment; } if (ch != '/') { if (blockCommentLevel > 0) { goto BlockComment; } lastChar = '\0'; goto NoneContinue; } } goto Finish; BlockComment: while (currCharOfs < end) { ch = src[currCharOfs++]; if (ch == '*') { goto BlockCommentEnd; } if (ch == '/') { goto BlockCommentBegin; } } goto Finish; BlockCommentEnd: while (currCharOfs < end) { ch = src[currCharOfs++]; if (ch == '/') { if (--blockCommentLevel > 0) { goto BlockComment; } goto None; } if (ch != '*') { goto BlockComment; } } goto Finish; SemiColon: while (currCharOfs < end) { ch = src[currCharOfs++]; if (ch != ' ' && ch != '\t' && ch != '\n' & ch != '\r' && ch != '\f') // We don't check for comments after the last ; yet { return(false); } } // implicit goto Finish Finish: dest.WriteString(src.Substring(currTokenBeg, end - currTokenBeg)); return(true); }
public void Serialize(Stream output) { var endian = this.Endian; output.WriteString("ATG CORE CEMENT LIBRARY", 24, Encoding.ASCII); output.Seek(8, SeekOrigin.Current); output.WriteValueU8(2); // majorVersion output.WriteValueU8(1); // minorVersion switch (endian) { case Endian.Little: { output.WriteValueB8(false); break; } case Endian.Big: { output.WriteValueB8(true); break; } default: { throw new InvalidOperationException("unsupported endian"); } } output.WriteValueU8(1); // unknown1 var offset = 0x3C; var indexSize = this.EstimateEntryTableSize(); output.WriteValueS32(offset, endian); // indexOffset output.WriteValueS32(indexSize, endian); // indexSize offset += indexSize; offset = offset.Align(2048); var metadataSize = this.EstimateMetadataTableSize(); output.WriteValueS32(offset, endian); // metadataOffset output.WriteValueS32(metadataSize, endian); // metadataSize //offset += metadataSize; output.WriteValueU32(0, endian); // unknown2 output.WriteValueS32(this.Entries.Count, endian); // entryCount foreach (var entry in this.Entries) { entry.Serialize(output, endian); } output.Seek(output.Position.Align(2048), SeekOrigin.Begin); output.WriteValueU32(2048, Endian.Little); output.WriteValueU32(0, Endian.Little); foreach (var metadata in this.Metadatas) { metadata.Serialize(output, endian); } output.Seek(output.Position.Align(2048), SeekOrigin.Begin); }
public void Write(Stream writer) { writer.WriteString(FilePath); }
public static void Write(object obj, Stream stream) { stream.WriteString((string)obj); }
public override void OnString(string obj) { Stream.WriteVarUInt32((uint)obj.Length + 1);//include '\0' Stream.WriteString(obj); }
public override void RenderCommand(Stream stream) { foreach (var fc in FileCommands.OfType<FileModifyCommand>()) { if (fc.Blob != null) stream.RenderCommand(fc.Blob); } stream.WriteLine(string.Format("commit {0}", Reference)); base.RenderMarkCommand(stream); if (Author != null) stream.RenderCommand(Author); stream.RenderCommand(Committer); stream.RenderCommand(CommitInfo); if (FromCommit != null) { stream.WriteString("from "); FromCommit.RenderMarkReference(stream); stream.WriteLineFeed(); } foreach (var mc in MergeCommits) { stream.WriteString("merge "); mc.RenderMarkReference(stream); stream.WriteLineFeed(); } foreach (var fc in FileCommands) stream.RenderCommand(fc); stream.WriteLineFeed(); }
public override void WriteTo(Stream stream) { stream.WriteString("Content-Type: application/octet-stream\r\n"); stream.WriteString(string.Format("Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\n\r\n", this.Key, this.FileName != null ? this.FileName.Replace("\n", "%0A").Replace("\r", "%0D").Replace("\"", "%22") : "file" )); this.WriteContent(stream); }
void AppendParameterPlaceHolder(Stream dest, NpgsqlParameter parameter, int paramNumber) { dest.WriteByte((byte)ASCIIBytes.ParenLeft); if (parameter.UseCast && parameter.Size > 0) { dest.WriteString("${0}::{1}", paramNumber, parameter.TypeInfo.GetCastName(parameter.Size)); } else { dest.WriteString("$" + paramNumber); } dest.WriteByte((byte)ASCIIBytes.ParenRight); }
private void AddFunctionColumnListSupport(Stream st) { bool isFirstOutputOrInputOutput = true; PGUtil.WriteString(st, " AS ("); for (int i = 0 ; i < Parameters.Count ; i++) { var p = Parameters[i]; switch(p.Direction) { case ParameterDirection.Output: case ParameterDirection.InputOutput: if (isFirstOutputOrInputOutput) { isFirstOutputOrInputOutput = false; } else { st.WriteString(", "); } st .WriteString(p.CleanName) .WriteBytes((byte)ASCIIBytes.Space) .WriteString(p.TypeInfo.Name); break; } } st.WriteByte((byte)ASCIIBytes.ParenRight); }
/// <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; int end = begin + length; 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 < end ; 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 ':' : if (currTokenLen > 0) { dest.WriteString(src.Substring(currTokenBeg, currTokenLen)); } currTokenType = TokenType.Colon; currTokenBeg = currCharOfs; currTokenLen = 1; break; case '<' : case '@' : if (currTokenLen > 0) { dest.WriteString(src.Substring(currTokenBeg, currTokenLen)); } currTokenType = TokenType.FullTextMatchOp; currTokenBeg = currCharOfs; currTokenLen = 1; break; case '-' : if (currTokenLen > 0) { dest.WriteString(src.Substring(currTokenBeg, currTokenLen)); } currTokenType = TokenType.LineCommentBegin; currTokenBeg = currCharOfs; currTokenLen = 1; break; case '/' : if (currTokenLen > 0) { dest.WriteString(src.Substring(currTokenBeg, currTokenLen)); } currTokenType = TokenType.BlockCommentBegin; currTokenBeg = currCharOfs; currTokenLen = 1; break; default : currTokenLen++; break; } break; case TokenType.Param : if (IsParamNameChar(ch)) { currTokenLen++; } 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.LineComment : if (ch == '\n') { currTokenType = TokenType.None; } currTokenLen++; break; case TokenType.BlockComment : if (ch == '*') { currTokenType = TokenType.BlockCommentEnd; } currTokenLen++; break; case TokenType.Colon : if (IsParamNameChar(ch)) { // Switch to parameter name token, include this character. currTokenType = TokenType.Param; currTokenBeg = currCharOfs; currTokenLen = 1; paramMarker = ':'; } else { // Demote to the unknown token type and continue. currTokenType = TokenType.None; currTokenLen++; } break; case TokenType.FullTextMatchOp : if (lastChar == '@' && IsParamNameChar(ch)) { // Switch to parameter name token, include this character. currTokenType = TokenType.Param; currTokenBeg = currCharOfs; currTokenLen = 1; paramMarker = '@'; } else { // Demote to the unknown token type. currTokenType = TokenType.None; // Re-evaluate this character goto ProcessCharacter; } break; case TokenType.LineCommentBegin : if (ch == '-') { currTokenType = TokenType.LineComment; currTokenLen++; } else { // Demote to the unknown token type. currTokenType = TokenType.None; // Re-evaluate this character goto ProcessCharacter; } break; case TokenType.BlockCommentBegin : if (ch == '*') { currTokenType = TokenType.BlockComment; currTokenLen++; } else { // Demote to the unknown token type. currTokenType = TokenType.None; // Re-evaluate this character goto ProcessCharacter; } break; case TokenType.BlockCommentEnd : if (ch == '/') { currTokenType = TokenType.None; currTokenLen++; } else { currTokenType = TokenType.BlockComment; currTokenLen++; } break; } lastChar = ch; } switch (currTokenType) { case TokenType.Param : 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; } }
private void AppendParameterValues(Stream dest) { bool first = true; for (int i = 0 ; i < parameters.Count ; i++) { NpgsqlParameter parameter = parameters[i]; if ( (parameter.Direction == ParameterDirection.Input) || (parameter.Direction == ParameterDirection.InputOutput) ) { if (first) { first = false; } else { dest.WriteString(", "); } AppendParameterValue(dest, parameter); } } }
/// <summary> /// Performs the initial handshake with the remote debugging server, verifying signature and version number and setting up SSL, /// and returns the opened socket and the SSL stream for that socket. /// </summary> /// <param name="hostName">Name of the host to connect to.</param> /// <param name="portNumber">Port number to connect to.</param> /// <param name="secret">Secret to authenticate with.</param> /// <param name="useSsl">Whether to use SSL for this connection.</param> /// <param name="sslErrorHandling">If using SSL, specifies how SSL certificate errors should be handled.</param> /// <param name="socket">Opened socket to the remote debugging server. The returned socket is owned by <paramref name="stream"/>.</param> /// <param name="stream">Opened SSL network stream to the remote debugging server. This stream owns the <paramref name="socket"/>, and will automatically close it.</param> /// <returns>Error code.</returns> /// <remarks><paramref name="socket"/> should not be used to send or receive data, since it is wrapped in a stream, and is owned by that stream. /// It is exposed solely to enable querying it for endpoint information and connectivity status.</remarks> public static ConnErrorMessages TryConnect(string hostName, ushort portNumber, string secret, bool useSsl, SslErrorHandling sslErrorHandling, out Socket socket, out Stream stream) { stream = null; socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); bool connected = false; try { socket.Connect(hostName, portNumber); var rawStream = new NetworkStream(socket, ownsSocket: true); if (useSsl) { var sslStream = new SslStream(rawStream, false, (sender, cert, chain, errs) => { if (errs == SslPolicyErrors.None || sslErrorHandling == SslErrorHandling.Ignore) { return true; } else if (sslErrorHandling == SslErrorHandling.Fail) { return false; } string errText = string.Format("Could not establish secure connection to {0}:{1} because of the following SSL issues:\n\n", hostName, portNumber); if ((errs & SslPolicyErrors.RemoteCertificateNotAvailable) != 0) { errText += "- no remote certificate provided\n"; } if ((errs & SslPolicyErrors.RemoteCertificateNameMismatch) != 0) { errText += "- remote certificate name does not match hostname\n"; } if ((errs & SslPolicyErrors.RemoteCertificateChainErrors) != 0) { errText += "- remote certificate is not trusted\n"; } errText += "\nConnect anyway?"; var dlgRes = MessageBox.Show(errText, null, MessageBoxButtons.YesNo, MessageBoxIcon.Warning); return dlgRes == DialogResult.Yes; }); try { sslStream.AuthenticateAsClient(hostName); } catch (AuthenticationException) { return ConnErrorMessages.RemoteSslError; } stream = sslStream; } else { stream = rawStream; } var buf = new byte[8]; int bufLen = stream.Read(buf, 0, DebuggerSignature.Length); string sig = Encoding.ASCII.GetString(buf, 0, bufLen); if (sig != DebuggerSignature) { return ConnErrorMessages.RemoteUnsupportedServer; } long ver = stream.ReadInt64(); if (ver != DebuggerProtocolVersion) { return ConnErrorMessages.RemoteUnsupportedServer; } stream.Write(DebuggerSignatureBytes); stream.WriteInt64(DebuggerProtocolVersion); stream.WriteString(secret); bufLen = stream.Read(buf, 0, Accepted.Length); string secretResp = Encoding.ASCII.GetString(buf, 0, bufLen); if (secretResp != Accepted) { return ConnErrorMessages.RemoteSecretMismatch; } connected = true; } catch (IOException) { return ConnErrorMessages.RemoteNetworkError; } catch (SocketException) { return ConnErrorMessages.RemoteNetworkError; } finally { if (!connected) { if (stream != null) { stream.Close(); } socket.Close(); socket = null; stream = null; } } return ConnErrorMessages.None; }
/// <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="prepare"></param> /// <param name="allowMultipleStatements"></param> /// <returns>false if the query has multiple statements which are not allowed</returns> private bool AppendCommandReplacingParameterValues(Stream dest, string src, bool prepare, bool allowMultipleStatements) { bool standardConformantStrings = connection != null && connection.Connector != null && connection.Connector.IsInitialized ? connection.UseConformantStrings : true; int currCharOfs = 0; int end = src.Length; char ch = '\0'; char lastChar = '\0'; int dollarTagStart = 0; int dollarTagEnd = 0; int currTokenBeg = 0; int blockCommentLevel = 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; } } if (allowMultipleStatements && parameters.Count == 0) { dest.WriteString(src); return true; } None: if (currCharOfs >= end) { goto Finish; } lastChar = ch; ch = src[currCharOfs++]; NoneContinue: for (; ; lastChar = ch, ch = src[currCharOfs++]) { switch (ch) { case '/': goto BlockCommentBegin; case '-': goto LineCommentBegin; case '\'': if (standardConformantStrings) goto Quoted; else goto Escaped; case '$': if (!IsIdentifier(lastChar)) goto DollarQuotedStart; else break; case '"': goto DoubleQuoted; case ':': if (lastChar != ':') goto ParamStart; else break; case '@': if (lastChar != '@') goto ParamStart; else break; case ';': if (!allowMultipleStatements) goto SemiColon; else break; case 'e': case 'E': if (!IsLetter(lastChar)) goto EscapedStart; else break; } if (currCharOfs >= end) { goto Finish; } } ParamStart: if (currCharOfs < end) { lastChar = ch; ch = src[currCharOfs]; if (IsParamNameChar(ch)) { if (currCharOfs - 1 > currTokenBeg) { dest.WriteString(src.Substring(currTokenBeg, currCharOfs - 1 - currTokenBeg)); } currTokenBeg = currCharOfs++ - 1; goto Param; } else { currCharOfs++; goto NoneContinue; } } goto Finish; Param: // We have already at least one character of the param name for (; ; ) { lastChar = ch; if (currCharOfs >= end || !IsParamNameChar(ch = src[currCharOfs])) { string paramName = src.Substring(currTokenBeg, currCharOfs - currTokenBeg); NpgsqlParameter parameter; 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); } currTokenBeg = currCharOfs; } } if (currCharOfs >= end) { goto Finish; } currCharOfs++; goto NoneContinue; } else { currCharOfs++; } } Quoted: while (currCharOfs < end) { if (src[currCharOfs++] == '\'') { ch = '\0'; goto None; } } goto Finish; DoubleQuoted: while (currCharOfs < end) { if (src[currCharOfs++] == '"') { ch = '\0'; goto None; } } goto Finish; EscapedStart: if (currCharOfs < end) { lastChar = ch; ch = src[currCharOfs++]; if (ch == '\'') { goto Escaped; } goto NoneContinue; } goto Finish; Escaped: while (currCharOfs < end) { ch = src[currCharOfs++]; if (ch == '\'') { goto MaybeConcatenatedEscaped; } if (ch == '\\') { if (currCharOfs >= end) { goto Finish; } currCharOfs++; } } goto Finish; MaybeConcatenatedEscaped: while (currCharOfs < end) { ch = src[currCharOfs++]; if (ch == '\r' || ch == '\n') { goto MaybeConcatenatedEscaped2; } if (ch != ' ' && ch != '\t' && ch != '\f') { lastChar = '\0'; goto NoneContinue; } } goto Finish; MaybeConcatenatedEscaped2: while (currCharOfs < end) { ch = src[currCharOfs++]; if (ch == '\'') { goto Escaped; } if (ch == '-') { if (currCharOfs >= end) { goto Finish; } ch = src[currCharOfs++]; if (ch == '-') { goto MaybeConcatenatedEscapeAfterComment; } lastChar = '\0'; goto NoneContinue; } if (ch != ' ' && ch != '\t' && ch != '\n' & ch != '\r' && ch != '\f') { lastChar = '\0'; goto NoneContinue; } } goto Finish; MaybeConcatenatedEscapeAfterComment: while (currCharOfs < end) { ch = src[currCharOfs++]; if (ch == '\r' || ch == '\n') { goto MaybeConcatenatedEscaped2; } } goto Finish; DollarQuotedStart: if (currCharOfs < end) { ch = src[currCharOfs]; if (ch == '$') { // Empty tag dollarTagStart = dollarTagEnd = currCharOfs; currCharOfs++; goto DollarQuoted; } if (IsIdentifierStart(ch)) { dollarTagStart = currCharOfs; currCharOfs++; goto DollarQuotedInFirstDelim; } lastChar = '$'; currCharOfs++; goto NoneContinue; } goto Finish; DollarQuotedInFirstDelim: while (currCharOfs < end) { lastChar = ch; ch = src[currCharOfs++]; if (ch == '$') { dollarTagEnd = currCharOfs - 1; goto DollarQuoted; } if (!IsDollarTagIdentifier(ch)) { goto NoneContinue; } } goto Finish; DollarQuoted: { string tag = src.Substring(dollarTagStart - 1, dollarTagEnd - dollarTagStart + 2); int pos = src.IndexOf(tag, dollarTagEnd + 1); // Not linear time complexity, but that's probably not a problem, since PostgreSQL backend's isn't either if (pos == -1) { currCharOfs = end; goto Finish; } currCharOfs = pos + dollarTagEnd - dollarTagStart + 2; ch = '\0'; goto None; } LineCommentBegin: if (currCharOfs < end) { ch = src[currCharOfs++]; if (ch == '-') { goto LineComment; } lastChar = '\0'; goto NoneContinue; } goto Finish; LineComment: while (currCharOfs < end) { ch = src[currCharOfs++]; if (ch == '\r' || ch == '\n') { goto None; } } goto Finish; BlockCommentBegin: while (currCharOfs < end) { ch = src[currCharOfs++]; if (ch == '*') { blockCommentLevel++; goto BlockComment; } if (ch != '/') { if (blockCommentLevel > 0) { goto BlockComment; } lastChar = '\0'; goto NoneContinue; } } goto Finish; BlockComment: while (currCharOfs < end) { ch = src[currCharOfs++]; if (ch == '*') { goto BlockCommentEnd; } if (ch == '/') { goto BlockCommentBegin; } } goto Finish; BlockCommentEnd: while (currCharOfs < end) { ch = src[currCharOfs++]; if (ch == '/') { if (--blockCommentLevel > 0) { goto BlockComment; } goto None; } if (ch != '*') { goto BlockComment; } } goto Finish; SemiColon: while (currCharOfs < end) { ch = src[currCharOfs++]; if (ch != ' ' && ch != '\t' && ch != '\n' & ch != '\r' && ch != '\f') // We don't check for comments after the last ; yet { return false; } } // implicit goto Finish Finish: dest.WriteString(src.Substring(currTokenBeg, end - currTokenBeg)); return true; }
public override bool SaveTo(Stream stream) { stream.Write((uint)Mode); stream.WriteString(Dir); return true; }
private PythonProcess(Stream stream, int pid, PythonLanguageVersion version, PythonDebugOptions debugOptions) { _pid = pid; _process = Process.GetProcessById(pid); _process.EnableRaisingEvents = true; _process.Exited += new EventHandler(_process_Exited); _delayUnregister = true; ListenForConnection(); stream.WriteInt32(DebugConnectionListener.ListenerPort); stream.WriteString(_processGuid.ToString()); stream.WriteString(debugOptions.ToString()); }
public void Serialize(Stream output) { const Endian endian = Endian.Little; output.WriteValueS32(this._Rooms.Count, endian); foreach (var room in this._Rooms) { output.WriteValueU32(room.Type, endian); output.WriteValueU32(room.Variant, endian); output.WriteValueU8(room.Difficulty); output.WriteString(room.Name, endian); output.WriteValueF32(room.Weight, endian); output.WriteValueU8(room.Width); output.WriteValueU8(room.Height); var doorCount = room.Doors == null ? 0 : room.Doors.Length; if (doorCount > byte.MaxValue) { throw new InvalidOperationException(); } var spawnCount = room.Spawns == null ? 0 : room.Spawns.Length; if (spawnCount > ushort.MaxValue) { throw new InvalidOperationException(); } output.WriteValueU8((byte)doorCount); output.WriteValueU16((ushort)spawnCount, endian); if (room.Doors != null) { foreach (var door in room.Doors) { output.WriteValueS16(door.X, endian); output.WriteValueS16(door.Y, endian); output.WriteValueB8(door.Exists); } } if (room.Spawns != null) { foreach (var spawn in room.Spawns) { output.WriteValueS16(spawn.X, endian); output.WriteValueS16(spawn.Y, endian); var entityCount = spawn.Entities == null ? 0 : spawn.Entities.Length; if (entityCount > byte.MaxValue) { throw new InvalidOperationException(); } output.WriteValueU8((byte)entityCount); if (spawn.Entities != null) { foreach (var entity in spawn.Entities) { output.WriteValueU16(entity.Type, endian); output.WriteValueU16(entity.Variant, endian); output.WriteValueU16(entity.Subtype, endian); output.WriteValueF32(entity.Weight, endian); } } } } } }
/// <summary> /// Connects to and performs the initial handshake with the remote debugging server, verifying protocol signature and version number, /// and returns the opened stream in a state ready to receive further ptvsd commands (e.g. attach). /// </summary> public static Stream Connect(Uri uri, bool warnAboutAuthenticationErrors) { var transport = DebuggerTransportFactory.Get(uri); if (transport == null) { throw new ConnectionException(ConnErrorMessages.RemoteInvalidUri); } Stream stream = null; do { try { stream = transport.Connect(uri, warnAboutAuthenticationErrors); } catch (AuthenticationException ex) { if (!warnAboutAuthenticationErrors) { // This should never happen, but if it does, we don't want to keep trying. throw new ConnectionException(ConnErrorMessages.RemoteSslError, ex); } string errText = ex.Message + "\nConnect anyway?"; var dlgRes = MessageBox.Show(errText, null, MessageBoxButtons.YesNo, MessageBoxIcon.Warning); if (dlgRes == DialogResult.Yes) { warnAboutAuthenticationErrors = false; } else { throw new ConnectionException(ConnErrorMessages.RemoteSslError, ex); } } } while (stream == null); bool connected = false; try { string sig = stream.ReadAsciiString(DebuggerSignature.Length); if (sig != DebuggerSignature) { throw new ConnectionException(ConnErrorMessages.RemoteUnsupportedServer); } long ver = stream.ReadInt64(); // If we are talking the same protocol but different version, reply with signature + version before bailing out // so that ptvsd has a chance to gracefully close the socket on its side. stream.Write(DebuggerSignatureBytes); stream.WriteInt64(DebuggerProtocolVersion); if (ver != DebuggerProtocolVersion) { throw new ConnectionException(ConnErrorMessages.RemoteUnsupportedServer); } stream.WriteString(uri.UserInfo); string secretResp = stream.ReadAsciiString(Accepted.Length); if (secretResp != Accepted) { throw new ConnectionException(ConnErrorMessages.RemoteSecretMismatch); } connected = true; return(stream); } catch (IOException ex) { throw new ConnectionException(ConnErrorMessages.RemoteNetworkError, ex); } catch (SocketException ex) { throw new ConnectionException(ConnErrorMessages.RemoteNetworkError, ex); } finally { if (!connected) { if (stream != null) { stream.Close(); } } } }
public override void WriteTo(Stream stream) { stream.WriteString($"Content-Disposition: form-data; name=\"{this.Key}\"\r\n\r\n"); stream.WriteString(this.Value); }
private void Write(Stream CITFile) { CITFile.Write(new byte[4], 0, 4); CITFile.WriteString(Magic); CITFile.Write(new byte[4] { 0xDD, 0xDD, 0xDD, 0xDD }, 0, 4); CITFile.WriteReverse(BitConverter.GetBytes((ushort)Chords.Count), 0, 2); CITFile.WriteReverse(BitConverter.GetBytes((ushort)Scales.Count), 0, 2); int TableOffset = 0x10 + (Chords.Count * 4) + (Scales.Count * 4); List <byte> ChordBytes = new List <byte>(); for (int i = 0; i < Chords.Count; i++) { CITFile.WriteReverse(BitConverter.GetBytes(TableOffset), 0, 4); TableOffset += 0x08; ChordBytes.Add((byte)Chords[i].RootNote); ChordBytes.Add((byte)Chords[i].Triad.Note1); ChordBytes.Add((byte)Chords[i].Triad.Note2); ChordBytes.Add((byte)Chords[i].Triad.Note3); ChordBytes.Add((byte)Chords[i].Extension.Note1); ChordBytes.Add((byte)Chords[i].Extension.Note2); ChordBytes.Add((byte)Chords[i].Extension.Note3); ChordBytes.Add((byte)Chords[i].Extension.Note4); } List <byte> ScaleBytes = new List <byte>(); for (int i = 0; i < Scales.Count; i++) { CITFile.WriteReverse(BitConverter.GetBytes(TableOffset), 0, 4); ScaleBytes.AddRange(BitConverter.GetBytes(TableOffset + 0x08).Reverse()); ScaleBytes.AddRange(BitConverter.GetBytes(TableOffset + 0x08 + 0x0C).Reverse()); ScaleBytes.Add((byte)Scales[i].Item1.Note1); ScaleBytes.Add((byte)Scales[i].Item1.Note2); ScaleBytes.Add((byte)Scales[i].Item1.Note3); ScaleBytes.Add((byte)Scales[i].Item1.Note4); ScaleBytes.Add((byte)Scales[i].Item1.Note5); ScaleBytes.Add((byte)Scales[i].Item1.Note6); ScaleBytes.Add((byte)Scales[i].Item1.Note7); ScaleBytes.Add((byte)Scales[i].Item1.Note8); ScaleBytes.Add((byte)Scales[i].Item1.Note9); ScaleBytes.Add((byte)Scales[i].Item1.Note10); ScaleBytes.Add((byte)Scales[i].Item1.Note11); ScaleBytes.Add((byte)Scales[i].Item1.Note12); ScaleBytes.Add((byte)Scales[i].Item2.Note1); ScaleBytes.Add((byte)Scales[i].Item2.Note2); ScaleBytes.Add((byte)Scales[i].Item2.Note3); ScaleBytes.Add((byte)Scales[i].Item2.Note4); ScaleBytes.Add((byte)Scales[i].Item2.Note5); ScaleBytes.Add((byte)Scales[i].Item2.Note6); ScaleBytes.Add((byte)Scales[i].Item2.Note7); ScaleBytes.Add((byte)Scales[i].Item2.Note8); ScaleBytes.Add((byte)Scales[i].Item2.Note9); ScaleBytes.Add((byte)Scales[i].Item2.Note10); ScaleBytes.Add((byte)Scales[i].Item2.Note11); ScaleBytes.Add((byte)Scales[i].Item2.Note12); TableOffset += 0x20; } CITFile.Write(ChordBytes.ToArray(), 0, ChordBytes.Count); CITFile.Write(ScaleBytes.ToArray(), 0, ScaleBytes.Count); CITFile.Position = 0x08; CITFile.WriteReverse(BitConverter.GetBytes((uint)CITFile.Length), 0, 4); CITFile.Position = CITFile.Length; CITFile.PadTo(32); }
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 WriteTo(Stream s) { s.WriteByte((byte)(IsAlpha ? 1 : 0)); s.WriteString(BinkFileName); }
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); }
public override void Serialize(Stream stream, ISerializable serializable) { stream.WriteString(Version.ToString()); WriteValue(stream, serializable); }
private void HandleRequestHandlers(Stream stream) { string filename = stream.ReadString(); Debug.WriteLine("Exception handlers requested for: " + filename); var statements = GetHandledExceptionRanges(filename); lock (_streamLock) { stream.Write(SetExceptionHandlerInfoCommandBytes); stream.WriteString(filename); stream.WriteInt32(statements.Count); foreach (var t in statements) { stream.WriteInt32(t.Item1); stream.WriteInt32(t.Item2); foreach (var expr in t.Item3) { stream.WriteString(expr); } stream.WriteString("-"); } } }
public static void WriteStringU32(this Stream output, string value, Endian endian) { output.WriteValueS32(value.Length, endian); output.WriteString(value, Encoding.ASCII); }
private static void WriteMultipartFormData(Stream stream, string boundary, IEnumerable<KeyValuePair<string, object>> prm) { const int bufferSize = 81920; prm.ForEach(x => { var valueStream = x.Value as Stream; var valueBytes = x.Value as IEnumerable<byte>; #if !PCL var valueFile = x.Value as FileInfo; #endif var valueString = x.Value.ToString(); #if WP var valueInputStream = x.Value as Windows.Storage.Streams.IInputStream; if(valueInputStream != null) valueStream = valueInputStream.AsStreamForRead(); #endif stream.WriteString("--" + boundary + "\r\n"); if(valueStream != null || valueBytes != null #if !PCL || valueFile != null #endif ) { stream.WriteString("Content-Type: application/octet-stream\r\n"); } stream.WriteString(string.Format(@"Content-Disposition: form-data; name=""{0}""", x.Key)); #if !PCL if(valueFile != null) stream.WriteString(string.Format(@"; filename=""{0}""", valueFile.Name.Replace("\n", "%0A").Replace("\r", "%0D").Replace("\"", "%22"))); else #endif if(valueStream != null || valueBytes != null) stream.WriteString(@"; filename=""file"""); stream.WriteString("\r\n\r\n"); #if !PCL if(valueFile != null) valueStream = valueFile.OpenRead(); #endif if(valueStream != null) { var buffer = new byte[bufferSize]; int count; while((count = valueStream.Read(buffer, 0, bufferSize)) > 0) stream.Write(buffer, 0, count); } else if(valueBytes != null) { var buffer = valueBytes as byte[]; if(buffer != null) stream.Write(buffer, 0, buffer.Length); else { buffer = new byte[bufferSize]; var i = 0; foreach(var b in valueBytes) { buffer[i++] = b; if(i == bufferSize) { stream.Write(buffer, 0, bufferSize); i = 0; } } if(i > 0) stream.Write(buffer, 0, i); } } else stream.WriteString(valueString); #if !PCL if(valueFile != null) valueStream.Close(); #endif stream.WriteString("\r\n"); }); stream.WriteString("--" + boundary + "--"); }
public void Serialize(Stream output, ArchiveSerializeOptions options) { var compress = (options & ArchiveSerializeOptions.Compress) > 0; var basePosition = output.Position; var endian = this._Endian; using (var data = new MemoryStream(12)) { data.WriteValueU32(Signature, Endian.Big); data.WriteValueU32(Version, endian); data.WriteValueU32((uint)this._Platform, Endian.Big); data.Flush(); output.WriteFromMemoryStreamSafe(data, endian); } var headerPosition = output.Position; Archive.FileHeader fileHeader; output.Seek(56, SeekOrigin.Current); fileHeader.ResourceTypeTableOffset = (uint)(output.Position - basePosition); output.WriteValueS32(this._ResourceTypes.Count, endian); foreach (var resourceType in this._ResourceTypes) { resourceType.Write(output, endian); } uint stride = (uint)(Version == 20 ? 38 : 30); uint alignment = (uint)(Version == 20 ? 0x10000 : 0x4000); var blockAlignment = (options & ArchiveSerializeOptions.OneBlock) != ArchiveSerializeOptions.None ? (uint)this._ResourceEntries.Sum(re => stride + (re.Data == null ? 0 : re.Data.Length)) : alignment; fileHeader.BlockTableOffset = (uint)(output.Position - basePosition); fileHeader.ResourceCount = 0; var blockStream = BlockWriterStream.ToStream(output, blockAlignment, endian, compress, ChosenGameType == GamesEnumerator.MafiaI_DE); foreach (var resourceEntry in this._ResourceEntries) { Archive.ResourceHeader resourceHeader; resourceHeader.TypeId = (uint)resourceEntry.TypeId; resourceHeader.Size = stride + (uint)(resourceEntry.Data == null ? 0 : resourceEntry.Data.Length); resourceHeader.Version = resourceEntry.Version; resourceHeader.FileHash = resourceEntry.FileHash; resourceHeader.SlotRamRequired = resourceEntry.SlotRamRequired; resourceHeader.SlotVramRequired = resourceEntry.SlotVramRequired; resourceHeader.OtherRamRequired = resourceEntry.OtherRamRequired; resourceHeader.OtherVramRequired = resourceEntry.OtherVramRequired; using (var data = new MemoryStream()) { resourceHeader.Write(data, endian, Version); data.Flush(); blockStream.WriteFromMemoryStreamSafe(data, endian); } blockStream.WriteBytes(resourceEntry.Data); fileHeader.ResourceCount++; } blockStream.Flush(); blockStream.Finish(); fileHeader.XmlOffset = (uint)(output.Position - basePosition); if (string.IsNullOrEmpty(this._ResourceInfoXml) == false) { output.WriteString(this._ResourceInfoXml, Encoding.ASCII); } fileHeader.SlotRamRequired = this.SlotRamRequired; fileHeader.SlotVramRequired = this.SlotVramRequired; fileHeader.OtherRamRequired = this.OtherRamRequired; fileHeader.OtherVramRequired = this.OtherVramRequired; fileHeader.Flags = 1; fileHeader.Unknown20 = this._Unknown20 ?? new byte[16]; output.Position = headerPosition; using (var data = new MemoryStream()) { fileHeader.Write(data, endian); data.Flush(); output.WriteFromMemoryStreamSafe(data, endian); } }