tangxu
2024-10-22 4d9fe5ed98ceb6b8fe9dc52ebfb80860ad1aee99
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
using System;
using System.ComponentModel;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Runtime.Serialization;
using System.Security;
using System.Security.Permissions;
using DPumpHydr.WinFrmUI.WenSkin.Json.Utilities;
 
namespace DPumpHydr.WinFrmUI.WenSkin.Json.Serialization
{
    internal static class JsonTypeReflector
    {
        private static bool? _dynamicCodeGeneration;
 
        private static bool? _fullyTrusted;
 
        public const string IdPropertyName = "$id";
 
        public const string RefPropertyName = "$ref";
 
        public const string TypePropertyName = "$type";
 
        public const string ValuePropertyName = "$value";
 
        public const string ArrayValuesPropertyName = "$values";
 
        public const string ShouldSerializePrefix = "ShouldSerialize";
 
        public const string SpecifiedPostfix = "Specified";
 
        private static readonly ThreadSafeStore<Type, Func<object[], object>> CreatorCache = new ThreadSafeStore<Type, Func<object[], object>>(GetCreator);
 
        private static readonly ThreadSafeStore<Type, Type> AssociatedMetadataTypesCache = new ThreadSafeStore<Type, Type>(GetAssociateMetadataTypeFromAttribute);
 
        private static ReflectionObject _metadataTypeAttributeReflectionObject;
 
        public static bool DynamicCodeGeneration
        {
            [SecuritySafeCritical]
            get
            {
                if (!_dynamicCodeGeneration.HasValue)
                {
                    try
                    {
                        new ReflectionPermission(ReflectionPermissionFlag.MemberAccess).Demand();
                        new ReflectionPermission(ReflectionPermissionFlag.RestrictedMemberAccess).Demand();
                        new SecurityPermission(SecurityPermissionFlag.SkipVerification).Demand();
                        new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Demand();
                        new SecurityPermission(PermissionState.Unrestricted).Demand();
                        _dynamicCodeGeneration = true;
                    }
                    catch (Exception)
                    {
                        _dynamicCodeGeneration = false;
                    }
                }
                return _dynamicCodeGeneration.GetValueOrDefault();
            }
        }
 
        public static bool FullyTrusted
        {
            get
            {
                if (!_fullyTrusted.HasValue)
                {
                    AppDomain currentDomain = AppDomain.CurrentDomain;
                    _fullyTrusted = currentDomain.IsHomogenous && currentDomain.IsFullyTrusted;
                }
                return _fullyTrusted.GetValueOrDefault();
            }
        }
 
        public static ReflectionDelegateFactory ReflectionDelegateFactory
        {
            get
            {
                if (DynamicCodeGeneration)
                {
                    return DynamicReflectionDelegateFactory.Instance;
                }
                return LateBoundReflectionDelegateFactory.Instance;
            }
        }
 
        public static T GetCachedAttribute<T>(object attributeProvider) where T : Attribute
        {
            return CachedAttributeGetter<T>.GetAttribute(attributeProvider);
        }
 
        public static DataContractAttribute GetDataContractAttribute(Type type)
        {
            Type type2 = type;
            while (type2 != null)
            {
                DataContractAttribute attribute = CachedAttributeGetter<DataContractAttribute>.GetAttribute(type2);
                if (attribute != null)
                {
                    return attribute;
                }
                type2 = type2.BaseType();
            }
            return null;
        }
 
        public static DataMemberAttribute GetDataMemberAttribute(MemberInfo memberInfo)
        {
            if (memberInfo.MemberType() == MemberTypes.Field)
            {
                return CachedAttributeGetter<DataMemberAttribute>.GetAttribute(memberInfo);
            }
            PropertyInfo propertyInfo = (PropertyInfo)memberInfo;
            DataMemberAttribute attribute = CachedAttributeGetter<DataMemberAttribute>.GetAttribute(propertyInfo);
            if (attribute == null && propertyInfo.IsVirtual())
            {
                Type type = propertyInfo.DeclaringType;
                while (attribute == null && type != null)
                {
                    PropertyInfo propertyInfo2 = (PropertyInfo)ReflectionUtils.GetMemberInfoFromType(type, propertyInfo);
                    if (propertyInfo2 != null && propertyInfo2.IsVirtual())
                    {
                        attribute = CachedAttributeGetter<DataMemberAttribute>.GetAttribute(propertyInfo2);
                    }
                    type = type.BaseType();
                }
            }
            return attribute;
        }
 
        public static MemberSerialization GetObjectMemberSerialization(Type objectType, bool ignoreSerializableAttribute)
        {
            JsonObjectAttribute cachedAttribute = GetCachedAttribute<JsonObjectAttribute>(objectType);
            if (cachedAttribute != null)
            {
                return cachedAttribute.MemberSerialization;
            }
            if (GetDataContractAttribute(objectType) != null)
            {
                return MemberSerialization.OptIn;
            }
            if (!ignoreSerializableAttribute && GetCachedAttribute<SerializableAttribute>(objectType) != null)
            {
                return MemberSerialization.Fields;
            }
            return MemberSerialization.OptOut;
        }
 
        public static JsonConverter GetJsonConverter(object attributeProvider)
        {
            JsonConverterAttribute cachedAttribute = GetCachedAttribute<JsonConverterAttribute>(attributeProvider);
            if (cachedAttribute != null)
            {
                Func<object[], object> func = CreatorCache.Get(cachedAttribute.ConverterType);
                if (func != null)
                {
                    return (JsonConverter)func(cachedAttribute.ConverterParameters);
                }
            }
            return null;
        }
 
        /// <summary>
        /// Lookup and create an instance of the JsonConverter type described by the argument.
        /// </summary>
        /// <param name="converterType">The JsonConverter type to create.</param>
        /// <param name="converterArgs">Optional arguments to pass to an initializing constructor of the JsonConverter.
        /// If null, the default constructor is used.</param>
        public static JsonConverter CreateJsonConverterInstance(Type converterType, object[] converterArgs)
        {
            return (JsonConverter)CreatorCache.Get(converterType)(converterArgs);
        }
 
        public static NamingStrategy CreateNamingStrategyInstance(Type namingStrategyType, object[] converterArgs)
        {
            return (NamingStrategy)CreatorCache.Get(namingStrategyType)(converterArgs);
        }
 
        public static NamingStrategy GetContainerNamingStrategy(JsonContainerAttribute containerAttribute)
        {
            if (containerAttribute.NamingStrategyInstance == null)
            {
                if (containerAttribute.NamingStrategyType == null)
                {
                    return null;
                }
                containerAttribute.NamingStrategyInstance = CreateNamingStrategyInstance(containerAttribute.NamingStrategyType, containerAttribute.NamingStrategyParameters);
            }
            return containerAttribute.NamingStrategyInstance;
        }
 
        private static Func<object[], object> GetCreator(Type type)
        {
            Func<object> defaultConstructor = (ReflectionUtils.HasDefaultConstructor(type, nonPublic: false) ? ReflectionDelegateFactory.CreateDefaultConstructor<object>(type) : null);
            return delegate(object[] parameters)
            {
                try
                {
                    if (parameters != null)
                    {
                        Type[] types = parameters.Select((object param) => param.GetType()).ToArray();
                        ConstructorInfo constructor = type.GetConstructor(types);
                        if (!(null != constructor))
                        {
                            throw new JsonException("No matching parameterized constructor found for '{0}'.".FormatWith(CultureInfo.InvariantCulture, type));
                        }
                        return ReflectionDelegateFactory.CreateParameterizedConstructor(constructor)(parameters);
                    }
                    if (defaultConstructor == null)
                    {
                        throw new JsonException("No parameterless constructor defined for '{0}'.".FormatWith(CultureInfo.InvariantCulture, type));
                    }
                    return defaultConstructor();
                }
                catch (Exception innerException)
                {
                    throw new JsonException("Error creating '{0}'.".FormatWith(CultureInfo.InvariantCulture, type), innerException);
                }
            };
        }
 
        public static TypeConverter GetTypeConverter(Type type)
        {
            return TypeDescriptor.GetConverter(type);
        }
 
        private static Type GetAssociatedMetadataType(Type type)
        {
            return AssociatedMetadataTypesCache.Get(type);
        }
 
        private static Type GetAssociateMetadataTypeFromAttribute(Type type)
        {
            Attribute[] attributes = ReflectionUtils.GetAttributes(type, null, inherit: true);
            foreach (Attribute attribute in attributes)
            {
                Type type2 = attribute.GetType();
                if (string.Equals(type2.FullName, "System.ComponentModel.DataAnnotations.MetadataTypeAttribute", StringComparison.Ordinal))
                {
                    if (_metadataTypeAttributeReflectionObject == null)
                    {
                        _metadataTypeAttributeReflectionObject = ReflectionObject.Create(type2, "MetadataClassType");
                    }
                    return (Type)_metadataTypeAttributeReflectionObject.GetValue(attribute, "MetadataClassType");
                }
            }
            return null;
        }
 
        private static T GetAttribute<T>(Type type) where T : Attribute
        {
            Type associatedMetadataType = GetAssociatedMetadataType(type);
            T attribute;
            if (associatedMetadataType != null)
            {
                attribute = ReflectionUtils.GetAttribute<T>(associatedMetadataType, inherit: true);
                if (attribute != null)
                {
                    return attribute;
                }
            }
            attribute = ReflectionUtils.GetAttribute<T>(type, inherit: true);
            if (attribute != null)
            {
                return attribute;
            }
            Type[] interfaces = type.GetInterfaces();
            for (int i = 0; i < interfaces.Length; i++)
            {
                attribute = ReflectionUtils.GetAttribute<T>(interfaces[i], inherit: true);
                if (attribute != null)
                {
                    return attribute;
                }
            }
            return null;
        }
 
        private static T GetAttribute<T>(MemberInfo memberInfo) where T : Attribute
        {
            Type associatedMetadataType = GetAssociatedMetadataType(memberInfo.DeclaringType);
            T attribute;
            if (associatedMetadataType != null)
            {
                MemberInfo memberInfoFromType = ReflectionUtils.GetMemberInfoFromType(associatedMetadataType, memberInfo);
                if (memberInfoFromType != null)
                {
                    attribute = ReflectionUtils.GetAttribute<T>(memberInfoFromType, inherit: true);
                    if (attribute != null)
                    {
                        return attribute;
                    }
                }
            }
            attribute = ReflectionUtils.GetAttribute<T>(memberInfo, inherit: true);
            if (attribute != null)
            {
                return attribute;
            }
            if (memberInfo.DeclaringType != null)
            {
                Type[] interfaces = memberInfo.DeclaringType.GetInterfaces();
                for (int i = 0; i < interfaces.Length; i++)
                {
                    MemberInfo memberInfoFromType2 = ReflectionUtils.GetMemberInfoFromType(interfaces[i], memberInfo);
                    if (memberInfoFromType2 != null)
                    {
                        attribute = ReflectionUtils.GetAttribute<T>(memberInfoFromType2, inherit: true);
                        if (attribute != null)
                        {
                            return attribute;
                        }
                    }
                }
            }
            return null;
        }
 
        public static T GetAttribute<T>(object provider) where T : Attribute
        {
            Type type = provider as Type;
            if (type != null)
            {
                return GetAttribute<T>(type);
            }
            MemberInfo memberInfo = provider as MemberInfo;
            if (memberInfo != null)
            {
                return GetAttribute<T>(memberInfo);
            }
            return ReflectionUtils.GetAttribute<T>(provider, inherit: true);
        }
    }
}