예제 #1
0
        public static object PropertyValue(this object obj, string propName)
        {
            if (obj == null || propName == null)
            {
                return(null);
            }

            if (propName.Contains("."))
            {
                string[] props = propName.Split('.');
                foreach (string innerProp in props)
                {
                    obj = obj.PropertyValue(innerProp);
                    if (obj == null)
                    {
                        break;
                    }
                }
                return(obj);
            }

            System.Reflection.PropertyInfo prop = obj.GetType().GetProperty(propName);

            if (prop != null)
            {
                return(prop.GetValue(obj));
            }
            else if (obj is IBHoMObject)
            {
                IBHoMObject bhom = obj as IBHoMObject;
                if (bhom.CustomData.ContainsKey(propName))
                {
                    if (!(bhom is CustomObject))
                    {
                        Compute.RecordNote($"{propName} is stored in CustomData");
                    }
                    return(bhom.CustomData[propName]);
                }
                else
                {
                    Compute.RecordWarning($"{bhom} does not contain a property: {propName}, or: CustomData[{propName}]");
                    return(null);
                }
            }
            else if (obj is IDictionary)
            {
                IDictionary dic = obj as IDictionary;
                if (dic.Contains(propName))
                {
                    return(dic[propName]);
                }
                else
                {
                    Compute.RecordWarning($"{dic} does not contain the key: {propName}");
                    return(null);
                }
            }
            else
            {
                Compute.RecordWarning($"This instance of {obj.GetType()} does not contain the property: {propName}");
                return(null);
            }
        }
예제 #2
0
        /***************************************************/
        /**** Private Methods                           ****/
        /***************************************************/

        private static void ExtractAllTypes()
        {
            m_BHoMTypeList    = new List <Type>();
            m_AdapterTypeList = new List <Type>();
            m_InterfaceList   = new List <Type>();

            foreach (Assembly asm in AppDomain.CurrentDomain.GetAssemblies())
            {
                try
                {
                    // Save BHoM objects only
                    string name = asm.GetName().Name;
                    if (name == "BHoM" || name.EndsWith("_oM"))
                    {
                        foreach (Type type in asm.GetTypes())
                        {
                            if (type.Namespace != null && type.Namespace.StartsWith("BH.oM"))
                            {
                                AddBHoMTypeToDictionary(type.FullName, type);
                                if (type.IsInterface)
                                {
                                    m_InterfaceList.Add(type);
                                }
                                else if (!(type.IsAbstract && type.IsSealed) && (type.IsEnum || typeof(IObject).IsAssignableFrom(type)))
                                {
                                    m_BHoMTypeList.Add(type);
                                }
                            }
                            if (!type.IsAutoGenerated())
                            {
                                m_AllTypeList.Add(type);
                            }
                        }
                    }
                    // Save adapters
                    else if (name.EndsWith("_Adapter"))
                    {
                        foreach (Type type in asm.GetTypes())
                        {
                            if (!type.IsAutoGenerated())
                            {
                                if (!type.IsInterface && type.IsLegal() && type.IsOfType("BHoMAdapter"))
                                {
                                    m_AdapterTypeList.Add(type);
                                }

                                m_AllTypeList.Add(type);
                            }
                        }
                    }
                    else
                    {
                        foreach (Type type in asm.GetTypes())
                        {
                            if (type.Namespace != null && type.Namespace.StartsWith("BH.") && !type.IsAutoGenerated())
                            {
                                m_AllTypeList.Add(type);
                            }
                        }
                    }
                }
                catch (Exception)
                {
                    Compute.RecordWarning("Cannot load types from assembly " + asm.GetName().Name);
                }
            }
        }
예제 #3
0
        public static object SetPropertyValue(this object obj, string propName, object value = null)
        {
            if (obj == null)
            {
                Compute.RecordError("Cannot set the property value of a null object.");
                return(obj);
            }

            if (propName == null)
            {
                Compute.RecordError("Cannot set the property value where the property name is null.");
                return(obj);
            }

            object toChange = obj;

            if (propName.Contains("."))
            {
                string[] props = propName.Split('.');
                for (int i = 0; i < props.Length - 1; i++)
                {
                    toChange = toChange.PropertyValue(props[i]);
                    if (toChange == null)
                    {
                        break;
                    }
                }
                propName = props[props.Length - 1];
            }

            System.Reflection.PropertyInfo prop = toChange.GetType().GetProperty(propName);
            if (prop != null)
            {
                if (!prop.CanWrite)
                {
                    Engine.Reflection.Compute.RecordError("This property doesn't have a public setter so it is not possible to modify it.");
                    return(obj);
                }

                Type propType = prop.PropertyType;
                if (value == null)
                {
                    if (propType == typeof(string))
                    {
                        value = "";
                    }
                    else if (propType.IsValueType || typeof(IEnumerable).IsAssignableFrom(propType))
                    {
                        value = Activator.CreateInstance(propType);
                    }
                }

                if (propType.IsEnum && value is string)
                {
                    string enumName = (value as string).Split('.').Last();
                    try
                    {
                        object enumValue = Enum.Parse(propType, enumName);
                        if (enumValue != null)
                        {
                            value = enumValue;
                        }
                    }
                    catch
                    {
                        Engine.Reflection.Compute.RecordError($"An enum of type {propType.ToText(true)} does not have a value of {enumName}");
                    }
                }

                if (propType == typeof(DateTime) && value is string)
                {
                    DateTime date;
                    if (DateTime.TryParse(value as string, out date))
                    {
                        value = date;
                    }
                    else
                    {
                        Engine.Reflection.Compute.RecordError($"The value provided for {propName} is not a valid DateTime.");
                        value = DateTime.MinValue;
                    }
                }

                if (propType == typeof(Type) && value is string)
                {
                    value = Create.Type(value as string);
                }

                if (value != null)
                {
                    if (value.GetType() != propType && value.GetType().GenericTypeArguments.Length > 0 && propType.GenericTypeArguments.Length > 0)
                    {
                        value = Modify.CastGeneric(value as dynamic, propType.GenericTypeArguments[0]);
                    }
                    if (value.GetType() != propType)
                    {
                        ConstructorInfo constructor = propType.GetConstructor(new Type[] { value.GetType() });
                        if (constructor != null)
                        {
                            value = constructor.Invoke(new object[] { value });
                        }
                    }
                }

                prop.SetValue(toChange, value);
                return(obj);
            }
            else
            {
                SetValue(toChange as dynamic, propName, value);
                return(obj);
            }
        }
예제 #4
0
        /***************************************************/

        private static bool SetValue(this object obj, string propName, object value)
        {
            Compute.RecordWarning("The objects does not contain any property with the name " + propName + ".");
            return(false);
        }
예제 #5
0
        /***************************************************/
        /**** Private Methods                           ****/
        /***************************************************/

        private static void ExtractAllMethods()
        {
            Compute.LoadAllAssemblies();

            m_BHoMMethodList = new List <MethodInfo>();
            m_AllMethodList  = new List <MethodBase>();
            m_EngineTypeList = new List <Type>();

            BindingFlags bindingBHoM = BindingFlags.Public | BindingFlags.DeclaredOnly | BindingFlags.Static;

            foreach (Assembly asm in AppDomain.CurrentDomain.GetAssemblies())
            {
                try
                {
                    // Save BHoM objects only
                    string name = asm.GetName().Name;
                    if (name.EndsWith("_Engine"))
                    {
                        foreach (Type type in asm.GetTypes())
                        {
                            // Get only the BHoM methods
                            if (!type.IsInterface && type.IsAbstract)
                            {
                                MethodInfo[] typeMethods = type.GetMethods(bindingBHoM);
                                m_BHoMMethodList.AddRange(typeMethods.Where(x => x.IsLegal()));
                            }

                            if (type.Name == "External")
                            {
                                MethodInfo getExternalMethods = type.GetMethod("Methods");
                                if (getExternalMethods != null)
                                {
                                    m_ExternalMethodList.AddRange((List <MethodInfo>)getExternalMethods.Invoke(null, null));
                                }
                                MethodInfo getExternalCtor = type.GetMethod("Constructors");
                                if (getExternalCtor != null)
                                {
                                    m_ExternalMethodList.AddRange((List <ConstructorInfo>)getExternalCtor.Invoke(null, null));
                                }
                            }
                            // Get everything
                            StoreAllMethods(type);
                        }
                    }
                    else if (name.EndsWith("oM") || name.EndsWith("_Adapter") || name.EndsWith("_UI") || name.EndsWith("_Test"))
                    {
                        foreach (Type type in asm.GetTypes())
                        {
                            StoreAllMethods(type);
                        }
                    }
                }
                catch (Exception e)
                {
                    string message = "Cannot load types from assembly " + asm.GetName().Name + ". Exception message: " + e.Message;

                    if (!string.IsNullOrEmpty(e.InnerException?.Message))
                    {
                        message += "\nInnerException: " + e.InnerException.Message;
                    }

                    Compute.RecordWarning(message);
                }
            }
        }
예제 #6
0
        public static string Description(this Type type, InputClassificationAttribute classification)
        {
            if (type == null)
            {
                Compute.RecordWarning("Cannot query the description of a null type. An empty string will be returned instead.");
                return("");
            }

            DescriptionAttribute attribute = type.GetCustomAttribute <DescriptionAttribute>();

            string desc = "";

            //If a quantity attribute is present, this is used to generate the default description
            if (classification != null)
            {
                desc += classification.IDescription();
                desc += " (as a " + type.ToText(type.Namespace.StartsWith("BH.")) + ")";
                return(desc);
            }

            //Add the default description
            desc += "This is a " + type.ToText(type.Namespace.StartsWith("BH."));

            if (attribute != null)
            {
                desc += ":" + Environment.NewLine;
                desc += attribute.Description;
            }

            //If type is enum, list options with descriptions
            if (type.IsEnum)
            {
                desc += EnumItemDescription(type);
            }

            Type innerType = type;

            while (typeof(IEnumerable).IsAssignableFrom(innerType) && innerType.IsGenericType)
            {
                innerType = innerType.GenericTypeArguments.First();
            }

            if (innerType.IsInterface)
            {
                desc += Environment.NewLine;
                desc += "This can be of the following types: ";
                List <Type> t = innerType.ImplementingTypes();
                int         m = Math.Min(15, t.Count);

                for (int i = 0; i < m; i++)
                {
                    desc += $"{t[i].ToText()}, ";
                }

                if (t.Count > m)
                {
                    desc += "and more...";
                }
                else
                {
                    desc = desc.Remove(desc.Length - 2, 2);
                }

                return(desc);
            }

            return(desc);
        }