Esempio n. 1
0
        private static void Register(Type type)
        {
            ChoTypeConverterAttribute customAttribute = type.GetCustomAttribute <ChoTypeConverterAttribute>();

            if (customAttribute != null)
            {
                _typeTypeConverterCache.Add(type, new object[] { customAttribute.CreateInstance() });
                _typeTypeConverterParamsCache.Add(type, new object[] { customAttribute.Parameters });
            }
            ChoPriorityQueue queue  = new ChoPriorityQueue();
            ChoPriorityQueue queue2 = new ChoPriorityQueue();

            foreach (Attribute attribute in ChoType.GetAttributes(type, typeof(ChoTypeConverterAttribute)))
            {
                ChoTypeConverterAttribute attribute2 = (ChoTypeConverterAttribute)attribute;
                if (attribute2 != null)
                {
                    queue.Enqueue(attribute2.Priority, attribute2.CreateInstance());
                    queue2.Enqueue(attribute2.Priority, attribute2.Parameters);
                }
            }
            if (queue.Count > 0)
            {
                _typeTypeConverterCache[type]       = queue.ToArray();
                _typeTypeConverterParamsCache[type] = queue2.ToArray();
                return;
            }

            TypeConverter converter = TypeDescriptor.GetConverter(type);

            if (converter != null && converter.GetType() != typeof(TypeConverter))
            {
                _typeTypeConverterCache.Add(type, new object[] { converter });
                _typeTypeConverterParamsCache.Add(type, EmptyParams);
            }
            else
            {
                _typeTypeConverterCache.Add(type, EmptyTypeConverters);
                _typeTypeConverterParamsCache.Add(type, EmptyParams);
            }
        }
        private void DiscoverCommands(Type builderType)
        {
            if (_commandsCache.ContainsKey(builderType))
            {
                return;
            }

            lock (_commandsCacheLock)
            {
                if (_commandsCache.ContainsKey(builderType))
                {
                    return;
                }

                Dictionary <string, Type> commands = new Dictionary <string, Type>();

                ChoCommandLineArgBuilderCommandAttribute[] attrs = null; // ChoType.GetAttributes<ChoCommandLineArgBuilderCommandAttribute>(builderType);
                ConstructorInfo constructorInfo = builderType.GetConstructor(new Type[] {});
                if (constructorInfo != null)
                {
                    attrs = ChoType.GetAttributes <ChoCommandLineArgBuilderCommandAttribute>(constructorInfo);
                }

                if (attrs != null)
                {
                    foreach (ChoCommandLineArgBuilderCommandAttribute attr in attrs)
                    {
                        commands.Add(attr.Command, attr.CommandType);
                    }
                }

                _commandsCache.Add(builderType, commands);

                List <ChoCommandLineArgBuilderCommandAttribute> attr1 = new List <ChoCommandLineArgBuilderCommandAttribute>(attrs);
                attr1.Sort((x, y) => x.Order.CompareTo(y.Order));
                _commandsAttrCache.Add(builderType, attr1);
            }
        }
Esempio n. 3
0
        //private static void SetAsNotDisposed(IChoProfile profile, bool dispose)
        //{
        //    if (profile == null)
        //        return;

        //    if (profile is ChoBufferProfile)
        //        ((ChoBufferProfile)profile).CanDispose = dispose;
        //    else if (profile is ChoStreamProfile)
        //        ((ChoStreamProfile)profile).CanDispose = dispose;
        //}

        private static string GetProfileName(string name, out MemberInfo memberInfo, out string typeProfileFileName,
                                             out ChoProfileAttribute memberProfileAttribute, out ChoProfileAttribute typeProfileAttribute)
        {
            typeProfileFileName = null;

            StackFrame stackFrame = ChoStackTrace.GetStackFrame(typeof(ChoProfile).Namespace);

            memberInfo = stackFrame.GetMethod();

            memberProfileAttribute = null;
            foreach (ChoProfileAttribute profileAttribute in ChoType.GetMemberAttributesByBaseType <ChoProfileAttribute>(memberInfo))
            {
                if (profileAttribute.Name == name)
                {
                    memberProfileAttribute = profileAttribute;
                    break;
                }
            }

            ChoProfileAttribute emptyTypeProfileAttribute = null;

            typeProfileAttribute = null;
            foreach (ChoProfileAttribute profileAttribute in ChoType.GetAttributes <ChoProfileAttribute>(memberInfo.ReflectedType))
            {
                if (String.IsNullOrEmpty(profileAttribute.Name))
                {
                    emptyTypeProfileAttribute = profileAttribute;
                }
                if (profileAttribute.Name == name)
                {
                    typeProfileAttribute = profileAttribute;
                    break;
                }
            }

            if (typeProfileAttribute == null)
            {
                if (emptyTypeProfileAttribute == null)
                {
                    typeProfileFileName = GLOBAL_PROFILE_NAME;
                }
                else
                {
                    typeProfileFileName = "{0}_{1}_{2}_{3}".FormatString(name.IsNullOrEmpty() ? "Default" : name, "Type", ChoThreadLocalStorage.Target == null ? 0 : ChoThreadLocalStorage.Target.GetHashCode(),
                                                                         ChoPropertyManager.ExpandProperties(ChoThreadLocalStorage.Target, emptyTypeProfileAttribute.Name));
                }
            }
            else
            {
                typeProfileFileName = "{0}_{1}_{2}_{3}".FormatString(name.IsNullOrEmpty() ? "Default" : name, "Type", ChoThreadLocalStorage.Target == null ? 0 : ChoThreadLocalStorage.Target.GetHashCode(),
                                                                     ChoPropertyManager.ExpandProperties(ChoThreadLocalStorage.Target, typeProfileAttribute.Name));
            }

            if (memberProfileAttribute != null)
            {
                return("{0}_{1}_{2}_{3}".FormatString(name.IsNullOrEmpty() ? "Default" : name, memberInfo.Name, ChoThreadLocalStorage.Target == null ? 0 : ChoThreadLocalStorage.Target.GetHashCode(),
                                                      ChoPropertyManager.ExpandProperties(ChoThreadLocalStorage.Target, memberProfileAttribute.Name)));
            }
            else
            {
                return(typeProfileFileName);
            }
        }
Esempio n. 4
0
        public static bool IsValidFor(this object @this, MemberInfo mi, out Exception aggEx)
        {
            aggEx = null;
            ChoGuard.ArgumentNotNullOrEmpty(@this, "Target");

            if (@this == null)
            {
                return(true);
            }

            var results = new List <ValidationResult>();

            if (@this is IChoValidatable)
            {
                ((IChoValidatable)@this).TryValidateFor(mi.Name, results);
            }
            else
            {
                //if (ChoObjectMemberMetaDataCache.Default.IsRequired(mi) && ChoType.GetMemberValue(@this, mi) == null)
                //    results.Add(new ValidationResult("Null value found for {0} member.".FormatString(mi.Name)));

                var context = new ValidationContext(@this, null, null);
                context.MemberName = mi.Name;

                Validator.TryValidateValue(ChoType.GetMemberValue(@this, mi), context, results, ChoType.GetAttributes <ValidationAttribute>(mi));
            }

            if (results.Count > 0)
            {
                aggEx = new ApplicationException("Failed to validate '{0}' member. {2}{1}".FormatString(mi.Name, ToString(results), Environment.NewLine));
                return(false);
            }
            else
            {
                return(true);
            }
        }
Esempio n. 5
0
        public static object[] GetTypeConverters(MemberInfo memberInfo)
        {
            if (memberInfo == null)
            {
                return(null);
            }

            Type memberType;

            if (ChoType.TryGetMemberType(memberInfo, out memberType) && (memberType == null /*|| memberType.IsSimple() */))
            {
                return(null);
            }

            if (_typeMemberTypeConverterCache.ContainsKey(memberInfo))
            {
                if (_typeMemberTypeConverterCache[memberInfo] == EmptyTypeConverters)
                {
                    if (_typeTypeConverterCache.ContainsKey(memberType))
                    {
                        return(_typeTypeConverterCache[memberType]);
                    }
                }

                return(_typeMemberTypeConverterCache[memberInfo]);
            }
            else
            {
                lock (_typeMemberTypeConverterCacheLockObject)
                {
                    if (!_typeMemberTypeConverterCache.ContainsKey(memberInfo))
                    {
                        Type typeConverterAttribute = typeof(ChoTypeConverterAttribute);

                        _typeMemberTypeConverterCache[memberInfo]       = EmptyTypeConverters;
                        _typeMemberTypeConverterParamsCache[memberInfo] = EmptyParams;

                        ChoPriorityQueue queue       = new ChoPriorityQueue();
                        ChoPriorityQueue paramsQueue = new ChoPriorityQueue();
                        foreach (Attribute attribute in ChoType.GetAttributes(memberInfo, typeof(ChoTypeConverterAttribute), false))
                        {
                            ChoTypeConverterAttribute converterAttribute = (ChoTypeConverterAttribute)attribute;
                            if (converterAttribute != null)
                            {
                                queue.Enqueue(converterAttribute.Priority, converterAttribute.CreateInstance());
                                paramsQueue.Enqueue(converterAttribute.Priority, converterAttribute.Parameters);
                            }

                            if (queue.Count > 0)
                            {
                                _typeMemberTypeConverterCache[memberInfo]       = queue.ToArray();
                                _typeMemberTypeConverterParamsCache[memberInfo] = paramsQueue.ToArray();

                                return(_typeMemberTypeConverterCache[memberInfo]);
                            }
                        }

                        if (queue.Count == 0 && !memberType.IsSimple())
                        {
                            if (!_typeTypeConverterCache.ContainsKey(memberType))
                            {
                                foreach (Type type in ChoType.GetTypes <ChoTypeConverterAttribute>())
                                {
                                    ChoTypeConverterAttribute converterAttribute = type.GetCustomAttribute <ChoTypeConverterAttribute>();
                                    if (converterAttribute != null && converterAttribute.ConverterType == memberType)
                                    {
                                        _typeTypeConverterCache.Add(memberType, new object[] { ChoType.CreateInstance(type) });
                                        _typeTypeConverterParamsCache.Add(memberType, new object[] { converterAttribute.Parameters });

                                        return(_typeTypeConverterCache[memberType]);
                                    }
                                }

                                TypeConverter converter = TypeDescriptor.GetConverter(memberType);
                                if (converter != null)
                                {
                                    _typeTypeConverterCache.Add(memberType, new object[] { converter });
                                }
                                else
                                {
                                    _typeTypeConverterCache.Add(memberType, EmptyTypeConverters);
                                }

                                _typeTypeConverterParamsCache.Add(memberType, EmptyParams);
                            }

                            return(_typeTypeConverterCache[memberType]);
                        }
                    }

                    return(_typeMemberTypeConverterCache.ContainsKey(memberInfo) ? _typeMemberTypeConverterCache[memberInfo] : EmptyTypeConverters);
                }
            }
        }
        public virtual string GetUsage()
        {
            Type type = GetType();

            DiscoverCommands(type);

            StringBuilder builder      = new StringBuilder();
            StringBuilder whereBuilder = new StringBuilder();

            builder.Append(Environment.NewLine);
            builder.Append("The syntax of this command is:");
            builder.Append(Environment.NewLine);
            builder.Append(Environment.NewLine);
            builder.Append(Path.GetFileNameWithoutExtension(ChoApplication.EntryAssemblyFileName).ToUpper());

            if (_commandsAttrCache.ContainsKey(type))
            {
                foreach (ChoCommandLineArgBuilderCommandAttribute attr in _commandsAttrCache[type].ToArray())
                {
                    if (whereBuilder.Length == 0)
                    {
                        whereBuilder.Append(attr.Command);
                    }
                    else
                    {
                        whereBuilder.Append(" | {0}".FormatString(attr.Command));
                    }
                }
                if (whereBuilder.Length > 0)
                {
                    builder.Append(" [{0}]".FormatString(whereBuilder.ToString()));
                }
            }

            builder.Append(Environment.NewLine);

            foreach (ChoCommandLineArgAdditionalUsageAttribute commandLineArgAdditionalUsageAttribute in ChoType.GetAttributes <ChoCommandLineArgAdditionalUsageAttribute>(type))
            {
                if (commandLineArgAdditionalUsageAttribute != null && !commandLineArgAdditionalUsageAttribute.AdditionalUsageText.IsNull())
                {
                    builder.Append(commandLineArgAdditionalUsageAttribute.AdditionalUsageText);

                    builder.Append(Environment.NewLine);
                    builder.Append(Environment.NewLine);
                }
            }

            return(builder.ToString());
        }
Esempio n. 7
0
        public virtual string GetUsage()
        {
            Type type = GetType();

            StringBuilder builder      = new StringBuilder();
            StringBuilder whereBuilder = new StringBuilder();

            ChoCommandLineParserSettings commandLineParserSettings = ChoCommandLineParserSettings.Me;
            char cmdLineValueSeparator = commandLineParserSettings.ValueSeparators != null && commandLineParserSettings.ValueSeparators.Length > 0 ? commandLineParserSettings.ValueSeparators[0] : ':';
            char cmdLineSwitchChar     = commandLineParserSettings.SwitchChars != null && commandLineParserSettings.SwitchChars.Length > 0 ? commandLineParserSettings.SwitchChars[0] : '-';

            builder.Append(Path.GetFileNameWithoutExtension(Assembly.GetEntryAssembly().Location).ToUpper());
            MemberInfo[] memberInfos = ChoTypeMembersCache.GetAllMemberInfos(type);

            if (memberInfos != null && memberInfos.Length > 0)
            {
                ChoCommandLineArgAttribute           commandLineArgumentAttribute   = null;
                ChoDefaultCommandLineArgAttribute    defaultCommandLineArgAttribute = null;
                ChoPositionalCommandLineArgAttribute posCommandLineArgAttribute     = null;

                List <Tuple <ChoDefaultCommandLineArgAttribute, MemberInfo> > memberList = new List <Tuple <ChoDefaultCommandLineArgAttribute, MemberInfo> >();
                foreach (MemberInfo memberInfo in memberInfos)
                {
                    commandLineArgumentAttribute   = null;
                    defaultCommandLineArgAttribute = null;

                    defaultCommandLineArgAttribute = commandLineArgumentAttribute = (ChoCommandLineArgAttribute)memberInfo.GetCustomAttribute <ChoCommandLineArgAttribute>(true);
                    if (commandLineArgumentAttribute == null)
                    {
                        defaultCommandLineArgAttribute = posCommandLineArgAttribute = (ChoPositionalCommandLineArgAttribute)memberInfo.GetCustomAttribute <ChoPositionalCommandLineArgAttribute>(true);
                        if (posCommandLineArgAttribute == null)
                        {
                            continue;
                        }
                    }

                    memberList.Add(new Tuple <ChoDefaultCommandLineArgAttribute, MemberInfo>(defaultCommandLineArgAttribute, memberInfo));
                }

                bool isEmptyShortName;

                memberList.Sort((x, y) =>
                                x.Item1.Order.CompareTo(y.Item1.Order));

                MemberInfo memberInfo1 = null;
                foreach (Tuple <ChoDefaultCommandLineArgAttribute, MemberInfo> tuple in memberList)
                {
                    memberInfo1 = tuple.Item2;

                    commandLineArgumentAttribute   = null;
                    defaultCommandLineArgAttribute = null;

                    defaultCommandLineArgAttribute = commandLineArgumentAttribute = (ChoCommandLineArgAttribute)memberInfo1.GetCustomAttribute <ChoCommandLineArgAttribute>(true);
                    if (commandLineArgumentAttribute == null)
                    {
                        defaultCommandLineArgAttribute = posCommandLineArgAttribute = (ChoPositionalCommandLineArgAttribute)memberInfo1.GetCustomAttribute <ChoPositionalCommandLineArgAttribute>(true);
                        if (posCommandLineArgAttribute == null)
                        {
                            continue;
                        }
                    }

                    isEmptyShortName = !defaultCommandLineArgAttribute.ShortName.IsNull() &&
                                       defaultCommandLineArgAttribute.ShortName.Length == 0;

                    if (!defaultCommandLineArgAttribute.IsRequired)
                    {
                        builder.Append(" [");
                    }
                    else
                    {
                        builder.Append(" ");
                    }

                    Type memberType = ChoType.GetMemberType(memberInfo1);
                    if (memberType.IsNullableType())
                    {
                        memberType = Nullable.GetUnderlyingType(memberType);
                    }

                    if (commandLineArgumentAttribute != null)
                    {
                        builder.Append("{0}{1}{2}".FormatString(cmdLineSwitchChar, commandLineArgumentAttribute.CommandLineSwitch, !isEmptyShortName ? cmdLineValueSeparator.ToString() : String.Empty));
                    }

                    string description = null;
                    if (commandLineArgumentAttribute != null)
                    {
                        description = commandLineArgumentAttribute.Description;
                    }
                    else if (posCommandLineArgAttribute != null)
                    {
                        description = posCommandLineArgAttribute.Description;
                    }
                    else
                    {
                        description = defaultCommandLineArgAttribute.Description;
                    }

                    if (_commandLineArgsObjectAttribute.GetDisplayDefaultValue())
                    {
                        string defaultValue = null;
                        defaultValue = GetDefaultValueText(memberInfo1);
                        if (defaultValue != null && memberType != typeof(bool))
                        {
                            description = "{0} [DEFAULT: {1}]".FormatString(description, defaultValue);
                        }
                    }

                    if (commandLineArgumentAttribute != null)
                    {
                        whereBuilder.AppendFormat("{1}{3}{2}{0}", Environment.NewLine, GetCmdLineSwitches(cmdLineSwitchChar, commandLineArgumentAttribute),
                                                  description.WrapLongLines(commandLineArgumentAttribute.DescriptionFormatLineSize, String.Empty,
                                                                            commandLineArgumentAttribute.DescriptionFormatLineBreakChar, commandLineArgumentAttribute.NoOfTabsSwitchDescFormatSeparator),
                                                  "\t".Repeat(commandLineArgumentAttribute.NoOfTabsSwitchDescFormatSeparator));
                    }
                    else if (posCommandLineArgAttribute != null)
                    {
                        whereBuilder.AppendFormat("{1}{3}{2}{0}", Environment.NewLine,
                                                  defaultCommandLineArgAttribute.ShortName.IsNull() ? "Position{0}".FormatString(posCommandLineArgAttribute.Position) : defaultCommandLineArgAttribute.ShortName,
                                                  description.WrapLongLines(posCommandLineArgAttribute.DescriptionFormatLineSize, String.Empty,
                                                                            posCommandLineArgAttribute.DescriptionFormatLineBreakChar, posCommandLineArgAttribute.NoOfTabsSwitchDescFormatSeparator),
                                                  "\t".Repeat(posCommandLineArgAttribute.NoOfTabsSwitchDescFormatSeparator));
                    }
                    else
                    {
                        whereBuilder.AppendFormat("{3}{2}{1}{0}", Environment.NewLine,
                                                  description.WrapLongLines(defaultCommandLineArgAttribute.DescriptionFormatLineSize, String.Empty,
                                                                            defaultCommandLineArgAttribute.DescriptionFormatLineBreakChar, defaultCommandLineArgAttribute.NoOfTabsSwitchDescFormatSeparator),
                                                  "\t".Repeat(defaultCommandLineArgAttribute.NoOfTabsSwitchDescFormatSeparator), DefaultCmdLineSwitch);
                    }

                    if (memberType == typeof(int))
                    {
                        if (!defaultCommandLineArgAttribute.ShortName.IsNull())
                        {
                            builder.Append(defaultCommandLineArgAttribute.ShortName);
                        }
                        else
                        {
                            builder.Append("<int>");
                        }
                    }
                    else if (memberType == typeof(uint))
                    {
                        if (!defaultCommandLineArgAttribute.ShortName.IsNull())
                        {
                            builder.Append(defaultCommandLineArgAttribute.ShortName);
                        }
                        else
                        {
                            builder.Append("<uint>");
                        }
                    }
                    else if (memberType == typeof(bool))
                    {
                        builder.Remove(builder.Length - 1, 1);
                    }
                    else if (memberType == typeof(string))
                    {
                        if (!defaultCommandLineArgAttribute.ShortName.IsNull())
                        {
                            builder.Append(defaultCommandLineArgAttribute.ShortName);
                        }
                        else
                        {
                            builder.Append("<string>");
                        }
                    }
                    else if (memberType.IsEnum)
                    {
                        //builder.Append("{0}{1}{2}".FormatString(cmdLineSwitchChar, commandLineArgumentAttribute.CommandLineSwitch, !isEmptyShortName ? cmdLineValueSeparator.ToString() : String.Empty));
                        builder.Append("{");
                        bool first = true;
                        foreach (FieldInfo field in memberType.GetFields())
                        {
                            if (field.IsStatic)
                            {
                                if (first)
                                {
                                    first = false;
                                }
                                else
                                {
                                    builder.Append(" | ");
                                }

                                builder.Append(field.Name);
                            }
                        }
                        builder.Append('}');
                    }
                    else
                    {
                        if (!defaultCommandLineArgAttribute.ShortName.IsNull())
                        {
                            builder.Append(defaultCommandLineArgAttribute.ShortName);
                        }
                        else
                        {
                            builder.Append("<Unknown>");
                        }
                    }

                    if (!defaultCommandLineArgAttribute.IsRequired)
                    {
                        builder.Append("]");
                    }
                }
            }

            if (!_commandLineArgsObjectAttribute.DoNotShowUsageDetail)
            {
                builder.Append(Environment.NewLine);
                builder.Append(Environment.NewLine);
                builder.Append(whereBuilder.ToString().Indent());
                builder.Append(Environment.NewLine);

                foreach (ChoCommandLineArgAdditionalUsageAttribute commandLineArgAdditionalUsageAttribute in ChoType.GetAttributes <ChoCommandLineArgAdditionalUsageAttribute>(type))
                {
                    if (commandLineArgAdditionalUsageAttribute != null && !commandLineArgAdditionalUsageAttribute.AdditionalUsageText.IsNull())
                    {
                        builder.Append(commandLineArgAdditionalUsageAttribute.AdditionalUsageText);

                        builder.Append(Environment.NewLine);
                        builder.Append(Environment.NewLine);
                    }
                }
            }
            return(builder.ToString());
        }