Index: Core/Common/src/Core.Common.Gui/Forms/PropertyGridView/PropertyResolver.cs
===================================================================
diff -u -rcd9655d356bdff388c7058eeff1cdbed076c407b -rb81978adc73edcf368115b58fd37f34dc7fb6ab5
--- Core/Common/src/Core.Common.Gui/Forms/PropertyGridView/PropertyResolver.cs (.../PropertyResolver.cs) (revision cd9655d356bdff388c7058eeff1cdbed076c407b)
+++ Core/Common/src/Core.Common.Gui/Forms/PropertyGridView/PropertyResolver.cs (.../PropertyResolver.cs) (revision b81978adc73edcf368115b58fd37f34dc7fb6ab5)
@@ -3,6 +3,7 @@
using System.Linq;
using Core.Common.Gui.Properties;
using Core.Common.Gui.PropertyBag;
+using Core.Common.Utils.Reflection;
namespace Core.Common.Gui.Forms.PropertyGridView
{
@@ -74,7 +75,8 @@
for (var i = 0; i < propertyInfoCount; i++)
{
- var firstType = getTypeAction(propertyInfo.ElementAt(i));
+ var propertyToBeConsidered = propertyInfo[i];
+ var firstType = getTypeAction(propertyToBeConsidered);
for (var j = 0; j < propertyInfoCount; j++)
{
@@ -83,11 +85,11 @@
continue;
}
- var secondType = getTypeAction(propertyInfo.ElementAt(j));
+ var secondType = getTypeAction(propertyInfo[j]);
- if (firstType != secondType && firstType.IsAssignableFrom(secondType))
+ if (firstType != secondType && secondType.Implements(firstType))
{
- propertyInfoWithUnInheritedType.Remove(propertyInfo.ElementAt(i));
+ propertyInfoWithUnInheritedType.Remove(propertyToBeConsidered);
break;
}
Index: Core/Common/src/Core.Common.Gui/Forms/ViewManager/ViewResolver.cs
===================================================================
diff -u -r42ca97fdb85a553c6aac3bfdfe57c7be4af90821 -rb81978adc73edcf368115b58fd37f34dc7fb6ab5
--- Core/Common/src/Core.Common.Gui/Forms/ViewManager/ViewResolver.cs (.../ViewResolver.cs) (revision 42ca97fdb85a553c6aac3bfdfe57c7be4af90821)
+++ Core/Common/src/Core.Common.Gui/Forms/ViewManager/ViewResolver.cs (.../ViewResolver.cs) (revision b81978adc73edcf368115b58fd37f34dc7fb6ab5)
@@ -165,7 +165,7 @@
var infos = ViewInfos.Where(vi => data.GetType().Implements(vi.DataType) && vi.AdditionalDataCheck(data));
return viewType != null
- ? infos.Where(vi => viewType.IsAssignableFrom(vi.ViewType))
+ ? infos.Where(vi => viewType.Implements(vi.ViewType))
: infos;
}
Index: Core/Common/src/Core.Common.Gui/RingtoetsGui.cs
===================================================================
diff -u -r3a8bff057967bdb42389382472f6ce55789a0ced -rb81978adc73edcf368115b58fd37f34dc7fb6ab5
--- Core/Common/src/Core.Common.Gui/RingtoetsGui.cs (.../RingtoetsGui.cs) (revision 3a8bff057967bdb42389382472f6ce55789a0ced)
+++ Core/Common/src/Core.Common.Gui/RingtoetsGui.cs (.../RingtoetsGui.cs) (revision b81978adc73edcf368115b58fd37f34dc7fb6ab5)
@@ -423,8 +423,6 @@
MapCursors.DisposeCursors();
- TypeUtils.ClearCaches();
-
Selection = null;
Project = null;
Index: Core/Common/src/Core.Common.Utils/Core.Common.Utils.csproj
===================================================================
diff -u -rc0c01906c23d8951360f8c299473e1eb92729451 -rb81978adc73edcf368115b58fd37f34dc7fb6ab5
--- Core/Common/src/Core.Common.Utils/Core.Common.Utils.csproj (.../Core.Common.Utils.csproj) (revision c0c01906c23d8951360f8c299473e1eb92729451)
+++ Core/Common/src/Core.Common.Utils/Core.Common.Utils.csproj (.../Core.Common.Utils.csproj) (revision b81978adc73edcf368115b58fd37f34dc7fb6ab5)
@@ -159,6 +159,7 @@
PublicResXFileCodeGenerator
Resources.Designer.cs
+ Designer
Index: Core/Common/src/Core.Common.Utils/Reflection/AssemblyUtils.cs
===================================================================
diff -u -r654d3a712eedbdeea718dc0448c5544f09e053cd -rb81978adc73edcf368115b58fd37f34dc7fb6ab5
--- Core/Common/src/Core.Common.Utils/Reflection/AssemblyUtils.cs (.../AssemblyUtils.cs) (revision 654d3a712eedbdeea718dc0448c5544f09e053cd)
+++ Core/Common/src/Core.Common.Utils/Reflection/AssemblyUtils.cs (.../AssemblyUtils.cs) (revision b81978adc73edcf368115b58fd37f34dc7fb6ab5)
@@ -13,37 +13,13 @@
///
public static class AssemblyUtils
{
- private enum MachineType : ushort
- {
- IMAGE_FILE_MACHINE_UNKNOWN = 0x0,
- IMAGE_FILE_MACHINE_AM33 = 0x1d3,
- IMAGE_FILE_MACHINE_AMD64 = 0x8664,
- IMAGE_FILE_MACHINE_ARM = 0x1c0,
- IMAGE_FILE_MACHINE_EBC = 0xebc,
- IMAGE_FILE_MACHINE_I386 = 0x14c,
- IMAGE_FILE_MACHINE_IA64 = 0x200,
- IMAGE_FILE_MACHINE_M32R = 0x9041,
- IMAGE_FILE_MACHINE_MIPS16 = 0x266,
- IMAGE_FILE_MACHINE_MIPSFPU = 0x366,
- IMAGE_FILE_MACHINE_MIPSFPU16 = 0x466,
- IMAGE_FILE_MACHINE_POWERPC = 0x1f0,
- IMAGE_FILE_MACHINE_POWERPCFP = 0x1f1,
- IMAGE_FILE_MACHINE_R4000 = 0x166,
- IMAGE_FILE_MACHINE_SH3 = 0x1a2,
- IMAGE_FILE_MACHINE_SH3DSP = 0x1a3,
- IMAGE_FILE_MACHINE_SH4 = 0x1a6,
- IMAGE_FILE_MACHINE_SH5 = 0x1a8,
- IMAGE_FILE_MACHINE_THUMB = 0x1c2,
- IMAGE_FILE_MACHINE_WCEMIPSV2 = 0x169,
- }
-
private static readonly ILog log = LogManager.GetLogger(typeof(AssemblyUtils));
///
/// Return attributes for a specific assembly
///
- ///
- ///
+ /// The assembly to read.
+ /// A structure containing all the assembly info provided.
public static AssemblyInfo GetAssemblyInfo(Assembly assembly)
{
AssemblyInfo info = new AssemblyInfo();
@@ -89,71 +65,20 @@
}
///
- /// Return attributes for the executing assembly
+ /// Return attributes for the current executing assembly.
///
- ///
+ /// A structure containing all the assembly info provided.
public static AssemblyInfo GetExecutingAssemblyInfo()
{
return GetAssemblyInfo(Assembly.GetExecutingAssembly());
}
///
- /// Gets types in a given assembly derived from a given type.
+ /// Returns the type based on the full type name.
///
- ///
- ///
- ///
- public static IList GetDerivedTypes(Type baseType, Assembly assembly)
- {
- List types = new List();
-
- // log.Debug(assembly.ToString());
- try
- {
- foreach (Type t in assembly.GetTypes())
- {
- if (t.IsSubclassOf(baseType))
- {
- types.Add(t);
- }
- else if (t.GetInterface(baseType.ToString()) != null)
- {
- types.Add(t);
- }
- }
- }
- catch (Exception e) //hack because of unregistered ocx files TOOLS-518
- {
- log.Debug(e);
- }
-
- return types;
- }
-
- ///
- /// Gets types derived from a given type. Searches all assemblies in a current application domain.
- ///
- ///
- ///
- public static IList GetDerivedTypes(Type baseType)
- {
- List types = new List();
- IList assemblies = new List(AppDomain.CurrentDomain.GetAssemblies());
-
- foreach (Assembly a in assemblies)
- {
- types.AddRange(GetDerivedTypes(baseType, a));
- }
-
- return types;
- }
-
- ///
- /// Returns the type based on the full type name. Throws an exception if the types
- /// is found in multiple assemblies
- ///
- ///
- ///
+ /// Full type name.
+ /// The matching the string name, null otherwise.
+ /// Specified type string is found in multiple assemblies.
public static Type GetTypeByName(string typeName)
{
Type result = null;
@@ -175,75 +100,45 @@
return result;
}
- public static IEnumerable GetAssemblyResourceStreams(Assembly assembly, Func resourceNameFilter)
- {
- return from resourceName in assembly.GetManifestResourceNames()
- where resourceNameFilter(resourceName)
- select assembly.GetManifestResourceStream(resourceName);
- }
-
- public static Stream GetAssemblyResourceStream(Assembly assembly, string fileName)
- {
- return
- assembly.GetManifestResourceNames().Where(resourceName => resourceName.EndsWith(fileName)).Select(
- assembly.GetManifestResourceStream).First();
- }
-
///
- /// This method checks if a file is a managed dll. It's based on how the file command on linux works, as explained in http://www.darwinsys.com/file/
+ /// Gets a to a embedded resource of an assembly.
///
- /// path of dll
- /// true if file is a managed dll
- public static bool IsManagedDll(string path)
+ /// The assembly from which to retrieve the embedded resource.
+ /// Name of the embedded file.
+ ///
+ /// Embedded resource file with name
+ /// cannot be found in .
+ public static Stream GetAssemblyResourceStream(Assembly assembly, string fileName)
{
- if (!path.EndsWith(".dll", StringComparison.Ordinal) && !path.EndsWith(".exe", StringComparison.Ordinal))
+ try
{
- return false;
+ return assembly.GetManifestResourceNames()
+ .Where(resourceName => resourceName.EndsWith(fileName))
+ .Select(assembly.GetManifestResourceStream)
+ .First();
}
-
- // HACK: skip python dlls somehow they look like .NET assemblies
- if (path.Contains("ic_msvcr90.dll") || path.Contains("python26.dll"))
+ catch (InvalidOperationException e)
{
- return false;
+ var message = string.Format("Cannot find embedded resource file '{0}' in '{1}.",
+ fileName, assembly.FullName);
+ throw new ArgumentException(message, "fileName", e);
}
-
- FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read);
- fs.Seek(0x3C, SeekOrigin.Begin); // PE, SizeOfHeaders starts at 0x3B, second byte is 0x80 for .NET
- int i1 = fs.ReadByte();
-
- fs.Seek(0x86, SeekOrigin.Begin); // 0x03 for managed code
- int i2 = fs.ReadByte();
-
- fs.Close();
-
- var isManagedDll = i1 == 0x80 && i2 == 0x03;
-
- //Debug.WriteLine(path + ": " + (isManagedDll?"managed":"unmanaged"));
-
- return isManagedDll;
}
- public static bool Is64BitDll(string path)
- {
- if (IsManagedDll(path))
- {
- var assemblyName = AssemblyName.GetAssemblyName(path);
- return assemblyName.ProcessorArchitecture == ProcessorArchitecture.Amd64 ||
- assemblyName.ProcessorArchitecture == ProcessorArchitecture.IA64;
- }
-
- switch (GetDllMachineType(path))
- {
- case MachineType.IMAGE_FILE_MACHINE_AMD64:
- case MachineType.IMAGE_FILE_MACHINE_IA64:
- return true;
- case MachineType.IMAGE_FILE_MACHINE_I386:
- return false;
- default:
- return false;
- }
- }
-
+ ///
+ /// Loads all assemblies from a given directory.
+ ///
+ /// The directory path.
+ /// The assemblies that have been loaded.
+ /// is a file name or a network error occurred.
+ /// The called does not have the required permission.
+ /// is a zero-length string, contains
+ /// only white space or contains one or more invalid characters as defined by .
+ /// is null.
+ /// The specified path, file name, or both
+ /// exceed the system-defined maximum length. For example, on Windows-based platforms,
+ /// paths must be less than 248 characters and file names must be less than 260 characters.
+ /// is invalid.
public static IEnumerable LoadAllAssembliesFromDirectory(string path)
{
foreach (string filename in Directory.GetFiles(path).Where(name => name.EndsWith(".dll")))
@@ -253,25 +148,46 @@
continue;
}
- var assemblyName = Path.GetFileNameWithoutExtension(filename);
-
- //log.DebugFormat("Loading {0}", filename);
-
Assembly a;
try
{
a = Assembly.LoadFrom(filename);
}
catch (Exception exception)
{
- log.ErrorFormat(Resources.AssemblyUtils_LoadAllAssembliesFromDirectory_Could_not_read_assembly_information_for_0_1_, assemblyName, exception.Message);
+ var assemblyName = Path.GetFileNameWithoutExtension(filename);
+ log.ErrorFormat(Resources.AssemblyUtils_LoadAllAssembliesFromDirectory_Could_not_read_assembly_information_for_0_1_,
+ assemblyName, exception.Message);
continue;
}
yield return a;
}
}
+ private static bool IsManagedDll(string path)
+ {
+ // Implementation based on http://www.darwinsys.com/file/
+
+ if (!path.EndsWith(".dll", StringComparison.Ordinal) && !path.EndsWith(".exe", StringComparison.Ordinal))
+ {
+ return false;
+ }
+
+ FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read);
+ fs.Seek(0x3C, SeekOrigin.Begin); // PE, SizeOfHeaders starts at 0x3B, second byte is 0x80 for .NET
+ int i1 = fs.ReadByte();
+
+ fs.Seek(0x86, SeekOrigin.Begin); // 0x03 for managed code
+ int i2 = fs.ReadByte();
+
+ fs.Close();
+
+ var isManagedDll = i1 == 0x80 && i2 == 0x03;
+
+ return isManagedDll;
+ }
+
private static T GetAssemblyAttributeValue(Assembly assembly) where T : class
{
object[] attributes = assembly.GetCustomAttributes(typeof(T), true);
@@ -284,41 +200,38 @@
return (T) attributes[0];
}
- private static MachineType GetDllMachineType(string dllPath)
- {
- //see http://www.microsoft.com/whdc/system/platform/firmware/PECOFF.mspx
- //offset to PE header is always at 0x3C
- //PE header starts with "PE\0\0" = 0x50 0x45 0x00 0x00
- //followed by 2-byte machine type field (see document above for enum)
- var fs = new FileStream(dllPath, FileMode.Open, FileAccess.Read);
- var br = new BinaryReader(fs);
- fs.Seek(0x3c, SeekOrigin.Begin);
- var peOffset = br.ReadInt32();
- fs.Seek(peOffset, SeekOrigin.Begin);
- var peHead = br.ReadUInt32();
- if (peHead != 0x00004550) // "PE\0\0", little-endian
- {
- throw new Exception("Can't find PE header");
- }
- var machineType = (MachineType) br.ReadUInt16();
- br.Close();
- fs.Close();
- return machineType;
- }
-
#region Nested type: AssemblyInfo
///
/// structure containing assembly attributes as strings.
///
+ /// Values will be null if they were not specified.
[Serializable]
public struct AssemblyInfo
{
+ ///
+ /// The company specified in the assembly.
+ ///
public string Company;
+ ///
+ /// The copyright text specified in the assembly.
+ ///
public string Copyright;
+ ///
+ /// The description text specified in the assembly.
+ ///
public string Description;
+ ///
+ /// The product text specified in the assembly.
+ ///
public string Product;
+ ///
+ /// The title text specified in the assembly.
+ ///
public string Title;
+ ///
+ /// The version specified in the assembly.
+ ///
public string Version;
}
Index: Core/Common/src/Core.Common.Utils/Reflection/TypeUtils.cs
===================================================================
diff -u -r654d3a712eedbdeea718dc0448c5544f09e053cd -rb81978adc73edcf368115b58fd37f34dc7fb6ab5
--- Core/Common/src/Core.Common.Utils/Reflection/TypeUtils.cs (.../TypeUtils.cs) (revision 654d3a712eedbdeea718dc0448c5544f09e053cd)
+++ Core/Common/src/Core.Common.Utils/Reflection/TypeUtils.cs (.../TypeUtils.cs) (revision b81978adc73edcf368115b58fd37f34dc7fb6ab5)
@@ -1,33 +1,46 @@
using System;
-using System.Collections;
-using System.Collections.Generic;
-using System.ComponentModel;
-using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using Core.Common.Utils.Properties;
-using log4net;
namespace Core.Common.Utils.Reflection
{
+ ///
+ /// Helper methods dealing with and reflection.
+ ///
public static class TypeUtils
{
- private static readonly ILog log = LogManager.GetLogger(typeof(TypeUtils));
-
- private static readonly IDictionary> PropertyInfoDictionary = new Dictionary>();
-
- private static readonly IDictionary CachedMethods = new Dictionary();
-
+ ///
+ /// Checks if a type implements, inherits from or is a certain other type.
+ ///
+ /// The type to check for.
+ /// Type to check.
+ /// True if is the same type as ,
+ /// or has that as (one of) its supertypes.
+ ///
public static bool Implements(this Type thisType)
{
return typeof(T).IsAssignableFrom(thisType);
}
+ ///
+ /// Checks if a type implements, inherits from or is a certain other type.
+ ///
+ /// Type to check.
+ /// The type to check for.
+ /// True if is the same type as ,
+ /// or has that as (one of) its supertypes.
+ ///
public static bool Implements(this Type thisType, Type type)
{
return type.IsAssignableFrom(thisType);
}
+ ///
+ /// Determines whether the given type can be considered a number or not.
+ ///
+ /// The type.
+ ///
public static bool IsNumericalType(this Type type)
{
return (type == typeof(Single) ||
@@ -36,184 +49,28 @@
type == typeof(Int64) ||
type == typeof(Int32) ||
type == typeof(Int16) ||
- type == typeof(Double));
+ type == typeof(byte) ||
+ type == typeof(Double) ||
+ type == typeof(Decimal));
}
///
- /// Usage: CreateGeneric(typeof(List<>), typeof(string));
+ /// Gets the name of the member.
///
- ///
- ///
- ///
- ///
- public static object CreateGeneric(Type generic, Type innerType, params object[] args)
+ /// The type of the class on which the expression takes place.
+ /// The expression.
+ /// The string name of the member.
+ /// When is invalid.
+ public static string GetMemberName(Expression> expression)
{
- Type specificType = generic.MakeGenericType(new[]
- {
- innerType
- });
- return Activator.CreateInstance(specificType, args);
- }
+ var member = expression.Body as MemberExpression;
- public static object CreateGeneric(Type generic, Type[] innerTypes, params object[] args)
- {
- Type specificType = generic.MakeGenericType(innerTypes);
- return Activator.CreateInstance(specificType, args);
- }
-
- public static object GetPropertyValue(object instance, string propertyName, bool throwOnError = true)
- {
- var implementingType = instance.GetType();
-
- var propertyInfo = GetPropertyInfo(implementingType, propertyName);
-
- if (!throwOnError && propertyInfo.GetIndexParameters().Any())
- {
- return null; //invalid combo, would throw
- }
-
- return propertyInfo.GetValue(instance, new object[0]);
- }
-
- public static PropertyInfo GetPropertyInfo(Type type, string propertyName)
- {
- IDictionary propertyInfoForType;
- PropertyInfo propertyInfo;
-
- lock (PropertyInfoDictionary)
- {
- if (!PropertyInfoDictionary.TryGetValue(type, out propertyInfoForType))
- {
- propertyInfoForType = new Dictionary();
- PropertyInfoDictionary.Add(type, propertyInfoForType);
- }
- }
-
- lock (propertyInfoForType)
- {
- if (!propertyInfoForType.TryGetValue(propertyName, out propertyInfo))
- {
- propertyInfo = GetPrivatePropertyInfo(type, propertyName);
- propertyInfoForType.Add(propertyName, propertyInfo);
- }
- }
- return propertyInfo;
- }
-
- public static object CallGenericMethod(Type declaringType, string methodName, Type genericType,
- object instance, params object[] args)
- {
- var key = declaringType + "_" + genericType + "_" + methodName;
-
- MethodInfo methodInfo;
-
- CachedMethods.TryGetValue(key, out methodInfo);
-
- if (methodInfo != null) // performance optimization, reflaction is very expensive
- {
- return CallMethod(methodInfo, instance, args);
- }
-
- MethodInfo nonGeneric = GetGenericMethod(declaringType, methodName);
-
- methodInfo = nonGeneric.MakeGenericMethod(genericType); // generify
-
- CachedMethods[key] = methodInfo;
-
- return CallMethod(methodInfo, instance, args);
- }
-
- public static object CallStaticGenericMethod(Type type, string methodName, Type genericType,
- params object[] args)
- {
- MethodInfo nonGeneric = type.GetMethod(methodName, BindingFlags.Static | BindingFlags.Public);
- MethodInfo methodGeneric = nonGeneric.MakeGenericMethod(genericType);
- return methodGeneric.Invoke(null, args);
- }
-
- public static IList GetTypedList(Type t)
- {
- return (IList) CreateGeneric(typeof(List<>), t);
- }
-
- public static IEnumerable ConvertEnumerableToType(IEnumerable enumerable, Type type)
- {
- return (IEnumerable) CallStaticGenericMethod(typeof(Enumerable), "Cast", type, enumerable);
- }
-
- ///
- /// Returns typeof(int) for List<int> etc.
- ///
- ///
- public static Type GetFirstGenericTypeParameter(Type t)
- {
- Type[] types = t.GetGenericArguments();
- if (types.Length > 0)
- {
- return types[0];
- }
- else
- {
- return null;
- }
- }
-
- public static IEnumerable GetAllFields(Type t, BindingFlags bindingFlags)
- {
- if (t == null)
- {
- return Enumerable.Empty();
- }
-
- BindingFlags flags = bindingFlags;
- return t.GetFields(flags).Union(GetAllFields(t.BaseType, bindingFlags));
- }
-
- public static string GetMemberDescription(Expression> e)
- {
- var member = e.Body as MemberExpression;
-
- // If the method gets a lambda expression
- // that is not a member access,
- // for example, () => x + y, an exception is thrown.
if (member != null)
{
- var descriptionAttribute = member.Member.GetCustomAttributes(false).OfType().FirstOrDefault();
- return descriptionAttribute != null ? descriptionAttribute.Description : member.Member.Name;
- }
-
- throw new ArgumentException("'" + e + "': is not a valid expression for this method");
- }
-
- ///
- /// Gets the attribute that is declared on a field.
- ///
- ///
- /// class A
- /// {
- /// [Description("int property")]
- /// int field
- /// }
- ///
- /// Attribute type to get
- /// Class type containing the field
- /// Name of the field
- public static TAttribute GetFieldAttribute(Type classType, string fieldName) where TAttribute : class
- {
- var fieldInfo = GetFieldInfo(classType, fieldName);
- return ((TAttribute[]) fieldInfo.GetCustomAttributes(typeof(TAttribute), false)).FirstOrDefault();
- }
-
- public static string GetMemberName(Expression> e)
- {
- var member = e.Body as MemberExpression;
-
- if (member != null)
- {
return GetMemberNameFromMemberExpression(member);
}
- var unary = e.Body as UnaryExpression;
+ var unary = expression.Body as UnaryExpression;
// If the method gets a lambda expression
// that is not a member access,
@@ -223,289 +80,139 @@
return GetMemberNameFromMemberExpression(unary.Operand as MemberExpression);
}
- var message = string.Format(Resources.TypeUtils_GetMemberName_0_is_not_a_valid_expression_for_this_method, e);
+ var message = string.Format(Resources.TypeUtils_GetMemberName_0_is_not_a_valid_expression_for_this_method,
+ expression);
throw new ArgumentException(message);
}
- public static string GetMemberName(Expression> e)
+ ///
+ /// Gets the value of a field of an instance.
+ ///
+ /// Type of the field.
+ /// Instance holding the field. Cannot be null.
+ /// Name of the field.
+ /// The value of the field.
+ /// When
+ /// doesn't have a field with the name .
+ /// When is null.
+ /// This method can be used for fields of any visibility.
+ public static TField GetField(object instance, string fieldName)
{
- return GetMemberNameFromMemberExpression(e.Body as MemberExpression);
- }
-
- public static object GetDefaultValue(Type type)
- {
- return type.IsValueType
- ? Activator.CreateInstance(type)
- : type == typeof(string) ? "" : null;
- }
-
- public static object GetField(object instance, string fieldName)
- {
- Type type = instance.GetType();
-
- FieldInfo fieldInfo = GetFieldInfo(type, fieldName);
-
+ FieldInfo fieldInfo = GetFieldInfo(instance.GetType(), fieldName);
if (fieldInfo == null)
{
throw new ArgumentOutOfRangeException("fieldName");
}
- return fieldInfo.GetValue(instance);
+ return (TField)fieldInfo.GetValue(instance);
}
- public static bool HasField(Type type, string fieldName)
- {
- return GetFieldInfoCore(type, fieldName) != null;
- }
-
///
- ///
+ /// Gets the value of a field of an instance.
///
- /// Type of the object where field is stored.
- /// Type of the field, used as return type
- ///
- ///
- ///
- public static TField GetField(object instance, string fieldName)
+ /// Instance holding the field. Cannot be null.
+ /// Name of the field.
+ /// The new value for the field.
+ /// When
+ /// doesn't have a field with the name .
+ /// is of incorrect type.
+ /// When is null.
+ /// This method can be used for fields of any visibility.
+ public static void SetField(object obj, string fieldName, object newValue)
{
- var fieldInfo = typeof(TObject).GetField(fieldName, BindingFlags.Instance
- | BindingFlags.NonPublic
- | BindingFlags.Public);
-
+ FieldInfo fieldInfo = GetFieldInfo(obj.GetType(), fieldName);
if (fieldInfo == null)
{
throw new ArgumentOutOfRangeException("fieldName");
}
- return (TField) fieldInfo.GetValue(instance);
+ fieldInfo.SetValue(obj, newValue);
}
///
- /// Returns the value of a private static field
+ /// Calls the private method that returns a value.
///
- /// Type of the field, used as return type
- /// The type of the class that holds the private static field
- /// The name of the private static field
- public static TField GetStaticField(Type type, string staticFieldName)
+ /// The return type of the method.
+ /// The instance declaring the method. Cannot be null.
+ /// Name of the method.
+ /// The arguments for the method.
+ /// The method referred to by
+ /// is not declared or inherited by the class of .
+ /// The invoked method or constructor throws an exception.
+ /// The
+ /// array does not have the correct number of arguments.
+ /// The type that declares the method
+ /// is an open generic type. That is, the
+ /// property returns true for the declaring type.
+ /// More than one method is found with
+ /// the specified name and matching the specified binding constraints.
+ /// is null.
+ /// The return value of the method.
+ public static T CallPrivateMethod(object instance, string methodName, params object[] arguments)
{
- var fieldInfo = type.GetField(staticFieldName, BindingFlags.NonPublic | BindingFlags.Static);
-
- if (fieldInfo == null)
+ var methodInfo = instance.GetType().GetMethod(methodName, BindingFlags.NonPublic | BindingFlags.Instance);
+ if (methodInfo == null)
{
- throw new ArgumentOutOfRangeException("staticFieldName");
+ throw new ArgumentOutOfRangeException("methodName");
}
- return (TField) fieldInfo.GetValue(null);
- }
-
- public static void SetField(object obj, string fieldName, object value)
- {
- var fieldInfo = GetFieldInfo(obj.GetType(), fieldName);
-
- if (fieldInfo == null)
- {
- throw new ArgumentOutOfRangeException("fieldName");
- }
-
- fieldInfo.SetValue(obj, value);
- }
-
- public static void SetField(object obj, string fieldName, object value)
- {
- var fieldInfo = typeof(T).GetField(fieldName, BindingFlags.Instance
- | BindingFlags.NonPublic
- | BindingFlags.Public | BindingFlags.FlattenHierarchy);
-
- if (fieldInfo == null)
- {
- throw new ArgumentOutOfRangeException("fieldName");
- }
-
- fieldInfo.SetValue(obj, value);
- }
-
- public static T CallPrivateMethod(object instance, string methodName, params object[] arguments)
- {
- var type = instance.GetType();
- var methodInfo = type.GetMethod(methodName, BindingFlags.NonPublic | BindingFlags.Instance);
-
return (T) methodInfo.Invoke(instance, arguments);
}
- public static void CallPrivateMethod(object instance, string methodName, params object[] arguments)
- {
- var type = instance.GetType();
- var methodInfo = type.GetMethod(methodName, BindingFlags.NonPublic | BindingFlags.Instance);
-
- methodInfo.Invoke(instance, arguments);
- }
-
- public static IEnumerable GetPublicProperties(Type type)
- {
- return type.GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.FlattenHierarchy);
- }
-
- public static object CallPrivateStaticMethod(Type type, string methodName, params object[] arguments)
- {
- var methodInfo = type.GetMethod(methodName, BindingFlags.NonPublic | BindingFlags.Static);
-
- return methodInfo.Invoke(null, arguments);
- }
-
- public static void SetPropertyValue(object instance, string propertyName, object value)
- {
- instance.GetType().GetProperty(propertyName).GetSetMethod().Invoke(instance, new[]
- {
- value
- });
- }
-
- public static void SetPrivatePropertyValue(object instance, string propertyName, object value)
- {
- instance.GetType().GetProperty(propertyName).SetValue(instance, value, null);
- }
-
- public static bool TrySetValueAnyVisibility(object instance, Type type, string propertyName, object value)
- {
- if (type == null)
- {
- return false;
- }
-
- var propertyInfo = type.GetProperties().First(p => p.Name == propertyName);
-
- if (propertyInfo == null)
- {
- return false;
- }
-
- if (!propertyInfo.CanWrite)
- {
- //try base type
- return TrySetValueAnyVisibility(instance, type.BaseType, propertyName, value);
- }
- propertyInfo.SetValue(instance, value, null);
- return true;
- }
-
///
- /// Test if the assembly is dynamic using a HACK...rewrite if we have more knowledge
+ /// Calls the private method that without returning its value.
///
- ///
- ///
- public static bool IsDynamic(this Assembly assembly)
+ /// The instance declaring the method. Cannot be null.
+ /// Name of the method.
+ /// The arguments for the method.
+ /// The method referred to by
+ /// is not declared or inherited by the class of .
+ /// The invoked method or constructor throws an exception.
+ /// The
+ /// array does not have the correct number of arguments.
+ /// The type that declares the method
+ /// is an open generic type. That is, the
+ /// property returns true for the declaring type.
+ /// More than one method is found with
+ /// the specified name and matching the specified binding constraints.
+ /// is null.
+ public static void CallPrivateMethod(object instance, string methodName, params object[] arguments)
{
- //see http://stackoverflow.com/questions/1423733/how-to-tell-if-a-net-assembly-is-dynamic
- //more nice than depending on an exception..
- return (assembly.ManifestModule.GetType().Namespace == "System.Reflection.Emit");
- }
-
- public static void ClearCaches()
- {
- PropertyInfoDictionary.Clear();
- CachedMethods.Clear();
- }
-
- internal static IEnumerable> GetNonInfrastructureFields(object inst, Type type)
- {
- foreach (var fi in GetAllAccessibleFieldsForType(type))
+ var methodInfo = instance.GetType().GetMethod(methodName, BindingFlags.NonPublic | BindingFlags.Instance);
+ if (methodInfo == null)
{
- //skip events
- var value = fi.GetValue(inst);
- if (value is Delegate)
- {
- continue; //don't copy events
- }
-
- yield return new KeyValuePair(fi, value);
+ throw new ArgumentOutOfRangeException("methodName");
}
- }
- internal static T CreateInstance(Type type)
- {
- if (type.IsArray)
- {
- return (T) (object) Array.CreateInstance(type.GetElementType(), 0);
- }
-
- var defaultConstructor = type.GetConstructors(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance)
- .FirstOrDefault(c => c.GetParameters().Length == 0);
-
- if (defaultConstructor == null)
- {
- throw new NotImplementedException(string.Format(Resources.TypeUtils_CreateInstance_No_default_constructor_available_for_type_0_, type));
- }
-
- return (T) Activator.CreateInstance(type, true);
+ methodInfo.Invoke(instance, arguments);
}
- private static PropertyInfo GetPrivatePropertyInfo(Type type, string propertyName)
- {
- //get the property by walking up the inheritance chain. See NHibernate's BasicPropertyAccessor
- //we could extend this logic more by looking there...
- if (type == typeof(object) || type == null)
- {
- // the full inheritance chain has been walked and we could
- // not find the PropertyInfo get
- return null;
- }
-
- var propertyInfo = type.GetProperty(propertyName,
- BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly);
- if (propertyInfo != null)
- {
- return propertyInfo;
- }
-
- return GetPrivatePropertyInfo(type.BaseType, propertyName);
- }
-
///
- /// Returns generic instance method of given name. Cannot use GetMethod() because this does not
- /// work if 2 members have the same name (eg. SetValues and SetValues<T>)
+ /// Sets the value of a property with a setter.
///
- ///
- ///
- ///
- private static MethodInfo GetGenericMethod(Type declaringType, string methodName)
- //,Type genericType,object instance,params object[]args )
+ /// The instance declaring the property. Cannot be null.
+ /// Name of the property to be set.
+ /// The new value of the property.
+ /// is null.
+ /// The property referred to by
+ /// is not declared or inherited by the class of .
+ /// The property has not setter.
+ /// Property is an indexed property.
+ /// An error occurred while setting the
+ /// property value. For example, an index value specified for an indexed property
+ /// is out of range. The property indicates
+ /// the reason for the error.
+ public static void SetPrivatePropertyValue(object instance, string propertyName, object value)
{
- var methods = declaringType.GetMembers(BindingFlags.InvokeMethod | BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
- return methods.OfType().First(m => m.Name == methodName && m.IsGenericMethod);
- }
-
- private static object CallMethod(MethodInfo methodInfo, object instance, object[] args)
- {
- object result;
- try
+ var propertyInfo = instance.GetType().GetProperty(propertyName);
+ if (propertyInfo == null)
{
- result = methodInfo.Invoke(instance, args);
+ throw new ArgumentOutOfRangeException("propertyName");
}
- catch (TargetInvocationException e)
- {
- // re-throw original exception
- if (e.InnerException != null)
- {
- log.Error(Resources.TypeUtils_CallMethod_Exception_occured, e); // log outer exception
- throw e.InnerException;
- }
-
- throw;
- }
-
- return result;
+ propertyInfo.SetValue(instance, value, null);
}
- private static IEnumerable GetAllAccessibleFieldsForType(Type type)
- {
- return type == null
- ? new FieldInfo[0]
- : type.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)
- .Where(fi => !fi.IsLiteral && !fi.IsInitOnly)
- .Concat(GetAllAccessibleFieldsForType(type.BaseType)).Distinct();
- }
-
private static string GetMemberNameFromMemberExpression(MemberExpression member)
{
// If the method gets a lambda expression
@@ -518,13 +225,17 @@
throw new ArgumentException(Resources.TypeUtils_GetMemberNameFromMemberExpression_member_not_a_valid_expression_for_this_method);
}
+ ///
+ /// Gets a field (of any visibility specification) declared on the type (as instance
+ /// or static field).
+ ///
+ /// Declaring type of the field.
+ /// Name of the field.
+ /// A object capturing the requested field, or null
+ /// if the field cannot be found in .
+ /// is null.
private static FieldInfo GetFieldInfo(Type type, string fieldName)
{
- return GetFieldInfoCore(type, fieldName);
- }
-
- private static FieldInfo GetFieldInfoCore(Type type, string fieldName)
- {
if (type == typeof(object) || type == null)
{
return null;
@@ -533,11 +244,7 @@
| BindingFlags.NonPublic
| BindingFlags.Public
| BindingFlags.Static);
- if (fieldInfo != null)
- {
- return fieldInfo;
- }
- return GetFieldInfoCore(type.BaseType, fieldName);
+ return fieldInfo ?? GetFieldInfo(type.BaseType, fieldName);
}
}
}
\ No newline at end of file
Index: Core/Common/test/Core.Common.Controls.Test/Views/HtmlPageViewTest.cs
===================================================================
diff -u -r959988504e0c650ed5d43eca648efae3f97f7b9c -rb81978adc73edcf368115b58fd37f34dc7fb6ab5
--- Core/Common/test/Core.Common.Controls.Test/Views/HtmlPageViewTest.cs (.../HtmlPageViewTest.cs) (revision 959988504e0c650ed5d43eca648efae3f97f7b9c)
+++ Core/Common/test/Core.Common.Controls.Test/Views/HtmlPageViewTest.cs (.../HtmlPageViewTest.cs) (revision b81978adc73edcf368115b58fd37f34dc7fb6ab5)
@@ -21,7 +21,7 @@
// Assert
Assert.IsInstanceOf(htmlPageView);
- var webBrowser = (WebBrowser) TypeUtils.GetField(htmlPageView, "webBrowser");
+ var webBrowser = TypeUtils.GetField(htmlPageView, "webBrowser");
Assert.IsTrue(webBrowser.ScriptErrorsSuppressed);
Assert.IsFalse(webBrowser.IsWebBrowserContextMenuEnabled);
}
@@ -42,7 +42,7 @@
// Assert
ShowHtmlPageView(htmlPageView, () =>
{
- var webBrowser = (WebBrowser) TypeUtils.GetField(htmlPageView, "webBrowser");
+ var webBrowser = TypeUtils.GetField(htmlPageView, "webBrowser");
Assert.AreSame(url, htmlPageView.Data);
Assert.IsNotNull(webBrowser.Url);
@@ -63,7 +63,7 @@
// Assert
ShowHtmlPageView(htmlPageView, () =>
{
- var webBrowser = (WebBrowser) TypeUtils.GetField(htmlPageView, "webBrowser");
+ var webBrowser = TypeUtils.GetField(htmlPageView, "webBrowser");
Assert.IsNull(htmlPageView.Data);
Assert.IsNotNull(webBrowser.Url);
@@ -87,7 +87,7 @@
// Assert
ShowHtmlPageView(htmlPageView, () =>
{
- var webBrowser = (WebBrowser) TypeUtils.GetField(htmlPageView, "webBrowser");
+ var webBrowser = TypeUtils.GetField(htmlPageView, "webBrowser");
Assert.AreSame(url, htmlPageView.Data);
Assert.IsNotNull(webBrowser.Url);
@@ -98,7 +98,7 @@
private static void ShowHtmlPageView(HtmlPageView htmlPageView, Action assertAction)
{
var documentCompleted = false;
- var webBrowser = (WebBrowser) TypeUtils.GetField(htmlPageView, "webBrowser");
+ var webBrowser = TypeUtils.GetField(htmlPageView, "webBrowser");
webBrowser.DocumentCompleted += (s, e) => { documentCompleted = true; };
Index: Core/Common/test/Core.Common.Controls.TreeView.Test/TreeViewControllerTest.cs
===================================================================
diff -u -r1a5f2017961803c9e6aa963a573219d118cab7aa -rb81978adc73edcf368115b58fd37f34dc7fb6ab5
--- Core/Common/test/Core.Common.Controls.TreeView.Test/TreeViewControllerTest.cs (.../TreeViewControllerTest.cs) (revision 1a5f2017961803c9e6aa963a573219d118cab7aa)
+++ Core/Common/test/Core.Common.Controls.TreeView.Test/TreeViewControllerTest.cs (.../TreeViewControllerTest.cs) (revision b81978adc73edcf368115b58fd37f34dc7fb6ab5)
@@ -256,7 +256,7 @@
mocks.ReplayAll();
- var controller = TypeUtils.GetField(treeview, "controller");
+ var controller = TypeUtils.GetField(treeview, "controller");
controller.RegisterNodePresenter(parentNodePresenter);
controller.RegisterNodePresenter(childNodePresenter);
@@ -313,7 +313,7 @@
mocks.ReplayAll();
- var controller = TypeUtils.GetField(treeview, "controller");
+ var controller = TypeUtils.GetField(treeview, "controller");
controller.RegisterNodePresenter(parentNodePresenter);
controller.RegisterNodePresenter(childNodePresenter);
Index: Core/Common/test/Core.Common.Utils.Test/Core.Common.Utils.Test.csproj
===================================================================
diff -u -rc0c01906c23d8951360f8c299473e1eb92729451 -rb81978adc73edcf368115b58fd37f34dc7fb6ab5
--- Core/Common/test/Core.Common.Utils.Test/Core.Common.Utils.Test.csproj (.../Core.Common.Utils.Test.csproj) (revision c0c01906c23d8951360f8c299473e1eb92729451)
+++ Core/Common/test/Core.Common.Utils.Test/Core.Common.Utils.Test.csproj (.../Core.Common.Utils.Test.csproj) (revision b81978adc73edcf368115b58fd37f34dc7fb6ab5)
@@ -104,7 +104,6 @@
-
Component
@@ -168,6 +167,9 @@
+
+
+