public void CompareWithWithoutImplicitDefaults() { var with = RuntimeTypeModel.Create(); var without = RuntimeTypeModel.Create(); without.AutoCompile = with.AutoCompile = false; with.UseImplicitZeroDefaults = true; without.UseImplicitZeroDefaults = false; Test(with, without, "Runtime"); with.CompileInPlace(); without.CompileInPlace(); Test(with, without, "CompileInPlace"); Test(with.Compile(), without.Compile(), "Compile"); }
public void TestTuple() { var model = RuntimeTypeModel.Create(); model.Add(typeof(Foo), true); string schema = model.GetSchema(typeof(Foo)); Assert.Equal(@"syntax = ""proto2""; package Examples.Issues; message Foo { map<int32,string> Lookup = 1; } ", schema); }
public void ShouldWorkWithAutoLoadDisabledRuntime() { var orig = new TypeWithDictionary { Data = new Dictionary <string, decimal> { { "abc", 123.45M } } }; var model = RuntimeTypeModel.Create(); model.AutoAddMissingTypes = false; model.Add(typeof(TypeWithDictionary), true); var clone = (TypeWithDictionary)model.DeepClone(orig); Assert.Single(clone.Data); Assert.Equal(123.45M, clone.Data["abc"]); }
public void ProtobufNet_DoesSupportNakedEnumerables() { var ser = RuntimeTypeModel.Create(); using (var ms = new MemoryStream()) { ser.Serialize(ms, new FooEnumerable { Bars = new[] { new Bar { } } }); ms.Position = 0; var clone = (FooEnumerable)ser.Deserialize(ms, null, typeof(FooEnumerable)); Assert.NotNull(clone.Bars); Assert.Single(clone.Bars); } }
public void CanSwapDefaultModel() { var oldModel = RuntimeTypeModel.Default; try { var newModel = RuntimeTypeModel.Create(); newModel.MakeDefault(); Assert.Same(newModel, RuntimeTypeModel.Default); } finally { oldModel.MakeDefault(); } }
public void TestPrimitiveCanSerialize() { var model = RuntimeTypeModel.Create(); Assert.True(model.CanSerialize(typeof(int))); Assert.True(model.CanSerialize(typeof(int?))); Assert.True(model.CanSerialize(typeof(short))); Assert.True(model.CanSerialize(typeof(short?))); Assert.True(model.CanSerialize(typeof(byte[]))); Assert.True(model.CanSerialize(typeof(string))); Assert.True(model.CanSerialize(typeof(DateTime))); Assert.True(model.CanSerialize(typeof(DateTime?))); #if !COREFX if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { AvoidJit(model);
public void EmitModelWithEverything() { var model = RuntimeTypeModel.Create(); MetaType meta = model.Add(typeof(TypeWithLists), false); meta.Add(1, "ListString"); meta.Add(2, "ListInt32"); meta.Add(3, "IListStringTyped"); meta.Add(4, "IListInt32Typed"); model.CompileInPlace(); model.Compile("EmitModelWithEverything", "EmitModelWithEverything.dll"); PEVerify.Verify("EmitModelWithEverything.dll"); }
private static void GetUInt32ofPB(int order, uint value) { var data1 = FromUint32(19.1D, -1, 7); Console.WriteLine(BitConverter.ToString(data1)); return; // [2020-09-07 02:10:36] 上传属性,属性值: 9.6, 属性名: 目标湿度, 设备号: 53, 测点号: 18, 测点类型: C // [2020-09-07 02:10:36] 上传属性, 结果: 成功(0), homeaddr: 389, 服务Id: 260608, iid: 7, 属性二进制值: 0x3809 // [2020-09-07 02:52:48] 上传属性,属性值: 12, 属性名: 当前湿度, 设备号: 53, 测点号: 14, 测点类型: C // [2020-09-07 02:52:48] 上传属性, 结果: 成功(0), homeaddr: 390, 服务Id: 260352, iid: 7, 属性二进制值: 0x3800 // [2020-09-07 02:52:48] 上传属性,属性值: 15.1, 属性名: 当前湿度, 设备号: 53, 测点号: 17, 测点类型: C // [2020-09-07 02:52:48] 上传属性, 结果: 成功(0), homeaddr: 390, 服务Id: 260608, iid: 6, 属性二进制值: 0x3000 // [2020-09-07 02:52:48] 上传属性,属性值: 19.1, 属性名: 目标湿度, 设备号: 53, 测点号: 18, 测点类型: C // [2020-09-07 02:52:48] 上传属性, 结果: 成功(0), homeaddr: 390, 服务Id: 260608, iid: 7, 属性二进制值: 0x3800 // [2020-09-07 02:52:48] 上传属性,属性值: 16.4, 属性名: 目标湿度, 设备号: 53, 测点号: 22, 测点类型: C // [2020-09-07 02:52:48] 上传属性, 结果: 成功(0), homeaddr: 390, 服务Id: 256512, iid: 12, 属性二进制值: 0x6000 // [2020-09-07 02:52:48] 上传属性,属性值: 7, 属性名: 频率控制, 设备号: 53, 测点号: 31, 测点类型: C // [2020-09-07 02:52:48] 上传属性, 结果: 成功(0), homeaddr: 390, 服务Id: 256512, iid: 7, 属性二进制值: 0x3800 // [2020-09-07 02:52:48] 上传属性,属性值: 17.5, 属性名: 频率反馈, 设备号: 53, 测点号: 32, 测点类型: C // [2020-09-07 02:52:48] 上传属性, 结果: 成功(0), homeaddr: 390, 服务Id: 256512, iid: 8, 属性二进制值: 0x4000 // [2020-09-07 02:52:48] 上传属性,属性值: False, 属性名: 故障状态, 设备号: 53, 测点号: 28, 测点类型: X // [2020-09-07 02:52:48] 上传属性, 结果: 成功(0), homeaddr: 390, 服务Id: 256512, iid: 3, 属性二进制值: 0x1800 // [2020-09-07 02:52:48] 上传属性,属性值: False, 属性名: 中效滤网状态, 设备号: 53, 测点号: 5, 测点类型: X // [2020-09-07 02:52:48] 上传属性, 结果: 成功(0), homeaddr: 390, 服务Id: 256768, iid: 2, 属性二进制值: 0x1000 var typeModel = RuntimeTypeModel.Create(); var ms = new MemoryStream(); var writer = ProtoWriter.State.Create(ms, typeModel); writer.WriteFieldHeader(order, WireType.Varint); writer.WriteUInt32(value); writer.Flush(); ms.Position = 0; var data = ms.ToArray(); ms.Close(); ms.Dispose(); ms = null; Print(order); void Print(int i) { Console.WriteLine($"Order:{i.ToString()}, Value: {value.ToString()}, Data: {BitConverter.ToString(data)}"); } }
/// <summary> /// Serializes all edges. /// </summary> /// <param name="stream"></param> /// <param name="graph"></param> protected override void SerializeEdges(LimitedStream stream, DynamicGraphRouterDataSource <CHEdgeData> graph) { var typeModel = RuntimeTypeModel.Create(); typeModel.Add(typeof(SerializableEdge), true); int blockSize = 1000; var arcsQueue = new List <SerializableEdge>(blockSize); uint vertex = 0; while (vertex < graph.VertexCount) { // keep looping and serialize all vertices. var arcs = graph.GetEdges(vertex).ToList(); if (arcs != null) { // serialize the arcs, but serialize them only once. // choose only those arcs that start at a vertex smaller than the target. for (int idx = 0; idx < arcs.Count; idx++) { arcsQueue.Add(new SerializableEdge() { FromId = vertex, ToId = arcs[idx].Neighbour, Meta = arcs[idx].EdgeData.Meta, Value = arcs[idx].EdgeData.Value, Weight = arcs[idx].EdgeData.Weight, Coordinates = arcs[idx].Intermediates.ToSimpleArray() }); if (arcsQueue.Count == blockSize) { // execute serialization. typeModel.SerializeWithSize(stream, arcsQueue.ToArray()); arcsQueue.Clear(); } } // serialize. vertex++; } } if (arcsQueue.Count > 0) { // execute serialization. typeModel.SerializeWithSize(stream, arcsQueue.ToArray()); arcsQueue.Clear(); } }
public void DeliberatelyCausedContentionShouldShow() { var model = RuntimeTypeModel.Create(); model.MetadataTimeoutMilliseconds = 400; string eek = null; model.LockContended += (s, a) => eek = a.OwnerStackTrace; ManualResetEvent workerReady = new ManualResetEvent(false), workerComplete = new ManualResetEvent(false), mainComplete = new ManualResetEvent(false); ThreadPool.QueueUserWorkItem(delegate { int opaqueToken = 0; try { model.TakeLock(ref opaqueToken); workerReady.Set(); if (!mainComplete.WaitOne(5000)) { throw new TimeoutException(); } } finally { model.ReleaseLock(opaqueToken); workerComplete.Set(); } }); if (!workerReady.WaitOne(5000)) { throw new TimeoutException(); } try { model[typeof(ThreadRace.A)].CompileInPlace(); Assert.Equal("oops", "Should have timed out"); } catch (TimeoutException) { Debug.WriteLine("Expected timeout occurred"); } mainComplete.Set(); if (!workerComplete.WaitOne(5000)) { throw new TimeoutException(); } Assert.NotNull(eek); }
public void InitialStartup(ref int progress) { RuntimeTypeModel current = RuntimeTypeModel.Create(); foreach (ITeachSerialization item in this.Teachers) { item.Teach(current);//Point teacher ain't loading progress++; } MetaType baseMessageType = current.Add(typeof(BaseMessage), true); List <IHasSubclasses> ToProcess = ReflectionUtil.LoadAllInterface <IHasSubclasses>(Assembly.GetAssembly(typeof(BaseMessage))); ToProcess.AddRange(ReflectionUtil.LoadAllInterface <IHasSubclasses>(Assembly.GetAssembly(typeof(Tile)))); foreach (IHasSubclasses item in ToProcess) { MetaType meta = current.Add(item.GetBaseType(), true); foreach (KeyValuePair <Type, int> subs in item.GetSubclassInformation()) { meta.AddSubType(subs.Value, subs.Key); } } //Must start at 2 because Protobuf-net can't have members and inheritance attributes with the same ID. I think. :D int i = 2; int length = this.Messages.Count + 2; while (i < length) { current.Add(this.Messages[i - 2], true); baseMessageType.AddSubType(i, this.Messages[i - 2]); BaseMessage sample = (BaseMessage)Activator.CreateInstance(this.Messages[i - 2]); ProtoUtil.IDToMessage.Add(sample.ID, this.Messages[i - 2]); i++; progress++; } //ProtoUtil.TypeModel = RuntimeTypeModel.Default. //ProtoUtil.TypeModel = current.Compile(); //ProtoUtil.TypeModel ProtoUtil.TypeModel = current; }
public void InitialStartup() { RuntimeTypeModel current = RuntimeTypeModel.Create(); foreach (ITeachSerialization item in this.Teachers) { item.Teach(current); } MetaType baseMessageType = current.Add(typeof(BaseMessage), true); List <IHasSubclasses> ToProcess = new List <IHasSubclasses>(); ToProcess.AddRange(ReflectionUtil.LoadAllInterface <IHasSubclasses>(Assembly.GetAssembly(typeof(Tile)))); foreach (IHasSubclasses item in ToProcess) { if (item.GetType().IsAbstract) { MetaType meta = current.Add(item.GetBaseType(), true); foreach (KeyValuePair <Type, int> subs in item.GetSubclassInformation()) { meta.AddSubType(subs.Value, subs.Key); } } } //Must start at 2 because Protobuf-net can't have members and inheritance attributes with the same ID. I think. :D int i = 3; int length = this.Messages.Count + 3; while (i < length) { current.Add(this.Messages[i - 3], true); baseMessageType.AddSubType(i, this.Messages[i - 3]); BaseMessage sample = (BaseMessage)Activator.CreateInstance(this.Messages[i - 3]); if (!ProtoUtil.IDToMessage.ContainsKey(sample.ID)) { ProtoUtil.IDToMessage.Add(sample.ID, this.Messages[i - 3]); } i++; } ProtoUtil.TypeModel = current; }
public void IsDefinedWorksWhenAddingSubTypes() { var baseType = typeof(MyBaseClass); var subType = typeof(MyDerivedClass); var m = RuntimeTypeModel.Create(); Assert.False(m.IsDefined(baseType)); Assert.False(m.IsDefined(subType)); var protoType = m.Add(baseType, true); Assert.True(m.IsDefined(baseType)); Assert.False(m.IsDefined(subType)); protoType.AddSubType(100, subType); Assert.True(m.IsDefined(baseType)); Assert.True(m.IsDefined(subType)); }
public void ExecuteSimpleNestedShouldNotBuffer() { var model = RuntimeTypeModel.Create(); #if DEBUG model.ForwardsOnly = true; #endif var obj = new BasicData { C = new C { Field1 = "abc", Field2 = "def" } }; var clone = (BasicData)model.DeepClone(obj); Assert.Equal("abc", clone.C.Field1); Assert.Equal("def", clone.C.Field2); Assert.NotSame(obj, clone); }
public void ChangesManagerTest() { // Конфигурируем ChangesSearcher changesSearcher = new ChangesSearcher(RuntimeTypeModel.Create()); PersonManager pm = new PersonManager(changesSearcher); DogManager dm = new DogManager(changesSearcher); pm.Initialize(); dm.Initialize(); // Ищем var changes = changesSearcher.GetChanges(_oldPerson, _newPerson); var fieldChanges = pm.ToData(changes); var formattedChanges = pm.GetFormatted(fieldChanges); }
public void LegacyTimeSpanBehaviors() { var model = RuntimeTypeModel.Create(); model.IncludeDateTimeKind = true; Verify(model, TimeSpan.MinValue, "0A-04-08-01-10-0F"); Verify(model, default(TimeSpan), "0A-00", ""); Verify(model, TimeSpan.MaxValue, "0A-04-08-02-10-0F"); Verify(model, new TimeSpan(32, 10, 25, 32, 123), "0A-08-08-B6-C7-C1-F0-14-10-04"); model = RuntimeTypeModel.Create(); model.IncludeDateTimeKind = false; Verify(model, TimeSpan.MinValue, "0A-04-08-01-10-0F"); Verify(model, default(TimeSpan), "0A-00", ""); Verify(model, TimeSpan.MaxValue, "0A-04-08-02-10-0F"); Verify(model, new TimeSpan(32, 10, 25, 32, 123), "0A-08-08-B6-C7-C1-F0-14-10-04");
public void Execute() { byte[] buffer = { 9, 8, 5, 26, 5, 24, 238, 98, 32, 1 }; var model = RuntimeTypeModel.Create(); model.AutoCompile = false; using (var ms = new MemoryStream(buffer)) { int len = ProtoReader.DirectReadVarintInt32(ms); var resp = (Response)model.Deserialize(ms, null, typeof(Response), len); Assert.Equal(5, resp.Type); Assert.Equal(1, resp.v3dDelta.Count); Assert.Equal(12654, resp.v3dDelta[0].ask); Assert.Equal(1, resp.v3dDelta[0].askSize); } }
[Fact] //(Skip = "breaking test harness; investigate"), Trait("kind", "test harness fail")] public void Execute() { #if DEBUG const int OuterLoop = 5; #else const int OuterLoop = 500; #endif var model = RuntimeTypeModel.Create(); model.AutoCompile = false; // Execute(OuterLoop, model, "RT"); model.CompileInPlace(); ExecuteImpl(OuterLoop, model, "CIP"); ExecuteImpl(OuterLoop, model.Compile(), "C"); var ext = model.Compile("SO18650486", "SO18650486.dll"); PEVerify.AssertValid("SO18650486.dll"); ExecuteImpl(OuterLoop, ext, "EXT"); }
public void StringInterned() { var model = RuntimeTypeModel.Create(); model.InternStrings = true; var obj = new StringInternedType { Foo = GetString(), Bar = GetString() }; Assert.False(ReferenceEquals(obj.Foo, obj.Bar)); var clone = (StringInternedType)model.DeepClone(obj); Assert.Equal(obj.Foo, clone.Foo); Assert.Equal(obj.Bar, clone.Bar); Assert.True(ReferenceEquals(clone.Foo, clone.Bar)); }
public void TupleDictionary() { var model = RuntimeTypeModel.Create(); model.AutoCompile = false; model.Add <Tuple <Dictionary <string, double>, Dictionary <string, double> > >(); Test(model); var dll = model.CompileAndVerify(); model.CompileInPlace(); Test(model); Test(model.Compile()); Test(dll); }
private static void TestSortedDictionaryImpl <T>([CallerMemberName] string name = null) where T : class, IImmutableCollectionWrapper, new() { var model = RuntimeTypeModel.Create(); model.AutoCompile = false; TestSortedDictionaryImpl <T>(model, "Runtime"); var external = model.Compile(name, name + ".dll"); PEVerify.AssertValid(name + ".dll"); TestSortedDictionaryImpl <T>(external, "External"); model.CompileInPlace(); TestSortedDictionaryImpl <T>(model, "CompileInPlace"); TestSortedDictionaryImpl <T>(model.Compile(), "Compile"); }
/// <summary> /// Serializes the vertices /// </summary> /// <param name="stream"></param> /// <param name="graph"></param> protected virtual void SerializeVertices(LimitedStream stream, DynamicGraphRouterDataSource <TEdgeData> graph) { RuntimeTypeModel typeModel = RuntimeTypeModel.Create(); typeModel.Add(typeof(SerializableVertex), true); int blockSize = 1000; var vertices = new SerializableVertex[blockSize]; uint vertex = 1; float latitude, longitude; while (vertex <= graph.VertexCount) { // adjust array size if needed. if (vertices.Length > graph.VertexCount - vertex) { // shrink array. vertices = new SerializableVertex[graph.VertexCount - vertex + 1]; } // build block. for (uint idx = 0; idx < vertices.Length; idx++) { uint current = vertex + idx; if (vertex <= graph.VertexCount && graph.GetVertex(current, out latitude, out longitude)) { // vertex in the graph. if (vertices[idx] == null) { // make sure there is a vertex. vertices[idx] = new SerializableVertex(); } vertices[idx].Latitude = latitude; vertices[idx].Longitude = longitude; } else { // vertex not in the graph. throw new Exception("Cannot serialize non-existing vertices!"); } } // serialize. typeModel.SerializeWithSize(stream, vertices); // move to the next vertex. vertex = (uint)(vertex + blockSize); } }
public void ExecuteWithSubType() { var m = RuntimeTypeModel.Create(); m.AutoCompile = false; m.Add(typeof(C), false).SetSurrogate(typeof(CS)); m.Add(typeof(O), false).SetSurrogate(typeof(OS)); m.Add(typeof(I), false).AddSubType(1, typeof(O)); var c = new C(); c.PopulateRun(); Test(m, c, "Runtime"); m.CompileInPlace(); Test(m, c, "CompileInPlace"); Test(m.Compile(), c, "Compile"); }
public void ExposeInterfaceWithDefaultImplementation() { var model = RuntimeTypeModel.Create(); // note the following sets for the ConstructType for the ISomeInferface, not specifically for Foo model.Add(typeof(ISomeInterface), false).Add("Foo").ConstructType = typeof(SomeClass2); model.Add(typeof(SomeClass), false).Add("SomeProperty"); var orig = new SomeClass { SomeProperty = new SomeClass2() }; orig.SomeProperty.Foo = 123; var clone = (SomeClass)model.DeepClone(orig); Assert.Equal(123, clone.SomeProperty.Foo); }
public void LoadTestCustomModel() { var model = RuntimeTypeModel.Create(); Database db = LoadDatabaseFromFile <Database>(model); DbMetrics("Database", db); model.CompileInPlace(); db = LoadDatabaseFromFile <Database>(model); DbMetrics("Database", db); db = LoadDatabaseFromFile <Database>(model.Compile()); DbMetrics("Database", db); db = LoadDatabaseFromFile <Database>(model.Compile("NWindModel", "NWindModel.dll")); PEVerify.AssertValid("NWindModel.dll"); DbMetrics("Database", db); }
public void CanDeserialiseImmutableList(bool autoCompile) { var testClass = new ImmutableListTestClass(ImmutableList.Create("a", "b", "c")); var model = RuntimeTypeModel.Create(); model.AutoCompile = autoCompile; ImmutableListTestClass testClassClone; using var ms = new MemoryStream(); model.Serialize(ms, testClass); ms.Position = 0; #pragma warning disable CS0618 testClassClone = (ImmutableListTestClass)model.Deserialize(ms, null, testClass.GetType()); #pragma warning restore CS0618 Assert.Equal((IEnumerable <string>)testClass.List, (IEnumerable <string>)testClassClone.List); }
public void Execute() { var model = RuntimeTypeModel.Create(); model.Add(typeof(A), true); model.Add(typeof(B), true); model.Add(typeof(C), true); model.Add(typeof(D), true); model.Add(typeof(TestCase), true); _ = model.GetSchema(null, ProtoSyntax.Default); Assert.Null(model[typeof(A)].BaseType); //, "A"); Assert.Same(model[typeof(A)], model[typeof(B)].BaseType); //, "B"); Assert.Same(model[typeof(A)], model[typeof(C)].BaseType); //, "C"); Assert.Same(model[typeof(A)], model[typeof(D)].BaseType); //, "D"); Assert.Null(model[typeof(TestCase)].BaseType); //, "TestCase"); }
public void TestPrimitiveMultidimArraysCannotSerialize() { var model = RuntimeTypeModel.Create(); Assert.False(model.CanSerialize(typeof(int[, ]))); Assert.False(model.CanSerialize(typeof(int?[, ]))); Assert.False(model.CanSerialize(typeof(short[, ]))); Assert.False(model.CanSerialize(typeof(short?[, ]))); Assert.False(model.CanSerialize(typeof(byte[, ]))); Assert.False(model.CanSerialize(typeof(string[, ]))); Assert.False(model.CanSerialize(typeof(DateTime[, ]))); Assert.False(model.CanSerialize(typeof(DateTime?[, ]))); #if !COREFX Assert.False(model.CanSerialize(typeof(System.Windows.Media.Color[, ]))); #endif Assert.False(model.CanSerialize(typeof(DateTimeOffset[, ]))); Assert.False(model.CanSerialize(typeof(Action[, ]))); }
public void TestPrimitiveArraysCanSerialize() { var model = RuntimeTypeModel.Create(); Assert.True(model.CanSerialize(typeof(int[])), "int"); Assert.True(model.CanSerialize(typeof(int?[])), "int?"); Assert.True(model.CanSerialize(typeof(short[])), "short"); Assert.True(model.CanSerialize(typeof(short?[])), "short?"); Assert.True(model.CanSerialize(typeof(byte[][])), "byte[]"); Assert.True(model.CanSerialize(typeof(string[])), "string"); Assert.True(model.CanSerialize(typeof(DateTime[])), "DateTime"); Assert.True(model.CanSerialize(typeof(DateTime?[])), "DateTime?"); #if !COREFX Assert.False(model.CanSerialize(typeof(System.Windows.Media.Color[])), "Color"); #endif Assert.False(model.CanSerialize(typeof(DateTimeOffset[])), "DateTimeOffset"); Assert.False(model.CanSerialize(typeof(Action[])), "Action"); }
public void TestPrimitiveCanSerialize() { var model = RuntimeTypeModel.Create(); Assert.True(model.CanSerialize(typeof(int))); Assert.True(model.CanSerialize(typeof(int?))); Assert.True(model.CanSerialize(typeof(short))); Assert.True(model.CanSerialize(typeof(short?))); Assert.True(model.CanSerialize(typeof(byte[]))); Assert.True(model.CanSerialize(typeof(string))); Assert.True(model.CanSerialize(typeof(DateTime))); Assert.True(model.CanSerialize(typeof(DateTime?))); #if !COREFX Assert.False(model.CanSerialize(typeof(System.Windows.Media.Color))); #endif Assert.False(model.CanSerialize(typeof(DateTimeOffset))); Assert.False(model.CanSerialize(typeof(Action))); }