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 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577
|
//------------------------------------------------------------------------------
// <copyright file="ObjectConverter.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.Reflection;
using System.Web.Resources;
namespace System.Web.Script.Serialization {
internal static class ObjectConverter {
private static readonly Type[] s_emptyTypeArray = new Type[] { };
private static Type _listGenericType = typeof(List<>);
private static Type _enumerableGenericType = typeof(IEnumerable<>);
private static Type _dictionaryGenericType = typeof(Dictionary<,>);
private static Type _idictionaryGenericType = typeof(IDictionary<,>);
// Helper method that recursively convert individual items in the old array
private static bool AddItemToList(IList oldList, IList newList, Type elementType, JavaScriptSerializer serializer, bool throwOnError) {
object convertedObject;
foreach (Object propertyValue in oldList) {
if (!ConvertObjectToTypeMain(propertyValue, elementType, serializer, throwOnError, out convertedObject)) {
return false;
}
newList.Add(convertedObject);
}
return true;
}
// Helper method that assigns the propertyValue to object o's member (memberName)
private static bool AssignToPropertyOrField(object propertyValue, object o, string memberName, JavaScriptSerializer serializer, bool throwOnError) {
IDictionary dictionary = o as IDictionary;
// if o is already an idictionary, assign the value to the dictionary
if (dictionary != null) {
if (!ConvertObjectToTypeMain(propertyValue, null, serializer, throwOnError, out propertyValue)) {
return false;
}
dictionary[memberName] = propertyValue;
return true;
}
Type serverType = o.GetType();
// First, look for a property
PropertyInfo propInfo = serverType.GetProperty(memberName,
BindingFlags.Instance | BindingFlags.IgnoreCase | BindingFlags.Public);
if (propInfo != null) {
// Ignore it if the property has no setter
MethodInfo setter = propInfo.GetSetMethod();
if (setter != null) {
// Deserialize the property value, with knownledge of the property type
if (!ConvertObjectToTypeMain(propertyValue, propInfo.PropertyType, serializer, throwOnError, out propertyValue)) {
return false;
}
// Set the property in the object
try {
setter.Invoke(o, new Object[] { propertyValue });
return true;
}
catch {
if (throwOnError) {
throw;
}
else {
return false;
}
}
}
}
// We couldn't find a property, so try a field
FieldInfo fieldInfo = serverType.GetField(memberName,
BindingFlags.Instance | BindingFlags.IgnoreCase | BindingFlags.Public);
if (fieldInfo != null) {
// Deserialize the field value, with knownledge of the field type
if (!ConvertObjectToTypeMain(propertyValue, fieldInfo.FieldType, serializer, throwOnError, out propertyValue)) {
return false;
}
// Set the field in the object
try {
fieldInfo.SetValue(o, propertyValue);
return true;
}
catch {
if (throwOnError) {
throw;
}
else {
return false;
}
}
}
// not a property or field, so it is ignored
return true;
}
// Method that converts an IDictionary<string, object> to an object of the right type
private static bool ConvertDictionaryToObject(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer, bool throwOnError, out object convertedObject) {
// The target type to instantiate.
Type targetType = type;
object s;
string serverTypeName = null;
object o = dictionary;
// Check if __serverType exists in the dictionary, use it as the type.
if (dictionary.TryGetValue(JavaScriptSerializer.ServerTypeFieldName, out s)) {
// Convert the __serverType value to a string.
if (!ConvertObjectToTypeMain(s, typeof(String), serializer, throwOnError, out s)) {
convertedObject = false;
return false;
}
serverTypeName = (string)s;
if (serverTypeName != null) {
// If we don't have the JavaScriptTypeResolver, we can't use it
if (serializer.TypeResolver != null) {
// Get the actual type from the resolver.
targetType = serializer.TypeResolver.ResolveType(serverTypeName);
// In theory, we should always find the type. If not, it may be some kind of attack.
if (targetType == null) {
if (throwOnError) {
throw new InvalidOperationException();
}
convertedObject = null;
return false;
}
}
// Remove the serverType from the dictionary, even if the resolver was null
dictionary.Remove(JavaScriptSerializer.ServerTypeFieldName);
}
}
JavaScriptConverter converter = null;
if (targetType != null && serializer.ConverterExistsForType(targetType, out converter)) {
try {
convertedObject = converter.Deserialize(dictionary, targetType, serializer);
return true;
}
catch {
if (throwOnError) {
throw;
}
convertedObject = null;
return false;
}
}
// Instantiate the type if it's coming from the __serverType argument.
if (serverTypeName != null || IsClientInstantiatableType(targetType, serializer)) {
// First instantiate the object based on the type.
o = Activator.CreateInstance(targetType);
}
#if INDIGO
StructuralContract contract = null;
if (suggestedType != null &&
suggestedType.GetCustomAttributes(typeof(DataContractAttribute), false).Length > 0)
contract = StructuralContract.Create(suggestedType);
#endif
// Use a different collection to avoid modifying the original during keys enumeration.
List<String> memberNames = new List<String>(dictionary.Keys);
// Try to handle the IDictionary<K, V> case
if (IsGenericDictionary(type)) {
Type keyType = type.GetGenericArguments()[0];
if (keyType != typeof(string) && keyType != typeof(object)) {
if (throwOnError) {
throw new InvalidOperationException(String.Format(CultureInfo.InvariantCulture, AtlasWeb.JSON_DictionaryTypeNotSupported, type.FullName));
}
convertedObject = null;
return false;
}
Type valueType = type.GetGenericArguments()[1];
IDictionary dict = null;
if (IsClientInstantiatableType(type, serializer)) {
dict = (IDictionary)Activator.CreateInstance(type);
}
else {
// Get the strongly typed Dictionary<K, V>
Type t = _dictionaryGenericType.MakeGenericType(keyType, valueType);
dict = (IDictionary)Activator.CreateInstance(t);
}
if (dict != null) {
foreach (string memberName in memberNames) {
object memberObject;
if (!ConvertObjectToTypeMain(dictionary[memberName], valueType, serializer, throwOnError, out memberObject)) {
convertedObject = null;
return false;
}
dict[memberName] = memberObject;
}
convertedObject = dict;
return true;
}
}
// Fail if we know we cannot possibly return the required type.
if (type != null && !type.IsAssignableFrom(o.GetType())) {
if (!throwOnError) {
convertedObject = null;
return false;
}
ConstructorInfo constructorInfo = type.GetConstructor(BindingFlags.Public | BindingFlags.Instance, null, s_emptyTypeArray, null);
if (constructorInfo == null) {
throw new MissingMethodException(String.Format(CultureInfo.InvariantCulture, AtlasWeb.JSON_NoConstructor, type.FullName));
}
throw new InvalidOperationException(String.Format(CultureInfo.InvariantCulture, AtlasWeb.JSON_DeserializerTypeMismatch, type.FullName));
}
foreach (string memberName in memberNames) {
object propertyValue = dictionary[memberName];
#if INDIGO
if (contract != null) {
Member member = contract.FindMember(memberName);
//
if (member == null)
throw new InvalidOperationException();
if (member.MemberType == MemberTypes.Field) {
member.SetValue(o, propertyValue);
}
else {
member.SetValue(o, propertyValue);
}
continue;
}
#endif
// Assign the value into a property or field of the object
if (!AssignToPropertyOrField(propertyValue, o, memberName, serializer, throwOnError)) {
convertedObject = null;
return false;
}
}
convertedObject = o;
return true;
}
internal static object ConvertObjectToType(object o, Type type, JavaScriptSerializer serializer) {
object convertedObject;
ConvertObjectToTypeMain(o, type, serializer, true, out convertedObject);
return convertedObject;
}
private static bool ConvertObjectToTypeMain(object o, Type type, JavaScriptSerializer serializer, bool throwOnError, out object convertedObject) {
// If it's null, there is nothing to convert
if (o == null) {
// need to special case Char, as we convert \0 to null
if (type == typeof(char)) {
convertedObject = '\0';
return true;
}
// Throw if its a value type and not a nullable
if (IsNonNullableValueType(type)) {
if (throwOnError) {
throw new InvalidOperationException(AtlasWeb.JSON_ValueTypeCannotBeNull);
}
else {
convertedObject = null;
return false;
}
}
convertedObject = null;
return true;
}
// simply return the current object if the current type is same as return type.
if (o.GetType() == type) {
convertedObject = o;
return true;
}
// otherwise use the converters to convert object into target type.
return ConvertObjectToTypeInternal(o, type, serializer, throwOnError, out convertedObject);
}
// Helper method that converts the object to the corresponding type using converters.
// Items in IDictionary<string, object> and ArrayList needs to be converted as well.
// Note this method does not invoke the custom converter for deserialization.
private static bool ConvertObjectToTypeInternal(object o, Type type, JavaScriptSerializer serializer, bool throwOnError, out object convertedObject) {
// First checks if the object is an IDictionary<string, object>
IDictionary<string, object> dictionary = o as IDictionary<string, object>;
if (dictionary != null) {
return ConvertDictionaryToObject(dictionary, type, serializer, throwOnError, out convertedObject);
}
// If it is an IList try to convert it to the requested type.
IList list = o as IList;
if (list != null) {
IList convertedList;
if (ConvertListToObject(list, type, serializer, throwOnError, out convertedList)) {
convertedObject = convertedList;
return true;
}
else {
convertedObject = null;
return false;
}
}
// simply return the current object if
// 1) the caller does not specify the return type.
// 2) if the current type is same as return type.
if (type == null || o.GetType() == type) {
convertedObject = o;
return true;
}
// Otherwise use the type converter to convert the string to the target type.
TypeConverter converter = TypeDescriptor.GetConverter(type);
// Use the memberType's converter to directly conver if supported.
if (converter.CanConvertFrom(o.GetType())) {
try {
convertedObject = converter.ConvertFrom(null, CultureInfo.InvariantCulture, o);
return true;
}
catch {
if (throwOnError) {
throw;
}
else {
convertedObject = null;
return false;
}
}
}
// Otherwise if the target type can be converted from a string
// 1. first use the propertyValue's converter to convert object to string,
// 2. then use the target converter to convert the string to target type.
if (converter.CanConvertFrom(typeof(String))) {
try {
string s;
if (o is DateTime) {
// when converting from DateTime it is important to use the 'u' format
// so it contains the 'Z' indicating that it is UTC time.
// If converting to DateTimeOffset this ensures the value is correct, since otherwise
// the deafult offset would be assumed, which is the server's timezone.
s = ((DateTime)o).ToUniversalTime().ToString("u", CultureInfo.InvariantCulture);
}
else {
TypeConverter propertyConverter = TypeDescriptor.GetConverter(o);
s = propertyConverter.ConvertToInvariantString(o);
}
convertedObject = converter.ConvertFromInvariantString(s);
return true;
}
catch {
if (throwOnError) {
throw;
}
else {
convertedObject = null;
return false;
}
}
}
// We can't convert object o to the target type, but perhaps o can be
// assigned directly to type?
if (type.IsAssignableFrom(o.GetType())) {
convertedObject = o;
return true;
}
// Nothing works
if (throwOnError) {
throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, AtlasWeb.JSON_CannotConvertObjectToType, o.GetType(), type));
}
else {
convertedObject = null;
return false;
}
}
// Method that converts client array to the request type. It handles the following cases:
// 1. type is not passed in - An ArrayList will be returned.
// 2. type is an array - An array of the right type will be returned.
// 3. type is an abstract collection interface, e.g. IEnumerable, ICollection -
// An ArrayList will be returned.
// 4. type is an generic abstract collection interface, e.g. IEnumerable<T> -
// An List<T> will be returned.
// 5. type is a concrete type that implements IList -
// The type will be instantiated and returned.
// Otherwise we throw InvalidOperationException.
private static bool ConvertListToObject(IList list, Type type, JavaScriptSerializer serializer, bool throwOnError, out IList convertedList) {
// Add the items into an ArrayList then convert to custom type when
// 1. Type is null or typeof(Object)
// 2. Type is an Array, in which case we call ArrayList.ToArray(type) or
// 3. Type is already an ArrayList
if (type == null || type == typeof(Object) || IsArrayListCompatible(type)) {
Type elementType = typeof(Object);
if (type != null && type != typeof(Object)) {
elementType = type.GetElementType();
}
ArrayList newList = new ArrayList();
// Add the items to the new List and recursive into each item.
if (!AddItemToList(list, newList, elementType, serializer, throwOnError)) {
convertedList = null;
return false;
}
if (type == typeof(ArrayList) || type == typeof(IEnumerable) || type == typeof(IList) || type == typeof(ICollection)) {
convertedList = newList;
return true;
}
convertedList = newList.ToArray(elementType);
return true;
}
// Add the items into an List<T> then convert to the custom generic type when
// 1. Type is a generic collection type
// 2. Type only has one generic parameter, eg. List<string> vs MyCustom<T, V>
// 3. Type implements IEnumerable<T>
else if (type.IsGenericType &&
type.GetGenericArguments().Length == 1) {
// gets the T of List<T> as the elementType
Type elementType = type.GetGenericArguments()[0];
// Get the strongly typed IEnumerable<T>
Type strongTypedEnumerable = _enumerableGenericType.MakeGenericType(elementType);
// Make sure the custom type can be assigned to IEnumerable<T>
if (strongTypedEnumerable.IsAssignableFrom(type)) {
// Get the strongly typed List<T>
Type t = _listGenericType.MakeGenericType(elementType);
// Create the List<T> instance or a MyList<T>
IList newList = null;
if (IsClientInstantiatableType(type, serializer) && typeof(IList).IsAssignableFrom(type)) {
newList = (IList)Activator.CreateInstance(type);
}
else {
// If this is MyList<T> and we can't assign to it, throw
if (t.IsAssignableFrom(type)) {
if (throwOnError) {
throw new InvalidOperationException(String.Format(CultureInfo.InvariantCulture, AtlasWeb.JSON_CannotCreateListType, type.FullName));
}
else {
convertedList = null;
return false;
}
}
newList = (IList)Activator.CreateInstance(t);
}
// Add the items to the new List and recursive into each item.
if (!AddItemToList(list, newList, elementType, serializer, throwOnError)) {
convertedList = null;
return false;
}
convertedList = newList;
return true;
}
}
// If the custom type implements IList and it's instantiable. Use that type.
else if (IsClientInstantiatableType(type, serializer) && typeof(IList).IsAssignableFrom(type)) {
IList newList = (IList)Activator.CreateInstance(type);
// Add the items to the new List and recursive into each item.
if (!AddItemToList(list, newList, null, serializer, throwOnError)) {
convertedList = null;
return false;
}
convertedList = newList;
return true;
}
if (throwOnError) {
throw new InvalidOperationException(String.Format(
CultureInfo.CurrentCulture, AtlasWeb.JSON_ArrayTypeNotSupported, type.FullName));
}
else {
convertedList = null;
return false;
}
}
private static bool IsArrayListCompatible(Type type) {
return type.IsArray || type == typeof(ArrayList) || type == typeof(IEnumerable) || type == typeof(IList) || type == typeof(ICollection);
}
// Is this a type for which we want to instantiate based on the client stub
internal static bool IsClientInstantiatableType(Type t, JavaScriptSerializer serializer) {
// Abstract classes and interfaces can't be instantiated
//
if (t == null || t.IsAbstract || t.IsInterface || t.IsArray)
return false;
// Even though 'object' is instantiatable, it is never useful to do this
if (t == typeof(object))
return false;
// Return true if a converter is registered for the given type, so the converter
// can generate code on the client to instantiate it.
JavaScriptConverter converter = null;
if (serializer.ConverterExistsForType(t, out converter)) {
return true;
}
// Value types are okay (i.e. structs);
if (t.IsValueType) {
return true;
}
// Ignore types that don't have a public default ctor
ConstructorInfo constructorInfo = t.GetConstructor(BindingFlags.Public | BindingFlags.Instance,
null, s_emptyTypeArray, null);
if (constructorInfo == null)
return false;
return true;
}
// these helper methods replace inline code.
// they simplify the code and reduce our cyclomatic complexity
private static bool IsGenericDictionary(Type type) {
return type != null &&
type.IsGenericType &&
(typeof(IDictionary).IsAssignableFrom(type) || type.GetGenericTypeDefinition() == _idictionaryGenericType) &&
type.GetGenericArguments().Length == 2;
}
private static bool IsNonNullableValueType(Type type) {
// the the type a value type, and if it is, is it not the nullable variety
return type != null && type.IsValueType &&
!(type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>));
}
internal static bool TryConvertObjectToType(object o, Type type, JavaScriptSerializer serializer, out object convertedObject) {
return ConvertObjectToTypeMain(o, type, serializer, false, out convertedObject);
}
}
}
|