public void TestSystem()
        {
            SerializableAttribute sa = new SerializableAttribute();

            Assert(sa.GetType().IsSubclassOf(typeof(System.Attribute)));
            NonSerializedAttribute nsa = new NonSerializedAttribute();

            Assert(nsa.GetType().IsSubclassOf(typeof(System.Attribute)));

            //just make sure the definition is in the right place
            System.Runtime.Serialization.ISerializable iSerial = null;
            AreEqual(iSerial, null);

            AreEqual(StringSplitOptions.None.ToString("D"), "0");
            AreEqual(StringSplitOptions.RemoveEmptyEntries.ToString("D"), "1");

            AreEqual(ConsoleColor.Black.ToString("D"), "0");
            AreEqual(ConsoleColor.DarkBlue.ToString("D"), "1");
            AreEqual(ConsoleColor.DarkGreen.ToString("D"), "2");
            AreEqual(ConsoleColor.DarkCyan.ToString("D"), "3");
            AreEqual(ConsoleColor.DarkRed.ToString("D"), "4");
            AreEqual(ConsoleColor.DarkMagenta.ToString("D"), "5");
            AreEqual(ConsoleColor.DarkYellow.ToString("D"), "6");
            AreEqual(ConsoleColor.Gray.ToString("D"), "7");
            AreEqual(ConsoleColor.DarkGray.ToString("D"), "8");
            AreEqual(ConsoleColor.Blue.ToString("D"), "9");
            AreEqual(ConsoleColor.Green.ToString("D"), "10");
            AreEqual(ConsoleColor.Cyan.ToString("D"), "11");
            AreEqual(ConsoleColor.Red.ToString("D"), "12");
            AreEqual(ConsoleColor.Magenta.ToString("D"), "13");
            AreEqual(ConsoleColor.Yellow.ToString("D"), "14");
            AreEqual(ConsoleColor.White.ToString("D"), "15");
        }
        public static MemberSerialization GetObjectMemberSerialization(Type objectType, bool ignoreSerializableAttribute)
        {
            JsonObjectAttribute objectAttribute = GetJsonObjectAttribute(objectType);

            if (objectAttribute != null)
            {
                return(objectAttribute.MemberSerialization);
            }

#if !PocketPC && !NET20
            DataContractAttribute dataContractAttribute = GetDataContractAttribute(objectType);
            if (dataContractAttribute != null)
            {
                return(MemberSerialization.OptIn);
            }
#endif

#if !(SILVERLIGHT || NETFX_CORE || PORTABLE)
            if (!ignoreSerializableAttribute)
            {
                SerializableAttribute serializableAttribute = GetSerializableAttribute(objectType);
                if (serializableAttribute != null)
                {
                    return(MemberSerialization.Fields);
                }
            }
#endif

            // the default
            return(MemberSerialization.OptOut);
        }
        public void ObjectNotTypeTest__SerializableAttributeCastToAbstractProductCallInvalidCastException()
        {
            var    obj     = new SerializableAttribute();
            string message = "Problem";

            ValidationHelper.ObjectNotType <AbstractGood>(obj, message);
        }
Exemple #4
0
        public static MemberSerialization GetObjectMemberSerialization(Type objectType, bool ignoreSerializableAttribute)
        {
            JsonObjectAttribute objectAttribute = GetCachedAttribute <JsonObjectAttribute>(objectType);

            if (objectAttribute != null)
            {
                return(objectAttribute.MemberSerialization);
            }

#if !NET20
            DataContractAttribute dataContractAttribute = GetDataContractAttribute(objectType);
            if (dataContractAttribute != null)
            {
                return(MemberSerialization.OptIn);
            }
#endif

#if !(DOTNET || PORTABLE40 || PORTABLE)
            if (!ignoreSerializableAttribute)
            {
                SerializableAttribute serializableAttribute = GetCachedAttribute <SerializableAttribute>(objectType);
                if (serializableAttribute != null)
                {
                    return(MemberSerialization.Fields);
                }
            }
#endif

            // the default
            return(MemberSerialization.OptOut);
        }
Exemple #5
0
        private static object[]? GetPseudoCustomAttributes(Type type)
        {
            int            count      = 0;
            TypeAttributes Attributes = type.Attributes;

            /* IsSerializable returns true for delegates/enums as well */
            if ((Attributes & TypeAttributes.Serializable) != 0)
            {
                count++;
            }
            if ((Attributes & TypeAttributes.Import) != 0)
            {
                count++;
            }

            if (count == 0)
            {
                return(null);
            }
            object[] attrs = new object[count];
            count = 0;

            if ((Attributes & TypeAttributes.Serializable) != 0)
            {
                attrs[count++] = new SerializableAttribute();
            }
            if ((Attributes & TypeAttributes.Import) != 0)
            {
                attrs[count++] = new ComImportAttribute();
            }

            return(attrs);
        }
Exemple #6
0
        public static MemberSerialization GetObjectMemberSerialization(Type objectType, bool ignoreSerializableAttribute)
        {
            JsonObjectAttribute objectAttribute = GetCachedAttribute <JsonObjectAttribute>(objectType);

            if (objectAttribute != null)
            {
                return(objectAttribute.MemberSerialization);
            }

            DataContractAttribute dataContractAttribute = GetDataContractAttribute(objectType);

            if (dataContractAttribute != null)
            {
                return(MemberSerialization.OptIn);
            }

            if (!ignoreSerializableAttribute)
            {
                SerializableAttribute serializableAttribute = GetCachedAttribute <SerializableAttribute>(objectType);
                if (serializableAttribute != null)
                {
                    return(MemberSerialization.Fields);
                }
            }

            // the default
            return(MemberSerialization.OptOut);
        }
Exemple #7
0
        /// <summary>
        /// 对象是否能序列化
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static bool IsSerializable(object obj)
        {
            if (obj == null)
            {
                return(false);
            }
            Type type          = obj.GetType();
            Type attributeType = typeof(SerializableAttribute);
            SerializableAttribute attribute = null;

            if (!(attributeType.IsSubclassOf(typeof(Attribute))))
            {
                return(false);
            }
            if (type.IsDefined(attributeType, false))
            {
                object[] attributes = type.GetCustomAttributes(attributeType, false);
                if (attributes.Length > 0)
                {
                    attribute = (SerializableAttribute)attributes[0];
                }
            }
            if (attribute != null)
            {
                return(true);
            }
            return(false);
        }
        public static MemberSerialization GetObjectMemberSerialization(Type objectType, bool ignoreSerializableAttribute)
        {
            JsonObjectAttribute objectAttribute = GetCachedAttribute <JsonObjectAttribute>(objectType);

            if (objectAttribute != null)
            {
                return(objectAttribute.MemberSerialization);
            }

#if HAVE_DATA_CONTRACTS
            DataContractAttribute dataContractAttribute = GetDataContractAttribute(objectType);
            if (dataContractAttribute != null)
            {
                return(MemberSerialization.OptIn);
            }
#endif

#if HAVE_BINARY_SERIALIZATION
            if (!ignoreSerializableAttribute)
            {
                SerializableAttribute serializableAttribute = GetCachedAttribute <SerializableAttribute>(objectType);
                if (serializableAttribute != null)
                {
                    return(MemberSerialization.Fields);
                }
            }
#endif

            // the default
            return(MemberSerialization.OptOut);
        }
        public void SerializableAttributeTest()
        {
            // Se comprueba la presencia del atributo  [Serializable]
            SerializableAttribute att =
                (SerializableAttribute)Attribute.GetCustomAttribute(typeof(SystemConfigData), typeof(SerializableAttribute));

            Assert.IsNotNull(att);
        }
        internal static bool IsDefined(RuntimeType type, Type caType)
        {
            int  num;
            bool flag = (caType == typeof(object)) || (caType == typeof(Attribute));

            if ((!flag && (s_pca[caType] == null)) && !IsSecurityAttribute(caType))
            {
                return(false);
            }
            return(((flag || (caType == typeof(SerializableAttribute))) && SerializableAttribute.IsDefined(type)) || (((flag || (caType == typeof(ComImportAttribute))) && ComImportAttribute.IsDefined(type)) || ((flag || IsSecurityAttribute(caType)) && (GetCustomAttributes(type, caType, true, out num).Length != 0))));
        }
        public void Test_Type1Attribute()
        {
            Type1Attribute a = typeof(AttributeClass1).GetMyAttribute <Type1Attribute>();

            Assert.AreEqual("20e00d57-fc17-4e90-8b93-8b0d1a51ed3f", a.Flag);


            SerializableAttribute sa = typeof(AttributeClass1).GetMyAttribute <SerializableAttribute>();

            Assert.IsNull(sa);
        }
Exemple #12
0
        /// <summary>
        /// Implements <see cref="ISerializable.GetObjectData"/>
        /// </summary>
        /// <param name="info">The <see cref="System.Runtime.Serialization.SerializationInfo"/> to populate with data.</param>
        /// <param name="context">The destination (<see cref="System.Runtime.Serialization.StreamingContext"/>) for this serialization.</param>
        public void GetObjectData(SerializationInfo info, StreamingContext context)
        {
            foreach (KeyValuePair <string, object> de in data)
            {   // es wird alles so geschrieben und nicht die Hashtable direkt abgespeichert
                // damit man beim Einlesen bessere Möglichkeiten hat, Fehler zu unterdrücken
                if (de.Value != null && !de.Value.GetType().IsGenericType)
                {
                    // so kann man feststellen, ob de.Value serialisierbar ist
                    SerializableAttribute sa = (SerializableAttribute)System.Attribute.GetCustomAttribute(de.Value.GetType(), typeof(SerializableAttribute));
                    if (sa != null)
                    {
                        info.AddValue(de.Key, de.Value, de.Value.GetType());
                    }
                    else if (de.Value is object[])
                    {
                        info.AddValue(de.Key, de.Value, de.Value.GetType()); // geht auch so bei object[]
                        //object[] oa = de.Value as object[];
                        //bool isString = true;
                        //for (int i = 0; i < oa.Length; i++)
                        //{
                        //    if (!(oa[i] is string)) isString = false;
                        //}
                        //if (isString)
                        //{
                        //    string[] sta = new string[oa.Length];
                        //    for (int i = 0; i < oa.Length; i++)
                        //    {
                        //        sta[i] = oa[i] as string;
                        //    }
                        //    SerializableAttribute dbg = (SerializableAttribute)System.Attribute.GetCustomAttribute(sta.GetType(), typeof(SerializableAttribute));
                        //    info.AddValue(de.Key, sta, sta.GetType());
                        //}
                    }
                    else if (de.Value.GetType().IsArray)
                    {
                        sa = (SerializableAttribute)System.Attribute.GetCustomAttribute(de.Value.GetType().GetElementType(), typeof(SerializableAttribute));
                        if (sa != null)
                        {
                            info.AddValue(de.Key, de.Value, de.Value.GetType());
                        }
                    }
#if DEBUG
                    if (de.Key == "SortingIndex")
                    {
                        System.Diagnostics.Trace.WriteLine("Writing: SortingIndex: " + de.Value.ToString());
                    }
#endif
                }
            }
        }
        internal static Attribute[] GetCustomAttributes(RuntimeType type, Type caType, bool includeSecCa, out int count)
        {
            count = 0;
            bool flag = (caType == typeof(object)) || (caType == typeof(Attribute));

            if ((!flag && (s_pca[caType] == null)) && !IsSecurityAttribute(caType))
            {
                return(new Attribute[0]);
            }
            List <Attribute> list = new List <Attribute>();
            Attribute        item = null;

            if (flag || (caType == typeof(SerializableAttribute)))
            {
                item = SerializableAttribute.GetCustomAttribute(type);
                if (item != null)
                {
                    list.Add(item);
                }
            }
            if (flag || (caType == typeof(ComImportAttribute)))
            {
                item = ComImportAttribute.GetCustomAttribute(type);
                if (item != null)
                {
                    list.Add(item);
                }
            }
            if ((includeSecCa && (flag || IsSecurityAttribute(caType))) && !type.IsGenericParameter)
            {
                object[] objArray;
                if (type.IsGenericType)
                {
                    type = (RuntimeType)type.GetGenericTypeDefinition();
                }
                GetSecurityAttributes(type.Module.ModuleHandle, type.MetadataToken, out objArray);
                if (objArray != null)
                {
                    foreach (object obj2 in objArray)
                    {
                        if ((caType == obj2.GetType()) || obj2.GetType().IsSubclassOf(caType))
                        {
                            list.Add((Attribute)obj2);
                        }
                    }
                }
            }
            count = list.Count;
            return(list.ToArray());
        }
        public void AttributesTest()
        {
            SerializableAttribute serializable_attr = new SerializableAttribute();
            FlagsAttribute        flags_attr        = new FlagsAttribute();

            CustomAttributeCollection attr_coll = new CustomAttributeCollection(serializable_attr, flags_attr);

            Attribute [] attributes = attr_coll.GetAttributes();
            Assert.AreEqual(true, attributes != null, "#A0");
            Assert.AreEqual(2, attributes.Length, "#A1");

            // The property is supposed to be giving us the same instance in all the invocations
            Assert.AreSame(attributes, attr_coll.GetAttributes(), "#A2");
        }
        private static List <FieldInfo> GetFields(Type type, BindingFlags flag, List <FieldInfo> list = null)
        {
            SerializableAttribute serializable = type.GetAttributeValue <SerializableAttribute> ();

            if (serializable != null)
            {
                flag = BindingFlags.NonPublic | BindingFlags.Public;
            }

            FieldInfo[] fieldInfos = type.GetFields(BindingFlags.Instance | flag);
            if (serializable != null)
            {
                if (list == null)
                {
                    list = new List <FieldInfo> ();
                }

                for (int i = 0; i < fieldInfos.Length; i++)
                {
                    if (fieldInfos [i].IsPrivate)
                    {
                        if (fieldInfos [i].GetAttributeValue <SerializeField> () == null)
                        {
                            continue;
                        }
                    }

                    list.Add(fieldInfos [i]);
                }

                return(list);
            }

            if (list == null)
            {
                list = new List <FieldInfo> (fieldInfos);
            }
            else
            {
                list.AddRange(fieldInfos);
            }

            if (!(type.BaseType is System.Object))
            {
                return(GetFields(type.BaseType, flag, list));
            }

            return(list);
        }
Exemple #16
0
        internal static Attribute[] GetCustomAttributes(RuntimeType type, RuntimeType caType, bool includeSecCa, out int count)
        {
            count = 0;
            bool flag = caType == (RuntimeType)typeof(object) || caType == (RuntimeType)typeof(Attribute);

            if (!flag && PseudoCustomAttribute.s_pca.GetValueOrDefault(caType) == null && !PseudoCustomAttribute.IsSecurityAttribute(caType))
            {
                return(new Attribute[0]);
            }
            List <Attribute> list = new List <Attribute>();

            if (flag || caType == (RuntimeType)typeof(SerializableAttribute))
            {
                Attribute customAttribute = SerializableAttribute.GetCustomAttribute(type);
                if (customAttribute != null)
                {
                    list.Add(customAttribute);
                }
            }
            if (flag || caType == (RuntimeType)typeof(ComImportAttribute))
            {
                Attribute customAttribute = ComImportAttribute.GetCustomAttribute(type);
                if (customAttribute != null)
                {
                    list.Add(customAttribute);
                }
            }
            if (includeSecCa && (flag || PseudoCustomAttribute.IsSecurityAttribute(caType)) && !type.IsGenericParameter && type.GetElementType() == null)
            {
                if (type.IsGenericType)
                {
                    type = (RuntimeType)type.GetGenericTypeDefinition();
                }
                object[] array;
                PseudoCustomAttribute.GetSecurityAttributes(type.Module.ModuleHandle.GetRuntimeModule(), type.MetadataToken, false, out array);
                if (array != null)
                {
                    foreach (object obj in array)
                    {
                        if (caType == obj.GetType() || obj.GetType().IsSubclassOf(caType))
                        {
                            list.Add((Attribute)obj);
                        }
                    }
                }
            }
            count = list.Count;
            return(list.ToArray());
        }
Exemple #17
0
        /// <summary>
        /// 将一个object对象序列化,返回一个byte[]
        /// </summary>
        /// <param name="obj">能序列化的对象</param>
        /// <returns></returns>
        public static byte[] ObjectToBytes <T>(T obj)
        {
            //检查传入的对象类是否有【Serializable】属性
            System.Reflection.MemberInfo info = typeof(T);
            SerializableAttribute        serializableAttribute = (SerializableAttribute)Attribute.GetCustomAttribute(info, typeof(SerializableAttribute));

            if (serializableAttribute != null)
            {
                using (MemoryStream ms = new MemoryStream())
                {
                    IFormatter formatter = new BinaryFormatter(); formatter.Serialize(ms, obj); return(ms.GetBuffer());
                }
            }
            else
            {
                return(null);
            }
        }
Exemple #18
0
        public void TestHeaderGeneration()
        {
            ProjectMappingManagerSetup.InitializeManager(ServiceProvider, "ProjectMapping.DataContractDsl.Tests.xml");

            DataContract rootElement = CreateDefaultDataContract();
            string       content     = RunTemplate(rootElement);

            Type generatedType = CompileAndGetType(content);

            Assert.AreEqual <string>(ElementName, generatedType.Name);
            SerializableAttribute serializableAttr = TypeAsserter.AssertAttribute <System.SerializableAttribute>(generatedType);

            Assert.IsNotNull(serializableAttr);
            XmlRootAttribute xmlRootAttr = TypeAsserter.AssertAttribute <XmlRootAttribute>(generatedType);

            Assert.AreEqual <string>(ElementNamespace, xmlRootAttr.Namespace);
            Assert.IsFalse(xmlRootAttr.IsNullable);
        }
Exemple #19
0
        static internal void Serialize(ISerializable obj, SerializationInfo info, string name)
        {
            Type t = obj.GetType();

            System.Reflection.TypeInfo tt = System.Reflection.IntrospectionExtensions.GetTypeInfo(t);

            SerializableAttribute attr =
                System.Reflection.CustomAttributeExtensions.GetCustomAttribute <SerializableAttribute>(tt);

            if (attr == null)
            {
                throw new Exception("Object have no Serializable attribute");
            }
            MemoryStream    ms = new MemoryStream();
            BinaryFormatter bf = new BinaryFormatter();

            bf.Serialize(ms, obj);
            info.AddValue(name, ms.GetBuffer(), typeof(byte[]));
        }
Exemple #20
0
        //Precondition: File, Save book item are activated
        //Postcondition: The finder would open and the user is prompted to save the
        //file to a certain location
        private void saveLibraryToolStripMenuItem_Click(object sender, EventArgs e)
        {
            DialogResult result;
            string       libraryName;

            using (SaveFileDialog filechooser = new SaveFileDialog())
            {
                filechooser.CheckFileExists = false;
                result      = filechooser.ShowDialog();
                libraryName = filechooser.FileName;
            }
            //Precondition: The dialog result is valid
            //Postcondition: Serializes the file and saves it in the location
            if (result == DialogResult.OK)
            {
                //Precondition: The string is null or empty
                //Postcondition: The message box is displayed
                if (string.IsNullOrEmpty(libraryName))
                {
                    MessageBox.Show("Invalid file name!");
                }
                else
                {
                    try
                    {
                        output = new FileStream(libraryName, FileMode.OpenOrCreate, FileAccess.Write);
                        saveLibraryItem.Enabled = false;
                        openLibraryItem.Enabled = true;
                        var record = new SerializableAttribute();
                        reader.Serialize(output, record);
                    }
                    catch (IOException)
                    {
                        MessageBox.Show("Error opening file", "Error",
                                        MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    finally
                    {
                        output?.Close();
                    }
                }
            }
        }
Exemple #21
0
        static void CheckAttributes(Type type, ConsoleColor color)
        {
            Console.ForegroundColor = color;
            Console.WriteLine($"-> Class <{type.Name}>, serializable <{type.IsSerializable}>");

            Console.WriteLine($"Class attributes:");
            foreach (var attr in type.GetCustomAttributes(true))
            {
                VehicleDescriptionAttribute v = attr as VehicleDescriptionAttribute;
                if (v != null)
                {
                    Console.WriteLine($"  Description <{v.Description}>");
                }
                ObsoleteAttribute o = attr as ObsoleteAttribute;
                if (o != null)
                {
                    Console.WriteLine($"  Obsolete attribute message <{o.Message}>, is error <{o.IsError}>");
                }
                SerializableAttribute s = attr as SerializableAttribute;
                if (s != null)
                {
                    Console.WriteLine($"  Serializable default <{s.IsDefaultAttribute()}>");
                }
            }

            Console.WriteLine($"Method attributes:");
            foreach (var m in type.GetMethods())
            {
                foreach (var a in m.GetCustomAttributes(true))
                {
                    VehicleDescriptionAttribute v = a as VehicleDescriptionAttribute;
                    if (v != null)
                    {
                        Console.WriteLine($"  Method <{m.Name}>: Description <{v.Description}>");
                    }
                }
            }
        }
        // Token: 0x060015A8 RID: 5544 RVA: 0x000671EC File Offset: 0x000653EC
        public static Class_383 GetObjectMemberSerialization(Type objectType, bool ignoreSerializableAttribute)
        {
            Class_379 cachedAttribute = Class_470.GetCachedAttribute <Class_379>(objectType);

            if (cachedAttribute != null)
            {
                return(cachedAttribute.MemberSerialization);
            }
            DataContractAttribute dataContractAttribute = Class_470.GetDataContractAttribute(objectType);

            if (dataContractAttribute != null)
            {
                return(Class_383.OptIn);
            }
            if (!ignoreSerializableAttribute)
            {
                SerializableAttribute cachedAttribute2 = Class_470.GetCachedAttribute <SerializableAttribute>(objectType);
                if (cachedAttribute2 != null)
                {
                    return(Class_383.Fields);
                }
            }
            return(Class_383.OptOut);
        }
Exemple #23
0
        public static MemberSerialization GetObjectMemberSerialization(Type objectType, bool ignoreSerializableAttribute)
        {
            JsonObjectAttribute jsonObjectAttribute = JsonTypeReflector.GetJsonObjectAttribute(objectType);

            if (jsonObjectAttribute != null)
            {
                return(jsonObjectAttribute.MemberSerialization);
            }
            DataContractAttribute dataContractAttribute = JsonTypeReflector.GetDataContractAttribute(objectType);

            if (dataContractAttribute != null)
            {
                return(MemberSerialization.OptIn);
            }
            if (!ignoreSerializableAttribute)
            {
                SerializableAttribute serializableAttribute = JsonTypeReflector.GetSerializableAttribute(objectType);
                if (serializableAttribute != null)
                {
                    return(MemberSerialization.Fields);
                }
            }
            return(MemberSerialization.OptOut);
        }
        public void GetAttributeInstance_ReturnsSerializableAttribute_FromCookie()
        {
            SerializableAttribute actual = ReflectionExtensions.GetAttributeInstance <SerializableAttribute>(typeof(Cookie));

            Assert.IsNotNull(actual);
        }
                private static void BuildTypeMap()
                {
                    //Build list of types of classes / structs with the Serializable  attribute
                    if (_tagToTypeMap == null || _typeToTagMap == null || _converterMap == null)
                    {
                        _tagToTypeMap = new Dictionary <string, Type>();
                        _typeToTagMap = new Dictionary <Type, string>();
                        _converterMap = new Dictionary <Type, ObjectConverter>();

                        Assembly[] assemblies = SystemUtils.GetUnityAssemblies();

                        foreach (Assembly assembly in assemblies)
                        {
                            Type[] types = assembly.GetTypes();

                            //First build dictionary of types marked with [Serializable] attribute
                            foreach (Type type in types)
                            {
                                SerializableAttribute attribute = SystemUtils.GetAttribute <SerializableAttribute>(type);
                                if (attribute != null)
                                {
                                    string xmlTag = type.Name;

                                    if (type.IsGenericType)
                                    {
                                        string name  = type.Name;
                                        int    index = name.IndexOf('`');
                                        xmlTag = index == -1 ? name : name.Substring(0, index);
                                    }

                                    if (!_tagToTypeMap.ContainsKey(xmlTag) && !_typeToTagMap.ContainsKey(type))
                                    {
                                        _tagToTypeMap.Add(xmlTag, type);
                                        _typeToTagMap.Add(type, xmlTag);
                                    }
#if DEBUG
                                    else
                                    {
                                        Debug.Log("Can't serialize type " + type.FullName + " as it shares a name with another class (" + _tagToTypeMap[xmlTag].FullName + ")");
                                    }
#endif
                                }
                            }

                            //Then find all XmlObjectConverterAttribute for those types
                            foreach (Type type in types)
                            {
                                XmlObjectConverterAttribute converterAttribute = SystemUtils.GetAttribute <XmlObjectConverterAttribute>(type);

                                if (converterAttribute != null)
                                {
                                    ObjectConverter converter = new ObjectConverter(SystemUtils.GetStaticMethodAsDelegate <OnConvertToXmlDelegate>(type, converterAttribute.OnConvertToXmlNodeMethod),
                                                                                    SystemUtils.GetStaticMethodAsDelegate <OnConvertFromXmlDelegate>(type, converterAttribute.OnConvertFromXmlNodeMethod),
                                                                                    SystemUtils.GetStaticMethodAsDelegate <ShouldWriteDelegate>(type, converterAttribute.ShouldWriteMethod));

                                    _converterMap[converterAttribute.ObjectType] = converter;
                                    _tagToTypeMap[converterAttribute.XmlTag]     = converterAttribute.ObjectType;
                                    _typeToTagMap[converterAttribute.ObjectType] = converterAttribute.XmlTag;
                                }
                            }
                        }
                    }
                }
        /**
         * Process a single object to be pickled.
         */
        private bool dispatch(Type t, object o)
        {
            Debug.Assert(t != null);
            Debug.Assert(o != null);
            Debug.Assert(t == o.GetType());

            // is it a primitive array?
            if (o is Array)
            {
                Type componentType = t.GetElementType();
                if (componentType != null && componentType.IsPrimitive)
                {
                    put_arrayOfPrimitives(componentType, o);
                }
                else if (o is string[] strings)
                {
                    put_arrayOfStrings(strings);
                }
                else
                {
                    put_arrayOfObjects((object[])o);
                }
                return(true);
            }

            if (t.IsPrimitive)
            {
                switch (o)
                {
                case double v:
                    put_float(v);
                    return(true);

                case int v:
                    put_long(v);
                    return(true);

                case bool v:
                    put_bool(v);
                    return(true);

                case float v:
                    put_float(v);
                    return(true);

                case long v:
                    put_long(v);
                    return(true);

                case byte v:
                    put_byte(v);
                    return(true);

                case sbyte v:
                    put_long(v);
                    return(true);

                case short v:
                    put_long(v);
                    return(true);

                case ushort v:
                    put_long(v);
                    return(true);

                case uint v:
                    put_long(v);
                    return(true);

                case ulong v:
                    put_ulong(v);
                    return(true);

                case char v:
                    put_string(v.ToString());
                    return(true);
                }
            }
            else
            {
                switch (o)
                {
                case string v:
                    put_string(v);
                    return(true);

                case Enum v:
                    put_string(o.ToString());
                    return(true);

                case decimal v:
                    put_decimal(v);
                    return(true);

                case DateTime v:
                    put_datetime(v);
                    return(true);

                case TimeSpan v:
                    put_timespan(v);
                    return(true);

                case IDictionary v:
                    put_map(v);
                    return(true);

                case IList v:
                    put_enumerable(v);
                    return(true);

                case IEnumerable v:
                    if (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(HashSet <>))
                    {
                        put_set(v);
                    }
                    else
                    {
                        put_enumerable(v);
                    }
                    return(true);
                }
            }

            // check registry
            IObjectPickler custompickler = pickler.getCustomPickler(t);

            if (custompickler != null)
            {
                // to support this scenario this type derives from Stream and implements Write methods
                custompickler.pickle(o, this, pickler);
                WriteMemo(o);
                return(true);
            }

            // more complex types
            DataContractAttribute dca = (DataContractAttribute)Attribute.GetCustomAttribute(t, typeof(DataContractAttribute));

            if (dca != null)
            {
                put_datacontract(t, o, dca);
                return(true);
            }

            SerializableAttribute sa = (SerializableAttribute)Attribute.GetCustomAttribute(t, typeof(SerializableAttribute));

            if (sa != null)
            {
                put_serializable(t, o);
                return(true);
            }

            if (hasPublicProperties(t))
            {
                put_objwithproperties(o);
                return(true);
            }

            return(false);
        }
Exemple #27
0
                private static void BuildTypeMap()
                {
                    //Build list of types of classes / structs with the Serializable  attribute
                    if (_tagToTypeMap == null || _typeToTagMap == null || _converterMap == null)
                    {
                        _tagToTypeMap = new Dictionary <string, Type>();
                        _typeToTagMap = new Dictionary <Type, string>();
                        _converterMap = new Dictionary <Type, ObjectConverter>();

                        Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();

                        foreach (Assembly assembly in assemblies)
                        {
                            Type[] types = assembly.GetTypes();

                            if ((assembly.FullName == "Assembly-CSharp, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null") ||
                                (assembly.FullName == "Assembly-CSharp-Editor, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"))
                            {
                                //First build dictionary of types marked with [Serializable] attribute
                                foreach (Type type in types)
                                {
                                    SerializableAttribute attribute = SystemUtils.GetAttribute <SerializableAttribute>(type);
                                    if (attribute != null)
                                    {
                                        string xmlTag = type.Name;

                                        if (type.IsGenericType)
                                        {
                                            string name  = type.Name;
                                            int    index = name.IndexOf('`');
                                            xmlTag = index == -1 ? name : name.Substring(0, index);
                                        }

                                        if (!_tagToTypeMap.ContainsKey(xmlTag))
                                        {
                                            _tagToTypeMap.Add(xmlTag, type);
                                            _typeToTagMap.Add(type, xmlTag);
                                        }
                                        else
                                        {
                                            //	throw new Exception("Can't serialize type " + type.FullName + " as it shares a name with another class");
                                        }
                                    }
                                }

                                //Then find all XmlObjectConverterAttribute for those types
                                foreach (Type type in types)
                                {
                                    XmlObjectConverterAttribute converterAttribute = SystemUtils.GetAttribute <XmlObjectConverterAttribute>(type);

                                    if (converterAttribute != null)
                                    {
                                        ObjectConverter converter = new ObjectConverter(SystemUtils.GetStaticMethodAsDelegate <OnConvertToXmlDelegate>(type, converterAttribute.OnConvertToXmlNodeMethod),
                                                                                        SystemUtils.GetStaticMethodAsDelegate <OnConvertFromXmlDelegate>(type, converterAttribute.OnConvertFromXmlNodeMethod),
                                                                                        SystemUtils.GetStaticMethodAsDelegate <ShouldWriteDelegate>(type, converterAttribute.ShouldWriteMethod));

                                        _converterMap[converterAttribute.ObjectType] = converter;
                                        _tagToTypeMap[converterAttribute.XmlTag]     = converterAttribute.ObjectType;
                                        _typeToTagMap[converterAttribute.ObjectType] = converterAttribute.XmlTag;
                                    }
                                }
                            }
                        }
                    }
                }
Exemple #28
0
        /**
         * Process a single object to be pickled.
         */
        private bool dispatch(Type t, object o)
        {
            // is it a primitive array?
            if (o is Array)
            {
                Type componentType = t.GetElementType();
                if (componentType.IsPrimitive)
                {
                    put_arrayOfPrimitives(componentType, o);
                }
                else
                {
                    put_arrayOfObjects((object[])o);
                }
                return(true);
            }

            // first the primitive types
            if (o is bool)
            {
                put_bool((Boolean)o);
                return(true);
            }
            if (o is byte)
            {
                put_long((byte)o);
                return(true);
            }
            if (o is sbyte)
            {
                put_long((sbyte)o);
                return(true);
            }
            if (o is short)
            {
                put_long((short)o);
                return(true);
            }
            if (o is ushort)
            {
                put_long((ushort)o);
                return(true);
            }
            if (o is int)
            {
                put_long((int)o);
                return(true);
            }
            if (o is uint)
            {
                put_long((uint)o);
                return(true);
            }
            if (o is long)
            {
                put_long((long)o);
                return(true);
            }
            if (o is ulong)
            {
                put_ulong((ulong)o);
                return(true);
            }
            if (o is float)
            {
                put_float((float)o);
                return(true);
            }
            if (o is double)
            {
                put_float((double)o);
                return(true);
            }
            if (o is char)
            {
                put_string("" + o);
                return(true);
            }

            // check registry
            IObjectPickler custompickler = getCustomPickler(t);

            if (custompickler != null)
            {
                custompickler.pickle(o, this.outs, this);
                WriteMemo(o);
                return(true);
            }

            // more complex types
            if (o is string)
            {
                put_string((String)o);
                return(true);
            }
            if (o is decimal)
            {
                put_decimal((decimal)o);
                return(true);
            }
            if (o is DateTime)
            {
                put_datetime((DateTime)o);
                return(true);
            }
            if (o is TimeSpan)
            {
                put_timespan((TimeSpan)o);
                return(true);
            }
            if (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(HashSet <>))
            {
                put_set((IEnumerable)o);
                return(true);
            }
            if (o is IDictionary)
            {
                put_map((IDictionary)o);
                return(true);
            }
            if (o is IList)
            {
                put_enumerable((IList)o);
                return(true);
            }
            if (o is IEnumerable)
            {
                put_enumerable((IEnumerable)o);
                return(true);
            }
            if (o is Enum)
            {
                put_string(o.ToString());
                return(true);
            }

            DataContractAttribute dca = (DataContractAttribute)Attribute.GetCustomAttribute(t, typeof(DataContractAttribute));

            if (dca != null)
            {
                put_datacontract(t, o, dca);
                return(true);
            }

            SerializableAttribute sa = (SerializableAttribute)Attribute.GetCustomAttribute(t, typeof(SerializableAttribute));

            if (sa != null)
            {
                put_serializable(t, o);
                return(true);
            }

            if (hasPublicProperties(o))
            {
                put_objwithproperties(o);
                return(true);
            }

            return(false);
        }
Exemple #29
0
        /**
         * Process a single object to be pickled.
         */
        private bool dispatch(Type t, object o)
        {
            Debug.Assert(t != null);
            Debug.Assert(o != null);
            Debug.Assert(t == o.GetType());

            // is it a primitive array?
            if (o is Array)
            {
                Type componentType = t.GetElementType();
                if (componentType != null && componentType.IsPrimitive)
                {
                    put_arrayOfPrimitives(componentType, o);
                }
                else
                {
                    put_arrayOfObjects((object[])o);
                }
                return(true);
            }

            // first check for enums, as GetTypeCode will return the underlying type.
            if (o is Enum)
            {
                put_string(o.ToString());
                return(true);
            }

            // first the primitive types
            switch (Type.GetTypeCode(t))
            {
            case TypeCode.Boolean:
                put_bool((bool)o);
                return(true);

            case TypeCode.Byte:
                put_long((byte)o);
                return(true);

            case TypeCode.SByte:
                put_long((sbyte)o);
                return(true);

            case TypeCode.Int16:
                put_long((short)o);
                return(true);

            case TypeCode.UInt16:
                put_long((ushort)o);
                return(true);

            case TypeCode.Int32:
                put_long((int)o);
                return(true);

            case TypeCode.UInt32:
                put_long((uint)o);
                return(true);

            case TypeCode.Int64:
                put_long((long)o);
                return(true);

            case TypeCode.UInt64:
                put_ulong((ulong)o);
                return(true);

            case TypeCode.Single:
                put_float((float)o);
                return(true);

            case TypeCode.Double:
                put_float((double)o);
                return(true);

            case TypeCode.Char:
                put_string(((char)o).ToString());
                return(true);

            case TypeCode.String:
                put_string((string)o);
                return(true);

            case TypeCode.Decimal:
                put_decimal((decimal)o);
                return(true);

            case TypeCode.DateTime:
                put_datetime((DateTime)o);
                return(true);
            }

            // check registry
            IObjectPickler custompickler = getCustomPickler(t);

            if (custompickler != null)
            {
                custompickler.pickle(o, outs, this);
                WriteMemo(o);
                return(true);
            }

            // more complex types
            if (o is TimeSpan)
            {
                put_timespan((TimeSpan)o);
                return(true);
            }
            if (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(HashSet <>))
            {
                put_set((IEnumerable)o);
                return(true);
            }

            var dictionary = o as IDictionary;

            if (dictionary != null)
            {
                put_map(dictionary);
                return(true);
            }

            var list = o as IList;

            if (list != null)
            {
                put_enumerable(list);
                return(true);
            }

            var enumerable = o as IEnumerable;

            if (enumerable != null)
            {
                put_enumerable(enumerable);
                return(true);
            }

            DataContractAttribute dca = (DataContractAttribute)Attribute.GetCustomAttribute(t, typeof(DataContractAttribute));

            if (dca != null)
            {
                put_datacontract(t, o, dca);
                return(true);
            }

            SerializableAttribute sa = (SerializableAttribute)Attribute.GetCustomAttribute(t, typeof(SerializableAttribute));

            if (sa != null)
            {
                put_serializable(t, o);
                return(true);
            }

            if (hasPublicProperties(o))
            {
                put_objwithproperties(o);
                return(true);
            }

            return(false);
        }
Exemple #30
0
        internal static bool IsDefined(RuntimeType type, RuntimeType caType)
        {
            bool flag = caType == (RuntimeType)typeof(object) || caType == (RuntimeType)typeof(Attribute);
            int  num;

            return((flag || !(PseudoCustomAttribute.s_pca.GetValueOrDefault(caType) == null) || PseudoCustomAttribute.IsSecurityAttribute(caType)) && (((flag || caType == (RuntimeType)typeof(SerializableAttribute)) && SerializableAttribute.IsDefined(type)) || ((flag || caType == (RuntimeType)typeof(ComImportAttribute)) && ComImportAttribute.IsDefined(type)) || ((flag || PseudoCustomAttribute.IsSecurityAttribute(caType)) && PseudoCustomAttribute.GetCustomAttributes(type, caType, true, out num).Length != 0)));
        }