static public JObject ProtoToJson(byte[] protodata) { Stream stream = new MemoryStream(protodata); ProtoReader s = ProtoReader.Create(stream, stream.Length); Regex regex = new Regex("[\u0000-\u0009\u000e-\u001f]"); JObject jObject = new JObject(); for (; s.Position < protodata.Length;) { int fieldNumber = s.ReadFieldHeader(); string name = "field_" + fieldNumber; switch (s.WireType) { case WireType.Variant: case WireType.Fixed32: case WireType.Fixed64: case WireType.SignedVariant: { string data = "0x" + s.ReadInt64().ToString("X"); jObject.AddEx(name, data); break; } case WireType.String: { byte[] b = s.ReadStringBytes(); string readstr = ""; if (b != null) { readstr = Encoding.UTF8.GetString(b); } if (b != null && regex.IsMatch(readstr)) { try { jObject.AddEx(name, ProtoToJson(b)); } catch { jObject.AddEx(name, readstr); } } else { jObject.AddEx(name, readstr); } break; } case WireType.StartGroup: //@string.Append('\t', depth + 1); @string.Append("Start Group\n"); break; case WireType.EndGroup: //@string.Append('\t', depth + 1); @string.Append("End Group\n"); break; default: break; } } return(jObject); }
/// <summary> /// Parses a TimeSpan from a protobuf stream using the standardized format, google.protobuf.Duration /// </summary> public static TimeSpan ReadDuration(ProtoReader source) { long seconds = 0; int nanos = 0; SubItemToken token = ProtoReader.StartSubItem(source); int fieldNumber; while ((fieldNumber = source.ReadFieldHeader()) > 0) { switch (fieldNumber) { case 1: seconds = source.ReadInt64(); break; case 2: nanos = source.ReadInt32(); break; default: source.SkipField(); break; } } ProtoReader.EndSubItem(token, source); return(FromDurationSeconds(seconds, nanos)); }
public object Read(object value, ProtoReader source) { Helpers.DebugAssert(value == null); // since replaces return(source.ReadInt64()); }
private static ActiveCodeReq Read(ActiveCodeReq acReq, ProtoReader protoReader) { int fieldNum; while ((fieldNum = protoReader.ReadFieldHeader()) > 0) { if (fieldNum != 1) { if (fieldNum != 2) { if (acReq == null) { ActiveCodeReq activeCodeReq = new ActiveCodeReq(); ProtoReader.NoteObject(activeCodeReq, protoReader); acReq = activeCodeReq; } protoReader.AppendExtensionData(acReq); } else { if (acReq == null) { ActiveCodeReq activeCodeReq = new ActiveCodeReq(); ProtoReader.NoteObject(activeCodeReq, protoReader); acReq = activeCodeReq; } string activeCode = protoReader.ReadString(); if (activeCode != null) { acReq.ActiveCode = activeCode; } } } else { if (acReq == null) { ActiveCodeReq activeCodeReq = new ActiveCodeReq(); ProtoReader.NoteObject(activeCodeReq, protoReader); acReq = activeCodeReq; } long accountId = protoReader.ReadInt64(); acReq.AccountId = accountId; } } if (acReq == null) { ActiveCodeReq activeCodeReq = new ActiveCodeReq(); ProtoReader.NoteObject(activeCodeReq, protoReader); acReq = activeCodeReq; } return(acReq); }
public void ShouldSerializeInt64Value() { // Arrange var value = 42L; var dataReader = this.CreateDataReader(value); // Act var reader = new ProtoReader(this.Serialize(dataReader), null, null); // Assert var readerContext = new ProtoReaderContext(reader); readerContext.ReadUntilFieldValue(); Assert.Equal(value, reader.ReadInt64()); }
public static TreeNodeStruct QuickDecodeProto(byte[] bytesIn, string RootKey, TreeNodeStruct NodeStruct) { var NodeList = new List <TreeNode>(); if (!string.IsNullOrEmpty(RootKey)) { NodeList.Add(NodeStruct.parentNode); var NodeCollection = NodeStruct.parentNode.Nodes; TreeNode[] Nodes = NodeCollection.Find(RootKey, true); if (Nodes.Count() > 0) { NodeStruct.parentNode = Nodes[0]; } } ProtoReader reader = null; using (var ms = new MemoryStream(bytesIn)) { reader = ProtoReader.Create(ms, null, null); } long start = reader.Position; int field = reader.ReadFieldHeader(); try { while (field > 0) { long payloadStart = reader.Position; switch (reader.WireType) { case WireType.Varint: { var val = reader.ReadInt64(); var key = "Field #" + reader.FieldNumber.ToString() + " [" + bytesIn[start].ToString("x2").ToUpper() + "] (Varint) " + "Value=" + val.ToString() + " Hex=" + BitConverter.ToString(BitConverter.GetBytes(val).Reverse().ToArray()).Replace("-", " ").Replace("00 00 00", "").Trim().TrimStart('0'); NodeStruct.parentNode.Nodes.Add(new TreeNode(key)); break; } case WireType.Fixed32: { var val = reader.ReadInt32(); var key = "Field #" + reader.FieldNumber.ToString() + " [" + bytesIn[start].ToString("x2").ToUpper() + "] (Fixed32) " + "Value=" + val.ToString() + " Hex=" + BitConverter.ToString(BitConverter.GetBytes(val).Reverse().ToArray()).Replace("-", " ").Replace("00 00 00", "").Trim().TrimStart('0'); NodeStruct.parentNode.Nodes.Add(new TreeNode(key)); break; } case WireType.Fixed64: { var val = reader.ReadInt64(); var key = "Field #" + reader.FieldNumber.ToString() + " [" + bytesIn[start].ToString("x2").ToUpper() + "] (Fixed32) " + "Value=" + val.ToString() + " Hex=" + BitConverter.ToString(BitConverter.GetBytes(val).Reverse().ToArray()).Replace("-", " ").Replace("00 00 00", "").Trim().TrimStart('0'); NodeStruct.parentNode.Nodes.Add(new TreeNode(key)); break; } case WireType.String: { var payloadBytes = ProtoReader.AppendBytes(null, reader); using (var subReader = ReadProto(payloadBytes)) { if (subReader != null) { var RandKey = (new Random()).Next().ToString(); var key = "Field #" + reader.FieldNumber.ToString() + " [" + bytesIn[start].ToString("x2").ToUpper() + "] (String-SubProto) " + "Length=" + payloadBytes.Length.ToString(); NodeStruct.parentNode.Nodes.Add(key + RandKey, key); QuickDecodeProto(payloadBytes, key + RandKey, NodeStruct); } else { var str = Encoding.UTF8.GetString(payloadBytes).Replace("\0", "").Replace("\n", "").Replace("\r\n", "").Replace("\r", "").Replace("\b", "").Replace("\f", "").Replace("\v", ""); var key = "Field #" + reader.FieldNumber.ToString() + " [" + bytesIn[start].ToString("x2").ToUpper() + "] (String) " + "Length=" + payloadBytes.Length.ToString() + " UTF8 =" + ((payloadBytes.Length == 0) ? "\"\"" : str); NodeStruct.parentNode.Nodes.Add(new TreeNode(key)); } } break; } case WireType.None: { var key = "Field #" + reader.FieldNumber.ToString() + " [" + bytesIn[start].ToString("x2").ToUpper() + "] (None) " + "Value=0"; NodeStruct.parentNode.Nodes.Add(new TreeNode(key)); break; } case WireType.StartGroup: { var key = "Field #" + reader.FieldNumber.ToString() + " [" + bytesIn[start].ToString("x2").ToUpper() + "] (StartGroup) " + "Value=StartGroup"; NodeStruct.parentNode.Nodes.Add(new TreeNode(key)); break; } case WireType.EndGroup: { var key = "Field #" + reader.FieldNumber.ToString() + " [" + bytesIn[start].ToString("x2").ToUpper() + "] (EndGroup) " + "Value=EndGroup"; NodeStruct.parentNode.Nodes.Add(new TreeNode(key)); break; } default: { break; } } start = reader.Position; field = reader.ReadFieldHeader(); } } catch (Exception ex) { bytesIn = bytesIn.Skip(1).ToArray(); QuickDecodeProto(bytesIn, "", NodeStruct); } return(NodeStruct); }
private static long ReadTimeSpanTicks(ProtoReader source, out DateTimeKind kind) { kind = DateTimeKind.Unspecified; switch (source.WireType) { case WireType.String: case WireType.StartGroup: SubItemToken token = ProtoReader.StartSubItem(source); int fieldNumber; TimeSpanScale scale = TimeSpanScale.Days; long value = 0; while ((fieldNumber = source.ReadFieldHeader()) > 0) { switch (fieldNumber) { case FieldTimeSpanScale: scale = (TimeSpanScale)source.ReadInt32(); break; case FieldTimeSpanValue: source.Assert(WireType.SignedVariant); value = source.ReadInt64(); break; case FieldTimeSpanKind: kind = (DateTimeKind)source.ReadInt32(); switch (kind) { case DateTimeKind.Unspecified: case DateTimeKind.Utc: case DateTimeKind.Local: break; // fine default: throw new ProtoException("Invalid date/time kind: " + kind.ToString()); } break; default: source.SkipField(); break; } } ProtoReader.EndSubItem(token, source); switch (scale) { case TimeSpanScale.Days: return(value * TimeSpan.TicksPerDay); case TimeSpanScale.Hours: return(value * TimeSpan.TicksPerHour); case TimeSpanScale.Minutes: return(value * TimeSpan.TicksPerMinute); case TimeSpanScale.Seconds: return(value * TimeSpan.TicksPerSecond); case TimeSpanScale.Milliseconds: return(value * TimeSpan.TicksPerMillisecond); case TimeSpanScale.Ticks: return(value); case TimeSpanScale.MinMax: switch (value) { case 1: return(long.MaxValue); case -1: return(long.MinValue); default: throw new ProtoException("Unknown min/max value: " + value.ToString()); } default: throw new ProtoException("Unknown timescale: " + scale.ToString()); } case WireType.Fixed64: return(source.ReadInt64()); default: throw new ProtoException("Unexpected wire-type: " + source.WireType.ToString()); } }
public object Read(object value, ProtoReader source) { Helpers.DebugAssert(value == null); // since replaces return source.ReadInt64(); }
private void ReadColumn() { var token = ProtoReader.StartSubItem(reader); int field; string name = null; var protoDataType = (ProtoDataType)(-1); while ((field = reader.ReadFieldHeader()) != 0) { switch (field) { case 1: name = reader.ReadString(); break; case 2: protoDataType = (ProtoDataType)reader.ReadInt32(); break; default: reader.SkipField(); break; } } switch (protoDataType) { case ProtoDataType.Int: colReaders.Add(() => reader.ReadInt32()); break; case ProtoDataType.Short: colReaders.Add(() => reader.ReadInt16()); break; case ProtoDataType.Decimal: colReaders.Add(() => BclHelpers.ReadDecimal(reader)); break; case ProtoDataType.String: colReaders.Add(() => reader.ReadString()); break; case ProtoDataType.Guid: colReaders.Add(() => BclHelpers.ReadGuid(reader)); break; case ProtoDataType.DateTime: colReaders.Add(() => BclHelpers.ReadDateTime(reader)); break; case ProtoDataType.Bool: colReaders.Add(() => reader.ReadBoolean()); break; case ProtoDataType.Byte: colReaders.Add(() => reader.ReadByte()); break; case ProtoDataType.Char: colReaders.Add(() => (char)reader.ReadInt16()); break; case ProtoDataType.Double: colReaders.Add(() => reader.ReadDouble()); break; case ProtoDataType.Float: colReaders.Add(() => reader.ReadSingle()); break; case ProtoDataType.Long: colReaders.Add(() => reader.ReadInt64()); break; case ProtoDataType.ByteArray: colReaders.Add(() => ProtoReader.AppendBytes(null, reader)); break; case ProtoDataType.CharArray: colReaders.Add(() => reader.ReadString().ToCharArray()); break; case ProtoDataType.TimeSpan: colReaders.Add(() => BclHelpers.ReadTimeSpan(reader)); break; default: throw new NotSupportedException(protoDataType.ToString()); } ProtoReader.EndSubItem(token, reader); dataTable.Columns.Add(name, ConvertProtoDataType.ToClrType(protoDataType)); }
/// <summary> /// This is the more "complete" version of Deserialize, which handles single instances of mapped types. /// The value is read as a complete field, including field-header and (for sub-objects) a /// length-prefix..kmc /// /// In addition to that, this provides support for: /// - basic values; individual int / string / Guid / etc /// - IList sets of any type handled by TryDeserializeAuxiliaryType /// </summary> private bool TryDeserializeAuxiliaryType(ProtoReader reader, DataFormat format, int tag, Type type, ref object value, bool skipOtherFields, bool asListItem) { if (type == null) throw new ArgumentNullException("type"); Type itemType = null; TypeCode typecode = Type.GetTypeCode(type); int modelKey; WireType wiretype = GetWireType(typecode, format, ref type, out modelKey); bool found = false; if (wiretype == WireType.None) { itemType = GetListItemType(type); if (itemType != null) { return TryDeserializeList(reader, format, tag, type, itemType, ref value); } // otherwise, not a happy bunny... ThrowUnexpectedType(type); } // to treat correctly, should read all values while (true) { // for convenience (re complex exit conditions), additional exit test here: // if we've got the value, are only looking for one, and we aren't a list - then exit if (found && asListItem) break; // read the next item int fieldNumber = reader.ReadFieldHeader(); if (fieldNumber <= 0) break; if (fieldNumber != tag) { if (skipOtherFields) { reader.SkipField(); continue; } throw ProtoReader.AddErrorData(new InvalidOperationException( "Expected field " + tag + ", but found " + fieldNumber), reader); } found = true; reader.Hint(wiretype); // handle signed data etc if (modelKey >= 0) { switch (wiretype) { case WireType.String: case WireType.StartGroup: SubItemToken token = ProtoReader.StartSubItem(reader); value = Deserialize(modelKey, value, reader); ProtoReader.EndSubItem(token, reader); continue; default: value = Deserialize(modelKey, value, reader); continue; } } switch (typecode) { case TypeCode.Int16: value = reader.ReadInt16(); continue; case TypeCode.Int32: value = reader.ReadInt32(); continue; case TypeCode.Int64: value = reader.ReadInt64(); continue; case TypeCode.UInt16: value = reader.ReadUInt16(); continue; case TypeCode.UInt32: value = reader.ReadUInt32(); continue; case TypeCode.UInt64: value = reader.ReadUInt64(); continue; case TypeCode.Boolean: value = reader.ReadBoolean(); continue; case TypeCode.SByte: value = reader.ReadSByte(); continue; case TypeCode.Byte: value = reader.ReadByte(); continue; case TypeCode.Char: value = (char)reader.ReadUInt16(); continue; case TypeCode.Double: value = reader.ReadDouble(); continue; case TypeCode.Single: value = reader.ReadSingle(); continue; case TypeCode.DateTime: value = BclHelpers.ReadDateTime(reader); continue; case TypeCode.Decimal: BclHelpers.ReadDecimal(reader); continue; case TypeCode.String: value = reader.ReadString(); continue; } if (type == typeof(byte[])) { value = ProtoReader.AppendBytes((byte[])value, reader); continue; } if (type == typeof(TimeSpan)) { value = BclHelpers.ReadTimeSpan(reader); continue; } if (type == typeof(Guid)) { value = BclHelpers.ReadGuid(reader); continue; } if (type == typeof(Uri)) { value = new Uri(reader.ReadString()); continue; } } if (!found && !asListItem) { value = Activator.CreateInstance(type); } return found; }
internal bool TryDeserializeAuxiliaryType(ProtoReader reader, DataFormat format, int tag, Type type, ref object value, bool skipOtherFields, bool asListItem, bool autoCreate, bool insideList) { if (type == null) { throw new ArgumentNullException("type"); } ProtoTypeCode typecode = Helpers.GetTypeCode(type); int modelKey; WireType wiretype = this.GetWireType(typecode, format, ref type, out modelKey); bool found = false; if (wiretype == WireType.None) { Type itemType = TypeModel.GetListItemType(this, type); if (itemType == null && type.IsArray && type.GetArrayRank() == 1 && type != typeof(byte[])) { itemType = type.GetElementType(); } if (itemType != null) { if (insideList) { throw TypeModel.CreateNestedListsNotSupported(); } found = this.TryDeserializeList(this, reader, format, tag, type, itemType, ref value); if (!found && autoCreate) { value = TypeModel.CreateListInstance(type, itemType); } return(found); } else { TypeModel.ThrowUnexpectedType(type); } } while (!found || !asListItem) { int fieldNumber = reader.ReadFieldHeader(); if (fieldNumber <= 0) { break; } if (fieldNumber != tag) { if (!skipOtherFields) { throw ProtoReader.AddErrorData(new InvalidOperationException("Expected field " + tag.ToString() + ", but found " + fieldNumber.ToString()), reader); } reader.SkipField(); } else { found = true; reader.Hint(wiretype); if (modelKey >= 0) { switch (wiretype) { case WireType.String: case WireType.StartGroup: { SubItemToken token = ProtoReader.StartSubItem(reader); value = this.Deserialize(modelKey, value, reader); ProtoReader.EndSubItem(token, reader); break; } default: value = this.Deserialize(modelKey, value, reader); break; } } else { ProtoTypeCode protoTypeCode = typecode; switch (protoTypeCode) { case ProtoTypeCode.Boolean: value = reader.ReadBoolean(); break; case ProtoTypeCode.Char: value = (char)reader.ReadUInt16(); break; case ProtoTypeCode.SByte: value = reader.ReadSByte(); break; case ProtoTypeCode.Byte: value = reader.ReadByte(); break; case ProtoTypeCode.Int16: value = reader.ReadInt16(); break; case ProtoTypeCode.UInt16: value = reader.ReadUInt16(); break; case ProtoTypeCode.Int32: value = reader.ReadInt32(); break; case ProtoTypeCode.UInt32: value = reader.ReadUInt32(); break; case ProtoTypeCode.Int64: value = reader.ReadInt64(); break; case ProtoTypeCode.UInt64: value = reader.ReadUInt64(); break; case ProtoTypeCode.Single: value = reader.ReadSingle(); break; case ProtoTypeCode.Double: value = reader.ReadDouble(); break; case ProtoTypeCode.Decimal: value = BclHelpers.ReadDecimal(reader); break; case ProtoTypeCode.DateTime: value = BclHelpers.ReadDateTime(reader); break; case (ProtoTypeCode)17: break; case ProtoTypeCode.String: value = reader.ReadString(); break; default: switch (protoTypeCode) { case ProtoTypeCode.TimeSpan: value = BclHelpers.ReadTimeSpan(reader); break; case ProtoTypeCode.ByteArray: value = ProtoReader.AppendBytes((byte[])value, reader); break; case ProtoTypeCode.Guid: value = BclHelpers.ReadGuid(reader); break; case ProtoTypeCode.Uri: value = new Uri(reader.ReadString()); break; } break; } } } } if (!found && !asListItem && autoCreate && type != typeof(string)) { value = Activator.CreateInstance(type); } return(found); }
/// <summary> /// This is the more "complete" version of Deserialize, which handles single instances of mapped types. /// The value is read as a complete field, including field-header and (for sub-objects) a /// length-prefix..kmc /// /// In addition to that, this provides support for: /// - basic values; individual int / string / Guid / etc /// - IList sets of any type handled by TryDeserializeAuxiliaryType /// </summary> private bool TryDeserializeAuxiliaryType(ProtoReader reader, DataFormat format, int tag, Type type, ref object value, bool skipOtherFields, bool asListItem) { if (type == null) { throw new ArgumentNullException("type"); } Type itemType = null; TypeCode typecode = Type.GetTypeCode(type); int modelKey; WireType wiretype = GetWireType(typecode, format, ref type, out modelKey); bool found = false; if (wiretype == WireType.None) { itemType = GetListItemType(type); if (itemType != null) { return(TryDeserializeList(reader, format, tag, type, itemType, ref value)); } // otherwise, not a happy bunny... ThrowUnexpectedType(type); } // to treat correctly, should read all values while (true) { // for convenience (re complex exit conditions), additional exit test here: // if we've got the value, are only looking for one, and we aren't a list - then exit if (found && asListItem) { break; } // read the next item int fieldNumber = reader.ReadFieldHeader(); if (fieldNumber <= 0) { break; } if (fieldNumber != tag) { if (skipOtherFields) { reader.SkipField(); continue; } throw ProtoReader.AddErrorData(new InvalidOperationException( "Expected field " + tag + ", but found " + fieldNumber), reader); } found = true; reader.Hint(wiretype); // handle signed data etc if (modelKey >= 0) { switch (wiretype) { case WireType.String: case WireType.StartGroup: SubItemToken token = ProtoReader.StartSubItem(reader); value = Deserialize(modelKey, value, reader); ProtoReader.EndSubItem(token, reader); continue; default: value = Deserialize(modelKey, value, reader); continue; } } switch (typecode) { case TypeCode.Int16: value = reader.ReadInt16(); continue; case TypeCode.Int32: value = reader.ReadInt32(); continue; case TypeCode.Int64: value = reader.ReadInt64(); continue; case TypeCode.UInt16: value = reader.ReadUInt16(); continue; case TypeCode.UInt32: value = reader.ReadUInt32(); continue; case TypeCode.UInt64: value = reader.ReadUInt64(); continue; case TypeCode.Boolean: value = reader.ReadBoolean(); continue; case TypeCode.SByte: value = reader.ReadSByte(); continue; case TypeCode.Byte: value = reader.ReadByte(); continue; case TypeCode.Char: value = (char)reader.ReadUInt16(); continue; case TypeCode.Double: value = reader.ReadDouble(); continue; case TypeCode.Single: value = reader.ReadSingle(); continue; case TypeCode.DateTime: value = BclHelpers.ReadDateTime(reader); continue; case TypeCode.Decimal: BclHelpers.ReadDecimal(reader); continue; case TypeCode.String: value = reader.ReadString(); continue; } if (type == typeof(byte[])) { value = ProtoReader.AppendBytes((byte[])value, reader); continue; } if (type == typeof(TimeSpan)) { value = BclHelpers.ReadTimeSpan(reader); continue; } if (type == typeof(Guid)) { value = BclHelpers.ReadGuid(reader); continue; } if (type == typeof(Uri)) { value = new Uri(reader.ReadString()); continue; } } if (!found && !asListItem) { value = Activator.CreateInstance(type); } return(found); }
private void WriteFieldsToTable(IWritableReactiveTable table, Dictionary <int, string> fieldIdsToColumns, ProtoReader reader, int rowId) { int fieldId; while ((fieldId = reader.ReadFieldHeader()) != 0) { var columnId = fieldIdsToColumns[fieldId]; var column = table.GetColumnByName(columnId); if (column.Type == typeof(int)) { table.SetValue(columnId, rowId, reader.ReadInt32()); } else if (column.Type == typeof(short)) { table.SetValue(columnId, rowId, reader.ReadInt16()); } else if (column.Type == typeof(string)) { var value = reader.ReadString(); table.SetValue(columnId, rowId, value); } else if (column.Type == typeof(bool)) { table.SetValue(columnId, rowId, reader.ReadBoolean()); } else if (column.Type == typeof(double)) { table.SetValue(columnId, rowId, reader.ReadDouble()); } else if (column.Type == typeof(long)) { table.SetValue(columnId, rowId, reader.ReadInt64()); } else if (column.Type == typeof(decimal)) { table.SetValue(columnId, rowId, BclHelpers.ReadDecimal(reader)); } else if (column.Type == typeof(DateTime)) { table.SetValue(columnId, rowId, BclHelpers.ReadDateTime(reader)); } else if (column.Type == typeof(TimeSpan)) { table.SetValue(columnId, rowId, BclHelpers.ReadTimeSpan(reader)); } else if (column.Type == typeof(Guid)) { table.SetValue(columnId, rowId, BclHelpers.ReadGuid(reader)); } else if (column.Type == typeof(byte)) { table.SetValue(columnId, rowId, reader.ReadByte()); } else if (column.Type == typeof(char)) { table.SetValue(columnId, rowId, (char)reader.ReadInt16()); } else if (column.Type == typeof(float)) { table.SetValue(columnId, rowId, reader.ReadSingle()); } } }
public static DataTable ProtoRead(Stream stream) { DataTable table = new DataTable(); object[] array = null; Func <object> item = null; Func <object> func2 = null; Func <object> func3 = null; Func <object> func4 = null; Func <object> func5 = null; Func <object> func6 = null; Func <object> func7 = null; Func <object> func8 = null; Func <object> func9 = null; Func <object> func10 = null; Func <object> func11 = null; using (ProtoReader reader = new ProtoReader(stream, null, null)) { int num; List <Func <object> > list = new List <Func <object> >(); while ((num = reader.ReadFieldHeader()) != 0) { SubItemToken token; string str; string str2; MappedType type; Type type2; switch (num) { case 1: { table.TableName = reader.ReadString(); continue; } case 2: str = null; str2 = string.Empty; type = ~MappedType.Boolean; token = ProtoReader.StartSubItem(reader); goto Label_00F1; case 3: if (array != null) { goto Label_0382; } array = new object[table.Columns.Count]; goto Label_038C; default: goto Label_03F3; } Label_009B: switch (num) { case 1: str = reader.ReadString(); break; case 2: type = (MappedType)reader.ReadInt32(); break; case 3: str2 = reader.ReadString(); break; default: reader.SkipField(); break; } Label_00F1: if ((num = reader.ReadFieldHeader()) != 0) { goto Label_009B; } switch (type) { case MappedType.Boolean: type2 = typeof(bool); if (item == null) { item = () => reader.ReadBoolean(); } list.Add(item); break; case MappedType.Byte: type2 = typeof(byte[]); if (func2 == null) { func2 = () => ReadBytes(reader); } list.Add(func2); break; case MappedType.Double: type2 = typeof(double); if (func3 == null) { func3 = () => reader.ReadDouble(); } list.Add(func3); break; case MappedType.Int16: type2 = typeof(short); if (func6 == null) { func6 = () => reader.ReadInt16(); } list.Add(func6); break; case MappedType.Int32: type2 = typeof(int); if (func5 == null) { func5 = () => reader.ReadInt32(); } list.Add(func5); break; case MappedType.Int64: type2 = typeof(long); if (func4 == null) { func4 = () => reader.ReadInt64(); } list.Add(func4); break; case MappedType.String: type2 = typeof(string); if (func8 == null) { func8 = () => reader.ReadString(); } list.Add(func8); break; case MappedType.Decimal: type2 = typeof(decimal); if (func7 == null) { func7 = () => BclHelpers.ReadDecimal(reader); } list.Add(func7); break; case MappedType.Guid: type2 = typeof(Guid); if (func9 == null) { func9 = () => BclHelpers.ReadGuid(reader); } list.Add(func9); break; case MappedType.DateTime: type2 = typeof(DateTime); if (func10 == null) { func10 = () => BclHelpers.ReadDateTime(reader); } list.Add(func10); break; case MappedType.TimeSpan: type2 = typeof(TimeSpan); if (func11 == null) { func11 = () => BclHelpers.ReadTimeSpan(reader); } list.Add(func11); break; default: throw new NotSupportedException(type.ToString()); } ProtoReader.EndSubItem(token, reader); table.Columns.Add(str, type2); if (!string.IsNullOrEmpty(str2)) { table.Columns[str].Caption = str2; } array = null; continue; Label_0382: Array.Clear(array, 0, array.Length); Label_038C: token = ProtoReader.StartSubItem(reader); while ((num = reader.ReadFieldHeader()) != 0) { if (num > array.Length) { reader.SkipField(); } else { int index = num - 1; array[index] = list[index](); } } ProtoReader.EndSubItem(token, reader); table.Rows.Add(array); continue; Label_03F3: reader.SkipField(); } } return(table); }
public object Read(ProtoReader source, ref ProtoReader.State state, object value) { Helpers.DebugAssert(value == null); // since replaces return(source.ReadInt64(ref state)); }
object BuildBody(uint realEMsg, Stream str) { EMsg eMsg = MsgUtil.GetMsg(realEMsg); if (eMsg == EMsg.ClientLogonGameServer) { eMsg = EMsg.ClientLogon; // temp hack for now } else if (eMsg == EMsg.ClientGamesPlayedWithDataBlob) { eMsg = EMsg.ClientGamesPlayed; } var protomsgType = typeof(CMClient).Assembly.GetTypes().ToList().Find(type => { if (type.GetInterfaces().ToList().Find(inter => inter == typeof(IExtensible)) == null) { return(false); } if (type.Name.EndsWith(eMsg.ToString())) { return(true); } return(false); }); if (protomsgType != null) { return(RuntimeTypeModel.Default.Deserialize(str, null, protomsgType)); } // lets first find the type by checking all EMsgs we have var msgType = typeof(CMClient).Assembly.GetTypes().ToList().Find(type => { if (type.GetInterfaces().ToList().Find(inter => inter == typeof(ISteamSerializableMessage)) == null) { return(false); } var gcMsg = Activator.CreateInstance(type) as ISteamSerializableMessage; return(gcMsg.GetEMsg() == eMsg); }); string eMsgName = eMsg.ToString(); eMsgName = eMsgName.Replace("Econ", "").Replace("AM", ""); // check name if (msgType == null) { msgType = GetSteamKitType(string.Format("SteamKit2.Msg{0}", eMsgName)); } if (msgType != null) { var body = Activator.CreateInstance(msgType) as ISteamSerializableMessage; body.Deserialize(str); return(body); } msgType = GetSteamKitType(string.Format("SteamKit2.CMsg{0}", eMsgName)); if (msgType != null) { return(Deserialize(msgType, str)); } if (eMsg == EMsg.ClientToGC || eMsg == EMsg.ClientFromGC) { return(Serializer.Deserialize <CMsgGCClient>(str)); } var gcMsgName = BuildEMsg(realEMsg); var gcMsgPossibleTypePrefixes = new[] { "SteamKit2.GC.Internal.CMsg", "SteamKit2.GC.Dota.Internal.CMsg", "SteamKit2.GC.CSGO.Internal.CMsg", "SteamKit2.GC.TF.Internal.CMsg", }; var typeMsgName = gcMsgName .Replace("GC", string.Empty) .Replace("k_", string.Empty) .Replace("ESOMsg", string.Empty) .TrimStart('_') .Replace("EMsg", string.Empty); if (typeMsgName == "Create" || typeMsgName == "Destroy" || typeMsgName == "Update") { typeMsgName = "SingleObject"; } else if (typeMsgName == "Multiple") { typeMsgName = "MultipleObjects"; } var possibleTypes = from type in typeof(CMClient).Assembly.GetTypes() from typePrefix in gcMsgPossibleTypePrefixes where type.GetInterfaces().Contains(typeof(IExtensible)) where type.FullName.StartsWith(typePrefix) && type.FullName.EndsWith(typeMsgName) select type; foreach (var type in possibleTypes) { var streamPos = str.Position; try { return(Deserialize(type, str)); } catch (Exception) { str.Position = streamPos; } } if (!MsgUtil.IsProtoBuf(realEMsg)) { return(false); } // try reading it as a protobuf using (ProtoReader reader = new ProtoReader(str, null, null)) { var fields = new Dictionary <int, List <object> >(); while (true) { int field = reader.ReadFieldHeader(); if (field == 0) { break; } object fieldValue = null; switch (reader.WireType) { case WireType.Variant: case WireType.Fixed32: case WireType.Fixed64: case WireType.SignedVariant: { try { fieldValue = reader.ReadInt64(); } catch (Exception) { fieldValue = "Unable to read Variant (debugme)"; } break; } case WireType.String: { try { fieldValue = reader.ReadString(); } catch (Exception) { fieldValue = "Unable to read String (debugme)"; } break; } default: { fieldValue = string.Format("{0} is not implemented", reader.WireType); break; } } if (!fields.ContainsKey(field)) { fields[field] = new List <object>(); } fields[field].Add(fieldValue); } if (fields.Count > 0) { return(fields); } } return(null); }
object BuildBody(uint realEMsg, Stream str, uint gcAppid = 0) { EMsg eMsg = MsgUtil.GetMsg(realEMsg); if (eMsg == EMsg.ClientLogonGameServer) { eMsg = EMsg.ClientLogon; // temp hack for now } else if (eMsg == EMsg.ClientGamesPlayedWithDataBlob) { eMsg = EMsg.ClientGamesPlayed; } var protomsgType = GetMessageBodyType(realEMsg); if (protomsgType != null) { return(RuntimeTypeModel.Default.Deserialize(str, null, protomsgType)); } // lets first find the type by checking all EMsgs we have var msgType = typeof(CMClient).Assembly.GetTypes().ToList().Find(type => { if (type.GetInterfaces().ToList().Find(inter => inter == typeof(ISteamSerializableMessage)) == null) { return(false); } var gcMsg = Activator.CreateInstance(type) as ISteamSerializableMessage; return(gcMsg.GetEMsg() == eMsg); }); string eMsgName = eMsg.ToString(); eMsgName = eMsgName.Replace("Econ", "").Replace("AM", ""); // check name if (msgType == null) { msgType = GetSteamKitType(string.Format("SteamKit2.Msg{0}", eMsgName)); } if (msgType != null) { var body = Activator.CreateInstance(msgType) as ISteamSerializableMessage; body.Deserialize(str); return(body); } msgType = GetSteamKitType(string.Format("SteamKit2.CMsg{0}", eMsgName)); if (msgType != null) { return(Deserialize(msgType, str)); } if (eMsg == EMsg.ClientToGC || eMsg == EMsg.ClientFromGC) { return(Serializer.Deserialize <CMsgGCClient>(str)); } foreach (var type in GetGCMessageBodyTypeCandidates(realEMsg, gcAppid)) { var streamPos = str.Position; try { return(Deserialize(type, str)); } catch (Exception) { str.Position = streamPos; } } if (!MsgUtil.IsProtoBuf(realEMsg)) { return(null); } // try reading it as a protobuf using (ProtoReader reader = new ProtoReader(str, null, null)) { var fields = new Dictionary <int, List <object> >(); while (true) { int field = reader.ReadFieldHeader(); if (field == 0) { break; } object fieldValue = null; switch (reader.WireType) { case WireType.Variant: case WireType.Fixed32: case WireType.Fixed64: case WireType.SignedVariant: { try { fieldValue = reader.ReadInt64(); } catch (Exception) { fieldValue = "Unable to read Variant (debugme)"; } break; } case WireType.String: { try { fieldValue = reader.ReadString(); } catch (Exception) { fieldValue = "Unable to read String (debugme)"; } break; } default: { fieldValue = string.Format("{0} is not implemented", reader.WireType); break; } } if (!fields.ContainsKey(field)) { fields[field] = new List <object>(); } fields[field].Add(fieldValue); } if (fields.Count > 0) { return(fields); } } return(null); }
internal bool TryDeserializeAuxiliaryType(ProtoReader reader, DataFormat format, int tag, Type type, ref object value, bool skipOtherFields, bool asListItem, bool autoCreate, bool insideList) { if (type == null) { throw new ArgumentNullException("type"); } Type type2 = null; ProtoTypeCode typeCode = Helpers.GetTypeCode(type); int modelKey; WireType wireType = GetWireType(typeCode, format, ref type, out modelKey); bool flag = false; if (wireType == WireType.None) { type2 = GetListItemType(this, type); if (type2 == null && type.IsArray && type.GetArrayRank() == 1 && type != typeof(byte[])) { type2 = type.GetElementType(); } if (type2 != null) { if (insideList) { throw CreateNestedListsNotSupported(); } flag = TryDeserializeList(this, reader, format, tag, type, type2, ref value); if (!flag && autoCreate) { value = CreateListInstance(type, type2); } return(flag); } ThrowUnexpectedType(type); } while (!flag || !asListItem) { int num = reader.ReadFieldHeader(); if (num <= 0) { break; } if (num != tag) { if (skipOtherFields) { reader.SkipField(); continue; } throw ProtoReader.AddErrorData(new InvalidOperationException("Expected field " + tag.ToString() + ", but found " + num.ToString()), reader); } flag = true; reader.Hint(wireType); if (modelKey >= 0) { if ((uint)(wireType - 2) <= 1u) { SubItemToken token = ProtoReader.StartSubItem(reader); value = Deserialize(modelKey, value, reader); ProtoReader.EndSubItem(token, reader); } else { value = Deserialize(modelKey, value, reader); } continue; } switch (typeCode) { case ProtoTypeCode.Int16: value = reader.ReadInt16(); break; case ProtoTypeCode.Int32: value = reader.ReadInt32(); break; case ProtoTypeCode.Int64: value = reader.ReadInt64(); break; case ProtoTypeCode.UInt16: value = reader.ReadUInt16(); break; case ProtoTypeCode.UInt32: value = reader.ReadUInt32(); break; case ProtoTypeCode.UInt64: value = reader.ReadUInt64(); break; case ProtoTypeCode.Boolean: value = reader.ReadBoolean(); break; case ProtoTypeCode.SByte: value = reader.ReadSByte(); break; case ProtoTypeCode.Byte: value = reader.ReadByte(); break; case ProtoTypeCode.Char: value = (char)reader.ReadUInt16(); break; case ProtoTypeCode.Double: value = reader.ReadDouble(); break; case ProtoTypeCode.Single: value = reader.ReadSingle(); break; case ProtoTypeCode.DateTime: value = BclHelpers.ReadDateTime(reader); break; case ProtoTypeCode.Decimal: value = BclHelpers.ReadDecimal(reader); break; case ProtoTypeCode.String: value = reader.ReadString(); break; case ProtoTypeCode.ByteArray: value = ProtoReader.AppendBytes((byte[])value, reader); break; case ProtoTypeCode.TimeSpan: value = BclHelpers.ReadTimeSpan(reader); break; case ProtoTypeCode.Guid: value = BclHelpers.ReadGuid(reader); break; case ProtoTypeCode.Uri: value = new Uri(reader.ReadString()); break; } } if (((!flag && !asListItem) & autoCreate) && type != typeof(string)) { value = Activator.CreateInstance(type); } return(flag); }
public static Dictionary <int, List <object> > ReadProtobuf(Stream stream) { // try reading it as a protobuf using (var reader = new ProtoReader(stream, null, null)) { var fields = new Dictionary <int, List <object> >(); while (true) { int field = reader.ReadFieldHeader(); if (field == 0) { break; } object fieldValue = null; switch (reader.WireType) { case WireType.Variant: case WireType.Fixed32: case WireType.Fixed64: case WireType.SignedVariant: { try { fieldValue = reader.ReadInt64(); } catch (Exception) { fieldValue = "Unable to read Variant (debugme)"; } break; } case WireType.String: { try { fieldValue = reader.ReadString(); } catch (Exception) { fieldValue = "Unable to read String (debugme)"; } break; } default: { fieldValue = string.Format("{0} is not implemented", reader.WireType); break; } } if (!fields.ContainsKey(field)) { fields[field] = new List <object>(); } fields[field].Add(fieldValue); } if (fields.Count > 0) { return(fields); } } return(null); }
public object Read(object value, ProtoReader source) { return source.ReadInt64(); }
/// <summary> /// 解析protobuf数据 /// </summary> /// <param name="reader"></param> /// <see cref="https://developers.google.com/protocol-buffers/docs/encoding"/> /// <returns>全部成功返回true,部分失败或全失败返回false,这时候可以通过LastError获取失败信息</returns> public bool Parse(ProtoReader reader) { buildIndex(); lastError.Clear(); try { int field_id; SubItemToken token; while ((field_id = reader.ReadFieldHeader()) != 0) { WireType pb_type = reader.WireType; FieldDescriptorProto desc; if (false == msgDescriptor.FieldIdIndex.TryGetValue(field_id, out desc)) { // unknown field skipped reader.SkipField(); continue; } // 类型校验 try { switch (desc.type) { case FieldDescriptorProto.Type.TYPE_DOUBLE: insertField(desc, reader.ReadDouble()); break; case FieldDescriptorProto.Type.TYPE_FLOAT: insertField(desc, reader.ReadSingle()); break; case FieldDescriptorProto.Type.TYPE_INT64: case FieldDescriptorProto.Type.TYPE_SINT64: case FieldDescriptorProto.Type.TYPE_SFIXED64: insertField(desc, reader.ReadInt64()); break; case FieldDescriptorProto.Type.TYPE_UINT64: case FieldDescriptorProto.Type.TYPE_FIXED64: insertField(desc, reader.ReadUInt64()); break; case FieldDescriptorProto.Type.TYPE_INT32: case FieldDescriptorProto.Type.TYPE_SINT32: case FieldDescriptorProto.Type.TYPE_SFIXED32: insertField(desc, reader.ReadInt32()); break; case FieldDescriptorProto.Type.TYPE_BOOL: insertField(desc, reader.ReadBoolean()); break; case FieldDescriptorProto.Type.TYPE_STRING: insertField(desc, reader.ReadString()); break; //case FieldDescriptorProto.Type.TYPE_GROUP: // deprecated // break; case FieldDescriptorProto.Type.TYPE_MESSAGE: token = ProtoReader.StartSubItem(reader); try { DynamicMessage sub_msg = CreateMessage(desc); if (null == sub_msg) { lastError.AddLast(string.Format("{0}.{1}.{2} => invalid message path {3}", msgDescriptor.Package, msgDescriptor.Protocol.name, desc.name, pickMsgName(desc))); break; } if (false == sub_msg.Parse(reader)) { lastError.AddLast(sub_msg.LastError); } else { insertField(desc, sub_msg); } } catch (Exception e) { lastError.AddLast(string.Format("{0}.{1}.{2} => {3}", msgDescriptor.Package, msgDescriptor.Protocol.name, desc.name, e.Message)); } ProtoReader.EndSubItem(token, reader); break; case FieldDescriptorProto.Type.TYPE_BYTES: insertField(desc, ProtoReader.AppendBytes(null, reader)); break; case FieldDescriptorProto.Type.TYPE_FIXED32: case FieldDescriptorProto.Type.TYPE_UINT32: insertField(desc, reader.ReadUInt32()); break; case FieldDescriptorProto.Type.TYPE_ENUM: insertField(desc, reader.ReadInt32()); break; default: // unsupported field lastError.AddLast(string.Format("field type {0} in {1}.{2}.{3} unsupported", desc.type.ToString(), msgDescriptor.Package, msgDescriptor.Protocol.name, desc.name)); reader.SkipField(); break; } } catch (Exception e) { lastError.AddLast(string.Format("{0}.{1}.{2} {3}", msgDescriptor.Package, msgDescriptor.Protocol.name, desc.name, e.ToString())); reader.SkipField(); } } } catch (Exception e) { lastError.AddLast(e.Message); } return(0 == lastError.Count); }
// Token: 0x06003588 RID: 13704 RVA: 0x00134AAF File Offset: 0x00132EAF public object Read(object value, ProtoReader source) { return(source.ReadInt64()); }
object ReadField(ProtoReader reader, Type memberT, string sClassName, CLS_Environment environment) { if (memberT == typeof(int)) { return(reader.ReadInt32()); } else if (memberT == typeof(uint)) { return(reader.ReadUInt32()); } else if (memberT == typeof(bool)) { return(reader.ReadBoolean()); } else if (memberT == typeof(byte)) { return(reader.ReadByte()); } else if (memberT == typeof(sbyte)) { return(reader.ReadSByte()); } else if (memberT == typeof(float)) { return(reader.ReadSingle()); } else if (memberT == typeof(double)) { return(reader.ReadDouble()); } else if (memberT == typeof(short)) { return(reader.ReadInt16()); } else if (memberT == typeof(ushort)) { return(reader.ReadUInt16()); } else if (memberT == typeof(long)) { return(reader.ReadInt64()); } else if (memberT == typeof(ulong)) { return(reader.ReadUInt64()); } else if (memberT == typeof(string)) { return(reader.ReadString()); } else if (memberT == typeof(byte[])) { return(ProtoReader.AppendBytes(null, reader)); } else if (memberT == typeof(SInstance)) { SubItemToken st = ProtoReader.StartSubItem(reader); CLS_Type_Class sClass = environment.GetTypeByKeywordQuiet(sClassName) as CLS_Type_Class; if (!sClass.compiled) { RuntimeCompilerClass(sClassName); } CLS_Content content = CLS_Content.NewContent(environment); CLS_Content.Value retVal = sClass.function.New(content, m_emptyParams); CLS_Content.PoolContent(content); SInstance sInstance = (SInstance)retVal.value; ReadSInstance(reader, sInstance, environment); ProtoReader.EndSubItem(st, reader); return(sInstance); } else { throw new NotImplementedException("未实现类型: " + memberT); } }