Beispiel #1
0
        public static _3DNInfo GetFileInfo(string Path)
        {
            try
            {
                using (var str = File.OpenRead(Path))
                {
                    var model = TypeModel.Create();
                    var data  = (_3DNInfo)model.Deserialize(str, null, typeof(_3DNInfo));

                    if (data == null || data.Title != "3dn")
                    {
                        return(null);
                    }

                    return(data);
                    //var info = Proto
                }
            }
            catch { return(null); }
        }
Beispiel #2
0
        static ProtoReader GetReader()
        {
            var model = TypeModel.Create();

            model.Add(typeof(Foo), true);
            model.CompileInPlace();

            var ms  = new MemoryStream();
            var obj = new Foo {
                Bar = "abc", Blap = "abc"
            };

            using (var writer = new ProtoWriter(ms, model, null))
            {
                writer.Model.Serialize(writer, obj);
            }
            ms.Position = 0;

            return(new ProtoReader(ms, model, null));
        }
Beispiel #3
0
        static void Main(string[] args)
        {
            var model = TypeModel.Create();

            model.AutoAddMissingTypes = true;

            var types = from type in typeof(ResponseMessage).Assembly.GetTypes()
                        let attribute = Attribute.GetCustomAttribute(type, typeof(ProtoContractAttribute))
                                        where attribute != null
                                        select type;

            foreach (var type in types)
            {
                model.Add(type, true);
            }

            model.Compile("DataContractsSerializer", "DataContractsSerializer.dll");

            File.Copy("DataContractsSerializer.dll", "../../../lib/WP7/DataContractsSerializer.dll", true);
        }
Beispiel #4
0
        public NitroxProtobufSerializer(params string[] assemblies)
        {
            model      = TypeModel.Create();
            knownTypes = (Dictionary <Type, int>) typeof(ProtobufSerializerPrecompiled).GetField("knownTypes", BindingFlags.NonPublic | BindingFlags.Static).GetValue(null);

            foreach (string assembly in assemblies)
            {
                RegisterAssemblyClasses(assembly);
            }

            foreach (Type type in Assembly.GetExecutingAssembly().GetTypes())
            {
                bool hasUweProtobuf = (type.GetCustomAttributes(typeof(ProtoContractAttribute), true).Length > 0);

                if (hasUweProtobuf)
                {
                    AddType(type);
                }
            }
        }
Beispiel #5
0
        public void LoadTestCustomModel()
        {
            var      model = TypeModel.Create(false, ProtoCompatibilitySettingsValue.FullCompatibility);
            Database db;

            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);
        }
Beispiel #6
0
        public void TestEnumProto_Proto2_RuntimeRenamed()
        {
            var model = TypeModel.Create();

            model[typeof(HazEnum.SomeEnum)][1].Name = "zzz";
            var schema = model.GetSchema(typeof(HazEnum), ProtoSyntax.Proto2);

            Assert.Equal(@"syntax = ""proto2"";
package ProtoBuf.Serializers;

message HazEnum {
   optional SomeEnum X = 1 [default = B];
}
enum SomeEnum {
   B = 0;
   zzz = 1;
   C = 2;
}
", schema);
        }
Beispiel #7
0
        static RuntimeTypeModel CreateSurrogateModel(bool comp)
        {
            ProtoCompatibilitySettingsValue fullComp = ProtoCompatibilitySettingsValue.FullCompatibility;

            fullComp.SuppressValueEnhancedFormat = false;
            var model = TypeModel.Create(false, comp ? fullComp : ProtoCompatibilitySettingsValue.Incompatible);

            model.SkipForcedAdvancedVersioning = true;
            if (comp)
            {
                model.SkipForcedLateReference = true;
            }
            model.AutoCompile = false;
            model[typeof(B)][2].AsReference = false; // or just remove AsReference on Items

            // this is the evil bit:
            model[typeof(KeyValuePair <int, A>)].SetSurrogate(typeof(RefPair <int, A>));
            model[typeof(KeyValuePair <int, A>)].AsReferenceDefault = true;
            return(model);
        }
Beispiel #8
0
        public void EmitModelWithEverything()
        {
            var      model = TypeModel.Create();
            MetaType meta  = model.Add(typeof(TypeWithLists), false);

            meta.Add(1, "ListString");
            meta.Add(2, "ListInt32");
            meta.Add(3, "IListStringTyped");
            meta.Add(4, "IListInt32Typed");

            meta.Add(5, "ArrayListString", typeof(string), null);
            meta.Add(6, "ArrayListInt32", typeof(int), null);
            meta.Add(7, "IListStringUntyped", typeof(string), null);
            meta.Add(8, "IListInt32Untyped", typeof(int), null);

            model.CompileInPlace();

            model.Compile("EmitModelWithEverything", "EmitModelWithEverything.dll");
            PEVerify.Verify("EmitModelWithEverything.dll");
        }
Beispiel #9
0
        public void TypeWithPairTest()
        {
            var orig = new TypeWithPair { Pair = new KeyValuePair<string, decimal>("abc", 123.45M) };
            var model = TypeModel.Create();
            var clone = (TypeWithPair)model.DeepClone(orig);
            Assert.AreEqual("abc", clone.Pair.Key, "Runtime");
            Assert.AreEqual(123.45M, clone.Pair.Value, "Runtime");

            model.Compile("TypeWithPairTest", "TypeWithPairTest.dll");
            PEVerify.Verify("TypeWithPairTest.dll");

            model.CompileInPlace();
            clone = (TypeWithPair)model.DeepClone(orig);
            Assert.AreEqual("abc", clone.Pair.Key, "CompileInPlace");
            Assert.AreEqual(123.45M, clone.Pair.Value, "CompileInPlace");

            clone = (TypeWithPair)model.Compile().DeepClone(orig);
            Assert.AreEqual("abc", clone.Pair.Key, "Compile");
            Assert.AreEqual(123.45M, clone.Pair.Value, "Compile");
        }
Beispiel #10
0
        public void SanityCheckListWrapper()
        {
            var model = TypeModel.Create();

            model.Add(typeof(ListWrapper), true);

            var schema = model.GetSchema(null);

            Assert.Equal(@"syntax = ""proto2"";
package Examples.Issues;

message ListWrapper {
   repeated string BasicList = 1;
   repeated string MyList = 2;
   repeated string MyContractList = 3;
}
", schema);
            model.Compile("SanityCheckListWrapper", "SanityCheckListWrapper.dll");
            PEVerify.AssertValid("SanityCheckListWrapper.dll");
        }
Beispiel #11
0
        public void TypeWithIDictionaryTest()
        {
            var orig = new TypeWithIDictionary { Data = new Dictionary<string, decimal> { { "abc", 123.45M } } };
            var model = TypeModel.Create();
            var clone = (TypeWithIDictionary)model.DeepClone(orig);
            Assert.AreEqual(1, clone.Data.Count);
            Assert.AreEqual(123.45M, clone.Data["abc"], "Runtime");

            model.Compile("TypeWithIDictionary", "TypeWithIDictionary.dll");
            PEVerify.Verify("TypeWithIDictionary.dll");

            model.CompileInPlace();
            clone = (TypeWithIDictionary)model.DeepClone(orig);
            Assert.AreEqual(1, clone.Data.Count);
            Assert.AreEqual(123.45M, clone.Data["abc"], "Runtime");

            clone = (TypeWithIDictionary)model.Compile().DeepClone(orig);
            Assert.AreEqual(1, clone.Data.Count);
            Assert.AreEqual(123.45M, clone.Data["abc"], "Runtime");
        }
Beispiel #12
0
        public void Execute()
        {
            var model = TypeModel.Create();

            model.AutoCompile = false;
            model.SetDefaultFactory(typeof(SO14532116).GetMethod("ObjectMaker"));

            int oldCount = Count;

            Test(model, "Runtime");
            model.CompileInPlace();
            Test(model, "CompileInPlace");
            Test(model.Compile(), "CompileInPlace");
            model.Compile("SO14532116", "SO14532116.dll");
            PEVerify.AssertValid("SO14532116.dll");

            int newCount = Count;

            Assert.Equal(oldCount + 3, newCount);
        }
Beispiel #13
0
        public void TestOrderLineGetDeserializedAndAttachedToOrder()
        {
            byte[] fileBytes = File.ReadAllBytes(@"NWind\nwind.proto.bin");

            RuntimeTypeModel ordersModel = TypeModel.Create();

            ordersModel.AutoCompile = false;

            Database     database = (Database)ordersModel.Deserialize(new MemoryStream(fileBytes), null, typeof(Database));
            List <Order> orders   = database.Orders;

            DbMetrics("From File", orders);

            var roundTrippedOrders = (List <Order>)ordersModel.DeepClone(orders);

            Assert.AreNotSame(orders, roundTrippedOrders);
            DbMetrics("Round trip", roundTrippedOrders);
            Assert.AreEqual(orders.SelectMany(o => o.Lines).Count(),
                            roundTrippedOrders.SelectMany(o => o.Lines).Count(), "total count");
        }
Beispiel #14
0
        public void Append()
        {
            var tm = TypeModel.Create();

            tm.Add(typeof(Container), true)[1].SetSettings(x => x.V.Collection.Append = true);
            var obj = new Container {
                Values = MakeArray()
            };

            using (var ms = new MemoryStream())
            {
                tm.Serialize(ms, obj);
                ms.Position = 0;
                var copy = (Container)tm.Deserialize(ms, null, typeof(Container));
                ms.Position = 0;
                copy        = tm.Deserialize(ms, copy);
                var twice = MakeArrayTwice();
                Assert.That(copy.Values, Is.EqualTo(twice));
            }
        }
        public void Execute()
        {
            var model = TypeModel.Create();

            model.AutoAddMissingTypes = false;
            model.AutoCompile         = false;
            // register container type
            this.RegisterListType(model, typeof(TestList <string>));
            model.Add(typeof(Container), true).AddField(1, "Content").AsReference = false;
            model.SkipCompiledVsNotCheck = true;
            model.CompileInPlace();

            var originalList = new List <string>()
            {
                "1", "2", "3"
            };

            // check without container
            {
                var deserializedList = model.DeepClone(new TestList <string>(originalList));

                Assert.That(deserializedList.InnerList, Is.EqualTo(originalList));
                Assert.That(deserializedList.IsDeserializationCalled, Is.EqualTo(true));
                // please note we've set metaType.UseConstructor = false
                Assert.That(deserializedList.IsDefaultConstructorCalled, Is.EqualTo(false));
            }

            // check with container
            {
                var deserialized = model.DeepClone(new Container()
                {
                    Content = new TestList <string>(originalList)
                });
                var deserializedList = deserialized.Content;

                Assert.That(deserializedList.InnerList, Is.EqualTo(originalList));
                Assert.That(deserializedList.IsDeserializationCalled, Is.EqualTo(true));
                // please note we've set metaType.UseConstructor = false
                Assert.That(deserializedList.IsDefaultConstructorCalled, Is.EqualTo(false));
            }
        }
Beispiel #16
0
        static RuntimeTypeModel CreateModel(bool baseFirst)
        {
            var model = TypeModel.Create();

            model.AutoCompile = false;
            model.Add(typeof(Tree), true);
            if (baseFirst)
            {
                model.Add(typeof(TreeNodeBase), true);
                model.Add(typeof(TreeNode), true);
            }
            else
            {
                model.Add(typeof(TreeNode), true);
                model.Add(typeof(TreeNodeBase), true);
            }


            model.AutoAddMissingTypes = false;
            return(model);
        }
Beispiel #17
0
        public void TestEnumerableStandard()
        {
            EnumParentStandardWrapper obj = new EnumParentStandardWrapper();
            var tm = TypeModel.Create();

            tm.SkipCompiledVsNotCheck = true;
            EnumParentStandardWrapper clone = tm.DeepClone(obj);

            // old: the source object should have been read twice
            // old: once to get the length-prefix, and once for the data
            // update: once only with buffering
            Assert.AreEqual(1, obj.Wrapper.SubData.IteratorCount, "obj IteratorCount");
            Assert.AreEqual(0, obj.Wrapper.SubData.Count, "obj Count");
            Assert.AreEqual(0, obj.Wrapper.SubData.Sum, "obj Sum");

            // the destination object should never have been read, but should have
            // had 5 values added
            Assert.AreEqual(0, clone.Wrapper.SubData.IteratorCount, "clone IteratorCount");
            Assert.AreEqual(5, clone.Wrapper.SubData.Count, "clone Count");
            Assert.AreEqual(1 + 2 + 3 + 4 + 5, clone.Wrapper.SubData.Sum, "clone Sum");
        }
Beispiel #18
0
        public void Execute()
        {
            var tm = TypeModel.Create();

            tm.AutoCompile            = true;
            tm.SkipCompiledVsNotCheck = true;
            var list = new List <int>()
            {
                1, 2, 3
            };
            var v = tm.DeepClone(new Container()
            {
                Member = new TestList()
                {
                    InnerList = list
                }
            });

            Assert.That(v.Member.SomeValue, Is.EqualTo(12345));
            Assert.That(v.Member.InnerList, Is.EqualTo(list));
        }
Beispiel #19
0
        public void TestDecimalUnits()
        {
            Primatives p = new Primatives {
                TestDecimalDefault = decimal.Zero
            };
            var tm = TypeModel.Create(false, ProtoCompatibilitySettingsValue.FullCompatibility);

            Assert.AreEqual(p.TestDecimalDefault, tm.DeepClone(p).TestDecimalDefault);

            p.TestDecimalDefault = decimal.MinusOne;
            Assert.AreEqual(p.TestDecimalDefault, tm.DeepClone(p).TestDecimalDefault);

            p.TestDecimalDefault = decimal.One;
            Assert.AreEqual(p.TestDecimalDefault, tm.DeepClone(p).TestDecimalDefault);

            p = Program.Build <Primatives>(0x1A, 0x00);
            Assert.AreEqual(decimal.Zero, p.TestDecimalDefault);

            p = Program.Build <Primatives>();
            Assert.AreEqual(29M, p.TestDecimalDefault);
        }
Beispiel #20
0
        static Serializer()
        {
            model = TypeModel.Create();
            model.AutoAddMissingTypes = true;
            //RuntimeTypeModel mdl = new RuntimeTypeModel();
            model.Add(typeof(Point), true).Add("X", "Y");
            model.Add(typeof(Demo.Entity), true).Add("tile", "x", "y", "pos").AddSubType(40, typeof(Demo.Mob));
            model.Add(typeof(SkillAreaKind), true);
            MetaType sk = model.Add(typeof(Skill), true).Add("minSkillDistance", "maxSkillDistance", "radius",
                                                             "areaKind", "damage", "hitsAllies", "name", "targetSquare");

            sk.UseConstructor = false;
            MetaType mb = model.Add(typeof(Demo.Mob), true).Add("hp_internal", "maxHP", "friendly",
                                                                "o_pos", "name", "moveSpeed", "actionCount", "skillList", "dlevelIndex");

            mb.UseConstructor = false;
            model.Add(typeof(Level), true).Add("floor", "entities", "o_entities", "allies", "map1D",
                                               "mapWidthBound", "mapHeightBound", "fixtures", "safeUpCells", "safeDownCells", "enemyBlockedCells");
            model.Add(typeof(Demo.GameState), true).Add("initiative", "currentInitiative", "fullDungeon", "levelIndex", "cursorX", "cursorY", "confirmKey", "backKey");
//            System.IO.File.WriteAllText("debuggery2.txt", model.GetTypes().ToString());
        }
        public void ShouldWorkWithAutoLoadDisabledCompile()
        {
            var orig = new TypeWithDictionary {
                Data = new Dictionary <string, decimal> {
                    { "abc", 123.45M }
                }
            };
            var model = TypeModel.Create();

            model.AutoAddMissingTypes = false;
            model.Add(typeof(TypeWithDictionary), true);

            var compiled = model.Compile("MapSerializer", "ShouldWorkWithAutoLoadDisabledCompile.dll");

            PEVerify.Verify("ShouldWorkWithAutoLoadDisabledCompile.dll");

            var clone = (TypeWithDictionary)model.Compile().DeepClone(orig);

            Assert.Single(clone.Data);
            Assert.Equal(123.45M, clone.Data["abc"]);
        }
        public void TestSkipConstructor()
        {
            var orig = new WithSkipConstructor {
                Values = new[] { 4, 5 }
            };
            var model = TypeModel.Create();

            model.AutoCompile = false;
            model.Add(typeof(WithSkipConstructor), true);

            var clone = (WithSkipConstructor)model.DeepClone(orig);

            Assert.True(clone.Values.SequenceEqual(new[] { 4, 5 }), "Runtime");

            model.CompileInPlace();
            clone = (WithSkipConstructor)model.DeepClone(orig);
            Assert.True(clone.Values.SequenceEqual(new[] { 4, 5 }), "CompileInPlace");

            clone = (WithSkipConstructor)(model.Compile()).DeepClone(orig);
            Assert.True(clone.Values.SequenceEqual(new[] { 4, 5 }), "Compile");
        }
Beispiel #23
0
        public void TestNonNullableDateTimeOffsetViaSurrogate()
        {
            var foo = new Foo {
                X = DateTimeOffset.Now
            };
            var model = TypeModel.Create();

            model.Add(typeof(DateTimeOffset), false).SetSurrogate(typeof(DateTimeOffsetSurrogate));
            model.AutoCompile = false;

            var clone = (Foo)model.DeepClone(foo);

            Assert.AreEqual(foo.X, clone.X, "runtime");

            model.CompileInPlace();
            clone = (Foo)model.DeepClone(foo);
            Assert.AreEqual(foo.X, clone.X, "CompileInPlace");

            clone = (Foo)model.Compile().DeepClone(foo);
            Assert.AreEqual(foo.X, clone.X, "Compile");
        }
        public void NonEmptyDictionaryShouldDeserializeViaInterface([Values(false, true)] bool reg, [Values(false, true)] bool compile)
        {
            var tm = TypeModel.Create();

            tm.AlwaysUseTypeRegistrationForCollections = reg;
            tm.AutoCompile = compile;
            using (var ms = new MemoryStream())
            {
                var data = new Dictionary <string, int> {
                    { "abc", 123 }
                };

                tm.Serialize(ms, data);
                ms.Position = 0;
                var clone = tm.Deserialize <IDictionary <string, int> >(ms);

                Assert.IsNotNull(clone);
                Assert.AreEqual(1, clone.Count);
                Assert.AreEqual(123, clone["abc"]);
            }
        }
Beispiel #25
0
        public void LockContention_BasicType()
        {
            var model = TypeModel.Create();
            Func <object, byte[]> serialize = obj =>
            {
                using (var ms = new MemoryStream())
                {
                    model.Serialize(ms, obj);
                    return(ms.ToArray());
                }
            };
            var tasks = new List <Task>(50000);

            for (var i = 0; i < 50000; i++)
            {
                tasks.Add(Task.Factory.StartNew(() => serialize(Guid.NewGuid().ToString())));
            }
            Task.WaitAll(tasks.ToArray());
            Assert.LessOrEqual(1, 2, "because I always get this backwards");
            Assert.LessOrEqual(model.LockCount, 50);
        }
        public void TestNullableDateTimeOffsetViaSurrogate()
        {
            var bar = new Bar {
                X = DateTimeOffset.Now
            };
            var model = TypeModel.Create();

            model.Add(typeof(DateTimeOffset), false).SetSurrogate(typeof(DateTimeOffsetSurrogate));
            model.AutoCompile = false;

            var clone = (Bar)model.DeepClone(bar);

            Assert.Equal(bar.X, clone.X); //, "runtime");

            model.CompileInPlace();
            clone = (Bar)model.DeepClone(bar);
            Assert.Equal(bar.X, clone.X); //, "CompileInPlace");

            clone = (Bar)model.Compile().DeepClone(bar);
            Assert.Equal(bar.X, clone.X); //, "Compile");
        }
Beispiel #27
0
        public void TestTagWithInferenceRoundtrip()
        {
            TagData data = new TagData
            {
                Bravo   = 15,
                Charlie = 17,
                Delta   = 4,
                Zulu    = 9
            };
            var tm = TypeModel.Create();

            // for compatibility with DataMember
            //tm.SkipForcedAdvancedVersioning = true;

            TagData clone = tm.DeepClone(data);

            Assert.AreEqual(data.Bravo, clone.Bravo, "Bravo");
            Assert.AreEqual(data.Charlie, clone.Charlie, "Charlie");
            Assert.AreEqual(data.Delta, clone.Delta, "Delta");
            Assert.AreEqual(data.Zulu, clone.Zulu, "Zulu");
        }
        /// <summary>
        /// Deserializes a tags collection from a byte array.
        /// </summary>
        /// <param name="tagsBytes"></param>
        /// <returns></returns>
        public TagsCollectionBase Deserialize(byte[] tagsBytes)
        {
            RuntimeTypeModel typeModel = TypeModel.Create();

            typeModel.Add(typeof(List <KeyValuePair <string, string> >), true);

            List <KeyValuePair <string, string> > tagsList = null;

            using (MemoryStream stream = new MemoryStream(tagsBytes))
            {
                tagsList = typeModel.Deserialize(stream, null, typeof(List <KeyValuePair <string, string> >)) as List <KeyValuePair <string, string> >;
            }

            TagsCollection tagsCollection = new TagsCollection();

            foreach (KeyValuePair <string, string> tag in tagsList)
            {
                tagsCollection.Add(tag.Key, tag.Value);
            }
            return(tagsCollection);
        }
Beispiel #29
0
        public void should_serialize_and_deserialize_type_with_identity_field()
        {
            var school = new School()
            {
                Id   = new SchoolId("school-49"),
                Name = "Minsk",
                Year = 56,
            };

            var model = TypeModel.Create();

            model[typeof(StringId)]
            .AddSubType(6, typeof(SchoolId));

            var bytes = ProtobufSerializer.SerializeProtocalBuffer(school, model);
            var back  = ProtobufSerializer.DeserializeProtocalBuffer <School>(bytes, model);

            Assert.That(back.Id.Value, Is.EqualTo(school.Id.Value));
            Assert.That(back.Name, Is.EqualTo(school.Name));
            Assert.That(back.Year, Is.EqualTo(school.Year));
        }
Beispiel #30
0
        public void TestRoundtripEnum()
        {
            var typeModel   = Roundtrip(TypeModel.Create(new[] { typeof(Int32Enum) }));
            var description = typeModel.GetTypeDescription <Int32Enum>();

            description.Classification.Should().Be(TypeClassification.Enum);
            description.Name.Should().Be("Int32Enum");
            description.Namespace.Should().Be("IsabelDb.Test.Entities");
            description.Fields.Should().HaveCount(3, "because the enum has 3 members");
            description.Fields[0].Name.Should().Be("A");
            description.Fields[0].MemberId.Should().Be(0);
            description.Fields[1].Name.Should().Be("B");
            description.Fields[1].MemberId.Should().Be(1);
            description.Fields[2].Name.Should().Be("C");
            description.Fields[2].MemberId.Should().Be(2);

            var other = description.UnderlyingEnumTypeDescription;

            other.Should().NotBeNull();
            other.ResolvedType.Should().Be <int>();
        }