Example #1
0
        public void Teach(RuntimeTypeModel model)
        {
            MetaType meta = model.Add(typeof(Microsoft.Xna.Framework.Point), false);

            meta.Add(1, "X");
            meta.Add(2, "Y");
        }
Example #2
0
        public void Teach(RuntimeTypeModel model)
        {
            MetaType meta = model.Add(typeof(Point2D), false);

            meta.Add(1, "X");
            meta.Add(2, "Y");
        }
Example #3
0
 public void ApplyTo(MetaType metaType)
 {
     if (_defaultValue == null)
     {
         metaType.Add(_fieldNumber, _memberName);
     }
     else
     {
         metaType.Add(_fieldNumber, _memberName, _defaultValue);
     }
 }
            /// <summary>
            /// Builds the runtime type model.
            /// </summary>
            /// <param name="typeModel"></param>
            protected override void BuildRuntimeTypeModel(RuntimeTypeModel typeModel)
            {
                MetaType collectionMetaType =
                    typeModel.Add(typeof(PrimitivesCollection), false);

                collectionMetaType.Add(1, "Data");
                collectionMetaType.Add(2, "MinX");
                collectionMetaType.Add(3, "MaxX");
                collectionMetaType.Add(4, "MinY");
                collectionMetaType.Add(5, "MaxY");
            }
Example #5
0
 public void Initialize(MetaType meta)
 {
     foreach (var configuration in _configurations.OrderBy(x => x.Order))
     {
         meta.Add(configuration.Order, configuration.Name);
     }
 }
Example #6
0
        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");
        }
Example #7
0
        public void Execute()
        {
            var      model = TypeModel.Create();
            MetaType t     = model.Add(typeof(hierarchy.B), false);

            t.Add("prop1", "prop2");
            // default for nullable type is minimal enhancement mode
            // flat will have them set same way
            t[1].SetSettings(x => x.V.Format = ValueFormat.MinimalEnhancement);
            t[2].SetSettings(x => x.V.Format = ValueFormat.MinimalEnhancement);

            var hb = new hierarchy.B();

            hb.prop1 = "prop1";
            hb.prop2 = "prop2";

            var ms = new MemoryStream();

            model.Serialize(ms, hb);
            var schemaHierarchy = model.GetDebugSchema(typeof(hierarchy.B));
            var schemaFlat      = model.GetDebugSchema(typeof(flat.B));

            ms.Position = 0;
            var flatB = Serializer.Deserialize <flat.B>(ms);

            Assert.AreEqual("prop1", hb.prop1);
            Assert.AreEqual("prop2", hb.prop2);
            Assert.AreEqual("prop1", flatB.prop1);
            Assert.AreEqual("prop2", flatB.prop2);
            Assert.AreEqual("prop1=prop1, prop2=prop2", hb.ToString());
            Assert.AreEqual("prop1=prop1, prop2=prop2", flatB.ToString());
        }
Example #8
0
        public static void RegisterCustomTypes()
        {
            // Add vector2 de/serialization support:
            if (!ProtoBuf.Meta.RuntimeTypeModel.Default.IsDefined(typeof(Vector2)))
            {
                MetaType metaType = ProtoBuf.Meta.RuntimeTypeModel.Default.Add(typeof(Vector2), applyDefaultBehaviour: false);
                metaType.Add("x", "y");
            }

            // Add vector3 de/serialization support:
            if (!ProtoBuf.Meta.RuntimeTypeModel.Default.IsDefined(typeof(Vector3)))
            {
                MetaType metaType = ProtoBuf.Meta.RuntimeTypeModel.Default.Add(typeof(Vector3), applyDefaultBehaviour: false);
                metaType.Add("x", "y", "z");
            }

            // Add vector4 de/serialization support:
            if (!ProtoBuf.Meta.RuntimeTypeModel.Default.IsDefined(typeof(Vector4)))
            {
                MetaType metaType = ProtoBuf.Meta.RuntimeTypeModel.Default.Add(typeof(Vector4), applyDefaultBehaviour: false);
                metaType.Add("x", "y", "z", "w");
            }

            // Append any other types here as needed
        }
Example #9
0
 private static void AddProperties(Type type, MetaType metaType)
 {
     foreach (var property in type.GetTypeInfo().DeclaredProperties)
     {
         metaType.Add(NextTypePropertyIndex(type), property.Name);
     }
 }
Example #10
0
 private static void LoadProtoTypeMember(Type myEntity, List <PropertyInfo> Properties, MetaType metaType, List <FieldInfo> Fields)
 {
     Properties.ForEach((o) =>
     {
         try
         {
             var fieldNumber = (o.GetCustomAttributes(typeof(ProtoMemberAttribute), false)[0] as ProtoMemberAttribute).Tag;
             if (metaType[fieldNumber] == null)
             {
                 metaType.Add(fieldNumber, o.Name);
             }
         }
         //忽略异常
         catch (Exception ex)
         {
             TraceLog.WriteError("Loading protobuf type \"{0}.{1}\" property error:{2}", myEntity.FullName, o.Name, ex);
         }
     });
     Fields.ForEach((o) =>
     {
         try
         {
             var fieldNumber = (o.GetCustomAttributes(typeof(ProtoMemberAttribute), false)[0] as ProtoMemberAttribute).Tag;
             if (metaType[fieldNumber] == null)
             {
                 metaType.AddField(fieldNumber, o.Name);
             }
         }
         //忽略异常
         catch (Exception ex)
         {
             TraceLog.WriteError("Loading protobuf type \"{0}.{1}\" field error:{2}", myEntity.FullName, o.Name, ex);
         }
     });
 }
Example #11
0
        public static void Serialize <T>(IThing microdataThing) where T : IThing
        {
            RuntimeTypeModel model     = TypeModel.Create();
            MetaType         metaType1 = model.Add(typeof(T), false);

            metaType1.Add(1, "Ancestors")
            .Add(2, "Properties")
            .Add(3, "Schema_Org_Url")
            .Add(4, "SubTypes")
            .Add(5, "SuperTypes")
            .Add(6, "TypeId")
            .Add(7, "Id")
            .Add(8, "Label");

            //Description
            MetaType metaTypeForDescription = model.Add(typeof(Description_Core), false);

            metaTypeForDescription.Add(9, "Id")
            .Add(1, "Label")
            .Add(2, "Domains")
            .Add(3, "PropertyId")
            .Add(4, "Ranges");

            //Image_Core Image
            MetaType metaTypeForImage = model.Add(typeof(Image_Core), false);

            metaTypeForImage.Add(14, "Id")
            .Add(1, "Label")
            .Add(2, "Domains")
            .Add(3, "PropertyId")
            .Add(4, "Ranges");

            //Name_Core Name
            MetaType metaTypeForName = model.Add(typeof(Name_Core), false);

            metaTypeForName.Add(19, "Id")
            .Add(1, "Label")
            .Add(2, "Domains")
            .Add(3, "PropertyId")
            .Add(4, "Ranges");

            //Properties.URL_Core
            MetaType metaTypeForURL = model.Add(typeof(URL_Core), false);

            metaTypeForURL.Add(24, "Id")
            .Add(1, "Label")
            .Add(2, "Domains")
            .Add(3, "PropertyId")
            .Add(4, "Ranges");

            int tagIndex = 29;

            for (int i = 0; i < microdataThing.Properties.Length; i++)
            {
                tagIndex++;
            }
        }
    protected virtual void FillModel()
    {
        Model = RuntimeTypeModel.Create();
        Model.Add(typeof(Family), false)
        .SetSurrogate(typeof(FamilySurrogate));
        MetaType mt = Model[typeof(FamilySurrogate)];

        mt.Add(1, "People");                 // This is a list of Person of course
        //mt.AddField(2, "FamilyHead").AsReference = true;  // Exception "A reference-tracked object changed reference during deserialization" - because using surrogate.
        mt.Add(2, "FamilyHead");
        mt.UseConstructor = false;
        Model.Add(typeof(Person), false)
        .SetSurrogate(typeof(PersonSurrogate));
        mt = Model[typeof(PersonSurrogate)]
             .Add(1, "Name")
             .Add(2, "Gender")
             .Add(3, "ReferenceId");
        mt.UseConstructor = false;                 // Avoids to use the parameter-less constructor.
    }
 public override void RegisterMetaType(MetaType type)
 {
     if (type.Type == typeof(Vector2))
     {
         type.Add("x", "y");
     }
     if (type.Type == typeof(Vector3))
     {
         type.Add("x", "y", "z");
     }
     if (type.Type == typeof(Vector4))
     {
         type.Add("x", "y", "z", "w");
     }
     if (type.Type == typeof(Quaternion))
     {
         type.Add("x", "y", "z", "w");
     }
     if (type.Type == typeof(Color))
     {
         type.Add("r", "g", "b", "a");
     }
 }
Example #14
0
        protected virtual void ApplyDefaultBehaviour(MetaType metaType, MappedMember mappedMember, int?implicitFirstTag)
        {
            MemberInfo member;

            if (mappedMember == null || (member = mappedMember.Member) == null)
            {
                return;                                                                 // nix
            }
            var s = mappedMember.MappingState;

            AttributeMap[] attribs = AttributeMap.Create(Model, member, true);
            AttributeMap   attrib;

            if (s.SerializationSettings.DefaultValue == null && (attrib = AttributeMap.GetAttribute(attribs, "System.ComponentModel.DefaultValueAttribute")) != null)
            {
                object tmp;
                if (attrib.TryGet("Value", out tmp))
                {
                    var m = s.MainValue;
                    s.SerializationSettings.DefaultValue = tmp;
                    s.MainValue = m;
                }
            }

            {
                var level0 = mappedMember.MappingState.SerializationSettings.GetSettingsCopy(0).Basic;
                {
                    Type defaultType = level0.Collection.ConcreteType;
                    if (defaultType == null)
                    {
                        var memberType = level0.EffectiveType ?? Helpers.GetMemberType(mappedMember.Member);
                        if (Helpers.IsInterface(memberType) || Helpers.IsAbstract(memberType))
                        {
                            level0.Collection.ConcreteType = FindDefaultInterfaceImplementation(memberType);
                        }
                    }
                }
                mappedMember.MappingState.SerializationSettings.SetSettings(level0, 0);
            }

            if (implicitFirstTag != null && !s.TagIsPinned)
            {
                mappedMember.Tag = metaType.GetNextFreeFieldNumber(implicitFirstTag.Value);
            }

            if (mappedMember.MappingState.Input.IsEnumValueMember || mappedMember.Tag > 0)
            {
                metaType.Add(mappedMember);
            }
        }
Example #15
0
        private static void RegisterType(Type dataContractType)
        {
            HandleSurrogateType(dataContractType);

            // Disable default handling of that type
            MetaType metaType = RuntimeTypeModel.Default.Add(dataContractType, false);

            // Get members with [DataMember] attribute
            var names = dataContractType
                        .GetMembers()
                        .Where(p => p.GetCustomAttribute <DataMemberAttribute>() != null)
                        .Select(property => property.Name);

            // Add these member names to serialization,
            names.ForEach(name => metaType.Add(name));
        }
        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");
        }
Example #17
0
        public void Initialize(bool isNeedInitProtobufTypeModel = true)
        {
            // Настраиваем поиск по полям.
            var builder = _changesSearcher.SearchBuilder <TModel>();

            foreach (var field in _fieldsInfos)
            {
                builder.Select(field.Key, field.Value.PropertyInfo.Name);
            }
            builder.Build();

            // Настраиваем Protobuf (если необходимо).
            if (isNeedInitProtobufTypeModel)
            {
                MetaType protoBuilder = _changesSearcher.ProtobufTypeModel.Add(typeof(TModel), false);
                foreach (var field in _fieldsInfos)
                {
                    protoBuilder.Add(field.Key, field.Value.PropertyInfo.Name);
                }
            }
        }
Example #18
0
        /// <summary>
        /// Adds a default protobuf data contract to the protobuf runtime model
        /// </summary>
        /// <param name="allTypes">All types available</param>
        /// <param name="type">The type to add to the model</param>
        private static void AddProtobufType(Type[] allTypes, Type type)
        {
            MetaType metaType = RuntimeTypeModel.Default.Add(type, true);

            string[] memberNames = (from pi in type.GetProperties()
                                    where pi.CanWrite
                                    select pi.Name).ToArray();

            metaType.Add(memberNames);

            int index = memberNames.Length;

            // add subtypes
            foreach (Type allType in allTypes)
            {
                if (allType.IsSubclassOf(type))
                {
                    metaType.AddSubType(++index, allType);
                }
            }
        }
Example #19
0
        /// <summary>
        /// Builds the runtime type model.
        /// </summary>
        /// <param name="typeModel"></param>
        protected override void BuildRuntimeTypeModel(RuntimeTypeModel typeModel)
        {
            typeModel.Add(typeof(PrimitivesCollection), true);
            MetaType iconMetaType = typeModel.Add(typeof(Icon2D), false);

            iconMetaType.Add(1, "X");
            iconMetaType.Add(2, "Y");
            iconMetaType.Add(3, "Image");
            iconMetaType.Add(4, "MinZoom");
            iconMetaType.Add(5, "MaxZoom");

            MetaType imagesMetaType = typeModel.Add(typeof(Image2D), false);

            imagesMetaType.Add(1, "ImageData");
            imagesMetaType.Add(2, "Left");
            imagesMetaType.Add(3, "Right");
            imagesMetaType.Add(4, "Top");
            imagesMetaType.Add(5, "Bottom");
            imagesMetaType.Add(6, "MinZoom");
            imagesMetaType.Add(7, "MaxZoom");

            MetaType lineMetaType = typeModel.Add(typeof(Line2D), false);

            lineMetaType.Add(1, "X");
            lineMetaType.Add(2, "Y");
            lineMetaType.Add(3, "Color");
            lineMetaType.Add(4, "Width");
            lineMetaType.Add(5, "LineJoin");
            lineMetaType.Add(6, "Dashes");
            lineMetaType.Add(7, "MinZoom");
            lineMetaType.Add(8, "MaxZoom");
            lineMetaType.Add(9, "MinX");
            lineMetaType.Add(10, "MaxX");
            lineMetaType.Add(11, "MinY");
            lineMetaType.Add(12, "MaxY");

            MetaType pointMetaType = typeModel.Add(typeof(Point2D), false);

            pointMetaType.Add(1, "X");
            pointMetaType.Add(2, "Y");
            pointMetaType.Add(3, "Color");
            pointMetaType.Add(4, "Size");
            pointMetaType.Add(5, "MinZoom");
            pointMetaType.Add(6, "MaxZoom");

            MetaType polygonMetaType = typeModel.Add(typeof(Polygon2D), false);

            polygonMetaType.Add(1, "X");
            polygonMetaType.Add(2, "Y");
            polygonMetaType.Add(3, "Color");
            polygonMetaType.Add(4, "Width");
            polygonMetaType.Add(5, "Fill");
            polygonMetaType.Add(6, "MinZoom");
            polygonMetaType.Add(7, "MaxZoom");
            polygonMetaType.Add(8, "MinX");
            polygonMetaType.Add(9, "MaxX");
            polygonMetaType.Add(10, "MinY");
            polygonMetaType.Add(11, "MaxY");

            MetaType textMetaType = typeModel.Add(typeof(Text2D), false);

            textMetaType.Add(1, "X");
            textMetaType.Add(2, "Y");
            textMetaType.Add(3, "Text");
            textMetaType.Add(4, "Size");
            textMetaType.Add(5, "MinZoom");
            textMetaType.Add(6, "MaxZoom");
            textMetaType.Add(7, "HaloRadius");
            textMetaType.Add(8, "HaloColor");
            textMetaType.Add(9, "Color");

            MetaType lineTextMetaType = typeModel.Add(typeof(LineText2D), false);

            lineTextMetaType.Add(1, "X");
            lineTextMetaType.Add(2, "Y");
            lineTextMetaType.Add(3, "Text");
            lineTextMetaType.Add(4, "Color");
            lineTextMetaType.Add(5, "Size");
            lineTextMetaType.Add(6, "MinZoom");
            lineTextMetaType.Add(7, "MaxZoom");
            lineTextMetaType.Add(8, "MinX");
            lineTextMetaType.Add(9, "MaxX");
            lineTextMetaType.Add(10, "MinY");
            lineTextMetaType.Add(11, "MaxY");
            lineTextMetaType.Add(12, "HaloRadius");
            lineTextMetaType.Add(13, "HaloColor");

            typeModel.Add(typeof(Icon2DEntry), true);
            typeModel.Add(typeof(Image2DEntry), true);
            typeModel.Add(typeof(Line2DEntry), true);
            typeModel.Add(typeof(Point2DEntry), true);
            typeModel.Add(typeof(Polygon2DEntry), true);
            typeModel.Add(typeof(Text2DEntry), true);
            typeModel.Add(typeof(LineText2DEntry), true);
        }
Example #20
0
        private bool InternalRegister(Type typeToRegister)
        {
            //Ok so here the fun begins.
            //We need a recursive algorithm for walking the graph of the Type to register each
            //serializable type. So, for every member we must look down into that Type recursively and register it.
            //However, we must make sure to check if it's already been registered or we might get circular graphs which
            //would overflow. But that'd be a weird type anyway.

            if (typeToRegister == null)
            {
                throw new ArgumentNullException(nameof(typeToRegister), $"Provided {typeToRegister} is a null arg.");
            }

            //Can't use isDefined exclusively but it'll fail when doing two-way subtypes
            if (registeredTypes.ContainsKey(typeToRegister))
            {
                return(true);
            }

            if (typeof(IEnumerable).IsAssignableFrom(typeToRegister) || typeToRegister.IsArray)
            {
                if (typeToRegister.IsArray)
                {
                    Register(typeToRegister.GetElementType());
                }
                else
                {
                    foreach (var gparam in typeToRegister.GetGenericArguments())
                    {
                        Register(gparam);
                    }
                }
            }

            //if (RuntimeTypeModel.Default.IsDefined(typeToRegister))
            //	return true;


            if (typeToRegister.IsEnum)
            {
                MetaType enumMetaType = RuntimeTypeModel.Default.Add(typeToRegister, false);
                enumMetaType.EnumPassthru       = true;
                enumMetaType.AsReferenceDefault = false;

                return(true);
            }

            //If it's not defined we need to add it.
            if (typeToRegister.Attribute <GladNetSerializationContractAttribute>() == null)
            {
                return(false);
            }

            MetaType typeModel = RuntimeTypeModel.Default.Add(typeToRegister, false);

            //Add each member
            foreach (MemberInfo mi in typeToRegister.MembersWith <GladNetMemberAttribute>(MemberTypes.Field | MemberTypes.Property, Flags.InstanceAnyDeclaredOnly))            //keep this declare only because of Unity3D serialization issues with NetSendable
            {
                typeModel.Add(mi.Attribute <GladNetMemberAttribute>().TagID, mi.Name);

                //Now we might need to register this type aswell.
                //Recur to try to register this type
                Register(mi.Type());
            }

            //If might have a include on it so we should check it to register it with the subtype

            IEnumerable <GladNetSerializationIncludeAttribute> includes = typeToRegister.Attributes <GladNetSerializationIncludeAttribute>();

            foreach (GladNetSerializationIncludeAttribute include in includes)
            {
                //if we don't know about the type register it
                if (!registeredTypes.ContainsKey(include.TypeToWireTo))
                {
                    Register(include.TypeToWireTo);
                }

                //this is the simple case; however unlike protobuf we support two-include
                if (include != null && include.IncludeForDerived)
                {
                    if (include.TypeToWireTo == typeModel.Type || !typeModel.Type.IsAssignableFrom(include.TypeToWireTo))
                    {
                        continue;
                    }
                    else
                    {
                        typeModel.AddSubType(include.TagID, include.TypeToWireTo);
                    }
                }
                else
                if (include != null && !include.IncludeForDerived)
                {
                    //this is not for mappping a base type to setup mapping for its child
                    //we need to map this child to its base
                    //so we need to get the MetaType for it
                    RuntimeTypeModel.Default[include.TypeToWireTo]
                    .AddSubType(include.TagID, typeToRegister);
                }
            }

            registeredTypes.Add(typeToRegister, null);

            return(true);
        }