Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/HeuristicLab.Common/3.3/ObjectExtensions.cs @ 17096

Last change on this file since 17096 was 16648, checked in by abeham, 6 years ago

#2992: exclude types from System.Net.Sockets in object graph traversal

File size: 5.5 KB
RevLine 
[6103]1#region License Information
2/* HeuristicLab
[16565]3 * Copyright (C) 2002-2019 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
[6103]4 *
5 * This file is part of HeuristicLab.
6 *
7 * HeuristicLab is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation, either version 3 of the License, or
10 * (at your option) any later version.
11 *
12 * HeuristicLab is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
19 */
20#endregion
21
22using System;
[6205]23using System.Collections;
[6103]24using System.Collections.Generic;
[6205]25using System.Collections.Specialized;
[6380]26using System.Linq;
[6103]27using System.Reflection;
[7139]28using System.Security;
[6500]29using System.Threading;
[6103]30
31namespace HeuristicLab.Common {
[14032]32
[14144]33  [AttributeUsage(AttributeTargets.Field)]
[14032]34  // this attribute can be used to mark fields that should be excluded from object graph traversal
35  public class ExcludeFromObjectGraphTraversalAttribute : Attribute {
36  }
37
[6103]38  public static class ObjectExtensions {
[8128]39    public static IEnumerable<T> ToEnumerable<T>(this T obj) {
40      yield return obj;
41    }
42
[8212]43    public static IEnumerable<object> GetObjectGraphObjects(this object obj, HashSet<object> excludedMembers = null, bool excludeStaticMembers = false) {
[6380]44      if (obj == null) return Enumerable.Empty<object>();
[8212]45      if (excludedMembers == null) excludedMembers = new HashSet<object>();
[9855]46      var fieldInfos = new Dictionary<Type, FieldInfo[]>();
[6380]47
[6103]48      var objects = new HashSet<object>();
[6380]49      var stack = new Stack<object>();
50
51      stack.Push(obj);
52      while (stack.Count > 0) {
53        object current = stack.Pop();
54        objects.Add(current);
55
[9855]56        foreach (object o in GetChildObjects(current, excludedMembers, excludeStaticMembers, fieldInfos)) {
[8310]57          if (o == null) continue;
58          if (ExcludeType(o.GetType())) continue;
59          if (objects.Contains(o)) continue;
60          stack.Push(o);
[6380]61        }
62      }
63
[6103]64      return objects;
65    }
[6891]66
[6192]67    /// <summary>
68    /// Types not collected:
69    ///   * System.Delegate
[6205]70    ///   * System.Reflection.Pointer
[6192]71    ///   * Primitives (Boolean, Byte, SByte, Int16, UInt16, Int32, UInt32, Int64, UInt64, IntPtr, UIntPtr, Char, Double, Single)
[7796]72    ///   * string, decimal, DateTime
[6205]73    ///   * Arrays of types not collected
[13494]74    ///   * All types from System.Reflection.Emit
[6192]75    /// </summary>
[6380]76    private static bool ExcludeType(Type type) {
77      return type.IsPrimitive ||
78             type == typeof(string) ||
[8310]79             type == typeof(string[]) ||
[6380]80             type == typeof(decimal) ||
[8310]81             type == typeof(decimal[]) ||
[7796]82             type == typeof(DateTime) ||
[8310]83             type == typeof(DateTime[]) ||
[6380]84             typeof(Delegate).IsAssignableFrom(type) ||
85             typeof(Pointer).IsAssignableFrom(type) ||
[13510]86             type.Namespace == "System.Reflection.Emit" ||
[16648]87             type.Namespace == "System.Net.Sockets" ||
[6380]88             (type.HasElementType && ExcludeType(type.GetElementType()));
89    }
[8212]90
[9855]91    private static IEnumerable<object> GetChildObjects(object obj, HashSet<object> excludedMembers, bool excludeStaticMembers, Dictionary<Type, FieldInfo[]> fieldInfos) {
[6192]92      Type type = obj.GetType();
[6181]93
[6500]94      if (type.IsSubclassOfRawGeneric(typeof(ThreadLocal<>))) {
95        PropertyInfo info = type.GetProperty("Value");
96        object value = info.GetValue(obj, null);
[8310]97        if (value != null && !excludedMembers.Contains(value))
[8212]98          yield return value;
[6500]99      } else if (type.IsSubclassOfRawGeneric(typeof(Dictionary<,>)) ||
100           type.IsSubclassOfRawGeneric(typeof(SortedDictionary<,>)) ||
101           type.IsSubclassOfRawGeneric(typeof(SortedList<,>)) ||
102           obj is SortedList ||
103           obj is OrderedDictionary ||
104           obj is ListDictionary ||
105           obj is Hashtable) {
[6205]106        var dictionary = obj as IDictionary;
[8212]107        foreach (object value in dictionary.Keys) {
[8310]108          if (excludedMembers.Contains(value)) continue;
[6380]109          yield return value;
[8212]110        }
111        foreach (object value in dictionary.Values) {
[8310]112          if (excludedMembers.Contains(value)) continue;
[6380]113          yield return value;
[8212]114        }
[6205]115      } else if (type.IsArray || type.IsSubclassOfRawGeneric(typeof(HashSet<>))) {
116        var enumerable = obj as IEnumerable;
[8212]117        foreach (var value in enumerable) {
[8310]118          if (excludedMembers.Contains(value)) continue;
[6380]119          yield return value;
[8212]120        }
[6380]121      } else {
[14144]122        FieldInfo[] fieldInfo;
123        if (!fieldInfos.TryGetValue(type, out fieldInfo)) {
124          fieldInfo = type.GetAllFields()
125            .Where(fi => !Attribute.IsDefined(fi, typeof(ExcludeFromObjectGraphTraversalAttribute)))
[14032]126            .ToArray();
[14144]127          fieldInfos.Add(type, fieldInfo);
128        }
129        foreach (FieldInfo f in fieldInfo) {
[6891]130          if (excludeStaticMembers && f.IsStatic) continue;
[7139]131          object fieldValue;
132          try {
133            fieldValue = f.GetValue(obj);
[14144]134          } catch (SecurityException) {
[7139]135            continue;
136          }
[8310]137          if (excludedMembers.Contains(fieldValue)) continue;
[7139]138          yield return fieldValue;
[6380]139        }
[6192]140      }
[6103]141    }
142  }
143}
Note: See TracBrowser for help on using the repository browser.