1 // Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information. 2 3 using System.Collections.Generic; 4 using System.Reflection; 5 using System.Runtime.CompilerServices; 6 using System.Web.Routing; 7 8 namespace System.Web.WebPages 9 { 10 internal static class TypeHelper 11 { 12 /// <summary> 13 /// Given an object of anonymous type, add each property as a key and associated with its value to a dictionary. 14 /// </summary> ObjectToDictionary(object value)15 internal static IDictionary<string, object> ObjectToDictionary(object value) 16 { 17 return new RouteValueDictionary(value); 18 } 19 20 /// <summary> 21 /// Given an object of anonymous type, add each property as a key and associated with its value to the given dictionary. 22 /// </summary> AddAnonymousObjectToDictionary(IDictionary<string, object> dictionary, object value)23 internal static void AddAnonymousObjectToDictionary(IDictionary<string, object> dictionary, object value) 24 { 25 var values = ObjectToDictionary(value); 26 foreach (var item in values) 27 { 28 dictionary.Add(item); 29 } 30 } 31 32 /// <remarks>This code is copied from http://www.liensberger.it/web/blog/?p=191 </remarks> IsAnonymousType(Type type)33 internal static bool IsAnonymousType(Type type) 34 { 35 if (type == null) 36 { 37 throw new ArgumentNullException("type"); 38 } 39 40 // TODO: The only way to detect anonymous types right now. 41 return Attribute.IsDefined(type, typeof(CompilerGeneratedAttribute), false) 42 && type.IsGenericType && type.Name.Contains("AnonymousType") 43 && (type.Name.StartsWith("<>", StringComparison.OrdinalIgnoreCase) || type.Name.StartsWith("VB$", StringComparison.OrdinalIgnoreCase)) 44 && (type.Attributes & TypeAttributes.NotPublic) == TypeAttributes.NotPublic; 45 } 46 } 47 } 48