public void DescriptionSafeBoxedNullTest()
 {
     var descriptionAttribute = new DescriptionAttribute(null);
     _enumattributeReader.Setup(x => x.AttributeSafe<DescriptionAttribute>(DayOfWeek.Friday))
         .Returns(descriptionAttribute)
         .Verifiable();
     _enumattributeReader.Object.DescriptionSafe((Enum) DayOfWeek.Friday);
 }
        public void DescriptionTest()
        {
            var descriptionAttribute = new DescriptionAttribute("123");
            _enumattributeReader.Setup(x => x.Attribute<DescriptionAttribute, DayOfWeek>(DayOfWeek.Friday)).Returns(descriptionAttribute).Verifiable();

            Assert.AreEqual(descriptionAttribute.Description, _enumattributeReader.Object.Description(DayOfWeek.Friday));
        }
 public void Init()
 {
     _mockFactory = new MockRepository(MockBehavior.Strict);
     _attributesReader = _mockFactory.Create<IAttributesReader>();
     _fieldReader = _mockFactory.Create<IEnumFieldReader>();
     _field = typeof (TestEnum).GetField(TestEnum.Value.ToString());
     _da = new DescriptionAttribute();
 }
        static EnumExtensions()
        {
            //let's collect the enums we care about
            List <Type> enumTypeList = new List <Type>();

            //probe this assembly for all enums
            System.Reflection.Assembly assembly = System.Reflection.Assembly.GetExecutingAssembly();
            Type[] exportedTypes = assembly.GetExportedTypes();
            foreach (Type type in exportedTypes)
            {
                if (type.IsEnum)
                {
                    enumTypeList.Add(type);
                }
            }
            //for each enum in our list, populate the appropriate dictionaries
            foreach (Type type in enumTypeList)
            {
                //add dictionaries for this type
                EnumExtensions.enumToStringDictionary.Add(type, new Dictionary <object, string>());
                EnumExtensions.stringToEnumDictionary.Add(type, new Dictionary <string, object>());
                Array values = Enum.GetValues(type);

                //its ok to manipulate 'value' as object, since when we convert we're given the type to cast to
                foreach (object value in values)
                {
                    System.Reflection.FieldInfo fieldInfo = type.GetField(value.ToString());

                    //check for an attribute
                    System.ComponentModel.DescriptionAttribute attribute =
                        Attribute.GetCustomAttribute(fieldInfo,
                                                     typeof(System.ComponentModel.DescriptionAttribute)) as System.ComponentModel.DescriptionAttribute;
                    //populate our dictionaries
                    if (attribute != null)
                    {
                        EnumExtensions.enumToStringDictionary[type].Add(value, attribute.Description);
                        EnumExtensions.stringToEnumDictionary[type].Add(attribute.Description, value);
                    }
                    else
                    {
                        EnumExtensions.enumToStringDictionary[type].Add(value, value.ToString());
                        EnumExtensions.stringToEnumDictionary[type].Add(value.ToString(), value);
                    }
                }
            }
        }
Exemple #5
0
        public void GenerateCommand()
        {
            var  g       = new DefaultSqlServerCommandGenerator();
            Type daoType = typeof(IUserDao);

            MethodInfo[] infos = daoType.GetMethods();
            foreach (var info in infos)
            {
                System.ComponentModel.DescriptionAttribute desc = info.GetCustomAttribute <System.ComponentModel.DescriptionAttribute>();
                if (desc == null)
                {
                    continue;
                }
                var d = g.Generate(info, null);
                Console.WriteLine(d);
                Assert.AreEqual(desc.Description, d.SqlCommand.Trim(), info.Name);
            }
        }
Exemple #6
0
        public void Apply(Schema model, SchemaFilterContext context)
        {
            if (!string.IsNullOrEmpty(model.Format))
            {
                model.Type = model.Title = model.Format;
            }
            return;

            if (context.SystemType.IsEnum)
            {
                IList <object> tmp = new List <object>();
                foreach (var val in model.Enum)
                {
                    object enumValue;
                    bool   b;
                    string Description;
                    b = Enum.TryParse(context.SystemType, val.ToString(), out enumValue);
                    if (b)
                    {
                        string str = enumValue.ToString();
                        System.Reflection.FieldInfo field = enumValue.GetType().GetField(str);
                        object[] objs = field.GetCustomAttributes(typeof(System.ComponentModel.DescriptionAttribute), false);
                        if (objs == null || objs.Length == 0)
                        {
                            Description = val.ToString();
                        }
                        else
                        {
                            System.ComponentModel.DescriptionAttribute da = (System.ComponentModel.DescriptionAttribute)objs[0];
                            Description = da.Description;
                        }

                        string ret = string.Format("0x{0:x2}:{1}", (int)enumValue, Description);
                        tmp.Add(ret);
                    }
                }
                model.Enum = tmp;
            }


            return;

            throw new NotImplementedException();
        }
Exemple #7
0
 public static string GetEnumDescription(Enum enumValue)
 {
     try
     {
         string str = enumValue.ToString();
         System.Reflection.FieldInfo field = enumValue.GetType().GetField(str);
         object[] objs = field.GetCustomAttributes(typeof(System.ComponentModel.DescriptionAttribute), false);
         if (objs == null || objs.Length == 0)
         {
             return(str);
         }
         System.ComponentModel.DescriptionAttribute da = (System.ComponentModel.DescriptionAttribute)objs[0];
         return(da.Description);
     }
     catch
     {
         return(string.Empty);
     }
 }
        public static bool GetFriendlyNameFromType(TokenType type, out string name)
        {
            if (!Enum.IsDefined(typeof(TokenType), type))
            {
                throw new ArgumentOutOfRangeException(nameof(type));
            }

            name = null;

            System.ComponentModel.DescriptionAttribute attribute = type.GetType()
                                                                   .GetField(type.ToString())
                                                                   .GetCustomAttributes(typeof(System.ComponentModel.DescriptionAttribute), false)
                                                                   .SingleOrDefault() as System.ComponentModel.DescriptionAttribute;
            name = attribute == null
                ? type.ToString()
                : attribute.Description;

            return(name != null);
        }
    public static string GetDescription(this Enum value)
    {
        Type   type = value.GetType();
        string name = Enum.GetName(type, value);

        if (name != null)
        {
            System.Reflection.FieldInfo field = type.GetField(name);
            if (field != null)
            {
                System.ComponentModel.DescriptionAttribute attr =
                    Attribute.GetCustomAttribute(field,
                                                 typeof(System.ComponentModel.DescriptionAttribute)) as System.ComponentModel.DescriptionAttribute;
                if (attr != null)
                {
                    return(attr.Description);
                }
            }
        }
        return(null);
    }
Exemple #10
0
        ///-------------------------------------------------------------------------------------------------
        /// <summary>
        ///     An Enum extension method that converts an enumeration to a localized description.
        /// </summary>
        ///
        /// <param name="enumeration">
        ///     The enumeration.
        /// </param>
        ///
        /// <returns>
        ///     enumeration as a string.
        /// </returns>
        ///-------------------------------------------------------------------------------------------------
        public static string ToLocalizedDescription(this Enum enumeration)
        {
            // Get the type
            Type type = enumeration.GetType();

            // Get fieldinfo for this type
            FieldInfo fieldInfo = type.GetField(enumeration.ToString());

            // Get the stringvalue attributes
            DescriptionAttribute attribs =
                (from attr in fieldInfo.GetCustomAttributes(typeof(DescriptionAttribute), false) select attr).Cast <DescriptionAttribute>().FirstOrDefault();

            // Return the first if there was a match.
            if (attribs != null)
            {
                string desc = attribs.GetLocalizedDescription(CultureInfo.CurrentUICulture);
                if (!string.IsNullOrWhiteSpace(desc))
                {
                    return(desc);
                }
            }
            else
            {
                System.ComponentModel.DescriptionAttribute descriptionAttribute =
                    (from attr in fieldInfo.GetCustomAttributes(typeof(System.ComponentModel.DescriptionAttribute), false) select attr).Cast <System.ComponentModel.DescriptionAttribute>().FirstOrDefault();

                // Return the first if there was a match.
                if (descriptionAttribute != null)
                {
                    string desc = descriptionAttribute.Description;
                    if (!string.IsNullOrWhiteSpace(desc))
                    {
                        return(desc);
                    }
                }
            }

            return(enumeration.ToString("G"));
        }
Exemple #11
0
        /// <summary>
        /// GetEnumItem
        /// </summary>
        /// <param name="type">typeof(TEnum)</param>
        /// <returns></returns>
        public static List <EnumItem> GetEnumItem(Type type)
        {
            if (!type.IsEnum)
            {
                throw new ArgumentException("TEnum requires a Enum", "TEnum");
            }
            FieldInfo[]     fields = type.GetFields();
            List <EnumItem> col    = new List <EnumItem>();

            foreach (FieldInfo field in fields)
            {
                object[] objs = field.GetCustomAttributes(typeof(System.ComponentModel.DescriptionAttribute), false);
                if (objs != null && objs.Length > 0)
                {
                    System.ComponentModel.DescriptionAttribute attr = objs[0] as System.ComponentModel.DescriptionAttribute;
                    col.Add(new EnumItem {
                        Description = attr.Description, Key = Enum.Parse(type, field.Name).ToString(), Value = (int)Enum.Parse(type, field.Name)
                    });
                }
            }
            return(col);
        }
Exemple #12
0
        public static System.Collections.DictionaryEntry GetEnumDict <TEnum>(Enum enumItem)
        {
            Type type = typeof(TEnum);

            if (!type.IsEnum)
            {
                throw new ArgumentException("TEnum requires a Enum", "TEnum");
            }
            FieldInfo[] fields = type.GetFields();
            System.Collections.DictionaryEntry dict = new System.Collections.DictionaryEntry();
            foreach (FieldInfo field in fields)
            {
                object[] objs = field.GetCustomAttributes(typeof(System.ComponentModel.DescriptionAttribute), false);
                if (objs != null && objs.Length > 0 && field.Name == enumItem.ToString())
                {
                    System.ComponentModel.DescriptionAttribute attr = objs[0] as System.ComponentModel.DescriptionAttribute;
                    dict = new System.Collections.DictionaryEntry(attr.Description, ((int)Enum.Parse(type, field.Name)).ToString());
                    break;
                }
            }
            return(dict);
        }
Exemple #13
0
        public static string GetEnumDescription(this Enum e)
        {
            System.Reflection.FieldInfo[] ms = e.GetType().GetFields();
            Type t = e.GetType();

            foreach (System.Reflection.FieldInfo f in ms)
            {
                if (f.Name != e.ToString())
                {
                    continue;
                }
                foreach (Attribute attr in f.GetCustomAttributes(true))
                {
                    System.ComponentModel.DescriptionAttribute dscript = attr as System.ComponentModel.DescriptionAttribute;
                    if (dscript != null)
                    {
                        return(dscript.Description);
                    }
                }
            }
            return(e.ToString());
        }
Exemple #14
0
        public static string EnumDesc(this Enum enumValue)
        {
            var value = enumValue?.ToString() ?? "";

            try
            {
                FieldInfo field = enumValue.GetType().GetField(value);
                //获取描述属性
                object[] objs = field.GetCustomAttributes(typeof(System.ComponentModel.DescriptionAttribute), false);
                //当描述属性没有时,直接返回名称
                if (objs.Length == 0)
                {
                    return(value);
                }
                System.ComponentModel.DescriptionAttribute descriptionAttribute = (System.ComponentModel.DescriptionAttribute)objs[0];
                return(descriptionAttribute.Description);
            }
            catch (Exception)
            {
                return(value);
            }
        }
Exemple #15
0
        static List <System.Collections.DictionaryEntry> ResolveEnum <TEnum>()
        {
            Type type = typeof(TEnum);

            if (!type.IsEnum)
            {
                throw new ArgumentException("TEnum requires a Enum", "TEnum");
            }
            FieldInfo[] fields = type.GetFields();
            List <System.Collections.DictionaryEntry> col = new List <System.Collections.DictionaryEntry>();

            foreach (FieldInfo field in fields)
            {
                object[] objs = field.GetCustomAttributes(typeof(System.ComponentModel.DescriptionAttribute), false);
                if (objs != null && objs.Length > 0)
                {
                    System.ComponentModel.DescriptionAttribute attr = objs[0] as System.ComponentModel.DescriptionAttribute;
                    col.Add(new System.Collections.DictionaryEntry(attr.Description, ((int)Enum.Parse(type, field.Name)).ToString()));
                }
            }
            return(col);
        }
Exemple #16
0
        public static string GetDescription <T>(this T value) where T : struct
        {
            CheckIsEnum <T>(false);
            string name = System.Enum.GetName(typeof(T), value);

            if (name != null)
            {
                System.Reflection.FieldInfo field = typeof(T).GetField(name);
                if (field != null)
                {
                    System.ComponentModel.DescriptionAttribute attr =
                        System.Attribute.GetCustomAttribute(field, typeof(System.ComponentModel.DescriptionAttribute))
                        as System.ComponentModel.DescriptionAttribute
                    ;

                    if (attr != null)
                    {
                        return(attr.Description);
                    }
                }
            }

            return(null);
        }
Exemple #17
0
        /// <summary>
        /// 获取枚举的描述 Description
        /// </summary>
        /// <param name="enumType"></param>
        /// <param name="val"></param>
        /// <returns></returns>
        public static string GetEnumDescription(Type enumType, object val)
        {
            if (val == null)
            {
                return("");
            }
            string enumvalue = System.Enum.GetName(enumType, val);

            if (string.IsNullOrEmpty(enumvalue))
            {
                return("");
            }
            System.Reflection.FieldInfo finfo = enumType.GetField(enumvalue);
            object[] enumAttr = finfo.GetCustomAttributes(typeof(System.ComponentModel.DescriptionAttribute), true);
            if (enumAttr.Length > 0)
            {
                System.ComponentModel.DescriptionAttribute desc = enumAttr[0] as System.ComponentModel.DescriptionAttribute;
                if (desc != null)
                {
                    return(desc.Description);
                }
            }
            return(enumvalue);
        }
        /// <summary>
        /// 把枚举转成下拉数据
        /// </summary>
        /// <param name="controller"></param>
        /// <param name="type"></param>
        /// <param name="emptyTitle"></param>
        /// <param name="emptyValue"></param>
        /// <param name="selectValue"></param>
        /// <returns></returns>
        public static IList <SelectListItem> EnumToSelectList(this Controller controller, Type type, string emptyTitle = "", string emptyValue = "", byte?selectValue = null)
        {
            IList <SelectListItem> list = new List <SelectListItem>();

            if (!string.IsNullOrWhiteSpace(emptyTitle))
            {
                list.Insert(0, new SelectListItem()
                {
                    Text = emptyTitle, Value = emptyValue, Selected = true
                });
            }
            string[] t = Enum.GetNames(type);
            foreach (string f in t)
            {
                var      text  = f;
                var      obj   = Enum.Parse(type, f);
                var      field = type.GetField(f);
                object[] objs  = field.GetCustomAttributes(typeof(System.ComponentModel.DescriptionAttribute), false);
                if (objs != null && objs.Length > 0)
                {
                    System.ComponentModel.DescriptionAttribute da = (System.ComponentModel.DescriptionAttribute)objs[0];
                    text = da.Description;
                }
                var d    = Convert.ToInt32(Convert.ChangeType(obj, type));
                var item = new SelectListItem()
                {
                    Text = text, Value = d.ToString()
                };
                if (selectValue.HasValue)
                {
                    item.Selected = d == selectValue.Value;
                }
                list.Add(item);
            }
            return(list);
        }
        /// <summary>
        /// Return a List of Variance records representing the differences between two entity objects
        /// </summary>
        /// <typeparam name="T">The Entity Type</typeparam>
        /// <param name="sourceObject">The Source object</param>
        /// <param name="targetObject">The Taget object</param>
        /// <param name="ignoreID">set to true to ensure the ID property is not compared</param>
        /// <returns>Lists of Variance records <see cref="List{T}"/> <seealso cref="Variance"/></returns>
        public static List <Variance> DetailedCompare <T>(this T sourceObject, T targetObject, bool ignoreID = false)
        {
            try
            {
                List <Variance> variances = new List <Variance>();
                if (sourceObject != null && targetObject != null)
                {
                    var properties = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);

                    foreach (var property in properties)
                    {
                        string propertyName = property.Name;
                        bool   isEditable   = true; // used to skip properties
                        var    ComputedATT  = property.GetCustomAttribute(typeof(Dapper.Contrib.Extensions.ComputedAttribute));
                        var    KeyAtt       = property.GetCustomAttribute(typeof(Dapper.Contrib.Extensions.KeyAttribute));
                        var    EditableATT  = property.GetCustomAttribute(typeof(EditableAttribute));
                        if (EditableATT != null)
                        {
                            isEditable = property.GetCustomAttribute <EditableAttribute>().AllowEdit;
                        }
                        if (ComputedATT != null)
                        {
                            isEditable = false;
                        }
                        if (isEditable)
                        {
                            if (property.Name.ToUpper() == "ID" && ignoreID)
                            {
                                continue;
                            }
                            string category = "Misc";
                            System.ComponentModel.AttributeCollection  attributes          = System.ComponentModel.TypeDescriptor.GetProperties(sourceObject)[property.Name].Attributes;
                            System.ComponentModel.CategoryAttribute    propertyCategory    = (System.ComponentModel.CategoryAttribute)attributes[typeof(System.ComponentModel.CategoryAttribute)];
                            System.ComponentModel.DisplayNameAttribute propertyDisplayName = (System.ComponentModel.DisplayNameAttribute)attributes[typeof(System.ComponentModel.DisplayNameAttribute)];
                            System.ComponentModel.DescriptionAttribute propertyDescription = (System.ComponentModel.DescriptionAttribute)attributes[typeof(System.ComponentModel.DescriptionAttribute)];
                            category = propertyCategory.Category;
                            if (property.PropertyType.IsClass)
                            {
                                category = "Class";
                            }
                            var v = new Variance
                            {
                                PropertyName        = property.Name,
                                PropertyType        = property.PropertyType,
                                PropertyCategory    = propertyCategory.Category,
                                PropertyDescription = propertyDescription.Description,
                                PropertyDisplayName = (!string.IsNullOrEmpty(propertyDisplayName.DisplayName) ? propertyDisplayName.DisplayName : property.Name),
                                OldValue            = property.GetValue(sourceObject),
                                NewValue            = property.GetValue(targetObject)
                            };

                            if (v.OldValue == null && v.NewValue == null)
                            {
                                continue;
                            }
                            if ((v.OldValue == null && v.NewValue != null) ||
                                (v.OldValue != null && v.NewValue == null))
                            {
                                variances.Add(v);
                                continue;
                            }
                            if (!v.OldValue.Equals(v.NewValue))
                            {
                                variances.Add(v);
                            }
                            if (v.OldValue.Equals(v.NewValue) && KeyAtt != null)
                            {
                                v.isKeyField = true;
                                variances.Add(v);
                            }
                        }
                    }
                }
                return(variances);
            }
            catch (System.Exception)
            {
                throw;
            }
        }
 public EnumDisplay(System.Type enumType, object enumValue, System.ComponentModel.DescriptionAttribute attr)
 {
     EnglishText = attr.Description;
     Value       = (int)enumValue;
     Name        = System.Enum.GetName(enumType, enumValue);
 }
Exemple #21
0
 public void Attributes_Cities_DescriptionAttribute_Property()
 {
     System.ComponentModel.DescriptionAttribute attr = ExpectPropertyAttribute <System.ComponentModel.DescriptionAttribute>(typeof(Zip), "Code");
     Assert.AreEqual("Zip codes must be 5 digits starting with 9", attr.Description);
 }
Exemple #22
0
 public void Attributes_Cities_DescriptionAttribute_Type()
 {
     System.ComponentModel.DescriptionAttribute attr = ExpectTypeAttribute <System.ComponentModel.DescriptionAttribute>(typeof(Zip));
     Assert.AreEqual("Zip code entity", attr.Description);
 }
Exemple #23
0
 private static void CheckDescribedOrHidden(PropertyInfo property)
 {
     System.ComponentModel.DescriptionAttribute attribute = property.GetCustomAttribute <System.ComponentModel.DescriptionAttribute>();
     attribute.Should().NotBeNull();
 }
Exemple #24
0
        public Hashtable GetDescription()
        {
            Hashtable hashtable = new Hashtable();

            if (_amfBody != null)
            {
                hashtable["version"] = "1.0";
                hashtable["address"] = _amfBody.TypeName;
                Type type = TypeHelper.Locate(_amfBody.TypeName);
                hashtable["description"] = "Service description not found.";
                ArrayList functions = new ArrayList();
                if (type != null)
                {
                    object[] attributes = type.GetCustomAttributes(typeof(System.ComponentModel.DescriptionAttribute), false);
                    if (attributes != null && attributes.Length > 0)
                    {
                        System.ComponentModel.DescriptionAttribute descriptionAttribute = attributes[0] as System.ComponentModel.DescriptionAttribute;
                        hashtable["description"] = descriptionAttribute.Description;
                    }

                    foreach (MethodInfo methodInfo in type.GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly))
                    {
                        if (TypeHelper.SkipMethod(methodInfo))
                        {
                            continue;
                        }

                        string description = TypeHelper.GetDescription(methodInfo);

                        Hashtable functionHashtable = new Hashtable();
                        functionHashtable["name"]        = methodInfo.Name;
                        functionHashtable["version"]     = "1.0";
                        functionHashtable["description"] = description;
                        if (methodInfo.ReturnType.Name == "Void")
                        {
                            functionHashtable["returns"] = "undefined";
                        }
                        else
                        {
                            functionHashtable["returns"] = methodInfo.ReturnType.Name;
                        }

                        ArrayList parameters = new ArrayList();
                        functionHashtable["arguments"] = parameters;

                        if (methodInfo.GetParameters() != null && methodInfo.GetParameters().Length > 0)
                        {
                            foreach (ParameterInfo parameterInfo in methodInfo.GetParameters())
                            {
                                Hashtable parameter = new Hashtable();
                                parameter["name"]     = parameterInfo.Name;
                                parameter["required"] = true;
                                if (parameterInfo.ParameterType.IsArray)
                                {
                                    parameter["type"] = "Array";
                                }
                                else
                                {
                                    parameter["type"] = parameterInfo.ParameterType.Name;
                                }
                                parameters.Add(parameter);
                            }
                        }

                        functions.Add(functionHashtable);
                    }
                }
                hashtable["functions"] = functions;
            }
            return(hashtable);
        }
Exemple #25
0
        // Basic setup - get description, category etc.
        private void SetAttributeInfo(object[] attributes)
        {
            // DOCUMENT: Description in ExcelFunctionAtribute overrides DescriptionAttribute
            // DOCUMENT: Default Category is Current Library Name.
            // Get System.ComponentModel.DescriptionAttribute
            // Search through attribs for Description
            foreach (object attrib in attributes)
            {
                System.ComponentModel.DescriptionAttribute desc =
                    attrib as System.ComponentModel.DescriptionAttribute;
                if (desc != null)
                {
                    Description = desc.Description;
                }

                // There was a problem with the type identification when checking the
                // attribute types, for the second instance of the .xll
                // that is loaded.
                // So I check on the names and access through reflection.
                // CONSIDER: Fix again? It should rather be
                //ExcelFunctionAttribute xlfunc = attrib as ExcelFunctionAttribute;
                //if (xlfunc != null)
                //{
                //    if (xlfunc.Name != null)
                //    {
                //        Name = xlfunc.Name;
                //    }
                //    if (xlfunc.Description != null)
                //    {
                //        Description = xlfunc.Description;
                //    }
                //    if (xlfunc.Category != null)
                //    {
                //        Category = xlfunc.Category;
                //    }
                //    if (xlfunc.HelpTopic != null)
                //    {
                //        HelpTopic = xlfunc.HelpTopic;
                //    }
                //    IsVolatile = xlfunc.IsVolatile;
                //    IsExceptionSafe = xlfunc.IsExceptionSafe;
                //    IsMacroType = xlfunc.IsMacroType;
                //}
                //ExcelCommandAttribute xlcmd = attrib as ExcelCommandAttribute;
                //if (xlcmd != null)
                //{
                //    if (xlcmd.Name != null)
                //    {
                //        Name = xlcmd.Name;
                //    }
                //    if (xlcmd.Description != null)
                //    {
                //        Description = xlcmd.Description;
                //    }
                //    if (xlcmd.HelpTopic != null)
                //    {
                //        HelpTopic = xlcmd.HelpTopic;
                //    }
                //    if (xlcmd.ShortCut != null)
                //    {
                //        ShortCut = xlcmd.ShortCut;
                //    }
                //    if (xlcmd.MenuName != null)
                //    {
                //        MenuName = xlcmd.MenuName;
                //    }
                //    if (xlcmd.MenuText != null)
                //    {
                //        MenuText = xlcmd.MenuText;
                //    }
                //    IsHidden = xlcmd.IsHidden;
                //    IsExceptionSafe = xlcmd.IsExceptionSafe;
                //}

                Type attribType = attrib.GetType();
                if (attribType.FullName == "ExcelDna.Integration.ExcelFunctionAttribute")
                {
                    string name            = (string)attribType.GetField("Name").GetValue(attrib);
                    string description     = (string)attribType.GetField("Description").GetValue(attrib);
                    string category        = (string)attribType.GetField("Category").GetValue(attrib);
                    string helpTopic       = (string)attribType.GetField("HelpTopic").GetValue(attrib);
                    bool   isVolatile      = (bool)attribType.GetField("IsVolatile").GetValue(attrib);
                    bool   isExceptionSafe = (bool)attribType.GetField("IsExceptionSafe").GetValue(attrib);
                    bool   isMacroType     = (bool)attribType.GetField("IsMacroType").GetValue(attrib);
                    bool   isHidden        = (bool)attribType.GetField("IsHidden").GetValue(attrib);
                    bool   isThreadSafe    = (bool)attribType.GetField("IsThreadSafe").GetValue(attrib);
                    if (name != null)
                    {
                        Name = name;
                    }
                    if (description != null)
                    {
                        Description = description;
                    }
                    if (category != null)
                    {
                        Category = category;
                    }
                    if (helpTopic != null)
                    {
                        HelpTopic = helpTopic;
                    }
                    IsVolatile      = isVolatile;
                    IsExceptionSafe = isExceptionSafe;
                    IsMacroType     = isMacroType;
                    IsHidden        = isHidden;
                    IsThreadSafe    = (!isMacroType && isThreadSafe);
                }

                if (attribType.FullName == "ExcelDna.Integration.ExcelCommandAttribute")
                {
                    string name        = (string)attribType.GetField("Name").GetValue(attrib);
                    string description = (string)attribType.GetField("Description").GetValue(attrib);
                    string helpTopic   = (string)attribType.GetField("HelpTopic").GetValue(attrib);
                    string shortCut    = (string)attribType.GetField("ShortCut").GetValue(attrib);
                    string menuName    = (string)attribType.GetField("MenuName").GetValue(attrib);
                    string menuText    = (string)attribType.GetField("MenuText").GetValue(attrib);
//                    bool isHidden = (bool)attribType.GetField("IsHidden").GetValue(attrib);
                    bool isExceptionSafe = (bool)attribType.GetField("IsExceptionSafe").GetValue(attrib);

                    if (name != null)
                    {
                        Name = name;
                    }
                    if (description != null)
                    {
                        Description = description;
                    }
                    if (helpTopic != null)
                    {
                        HelpTopic = helpTopic;
                    }
                    if (shortCut != null)
                    {
                        ShortCut = shortCut;
                    }
                    if (menuName != null)
                    {
                        MenuName = menuName;
                    }
                    if (menuText != null)
                    {
                        MenuText = menuText;
                    }
//                    IsHidden = isHidden;  // Only for functions.
                    IsExceptionSafe = isExceptionSafe;
                }
            }
        }
Exemple #26
0
        public Type BoxedValueType;             // Causes a wrapper to be created that boxes the return type from the user method,
        // allowing Custom Marshaling to be injected

        public XlParameterInfo(ParameterInfo paramInfo)
        {
            // Add Name and Description
            // CONSIDER: Override Marshaler for row/column arrays according to some attribute

            // Some pre-checks
            if (paramInfo.ParameterType.IsByRef)
            {
                throw new DnaMarshalException("Parameter is ByRef: " + paramInfo.Name);
            }

            // Default Name and Description
            Name           = paramInfo.Name;
            Description    = "";
            AllowReference = false;

            // Get Description
            object[] attribs = paramInfo.GetCustomAttributes(false);
            // Search through attribs for Description
            foreach (object attrib in attribs)
            {
                System.ComponentModel.DescriptionAttribute desc =
                    attrib as System.ComponentModel.DescriptionAttribute;
                if (desc != null)
                {
                    Description = desc.Description;
                }
                //// HACK: Some problem with library references -
                //// For now relax the assembly reference and use late-bound
                Type attribType = attrib.GetType();
                if (attribType.FullName == "ExcelDna.Integration.ExcelArgumentAttribute")
                {
                    string name           = (string)attribType.GetField("Name").GetValue(attrib);
                    string description    = (string)attribType.GetField("Description").GetValue(attrib);
                    object allowReference = attribType.GetField("AllowReference").GetValue(attrib);

                    if (name != null)
                    {
                        Name = name;
                    }
                    if (description != null)
                    {
                        Description = description;
                    }
                    if (allowReference != null)
                    {
                        AllowReference = (bool)allowReference;
                    }
                }
                // HACK: Here is the other code:
                //ExcelArgumentAttribute xlparam = attrib as ExcelArgumentAttribute;
                //if (xlparam != null)
                //{
                //    if (xlparam.Name != null)
                //    {
                //        Name = xlparam.Name;
                //    }
                //    if (xlparam.Description != null)
                //    {
                //        Description = xlparam.Description;
                //    }
                //    AllowReference = xlparam.AllowReference;
                //}
            }
            SetTypeInfo(paramInfo.ParameterType, false, false);
        }
Exemple #27
0
        public void Build(Type type, Hashtable typeDescriptorDictionary)
        {
            _attributeCollection.Clear();
            _fullName      = type.FullName;
            _name          = type.Name;
            _isArray       = type.IsArray;
            this.Namespace = type.Namespace;

            ArrayList interfaces = new ArrayList();

            foreach (Type typeInterface in type.GetInterfaces())
            {
                if (!typeDescriptorDictionary.Contains(typeInterface))
                {
                    TypeDescriptor typeDescriptorTmp = new TypeDescriptor(typeInterface);
                    typeDescriptorDictionary.Add(typeInterface, typeDescriptorTmp);
                    typeDescriptorTmp.Build(typeInterface, typeDescriptorDictionary);
                }
                TypeDescriptor typeDescriptor = typeDescriptorDictionary[typeInterface] as TypeDescriptor;
                interfaces.Add(typeDescriptor);
            }
            _interfaces = interfaces.ToArray(typeof(TypeDescriptor)) as TypeDescriptor[];

            ArrayList methods = new ArrayList();

            foreach (MethodInfo methodInfo in type.GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly))
            {
                if (SkipMethod(methodInfo))
                {
                    continue;
                }

                MethodDescriptor methodDescriptor = new MethodDescriptor();
                methodDescriptor.Build(methodInfo);
                methods.Add(methodDescriptor);
            }
            _methods = methods.ToArray(typeof(MethodDescriptor)) as MethodDescriptor[];

            PropertyInfo[] propertyInfos = type.GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly);
            ArrayList      properties    = new ArrayList(propertyInfos);
            int            i             = 0;

            for (i = properties.Count - 1; i >= 0; i--)
            {
                PropertyInfo propertyInfo = properties[i] as PropertyInfo;
                if (propertyInfo.GetCustomAttributes(typeof(NonSerializedAttribute), true).Length > 0)
                {
                    properties.RemoveAt(i);
                }
                if (propertyInfo.GetCustomAttributes(typeof(TransientAttribute), true).Length > 0)
                {
                    properties.RemoveAt(i);
                }
                if (propertyInfo.GetGetMethod() == null || propertyInfo.GetGetMethod().GetParameters().Length > 0)
                {
                    properties.RemoveAt(i);
                }
            }
            ArrayList tmp = new ArrayList(properties.Count);

            foreach (PropertyInfo propertyInfo in properties)
            {
                if (!typeDescriptorDictionary.Contains(propertyInfo.PropertyType))
                {
                    TypeDescriptor typeDescriptorTmp = new TypeDescriptor(propertyInfo.PropertyType);
                    typeDescriptorDictionary.Add(propertyInfo.PropertyType, typeDescriptorTmp);
                    typeDescriptorTmp.Build(propertyInfo.PropertyType, typeDescriptorDictionary);
                }
                TypeDescriptor     typeDescriptor     = typeDescriptorDictionary[propertyInfo.PropertyType] as TypeDescriptor;
                PropertyDescriptor propertyDescriptor = new PropertyDescriptor(propertyInfo.Name, typeDescriptor);
                tmp.Add(propertyDescriptor);
            }
            _properties = tmp.ToArray(typeof(PropertyDescriptor)) as PropertyDescriptor[];

            FieldInfo[] fieldInfos = type.GetFields(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly);
            ArrayList   fields     = new ArrayList(fieldInfos);

            for (i = fields.Count - 1; i >= 0; i--)
            {
                FieldInfo fieldInfo = fields[i] as FieldInfo;
                if (fieldInfo.GetCustomAttributes(typeof(NonSerializedAttribute), true).Length > 0)
                {
                    fields.RemoveAt(i);
                }
                if (fieldInfo.GetCustomAttributes(typeof(TransientAttribute), true).Length > 0)
                {
                    fields.RemoveAt(i);
                }
            }
            tmp = new ArrayList(fields.Count);
            foreach (FieldInfo fieldInfo in fields)
            {
                if (!typeDescriptorDictionary.Contains(fieldInfo.FieldType))
                {
                    TypeDescriptor typeDescriptorTmp = new TypeDescriptor(fieldInfo.FieldType);
                    typeDescriptorDictionary.Add(fieldInfo.FieldType, typeDescriptorTmp);
                    typeDescriptorTmp.Build(fieldInfo.FieldType, typeDescriptorDictionary);
                }
                TypeDescriptor  typeDescriptor  = typeDescriptorDictionary[fieldInfo.FieldType] as TypeDescriptor;
                FieldDescriptor fieldDescriptor = new FieldDescriptor(fieldInfo.Name, typeDescriptor);
                tmp.Add(fieldDescriptor);
            }
            _fields = tmp.ToArray(typeof(FieldDescriptor)) as FieldDescriptor[];


            object[] attrs = type.GetCustomAttributes(typeof(System.ComponentModel.DescriptionAttribute), false);
            if (attrs.Length > 0)
            {
                System.ComponentModel.DescriptionAttribute descriptionAttribute = attrs[0] as System.ComponentModel.DescriptionAttribute;
                _description = descriptionAttribute.Description;
            }

            attrs = type.GetCustomAttributes(true);
            if (attrs != null && attrs.Length > 0)
            {
                for (i = 0; i < attrs.Length; i++)
                {
                    Attribute attribute = attrs[i] as Attribute;
                    if (attribute is System.ComponentModel.DescriptionAttribute)
                    {
                        continue;
                    }
                    AttributeDescriptor attributeDescriptor = new AttributeDescriptor(attribute.GetType().Name);
                    if (!_attributeCollection.Contains(attributeDescriptor.Name))
                    {
                        _attributeCollection.Add(attributeDescriptor);
                    }
                }
            }
        }
Exemple #28
0
        // Basic setup - get description, category etc.
        void SetAttributeInfo(object attrib)
        {
            if (attrib == null)
            {
                return;
            }

            // DOCUMENT: Description in ExcelFunctionAtribute overrides DescriptionAttribute
            // DOCUMENT: Default Category is Current Library Name.
            // Get System.ComponentModel.DescriptionAttribute
            // Search through attribs for Description
            System.ComponentModel.DescriptionAttribute desc =
                attrib as System.ComponentModel.DescriptionAttribute;
            if (desc != null)
            {
                Description = desc.Description;
                return;
            }

            // There was a problem with the type identification when checking the
            // attribute types, for the second instance of the .xll
            // that is loaded.
            // So I check on the names and access through reflection.
            // CONSIDER: Fix again? It should rather be
            //ExcelFunctionAttribute xlfunc = attrib as ExcelFunctionAttribute;
            //if (xlfunc != null)
            //{
            //    if (xlfunc.Name != null)
            //    {
            //        Name = xlfunc.Name;
            //    }
            //    if (xlfunc.Description != null)
            //    {
            //        Description = xlfunc.Description;
            //    }
            //    if (xlfunc.Category != null)
            //    {
            //        Category = xlfunc.Category;
            //    }
            //    if (xlfunc.HelpTopic != null)
            //    {
            //        HelpTopic = xlfunc.HelpTopic;
            //    }
            //    IsVolatile = xlfunc.IsVolatile;
            //    IsExceptionSafe = xlfunc.IsExceptionSafe;
            //    IsMacroType = xlfunc.IsMacroType;
            //}
            //ExcelCommandAttribute xlcmd = attrib as ExcelCommandAttribute;
            //if (xlcmd != null)
            //{
            //    if (xlcmd.Name != null)
            //    {
            //        Name = xlcmd.Name;
            //    }
            //    if (xlcmd.Description != null)
            //    {
            //        Description = xlcmd.Description;
            //    }
            //    if (xlcmd.HelpTopic != null)
            //    {
            //        HelpTopic = xlcmd.HelpTopic;
            //    }
            //    if (xlcmd.ShortCut != null)
            //    {
            //        ShortCut = xlcmd.ShortCut;
            //    }
            //    if (xlcmd.MenuName != null)
            //    {
            //        MenuName = xlcmd.MenuName;
            //    }
            //    if (xlcmd.MenuText != null)
            //    {
            //        MenuText = xlcmd.MenuText;
            //    }
            //    IsExceptionSafe = xlcmd.IsExceptionSafe;
            //    IsCommand = true;
            //}

            Type attribType = attrib.GetType();

            if (TypeHelper.TypeHasAncestorWithFullName(attribType, "ExcelDna.Integration.ExcelFunctionAttribute"))
            {
                string name                 = (string)attribType.GetField("Name").GetValue(attrib);
                string description          = (string)attribType.GetField("Description").GetValue(attrib);
                string category             = (string)attribType.GetField("Category").GetValue(attrib);
                string helpTopic            = (string)attribType.GetField("HelpTopic").GetValue(attrib);
                bool   isVolatile           = (bool)attribType.GetField("IsVolatile").GetValue(attrib);
                bool   isExceptionSafe      = (bool)attribType.GetField("IsExceptionSafe").GetValue(attrib);
                bool   isMacroType          = (bool)attribType.GetField("IsMacroType").GetValue(attrib);
                bool   isHidden             = (bool)attribType.GetField("IsHidden").GetValue(attrib);
                bool   isThreadSafe         = (bool)attribType.GetField("IsThreadSafe").GetValue(attrib);
                bool   isClusterSafe        = (bool)attribType.GetField("IsClusterSafe").GetValue(attrib);
                bool   explicitRegistration = (bool)attribType.GetField("ExplicitRegistration").GetValue(attrib);
                if (name != null)
                {
                    Name = name;
                }
                if (description != null)
                {
                    Description = description;
                }
                if (category != null)
                {
                    Category = category;
                }
                if (helpTopic != null)
                {
                    HelpTopic = helpTopic;
                }
                IsVolatile      = isVolatile;
                IsExceptionSafe = isExceptionSafe;
                IsMacroType     = isMacroType;
                IsHidden        = isHidden;
                IsThreadSafe    = (!isMacroType && isThreadSafe);
                // DOCUMENT: IsClusterSafe function MUST NOT be marked as IsMacroType=true and MAY be marked as IsThreadSafe = true.
                //           [xlfRegister (Form 1) page in the Microsoft Excel 2010 XLL SDK Documentation]
                IsClusterSafe        = (!isMacroType && isClusterSafe);
                ExplicitRegistration = explicitRegistration;
                IsCommand            = false;
            }
            else if (TypeHelper.TypeHasAncestorWithFullName(attribType, "ExcelDna.Integration.ExcelCommandAttribute"))
            {
                string name        = (string)attribType.GetField("Name").GetValue(attrib);
                string description = (string)attribType.GetField("Description").GetValue(attrib);
                string helpTopic   = (string)attribType.GetField("HelpTopic").GetValue(attrib);
                string shortCut    = (string)attribType.GetField("ShortCut").GetValue(attrib);
                string menuName    = (string)attribType.GetField("MenuName").GetValue(attrib);
                string menuText    = (string)attribType.GetField("MenuText").GetValue(attrib);
//                    bool isHidden = (bool)attribType.GetField("IsHidden").GetValue(attrib);
                bool isExceptionSafe      = (bool)attribType.GetField("IsExceptionSafe").GetValue(attrib);
                bool explicitRegistration = (bool)attribType.GetField("ExplicitRegistration").GetValue(attrib);

                if (name != null)
                {
                    Name = name;
                }
                if (description != null)
                {
                    Description = description;
                }
                if (helpTopic != null)
                {
                    HelpTopic = helpTopic;
                }
                if (shortCut != null)
                {
                    ShortCut = shortCut;
                }
                if (menuName != null)
                {
                    MenuName = menuName;
                }
                if (menuText != null)
                {
                    MenuText = menuText;
                }
//                    IsHidden = isHidden;  // Only for functions.
                IsExceptionSafe      = isExceptionSafe;
                ExplicitRegistration = explicitRegistration;

                // Override IsCommand, even though this 'macro' might have a return value.
                // Allow for more flexibility in what kind of macros are supported, particularly for calling
                // via Application.Run.
                IsCommand = true;
            }
        }