Пример #1
0
        public void GetDescription()
        {
            var description = "test description";
            var attribute = new DescriptionAttribute(description);

            Assert.Equal(description, attribute.Description);
        }
        public void Equals_DifferentCategories()
        {
            var firstAttribute = new CategoryAttribute("category");
            var secondAttribute = new DescriptionAttribute(string.Empty);

            Assert.False(firstAttribute.Equals(secondAttribute));
        }
Пример #3
0
        public void Equals_DifferentDescriptions()
        {
            var firstAttribute = new DescriptionAttribute("description");
            var secondAttribute = new DescriptionAttribute(string.Empty);

            Assert.False(firstAttribute.Equals(secondAttribute));
        }
    static void Main()
    {
        // Custom attributes typemap tests
        //
        // cstype typemap attributechecks
        //
        // Global function cstype typemap attributes check
        Type globaltype = typeof(csharp_attributes);
        {
            MethodInfo member = (MethodInfo)globaltype.GetMember("GlobalFunction")[0];
            if (Attribute.GetCustomAttribute(member, typeof(IntOutAttribute)) == null)
            {
                throw new Exception("No IntOut attribute for " + member.Name);
            }
            ParameterInfo parameter = member.GetParameters()[0]; // expecting one parameter
            if (parameter.Name != "myInt")
            {
                throw new Exception("Incorrect parameter name");
            }
            Attribute attribute = Attribute.GetCustomAttributes(parameter)[0];
            if (attribute.GetType() != typeof(IntInAttribute))
            {
                throw new Exception("Expecting IntIn attribute");
            }
        }
        // Constant - cstype typemap attributes check
        {
            MemberInfo member = (MemberInfo)globaltype.GetMember("TESTMACRO")[0];
            if (Attribute.GetCustomAttribute(member, typeof(IntOutAttribute)) == null)
            {
                throw new Exception("No IntOut attribute for " + member.Name);
            }
        }

        // Non-static method cstype typemap attributes check
        Type type = typeof(Stations);
        {
            MethodInfo member = (MethodInfo)type.GetMember("Reading")[0];
            if (Attribute.GetCustomAttribute(member, typeof(IntOutAttribute)) == null)
            {
                throw new Exception("No IntOut attribute for " + member.Name);
            }
            ParameterInfo parameter = member.GetParameters()[0]; // expecting one parameter
            if (parameter.Name != "myInt")
            {
                throw new Exception("Incorrect parameter name");
            }
            Attribute attribute = Attribute.GetCustomAttributes(parameter)[0];
            if (attribute.GetType() != typeof(IntInAttribute))
            {
                throw new Exception("Expecting IntIn attribute");
            }
        }
        // Static method cstype typemap attributes check
        {
            MethodInfo member = (MethodInfo)type.GetMember("Swindon")[0];
            if (Attribute.GetCustomAttribute(member, typeof(IntOutAttribute)) == null)
            {
                throw new Exception("No IntOut attribute for " + member.Name);
            }
            ParameterInfo parameter = member.GetParameters()[0]; // expecting one parameter
            if (parameter.Name != "myInt")
            {
                throw new Exception("Incorrect parameter name");
            }
            Attribute attribute = Attribute.GetCustomAttributes(parameter)[0];
            if (attribute.GetType() != typeof(IntInAttribute))
            {
                throw new Exception("Expecting IntIn attribute");
            }
        }
        // Constructor cstype typemap attributes check
        {
            ConstructorInfo member    = (ConstructorInfo)type.GetConstructors()[0];
            ParameterInfo   parameter = member.GetParameters()[0]; // expecting one parameter
            if (parameter.Name != "myInt")
            {
                throw new Exception("Incorrect parameter name");
            }
            Attribute attribute = Attribute.GetCustomAttributes(parameter)[0];
            if (attribute.GetType() != typeof(IntInAttribute))
            {
                throw new Exception("Expecting IntIn attribute");
            }
        }

        //
        // imtype typemap attributechecks
        //
        // Global function imtype typemap attributes check
        Type imclasstype = typeof(csharp_attributesPINVOKE);
        {
            MethodInfo member = (MethodInfo)imclasstype.GetMember("GlobalFunction")[0];
            if (Attribute.GetCustomAttribute(member, typeof(IntegerOutAttribute)) == null)
            {
                throw new Exception("No IntegerOut attribute for " + member.Name);
            }
            ParameterInfo parameter = member.GetParameters()[0]; // checking 1st parameter
            Attribute     attribute = Attribute.GetCustomAttributes(parameter)[0];
            if (attribute.GetType() != typeof(IntegerInAttribute))
            {
                throw new Exception("Expecting IntegerIn attribute");
            }
        }
        // Constant - imtype typemap attributes check
        {
            MethodInfo member = (MethodInfo)imclasstype.GetMember("TESTMACRO_get")[0];
            if (Attribute.GetCustomAttribute(member, typeof(IntegerOutAttribute)) == null)
            {
                throw new Exception("No IntegerOut attribute for " + member.Name);
            }
        }
        // Non-static method imtype typemap attributes check
        {
            MethodInfo member = (MethodInfo)imclasstype.GetMember("Stations_Reading")[0];
            if (Attribute.GetCustomAttribute(member, typeof(IntegerOutAttribute)) == null)
            {
                throw new Exception("No IntegerOut attribute for " + member.Name);
            }
            ParameterInfo parameter = member.GetParameters()[1]; // checking 2nd parameter
            Attribute     attribute = Attribute.GetCustomAttributes(parameter)[0];
            if (attribute.GetType() != typeof(IntegerInAttribute))
            {
                throw new Exception("Expecting IntegerIn attribute");
            }
        }
        // Static method imtype typemap attributes check
        {
            MethodInfo member = (MethodInfo)imclasstype.GetMember("Stations_Swindon")[0];
            if (Attribute.GetCustomAttribute(member, typeof(IntegerOutAttribute)) == null)
            {
                throw new Exception("No IntegerOut attribute for " + member.Name);
            }
            ParameterInfo parameter = member.GetParameters()[0]; // checking 1st parameter
            Attribute     attribute = Attribute.GetCustomAttributes(parameter)[0];
            if (attribute.GetType() != typeof(IntegerInAttribute))
            {
                throw new Exception("Expecting IntegerIn attribute");
            }
        }

        //
        // attributes feature
        //
        Type moretype = typeof(MoreStations);

        // Constructor attributes feature check
        {
            ConstructorInfo member = (ConstructorInfo)moretype.GetConstructors()[0];
            if (Attribute.GetCustomAttribute(member, typeof(InterCity1Attribute)) == null)
            {
                throw new Exception("MoreStations::MoreStations attribute failed");
            }
        }
        // Non-static method attributes feature check
        {
            MethodInfo member = (MethodInfo)moretype.GetMember("Chippenham")[0];
            if (Attribute.GetCustomAttribute(member, typeof(InterCity2Attribute)) == null)
            {
                throw new Exception("MoreStations::Chippenham attribute failed");
            }
        }
        // Static method attributes feature check
        {
            MethodInfo member = (MethodInfo)moretype.GetMember("Bath")[0];
            if (Attribute.GetCustomAttribute(member, typeof(InterCity3Attribute)) == null)
            {
                throw new Exception("MoreStations::Bath attribute failed");
            }
        }
        // Non-static member variable attributes feature check
        {
            PropertyInfo member = (PropertyInfo)moretype.GetProperty("Bristol");
            if (Attribute.GetCustomAttribute(member, typeof(InterCity4Attribute)) == null)
            {
                throw new Exception("MoreStations::Bristol attribute failed");
            }
        }
        // Static member variable attributes feature check
        {
            PropertyInfo member = (PropertyInfo)moretype.GetProperty("WestonSuperMare");
            if (Attribute.GetCustomAttribute(member, typeof(InterCity5Attribute)) == null)
            {
                throw new Exception("MoreStations::Bristol attribute failed");
            }
        }
        // Global function attributes feature check
        {
            MethodInfo member = (MethodInfo)globaltype.GetMember("Paddington")[0];
            if (Attribute.GetCustomAttribute(member, typeof(InterCity7Attribute)) == null)
            {
                throw new Exception("MoreStations::Paddington attribute failed");
            }
        }
        // Global variables attributes feature check
        {
            PropertyInfo member = (PropertyInfo)globaltype.GetProperty("DidcotParkway");
            if (Attribute.GetCustomAttribute(member, typeof(InterCity8Attribute)) == null)
            {
                throw new Exception("MoreStations::Paddington attribute failed");
            }
        }

        //
        // csattribute typemaps
        //
        // Class csattribute typemap
        {
            Object[]           attribs = moretype.GetCustomAttributes(true);
            Eurostar1Attribute tgv     = (Eurostar1Attribute)attribs[0];
            if (tgv == null)
            {
                throw new Exception("No attribute for MoreStations");
            }
        }
        // Nested enum csattribute typemap
        {
            MemberInfo member = (MemberInfo)moretype.GetMember("Wales")[0];
            if (Attribute.GetCustomAttribute(member, typeof(Eurostar2Attribute)) == null)
            {
                throw new Exception("No attribute for " + member.Name);
            }
        }
        // Enum value attributes
        Type walesType = typeof(MoreStations.Wales);
        {
            MemberInfo           member    = (MemberInfo)walesType.GetMember("Cardiff")[0];
            DescriptionAttribute attribute = (DescriptionAttribute)Attribute.GetCustomAttribute(member, typeof(System.ComponentModel.DescriptionAttribute));
            if (attribute == null)
            {
                throw new Exception("No attribute for " + member.Name);
            }
            if (attribute.Description != "Cardiff city station")
            {
                throw new Exception("Incorrect attribute value for " + member.Name);
            }
        }
        {
            MemberInfo           member    = (MemberInfo)walesType.GetMember("Swansea")[0];
            DescriptionAttribute attribute = (DescriptionAttribute)Attribute.GetCustomAttribute(member, typeof(System.ComponentModel.DescriptionAttribute));
            if (attribute == null)
            {
                throw new Exception("No attribute for " + member.Name);
            }
            if (attribute.Description != "Swansea city station")
            {
                throw new Exception("Incorrect attribute value for " + member.Name);
            }
        }
        // Enum csattribute typemap
        {
            Type               cymrutype = typeof(Cymru);
            Object[]           attribs   = cymrutype.GetCustomAttributes(true);
            Eurostar3Attribute tgv       = (Eurostar3Attribute)attribs[0];
            if (tgv == null)
            {
                throw new Exception("No attribute for Cymru");
            }
        }

        // No runtime test for directorinattributes and directoroutattributes
    }
Пример #5
0
        private void LoadParameter()
        {
            DescriptionAttribute da = mMethod.GetCustomAttribute <DescriptionAttribute>(false);

            if (da != null)
            {
                this.Remark = da.Description;
            }
            foreach (System.Reflection.ParameterInfo pi in mMethod.GetParameters())
            {
                ParameterBinder   pb       = new DefaultParameter();
                ParameterBinder[] customPB = (ParameterBinder[])pi.GetCustomAttributes(typeof(ParameterBinder), false);
                if (customPB != null && customPB.Length > 0)
                {
                    pb = customPB[0];
                }
                else if (pi.ParameterType == typeof(Boolean))
                {
                    pb = new BooleanParameter();
                }
                else if (pi.ParameterType == typeof(string))
                {
                    pb = new StringParameter();
                }
                else if (pi.ParameterType == typeof(DateTime))
                {
                    pb = new DateTimeParameter();
                }

                else if (pi.ParameterType == typeof(Decimal))
                {
                    pb = new DecimalParameter();
                }
                else if (pi.ParameterType == typeof(float))
                {
                    pb = new FloatParameter();
                }
                else if (pi.ParameterType == typeof(double))
                {
                    pb = new DoubleParameter();
                }
                else if (pi.ParameterType == typeof(short))
                {
                    pb = new ShortParameter();
                }
                else if (pi.ParameterType == typeof(int))
                {
                    pb = new IntParameter();
                }
                else if (pi.ParameterType == typeof(long))
                {
                    pb = new LongParameter();
                }
                else if (pi.ParameterType == typeof(ushort))
                {
                    pb = new UShortParameter();
                }
                else if (pi.ParameterType == typeof(uint))
                {
                    pb = new UIntParameter();
                }
                else if (pi.ParameterType == typeof(ulong))
                {
                    pb = new ULongParameter();
                }
                else if (pi.ParameterType == typeof(HttpRequest))
                {
                    pb = new RequestParameter();
                }
                else if (pi.ParameterType == typeof(IHttpContext))
                {
                    pb = new HttpContextParameter();
                }
                else if (pi.ParameterType == typeof(IDataContext))
                {
                    pb = new DataContextParameter();
                }
                else if (pi.ParameterType == typeof(HttpApiServer))
                {
                    pb = new HttpApiServerParameter();
                }
                else if (pi.ParameterType == typeof(HttpResponse))
                {
                    pb = new ResponseParameter();
                }
                else if (pi.ParameterType == typeof(PostFile))
                {
                    pb = new PostFileParameter();
                }
                else
                {
                    pb = new DefaultParameter();
                }
                pb.ParameterInfo = pi;
                pb.Name          = pi.Name;
                pb.Type          = pi.ParameterType;
                Parameters.Add(pb);
            }
        }
Пример #6
0
        private static DefinitionProperty ProcessProperty(PropertyInfo propertyInfo, IList <string> hiddenTags,
                                                          Stack <Type> typesStack)
        {
            if (propertyInfo.GetCustomAttribute <SwaggerWcfHiddenAttribute>() != null ||
                propertyInfo.GetCustomAttributes <SwaggerWcfTagAttribute>()
                .Select(t => t.TagName)
                .Any(hiddenTags.Contains))
            {
                return(null);
            }

            TypeFormat typeFormat = Helpers.MapSwaggerType(propertyInfo.PropertyType, null);

            DefinitionProperty prop = new DefinitionProperty {
                Title = propertyInfo.Name
            };

            DataMemberAttribute dataMemberAttribute = propertyInfo.GetCustomAttribute <DataMemberAttribute>();

            if (dataMemberAttribute != null)
            {
                if (!string.IsNullOrEmpty(dataMemberAttribute.Name))
                {
                    prop.Title = dataMemberAttribute.Name;
                }

                prop.Required = dataMemberAttribute.IsRequired;
            }

            // Special case - if it came out required, but we unwrapped a null-able type,
            // then it's necessarily not required.  Ideally this would only set the default,
            // but we can't tell the difference between an explicit delaration of
            // IsRequired =false on the DataMember attribute and no declaration at all.
            if (prop.Required && propertyInfo.PropertyType.IsGenericType &&
                propertyInfo.PropertyType.GetGenericTypeDefinition() == typeof(Nullable <>))
            {
                prop.Required = false;
            }

            DescriptionAttribute descriptionAttribute = propertyInfo.GetCustomAttribute <DescriptionAttribute>();

            if (descriptionAttribute != null)
            {
                prop.Description = descriptionAttribute.Description;
            }

            prop.TypeFormat = typeFormat;

            if (prop.TypeFormat.Type == ParameterType.Object)
            {
                typesStack.Push(propertyInfo.PropertyType);

                prop.Ref = propertyInfo.PropertyType.FullName;

                return(prop);
            }

            if (prop.TypeFormat.Type == ParameterType.Array)
            {
                Type subType = GetEnumerableType(propertyInfo.PropertyType);
                if (subType != null)
                {
                    TypeFormat subTypeFormat = Helpers.MapSwaggerType(subType, null);

                    if (subTypeFormat.Type == ParameterType.Object)
                    {
                        typesStack.Push(subType);
                    }

                    prop.Items = new ParameterItems
                    {
                        TypeFormat = subTypeFormat
                    };
                }
            }

            if (prop.TypeFormat.Type == ParameterType.String && prop.TypeFormat.Format == "enum")
            {
                prop.Enum = new List <string>();

                Type propType = propertyInfo.PropertyType;

                if (propType.IsGenericType && propType.GetGenericTypeDefinition() == typeof(Nullable <>))
                {
                    propType = propType.GetEnumerableType();
                }

                List <string> listOfEnumNames = propType.GetEnumNames().ToList();
                foreach (string enumName in listOfEnumNames)
                {
                    prop.Enum.Add(GetEnumMemberValue(propType, enumName));
                }
            }

            // Apply any options set in a [SwaggerWcfProperty]
            ApplyAttributeOptions(propertyInfo, prop);

            return(prop);
        }
Пример #7
0
        public static void FillTable()
        {
            List <CommandEntry> commands = new List <CommandEntry>(CommandSystem.Entries.Values);
            List <CommandInfo>  list     = new List <CommandInfo>();

            commands.Sort();
            commands.Reverse();
            Docs.Clean(commands);

            for (int i = 0; i < commands.Count; ++i)
            {
                CommandEntry e = commands[i];

                MethodInfo mi = e.Handler.Method;

                object[] attrs = mi.GetCustomAttributes(typeof(UsageAttribute), false);

                if (attrs.Length == 0)
                {
                    continue;
                }

                UsageAttribute usage = attrs[0] as UsageAttribute;

                attrs = mi.GetCustomAttributes(typeof(DescriptionAttribute), false);

                if (attrs.Length == 0)
                {
                    continue;
                }

                DescriptionAttribute desc = attrs[0] as DescriptionAttribute;

                if (usage == null || desc == null)
                {
                    continue;
                }

                attrs = mi.GetCustomAttributes(typeof(AliasesAttribute), false);

                AliasesAttribute aliases = attrs.Length == 0 ? null : attrs[0] as AliasesAttribute;

                string descString = desc.Description.Replace("<", "(").Replace(">", ")");

                if (aliases == null)
                {
                    list.Add(new CommandInfo(e.AccessLevel, e.Command, null, usage.Usage, descString));
                }
                else
                {
                    list.Add(new CommandInfo(e.AccessLevel, e.Command, aliases.Aliases, usage.Usage, descString));

                    for (int j = 0; j < aliases.Aliases.Length; j++)
                    {
                        string[] newAliases = new string[aliases.Aliases.Length];

                        aliases.Aliases.CopyTo(newAliases, 0);

                        newAliases[j] = e.Command;

                        list.Add(new CommandInfo(e.AccessLevel, aliases.Aliases[j], newAliases, usage.Usage, descString));
                    }
                }
            }

            for (int i = 0; i < TargetCommands.AllCommands.Count; ++i)
            {
                BaseCommand command = TargetCommands.AllCommands[i];

                string usage = command.Usage;
                string desc  = command.Description;

                if (usage == null || desc == null)
                {
                    continue;
                }

                string[] cmds    = command.Commands;
                string   cmd     = cmds[0];
                string[] aliases = new string[cmds.Length - 1];

                for (int j = 0; j < aliases.Length; ++j)
                {
                    aliases[j] = cmds[j + 1];
                }

                desc = desc.Replace("<", "(").Replace(">", ")");

                if (command.Supports != CommandSupport.Single)
                {
                    StringBuilder sb = new StringBuilder(50 + desc.Length);

                    sb.Append("Modifiers: ");

                    if ((command.Supports & CommandSupport.Global) != 0)
                    {
                        sb.Append("<i>Global</i>, ");
                    }

                    if ((command.Supports & CommandSupport.Online) != 0)
                    {
                        sb.Append("<i>Online</i>, ");
                    }

                    if ((command.Supports & CommandSupport.Region) != 0)
                    {
                        sb.Append("<i>Region</i>, ");
                    }

                    if ((command.Supports & CommandSupport.Contained) != 0)
                    {
                        sb.Append("<i>Contained</i>, ");
                    }

                    if ((command.Supports & CommandSupport.Multi) != 0)
                    {
                        sb.Append("<i>Multi</i>, ");
                    }

                    if ((command.Supports & CommandSupport.Area) != 0)
                    {
                        sb.Append("<i>Area</i>, ");
                    }

                    if ((command.Supports & CommandSupport.Self) != 0)
                    {
                        sb.Append("<i>Self</i>, ");
                    }

                    sb.Remove(sb.Length - 2, 2);
                    sb.Append("<br>");
                    sb.Append(desc);

                    desc = sb.ToString();
                }

                list.Add(new CommandInfo(command.AccessLevel, cmd, aliases, usage, desc));

                for (int j = 0; j < aliases.Length; j++)
                {
                    string[] newAliases = new string[aliases.Length];

                    aliases.CopyTo(newAliases, 0);

                    newAliases[j] = cmd;

                    list.Add(new CommandInfo(command.AccessLevel, aliases[j], newAliases, usage, desc));
                }
            }

            List <BaseCommandImplementor> commandImpls = BaseCommandImplementor.Implementors;

            for (int i = 0; i < commandImpls.Count; ++i)
            {
                BaseCommandImplementor command = commandImpls[i];

                string usage = command.Usage;
                string desc  = command.Description;

                if (usage == null || desc == null)
                {
                    continue;
                }

                string[] cmds    = command.Accessors;
                string   cmd     = cmds[0];
                string[] aliases = new string[cmds.Length - 1];

                for (int j = 0; j < aliases.Length; ++j)
                {
                    aliases[j] = cmds[j + 1];
                }

                desc = desc.Replace("<", ")").Replace(">", ")");

                list.Add(new CommandInfo(command.AccessLevel, cmd, aliases, usage, desc));

                for (int j = 0; j < aliases.Length; j++)
                {
                    string[] newAliases = new string[aliases.Length];

                    aliases.CopyTo(newAliases, 0);

                    newAliases[j] = cmd;

                    list.Add(new CommandInfo(command.AccessLevel, aliases[j], newAliases, usage, desc));
                }
            }

            list.Sort(new CommandInfoSorter());

            m_SortedHelpInfo = list;

            foreach (CommandInfo c in m_SortedHelpInfo)
            {
                if (!m_HelpInfos.ContainsKey(c.Name.ToLower()))
                {
                    m_HelpInfos.Add(c.Name.ToLower(), c);
                }
            }
        }
Пример #8
0
        public static MDataColumn GetColumns(Type typeInfo)
        {
            string key = "ColumnCache_" + typeInfo.FullName;

            if (_ColumnCache.ContainsKey(key))
            {
                return(_ColumnCache[key].Clone());
            }
            else
            {
                #region 获取列结构
                MDataColumn mdc = new MDataColumn();
                mdc.TableName = typeInfo.Name;
                switch (StaticTool.GetSystemType(ref typeInfo))
                {
                case SysType.Base:
                case SysType.Enum:
                    mdc.Add(typeInfo.Name, DataType.GetSqlType(typeInfo), false);
                    return(mdc);

                case SysType.Generic:
                case SysType.Collection:
                    Type[] argTypes;
                    Tool.StaticTool.GetArgumentLength(ref typeInfo, out argTypes);
                    foreach (Type type in argTypes)
                    {
                        mdc.Add(type.Name, DataType.GetSqlType(type), false);
                    }
                    argTypes = null;
                    return(mdc);
                }

                List <PropertyInfo> pis = StaticTool.GetPropertyInfo(typeInfo);
                if (pis.Count > 0)
                {
                    for (int i = 0; i < pis.Count; i++)
                    {
                        SetStruct(mdc, pis[i], null, i, pis.Count);
                    }
                }
                else
                {
                    List <FieldInfo> fis = StaticTool.GetFieldInfo(typeInfo);
                    if (fis.Count > 0)
                    {
                        for (int i = 0; i < fis.Count; i++)
                        {
                            SetStruct(mdc, null, fis[i], i, fis.Count);
                        }
                    }
                }
                object[] tableAttr = typeInfo.GetCustomAttributes(typeof(DescriptionAttribute), false);//看是否设置了表特性,获取表名和表描述
                if (tableAttr != null && tableAttr.Length == 1)
                {
                    DescriptionAttribute attr = tableAttr[0] as DescriptionAttribute;
                    if (attr != null && !string.IsNullOrEmpty(attr.Description))
                    {
                        mdc.Description = attr.Description;
                    }
                }
                pis = null;
                #endregion

                if (!_ColumnCache.ContainsKey(key))
                {
                    _ColumnCache.Set(key, mdc.Clone());
                }

                return(mdc);
            }
        }
Пример #9
0
 public EnumValue(FieldInfo field)
 {
     _value       = (T)field.GetValue(null);
     _title       = (TitleAttribute)field.GetCustomAttributes(typeof(TitleAttribute), false)[0];
     _description = (DescriptionAttribute)field.GetCustomAttributes(typeof(DescriptionAttribute), false)[0];
 }
Пример #10
0
        private void treeView_AfterSelect(object sender, TreeViewEventArgs e)
        {
            this.listView.Clear();

            this.textBoxHelp.Text = String.Empty;
            Type t = this.treeView.SelectedNode.Tag as Type;

            if (this.treeView.SelectedNode == this.treeView.Nodes[0])
            {
                this.textBoxHelp.Text = "Information exchange for building a bridge. [FHWA Design-to-Construction information change updated for IFC 4.1]";
            }
            else if (this.treeView.SelectedNode == this.treeView.Nodes[1])
            {
                this.textBoxHelp.Text = "Information exchange for structural analysis of a bridge. [For illustration purposes -- not implemented].";
            }
            else if (t != null)
            {
                DescriptionAttribute attr = t.GetCustomAttribute <DescriptionAttribute>();
                if (attr != null)
                {
                    this.textBoxHelp.Text = attr.Description;
                }
            }
            else
            {
                PropertyInfo prop = this.treeView.SelectedNode.Tag as PropertyInfo;
                if (prop != null)
                {
                    t = this.treeView.SelectedNode.Parent.Tag as Type;

                    string       mapval   = String.Empty;
                    PropertyInfo fieldMap = t.GetProperty(prop.Name, BindingFlags.Static | BindingFlags.NonPublic);
                    if (fieldMap != null)
                    {
                        mapval = fieldMap.GetValue(null) as string;
                    }

                    string desval             = String.Empty;
                    DescriptionAttribute attr = prop.GetCustomAttribute <DescriptionAttribute>();
                    if (attr != null)
                    {
                        desval = attr.Description;
                    }

                    this.textBoxHelp.Text = desval + "\r\n\r\n" + mapval;
                }
            }

            if (t != null)
            {
                ColumnHeader colheaderIndex = new ColumnHeader();
                colheaderIndex.Text       = "#";
                colheaderIndex.Width      = 60;
                colheaderIndex.ImageIndex = 0;
                this.listView.Columns.Add(colheaderIndex);

                // build columns
                PropertyInfo[] props  = t.GetProperties();
                Color[]        colors = new Color[props.Length];
                int            iColor = 0;
                foreach (PropertyInfo prop in props)
                {
                    if (prop.Name != "Target")
                    {
                        ColumnHeader colheader = new ColumnHeader();
                        colheader.Tag        = prop;
                        colheader.Text       = prop.Name;
                        colheader.Width      = 120;
                        colheader.ImageIndex = 0;
                        this.listView.Columns.Add(colheader);
                    }

                    if (prop.PropertyType.IsGenericType && prop.PropertyType.GetGenericTypeDefinition() == typeof(Nullable <>))
                    {
                        colors[iColor] = Color.LimeGreen; // optional
                    }
                    else if (prop.PropertyType.IsGenericType && prop.PropertyType.GetGenericTypeDefinition() == typeof(ISet <>))
                    {
                        colors[iColor] = Color.Orange; // list reference
                    }
                    else if (prop.PropertyType.IsClass && prop.PropertyType != typeof(string))
                    {
                        colors[iColor] = Color.Orange; // reference
                    }
                    else
                    {
                        colors[iColor] = Color.Yellow; // required property
                    }

                    iColor++;
                }

                // get all instances of type...

                // get the target type
                Dictionary <object, string[]> results = null;
                if (!this.m_results.TryGetValue(t, out results))
                {
                    return;
                }

                int[] tracker = new int[this.listView.Columns.Count];


                Font fontUnderline = new Font(this.listView.Font, FontStyle.Underline);

                foreach (object o in results.Keys)
                {
                    ListViewItem lvi = new ListViewItem();
                    lvi.Tag  = o;
                    lvi.Text = (this.listView.Items.Count + 1).ToString();
                    lvi.UseItemStyleForSubItems = false;

                    string[] vals = results[o];

                    bool pass = true;
                    for (int iCol = 1; iCol < this.listView.Columns.Count; iCol++)
                    {
                        string text = vals[iCol - 1];

                        Color colorBack = colors[iCol - 1];

                        ListViewItem.ListViewSubItem lviSub = new ListViewItem.ListViewSubItem();
                        lviSub.Text      = text;
                        lviSub.BackColor = colorBack;

                        PropertyInfo prop = props[iCol - 1];
                        if (prop.PropertyType.IsClass && prop.PropertyType != typeof(string))
                        {
                            //lviSub.Font = fontUnderline;
                        }

                        lvi.SubItems.Add(lviSub);//text, listView.ForeColor, colorBack, this.listView.Font);

                        if (!String.IsNullOrEmpty(text))
                        {
                            tracker[iCol]++;
                        }
                        else
                        {
                            pass = false;
                        }
                    }

                    lvi.ImageIndex = (pass ? 1 : 2);
                    this.listView.Items.Add(lvi);

                    if (pass)
                    {
                        tracker[0]++;
                    }
                }

                for (int i = 0; i < tracker.Length; i++)
                {
                    int count = tracker[i];
                    if (this.listView.Items.Count == 0)
                    {
                        this.listView.Columns[i].ImageIndex = 0; // no instances
                    }
                    else if (count == this.listView.Items.Count)
                    {
                        // all pass
                        this.listView.Columns[i].ImageIndex = 1;
                    }
                    else if (count == 0)
                    {
                        // all fail
                        this.listView.Columns[i].ImageIndex = 2;
                    }
                    else
                    {
                        // some pass
                        this.listView.Columns[i].ImageIndex = 3;
                    }
                }
            }
        }
Пример #11
0
        /// <summary>构造函数</summary>
        /// <param name="table"></param>
        /// <param name="property">属性</param>
        public FieldItem(TableItem table, PropertyInfo property)
        {
            Table = table;

            if (property != null)
            {
                _Property = property;
                var dc = _Column = BindColumnAttribute.GetCustomAttribute(property);
                var df = _DataObjectField = property.GetCustomAttribute <DataObjectFieldAttribute>();
                var ds = _Description = property.GetCustomAttribute <DescriptionAttribute>();
                var di = _DisplayName = property.GetCustomAttribute <DisplayNameAttribute>();
                Map           = property.GetCustomAttribute <MapAttribute>();
                Name          = property.Name;
                Type          = property.PropertyType;
                DeclaringType = property.DeclaringType;

                if (df != null)
                {
                    IsIdentity = df.IsIdentity;
                    PrimaryKey = df.PrimaryKey;
                    IsNullable = df.IsNullable;
                    Length     = df.Length;

                    IsDataObjectField = true;
                }

                if (dc != null)
                {
                    _ID    = dc.Order;
                    Master = dc.Master;
                }

                if (dc != null && !dc.Name.IsNullOrWhiteSpace())
                {
                    ColumnName = dc.Name;
                }
                else
                {
                    ColumnName = Name;
                }

                if (ds != null && !String.IsNullOrEmpty(ds.Description))
                {
                    Description = ds.Description;
                }
                else if (dc != null && !String.IsNullOrEmpty(dc.Description))
                {
                    Description = dc.Description;
                }
                if (di != null && !di.DisplayName.IsNullOrEmpty())
                {
                    DisplayName = di.DisplayName;
                }

                var map = Map;
                if (map == null || map.Provider == null)
                {
                    ReadOnly = !property.CanWrite;
                }
                var ra = property.GetCustomAttribute <ReadOnlyAttribute>();
                if (ra != null)
                {
                    ReadOnly = ra.IsReadOnly;
                }
            }
        }
Пример #12
0
        internal ConfigurationProperty(PropertyInfo info)
        {
            Debug.Assert(info != null, "info != null");

            ConfigurationPropertyAttribute propertyAttribute    = null;
            DescriptionAttribute           descriptionAttribute = null;

            // For compatibility we read the component model default value attribute. It is only
            // used if ConfigurationPropertyAttribute doesn't provide the default value.
            DefaultValueAttribute defaultValueAttribute = null;

            TypeConverter typeConverter          = null;
            ConfigurationValidatorBase validator = null;

            // Look for relevant attributes
            foreach (Attribute attribute in Attribute.GetCustomAttributes(info))
            {
                if (attribute is TypeConverterAttribute)
                {
                    typeConverter = TypeUtil.CreateInstance <TypeConverter>(((TypeConverterAttribute)attribute).ConverterTypeName);
                }
                else if (attribute is ConfigurationPropertyAttribute)
                {
                    propertyAttribute = (ConfigurationPropertyAttribute)attribute;
                }
                else if (attribute is ConfigurationValidatorAttribute)
                {
                    if (validator != null)
                    {
                        // We only allow one validator to be specified on a property.
                        //
                        // Consider: introduce a new validator type ( CompositeValidator ) that is a
                        // list of validators and executes them all

                        throw new ConfigurationErrorsException(
                                  string.Format(SR.Validator_multiple_validator_attributes, info.Name));
                    }

                    ConfigurationValidatorAttribute validatorAttribute = (ConfigurationValidatorAttribute)attribute;
                    validatorAttribute.SetDeclaringType(info.DeclaringType);
                    validator = validatorAttribute.ValidatorInstance;
                }
                else if (attribute is DescriptionAttribute)
                {
                    descriptionAttribute = (DescriptionAttribute)attribute;
                }
                else if (attribute is DefaultValueAttribute)
                {
                    defaultValueAttribute = (DefaultValueAttribute)attribute;
                }
            }

            Type propertyType = info.PropertyType;

            // If the property is a Collection we need to look for the ConfigurationCollectionAttribute for
            // additional customization.
            if (typeof(ConfigurationElementCollection).IsAssignableFrom(propertyType))
            {
                // Look for the ConfigurationCollection attribute on the property itself, fall back
                // on the property type.
                ConfigurationCollectionAttribute collectionAttribute =
                    Attribute.GetCustomAttribute(info,
                                                 typeof(ConfigurationCollectionAttribute)) as ConfigurationCollectionAttribute ??
                    Attribute.GetCustomAttribute(propertyType,
                                                 typeof(ConfigurationCollectionAttribute)) as ConfigurationCollectionAttribute;

                if (collectionAttribute != null)
                {
                    if (collectionAttribute.AddItemName.IndexOf(',') == -1)
                    {
                        AddElementName = collectionAttribute.AddItemName;
                    }
                    RemoveElementName = collectionAttribute.RemoveItemName;
                    ClearElementName  = collectionAttribute.ClearItemsName;
                }
            }

            // This constructor shouldn't be invoked if the reflection info is not for an actual config property
            Debug.Assert(propertyAttribute != null, "attribProperty != null");

            ConstructorInit(propertyAttribute.Name,
                            info.PropertyType,
                            propertyAttribute.Options,
                            validator,
                            typeConverter);

            // Figure out the default value
            InitDefaultValueFromTypeInfo(propertyAttribute, defaultValueAttribute);

            // Get the description
            if (!string.IsNullOrEmpty(descriptionAttribute?.Description))
            {
                Description = descriptionAttribute.Description;
            }
        }
Пример #13
0
        public static EditableValue Create(object o, System.Reflection.PropertyInfo info)
        {
            var ret = new EditableValue();

            ret.Value = o;

            var p          = info;
            var attributes = p.GetCustomAttributes(false);

            var undo = attributes.Where(_ => _.GetType() == typeof(UndoAttribute)).FirstOrDefault() as UndoAttribute;

            if (undo != null && !undo.Undo)
            {
                ret.IsUndoEnabled = false;
            }
            else
            {
                ret.IsUndoEnabled = true;
            }

            var shown = attributes.Where(_ => _.GetType() == typeof(ShownAttribute)).FirstOrDefault() as ShownAttribute;

            if (shown != null && !shown.Shown)
            {
                ret.IsShown = false;
            }

            var selector_attribute = (from a in attributes where a is Data.SelectorAttribute select a).FirstOrDefault() as Data.SelectorAttribute;

            if (selector_attribute != null)
            {
                ret.SelfSelectorID = selector_attribute.ID;
            }

            // collect selected values
            var selectedAttributes = attributes.OfType <Data.SelectedAttribute>();

            if (selectedAttributes.Count() > 0)
            {
                if (selectedAttributes.Select(_ => _.ID).Distinct().Count() > 1)
                {
                    throw new Exception("Same IDs are required.");
                }

                ret.TargetSelectorID       = selectedAttributes.First().ID;
                ret.RequiredSelectorValues = selectedAttributes.Select(_ => _.Value).ToArray();
            }

            var key     = KeyAttribute.GetKey(attributes);
            var nameKey = key + "_Name";

            if (string.IsNullOrEmpty(key))
            {
                nameKey = info.ReflectedType.Name + "_" + info.Name + "_Name";
            }

            if (MultiLanguageTextProvider.HasKey(nameKey))
            {
                ret.Title = new MultiLanguageString(nameKey);
            }
            else
            {
                ret.Title = NameAttribute.GetName(attributes);
                //if (!string.IsNullOrEmpty(ret.Title.ToString()))
                //{
                //	System.IO.File.AppendAllText("kv.csv", nameKey + ","  + "\"" + ret.Title.ToString() + "\"" + "\r\n");
                //}
            }

            var descKey = key + "_Desc";

            if (string.IsNullOrEmpty(key))
            {
                descKey = info.ReflectedType.Name + "_" + info.Name + "_Desc";
            }

            if (MultiLanguageTextProvider.HasKey(descKey))
            {
                ret.Description = new MultiLanguageString(descKey);
            }
            else
            {
                ret.Description = DescriptionAttribute.GetDescription(attributes);

                //if(!string.IsNullOrEmpty(ret.Description.ToString()))
                //{
                //	System.IO.File.AppendAllText("kv.csv", descKey + "," + "\"" + ret.Description.ToString() + "\"" + "\r\n");
                //}
            }

            var treeNode = attributes.OfType <TreeNodeAttribute>().FirstOrDefault();

            if (treeNode != null)
            {
                ret.TreeNodeID = treeNode.id;

                if (MultiLanguageTextProvider.HasKey(treeNode.key))
                {
                    ret.Title = new MultiLanguageString(treeNode.key);
                }
            }

            return(ret);
        }
Пример #14
0
 private static void SetupUIElement(RectTransform element, DisplayNameAttribute display, DescriptionAttribute descriptionAttr, PropertyInfo prop, Vector2 anchorPosition)
 {
     element.gameObject.SetActive(true);
     element.name             = prop.Name;
     element.anchoredPosition = anchorPosition;
     if (descriptionAttr != null)
     {
         element.gameObject.AddComponent <Tooltip>();
         element.gameObject.GetComponent <Tooltip>().Title = display.DisplayName;
         element.gameObject.GetComponent <Tooltip>().Text  = descriptionAttr.Description;
     }
     element.GetComponent <Localizer>().enabled = false;
     element.GetComponent <Text>().text         = display.DisplayName;
 }
Пример #15
0
        private static void CreateNumberControl(DisplayNameAttribute control, DescriptionAttribute descriptionAttr, PropertyInfo prop, Vector2 anchorPosition, RectTransform container)
        {
            UIRangeAttribute rangeAttr     = prop.GetCustomAttribute <UIRangeAttribute>();
            bool             sliderControl = rangeAttr != null && rangeAttr.Slider;

            RectTransform element = Object.Instantiate(sliderControl ? sliderTemplate : inputTemplate, container, false);

            SetupUIElement(element, control, descriptionAttr, prop, anchorPosition);

            bool isFloatingPoint = prop.PropertyType == typeof(float) || prop.PropertyType == typeof(double);

            if (sliderControl)
            {
                Slider slider = element.GetComponentInChildren <Slider>();
                slider.minValue     = rangeAttr.Min;
                slider.maxValue     = rangeAttr.Max;
                slider.wholeNumbers = !isFloatingPoint;
                Text sliderThumbText = slider.GetComponentInChildren <Text>();
                slider.onValueChanged.RemoveAllListeners();
                slider.onValueChanged.AddListener((value) =>
                {
                    prop.SetValue(tempMultiplayerOptions, value, null);
                    sliderThumbText.text = value.ToString(isFloatingPoint ? "0.00" : "0");
                });

                tempToUICallbacks[prop.Name] = () =>
                {
                    slider.value         = (float)prop.GetValue(tempMultiplayerOptions, null);
                    sliderThumbText.text = slider.value.ToString(isFloatingPoint ? "0.00" : "0");
                };
            }
            else
            {
                InputField input = element.GetComponentInChildren <InputField>();

                input.onValueChanged.RemoveAllListeners();
                input.onValueChanged.AddListener((str) =>
                {
                    try
                    {
                        TypeConverter converter  = TypeDescriptor.GetConverter(prop.PropertyType);
                        System.IComparable value = (System.IComparable)converter.ConvertFromString(str);

                        if (rangeAttr != null)
                        {
                            System.IComparable min = (System.IComparable)System.Convert.ChangeType(rangeAttr.Min, prop.PropertyType);
                            System.IComparable max = (System.IComparable)System.Convert.ChangeType(rangeAttr.Max, prop.PropertyType);
                            if (value.CompareTo(min) < 0)
                            {
                                value = min;
                            }

                            if (value.CompareTo(max) > 0)
                            {
                                value = max;
                            }

                            input.text = value.ToString();
                        }

                        prop.SetValue(tempMultiplayerOptions, value, null);
                    }
                    catch
                    {
                        // If the char is not a number, rollback to previous value
                        input.text = prop.GetValue(tempMultiplayerOptions, null).ToString();
                    }
                });

                tempToUICallbacks[prop.Name] = () =>
                {
                    input.text = prop.GetValue(tempMultiplayerOptions, null).ToString();
                };
            }
        }
Пример #16
0
        private string WriteProperty(PropertyInfo pi, Stack <Type> typeStack)
        {
            StringBuilder sb = new StringBuilder();
            StringWriter  sw = new StringWriter(sb);

            Type pType    = pi.PropertyType;
            bool required = true;

            if (pType.IsGenericType && pType.GetGenericTypeDefinition() == typeof(System.Nullable <>))
            {
                required = false;
                pType    = pType.GetGenericArguments().First();
            }

            using (JsonWriter writer = new JsonTextWriter(sw))
            {
                var memberProperties = pi.GetCustomAttribute <MemberPropertiesAttribute>();

                var typeValue = memberProperties != null?Helpers.MapSwaggerType(pType, typeStack, memberProperties.TypeSizeNote) : Helpers.MapSwaggerType(pType, typeStack);

                //If the Name property in DataContract is defined for this property type, use that name instead.
                //Needed for cases where a DataContract uses another DataContract as a return type for a member.
                var dcName = Helpers.GetDataContractNamePropertyValue(pType);

                if (!string.IsNullOrEmpty(dcName))
                {
                    typeValue = dcName;
                    if (memberProperties != null && !string.IsNullOrEmpty(memberProperties.TypeSizeNote))
                    {
                        typeValue = string.Format("{0}({1})", dcName, memberProperties.TypeSizeNote);
                    }
                }


                writer.WriteStartObject();

                writer.WritePropertyName("type");
                writer.WriteValue(typeValue);

                writer.WritePropertyName("required");
                writer.WriteValue(required);

                DescriptionAttribute description = pi.GetCustomAttribute <DescriptionAttribute>();
                if (description != null)
                {
                    writer.WritePropertyName("description");
                    writer.WriteValue(description.Description);
                }
                else
                {
                    if (memberProperties != null)
                    {
                        writer.WritePropertyName("description");
                        writer.WriteValue(memberProperties.Description);
                    }
                }

                if (Helpers.MapSwaggerType(pType, typeStack) == "array")
                {
                    writer.WritePropertyName("items");
                    writer.WriteStartObject();
                    writer.WritePropertyName("$ref");
                    writer.WriteValue(Helpers.MapElementType(pType, typeStack));
                }

                if (pType.IsEnum)
                {
                    writer.WritePropertyName("enum");
                    writer.WriteStartArray();
                    foreach (string value in pType.GetEnumNames())
                    {
                        writer.WriteValue(value);
                    }
                    writer.WriteEndArray();
                }

                writer.WriteEnd();
            }
            return(sb.ToString());
        }
Пример #17
0
        /// <summary>
        /// OEO配置
        /// </summary>
        /// <param name="modules"></param>
        /// <param name="ip"></param>
        /// <param name="port"></param>
        /// <param name="slot"></param>
        /// <returns></returns>
        public ActionResult SetConfiguration(List <SFPModule> modules, int mfId, string ip, int port, int slot, List <SFPModuleConfigRecord> records)
        {
            JsonResult result = new JsonResult();
            var        tcp    = TcpClientServicePool.GetService(ip, port);

            if (tcp != null)
            {
                try
                {
                    List <DeviceOperationLog> logs          = new List <DeviceOperationLog>();
                    List <string>             listException = new List <string>();
                    OEOInfo        oeoInfo = new OEOInfo();
                    OEOCommService service = new OEOCommService(tcp, slot);
                    oeoInfo.RefreshData(service);
                    var srvType = service.GetType();
                    foreach (var sfp in modules)
                    {
                        var record = (from r in records
                                      where r.Slot == sfp.SlotPosition
                                      select r).FirstOrDefault();
                        if (record != null)
                        {
                            foreach (var p in record.ChangeItems)
                            {
                                //获取属性
                                var prop = sfp.GetType().GetProperty(p);
                                if (prop != null)
                                {
                                    //获取属性值
                                    var    value      = prop.GetValue(sfp);
                                    var    methodName = "Set" + p.Replace("_", "");
                                    var    methodInfo = srvType.GetMethod(methodName);
                                    string operation  = "";
                                    if (methodInfo != null)
                                    {
                                        //获取设置项说明
                                        object[] arrDescription = methodInfo.GetCustomAttributes(typeof(DescriptionAttribute), false);
                                        if (arrDescription != null && arrDescription.Length > 0)
                                        {
                                            DescriptionAttribute desc = (DescriptionAttribute)arrDescription[0];
                                            if (desc != null)
                                            {
                                                operation = desc.Description;
                                            }
                                        }
                                        //获取方法参数信息
                                        var      paramInfo   = methodInfo.GetParameters();
                                        object[] paramObject = new object[paramInfo.Length];
                                        object[] values      = new object[] { sfp.SlotPosition, value };
                                        int      i           = 0;
                                        foreach (var e in paramInfo)
                                        {
                                            paramObject[i] = Convert.ChangeType(values[i], e.ParameterType);
                                            i++;
                                        }
                                        var ret = (bool)methodInfo.Invoke(service, paramObject);
                                        if (!ret)
                                        {
                                            listException.Add(string.Format("光模块{0}", sfp.SlotPosition) + operation);
                                        }
                                        var log = new DeviceOperationLog
                                        {
                                            DOLCardSN           = oeoInfo.Serial_Number,
                                            DOLCardType         = "OEO",
                                            DOLDeviceSlot       = short.Parse(slot.ToString()),
                                            DOLOperationDetials = string.Format("光模块{0}{1}", sfp.SlotPosition, operation),
                                            DOLOperationType    = "板卡配置",
                                            DOLOperationResult  = ret ? "成功" : "失败",
                                            DOLOperationTime    = DateTime.Now,
                                            Remark = ""
                                        };
                                        logs.Add(log);
                                    }
                                }
                            }
                        }

                        /*if(!service.SetWorkMode(sfp.SlotPosition, sfp.Work_Mode))
                         * {
                         *  listException.Add(string.Format("SFP模块{0}工作模式", sfp.SlotPosition));
                         * }
                         * if(!service.SetTxPowerControl(sfp.SlotPosition, sfp.Tx_Power_Control))
                         * {
                         *  listException.Add(string.Format("SFP模块{0}发功率控制", sfp.SlotPosition));
                         * }*/
                    }
                    if (listException.Count == 0)
                    {
                        result.Data = new { Code = "", Data = "配置成功" };
                    }
                    else
                    {
                        string data = "配置失败:";
                        foreach (var e in listException)
                        {
                            data += e + " ";
                        }
                        result.Data = new { Code = "Exception", Data = data };
                    }
                    using (var ctx = new GlsunViewEntities())
                    {
                        MachineFrame frame = ctx.MachineFrame.Find(mfId);
                        var          user  = ctx.User.Where(u => u.ULoginName == HttpContext.User.Identity.Name).FirstOrDefault();
                        foreach (var log in logs)
                        {
                            //基本信息
                            log.DID        = frame.ID;
                            log.DName      = frame.MFName;
                            log.DAddress   = frame.MFIP;
                            log.UID        = user.ID;
                            log.ULoginName = user.ULoginName;
                            log.UName      = user.UName;
                        }
                        ctx.DeviceOperationLog.AddRange(logs);
                        //异步保存不阻塞网页
                        ctx.SaveChanges();
                    }
                }
                catch (Exception ex)
                {
                    result.Data = new { Code = "Exception", Data = ex.Message };
                }
                finally
                {
                    TcpClientServicePool.FreeService(tcp);
                }
            }
            else
            {
                result.Data = new { Code = "Exception", Data = "获取TCP连接失败" };
            }
            return(result);
        }
Пример #18
0
        public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destType)
        {
            DescriptionAttribute descriptionAttribute = (DescriptionAttribute)Attribute.GetCustomAttribute(_enumType.GetField(Enum.GetName(_enumType, value)), typeof(DescriptionAttribute));

            return(descriptionAttribute == null?value.ToString() : descriptionAttribute.Description);
        }
Пример #19
0
        public static string GetAttributeName(MemberInfo mi)
        {
            DescriptionAttribute att = Attribute.GetCustomAttribute(mi, typeof(DescriptionAttribute)) as DescriptionAttribute;

            return(att != null ? att.Description : "");
        }
Пример #20
0
        /*
         *
         *              string jsonString = JsonSerializer.Serialize(weatherForecast);
         *      }
         * }
         *
         *
         *
         *
         *
         *
         *
         * using (WebUI.HtmlTextWriter html = new WebUI.HtmlTextWriter(writer))
         * {
         *      html.WriteLine("<!DOCTYPE html>");
         *      html.RenderBeginTag(WebUI.HtmlTextWriterTag.Html);
         *      {
         *              WriteHeader(html, string.Format("{0} Message Dump for {1}", System.Windows.Forms.Application.ProductName, strippedName));
         *
         *              html.RenderBeginTag(WebUI.HtmlTextWriterTag.Body);
         *              {
         *                      html.AddAttribute(WebUI.HtmlTextWriterAttribute.Class, "container");
         *                      html.RenderBeginTag(WebUI.HtmlTextWriterTag.Div);
         *                      {
         *                              html.WriteEncodedText(string.Format("Message dump created by {0} {1}; dumping {2}, {3} tables...",
         *                                      System.Windows.Forms.Application.ProductName,
         *                                      VersionManagement.CreateVersionString(System.Windows.Forms.Application.ProductVersion),
         *                                      (tableFiles.FirstOrDefault().FileNumber != -1 ? string.Format("{0}, file #{1}", strippedName, tableFiles.FirstOrDefault().FileNumber) : strippedName),
         *                                      numTables));
         *                              html.WriteBreak();
         *                              html.WriteBreak();
         *                      }
         *                      html.RenderEndTag();
         *
         *                      for (int i = 0; i < numTables; i++)
         *                      {
         *                              string tableId = string.Format("table-{0:D4}", i);
         *
         *                              html.AddAttribute(WebUI.HtmlTextWriterAttribute.Class, "header");
         *                              html.RenderBeginTag(WebUI.HtmlTextWriterTag.Div);
         *                              {
         *                                      html.AddAttribute(WebUI.HtmlTextWriterAttribute.Class, "header-text");
         *                                      html.RenderBeginTag(WebUI.HtmlTextWriterTag.Span);
         *                                      {
         *                                              html.Write("Table {0}", i + 1);
         *                                      }
         *                                      html.RenderEndTag();
         *
         *                                      html.AddAttribute(WebUI.HtmlTextWriterAttribute.Class, "header-toggle");
         *                                      html.RenderBeginTag(WebUI.HtmlTextWriterTag.Span);
         *                                      {
         *                                              html.AddAttribute(WebUI.HtmlTextWriterAttribute.Href, string.Format("javascript:toggle('{0}');", tableId), false);
         *                                              html.RenderBeginTag(WebUI.HtmlTextWriterTag.A);
         *                                              {
         *                                                      html.Write("+/-");
         *                                              }
         *                                              html.RenderEndTag();
         *                                      }
         *                                      html.RenderEndTag();
         *                              }
         *                              html.RenderEndTag();
         *
         *                              html.AddAttribute(WebUI.HtmlTextWriterAttribute.Id, tableId);
         *                              html.AddStyleAttribute(WebUI.HtmlTextWriterStyle.Display, "table");
         *                              html.RenderBeginTag(WebUI.HtmlTextWriterTag.Table);
         *                              {
         *                                      html.RenderBeginTag(WebUI.HtmlTextWriterTag.Tr);
         *                                      {
         *                                              html.RenderBeginTag(WebUI.HtmlTextWriterTag.Th);
         *                                              {
         *                                                      html.Write("ID");
         *                                              }
         *                                              html.RenderEndTag();
         *
         *                                              foreach (TableFile file in tableFiles)
         *                                              {
         *                                                      html.RenderBeginTag(WebUI.HtmlTextWriterTag.Th);
         *                                                      {
         *                                                              string language = Path.GetFileNameWithoutExtension(file.Filename);
         *                                                              language = gameDataManager.LanguageSuffixes.FirstOrDefault(x => x.Value == language.Substring(language.LastIndexOf('_'), 3)).Key.ToString();
         *                                                              html.Write(language);
         *                                                      }
         *                                                      html.RenderEndTag();
         *                                              }
         *                                      }
         *                                      html.RenderEndTag();
         *
         *                                      int numMessages = (int)(tableFiles.FirstOrDefault().Tables[i] as MessageTable).NumMessages;
         *                                      for (int j = 0; j < numMessages; j++)
         *                                      {
         *                                              if ((tableFiles.FirstOrDefault().Tables[i] as MessageTable).Messages[j].RawData.Length == 0) continue;
         *
         *                                              html.RenderBeginTag(WebUI.HtmlTextWriterTag.Tr);
         *                                              {
         *                                                      html.AddAttribute(WebUI.HtmlTextWriterAttribute.Class, "desc-column-mesg");
         *                                                      html.RenderBeginTag(WebUI.HtmlTextWriterTag.Th);
         *                                                      {
         *                                                              html.Write("#{0}", j);
         *                                                      }
         *                                                      html.RenderEndTag();
         *
         *                                                      for (int k = 0; k < tableFiles.Count; k++)
         *                                                      {
         *                                                              html.RenderBeginTag(WebUI.HtmlTextWriterTag.Td);
         *                                                              {
         *                                                                      string message = (tableFiles[k].Tables[i] as MessageTable).Messages[j].ConvertedString;
         *                                                                      message = message.Replace("<!pg>", "");
         *                                                                      message = message.Replace(" ", "&nbsp;");
         *                                                                      message = message.Replace("<", "&lt;");
         *                                                                      message = message.Replace(">", "&gt;");
         *                                                                      message = message.Replace(Environment.NewLine, "<br />");
         *                                                                      html.Write(message);
         *                                                              }
         *                                                              html.RenderEndTag();
         *                                                      }
         *                                              }
         *                                              html.RenderEndTag();
         *                                      }
         *                              }
         *                              html.RenderEndTag();
         *                              html.WriteBreak();
         *                      }
         *              }
         *              html.RenderEndTag();
         *      }
         *      html.RenderEndTag();
         * }
         * writer.Close();
         *
         * }
         */

        public static void DumpParsers(GameDataManager gameDataManager, Type parserType, string outputFilename)
        {
            Logger log = new Logger("dump_parsers_text_html.txt");

            List <BaseParser> parsedToDump = gameDataManager.ParsedData.Where(x => x.GetType() == parserType).ToList();

            PropertyInfo[] properties = parserType.GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.FlattenHierarchy)
                                        .Where(x => !x.GetGetMethod().IsVirtual&& (x.GetAttribute <BrowsableAttribute>() == null || x.GetAttribute <BrowsableAttribute>().Browsable == true) && x.DeclaringType != typeof(BaseParser))
                                        .OrderBy(x => x.GetAttribute <Yggdrasil.Attributes.PrioritizedCategory>().Category)
                                        .ToArray();

            TextWriter writer = File.CreateText(outputFilename);

            using (WebUI.HtmlTextWriter html = new WebUI.HtmlTextWriter(writer))
            {
                html.WriteLine("<!DOCTYPE html>");
                html.RenderBeginTag(WebUI.HtmlTextWriterTag.Html);
                {
                    WriteHeader(html, string.Format("{0} Data Dump for {1}", System.Windows.Forms.Application.ProductName, parserType.GetAttribute <Yggdrasil.Attributes.ParserDescriptor>().Description));

                    html.RenderBeginTag(WebUI.HtmlTextWriterTag.Body);
                    {
                        html.AddAttribute(WebUI.HtmlTextWriterAttribute.Class, "container");
                        html.RenderBeginTag(WebUI.HtmlTextWriterTag.Div);
                        {
                            html.WriteEncodedText(string.Format("Data dump created by {0} {1}; dumping {2} entries of type '{3}'...",
                                                                System.Windows.Forms.Application.ProductName,
                                                                VersionManagement.CreateVersionString(System.Windows.Forms.Application.ProductVersion),
                                                                parsedToDump.Count,
                                                                parserType.GetAttribute <Yggdrasil.Attributes.ParserDescriptor>().Description));
                            html.WriteBreak();
                            html.WriteBreak();
                        }
                        html.RenderEndTag();

                        foreach (BaseParser parser in parsedToDump)
                        {
                            string parserId = string.Format("table-{0:D4}", parser.EntryNumber);

                            html.AddAttribute(WebUI.HtmlTextWriterAttribute.Class, "container");
                            html.RenderBeginTag(WebUI.HtmlTextWriterTag.Div);
                            {
                                html.AddAttribute(WebUI.HtmlTextWriterAttribute.Class, "header");
                                html.RenderBeginTag(WebUI.HtmlTextWriterTag.Div);
                                {
                                    html.AddAttribute(WebUI.HtmlTextWriterAttribute.Class, "header-text");
                                    html.RenderBeginTag(WebUI.HtmlTextWriterTag.Span);
                                    {
                                        html.WriteEncodedText(string.Format("Entry {0:D4}: {1}", parser.EntryNumber, parser.EntryDescription));
                                    }
                                    html.RenderEndTag();

                                    html.AddAttribute(WebUI.HtmlTextWriterAttribute.Class, "header-toggle");
                                    html.RenderBeginTag(WebUI.HtmlTextWriterTag.Span);
                                    {
                                        html.AddAttribute(WebUI.HtmlTextWriterAttribute.Href, string.Format("javascript:toggle('{0}');", parserId), false);
                                        html.RenderBeginTag(WebUI.HtmlTextWriterTag.A);
                                        {
                                            html.Write("+/-");
                                        }
                                        html.RenderEndTag();
                                    }
                                    html.RenderEndTag();
                                }
                                html.RenderEndTag();

                                html.AddAttribute(WebUI.HtmlTextWriterAttribute.Id, parserId);
                                html.RenderBeginTag(WebUI.HtmlTextWriterTag.Table);
                                {
                                    string lastCategory = string.Empty;
                                    foreach (PropertyInfo property in properties)
                                    {
                                        string propCategory = ((string)property.GetAttribute <Yggdrasil.Attributes.PrioritizedCategory>().Category).Replace("\t", "");
                                        if (propCategory != lastCategory)
                                        {
                                            lastCategory = propCategory;
                                            html.RenderBeginTag(WebUI.HtmlTextWriterTag.Tr);
                                            {
                                                html.AddAttribute(WebUI.HtmlTextWriterAttribute.Class, "header");
                                                html.AddAttribute(WebUI.HtmlTextWriterAttribute.Colspan, "2");
                                                html.RenderBeginTag(WebUI.HtmlTextWriterTag.Td);
                                                {
                                                    html.Write(propCategory);
                                                }
                                                html.RenderEndTag();
                                            }
                                            html.RenderEndTag();
                                        }
                                        html.RenderBeginTag(WebUI.HtmlTextWriterTag.Tr);
                                        {
                                            html.AddAttribute(WebUI.HtmlTextWriterAttribute.Class, "desc-column");
                                            html.RenderBeginTag(WebUI.HtmlTextWriterTag.Td);
                                            {
                                                DisplayNameAttribute displayName = property.GetAttribute <DisplayNameAttribute>();
                                                DescriptionAttribute description = property.GetAttribute <DescriptionAttribute>();
                                                log.LogMessageJSON("DisplayName:" + displayName.DisplayName);

                                                html.AddAttribute(WebUI.HtmlTextWriterAttribute.Class, "tooltip");
                                                html.RenderBeginTag(WebUI.HtmlTextWriterTag.Span);
                                                {
                                                    html.WriteEncodedText(displayName.DisplayName);
                                                    if (description != null)
                                                    {
                                                        html.RenderBeginTag(WebUI.HtmlTextWriterTag.Span);
                                                        {
                                                            html.WriteEncodedText(description.Description);
                                                        }
                                                        html.RenderEndTag();
                                                    }
                                                }
                                                html.RenderEndTag();
                                            }
                                            html.RenderEndTag();

                                            html.RenderBeginTag(WebUI.HtmlTextWriterTag.Td);
                                            {
                                                object v = property.GetValue(parser, null);
                                                TypeConverterAttribute ca = (TypeConverterAttribute)property.GetCustomAttributes(typeof(TypeConverterAttribute), false).FirstOrDefault();
                                                TypeConverter          c  = new TypeConverter();
                                                if (ca != null)
                                                {
                                                    Type ct = Type.GetType(ca.ConverterTypeName);
                                                    if (ct == typeof(EnumConverter))
                                                    {
                                                        c = (TypeConverter)Activator.CreateInstance(ct, new object[] { property.PropertyType });
                                                    }
                                                    else
                                                    {
                                                        c = (TypeConverter)Activator.CreateInstance(ct);
                                                    }
                                                }
                                                var tmp = c.ConvertTo(v, typeof(string));
                                                html.WriteEncodedText(tmp as string);
                                                log.LogMessageJSON(tmp as string);
                                            }
                                            html.RenderEndTag();
                                        }
                                        html.RenderEndTag();
                                    }
                                }
                                html.RenderEndTag();
                            }
                            html.RenderEndTag();
                        }
                    }
                    html.RenderEndTag();
                }
                html.RenderEndTag();
            }
            writer.Close();
        }
Пример #21
0
        public static PropertyDescriptorCollection GetDispMembers(Type t)
        {
            string[] order = AdvBrowsableOrderAttribute.GetOrder(t);
            List <PropertyDescriptor> rv = new List <PropertyDescriptor>();

            object[] atts;
            foreach (PropertyInfo info in t.GetProperties())
            {
                atts = info.GetCustomAttributes(typeof(AdvBrowsableAttribute), true);
                if (atts.Length > 0)
                {
                    AdvBrowsableAttribute att = (AdvBrowsableAttribute)atts[0];
                    AdvPropertyDescriptor descriptor;
                    if (att.Name != null)
                    {
                        descriptor = new AdvPropertyDescriptor(att.Name, info);
                    }
                    else
                    {
                        descriptor = new AdvPropertyDescriptor(info);
                    }
                    atts = info.GetCustomAttributes(typeof(DescriptionAttribute), true);
                    if (atts.Length > 0)
                    {
                        DescriptionAttribute att2 = (DescriptionAttribute)atts[0];
                        descriptor.SetDescription(att2.Description);
                    }
                    rv.Add(descriptor);
                }
            }
            foreach (FieldInfo info in t.GetFields())
            {
                atts = info.GetCustomAttributes(typeof(AdvBrowsableAttribute), true);
                if (atts.Length > 0)
                {
                    AdvBrowsableAttribute att = (AdvBrowsableAttribute)atts[0];
                    AdvPropertyDescriptor descriptor;
                    if (att.Name != null)
                    {
                        descriptor = new AdvPropertyDescriptor(att.Name, info);
                    }
                    else
                    {
                        descriptor = new AdvPropertyDescriptor(info);
                    }
                    atts = info.GetCustomAttributes(typeof(DescriptionAttribute), true);
                    if (atts.Length > 0)
                    {
                        DescriptionAttribute att2 = (DescriptionAttribute)atts[0];
                        descriptor.SetDescription(att2.Description);
                    }
                    rv.Add(descriptor);
                }
            }
            if (rv.Count == 0)
            {
                return(null);
            }
            if (order != null)
            {
                return(new PropertyDescriptorCollection(rv.ToArray()).Sort(order));
            }
            return(new PropertyDescriptorCollection(rv.ToArray()));
        }
Пример #22
0
        private static DefinitionProperty ProcessProperty(PropertyInfo propertyInfo, IList <string> hiddenTags,
                                                          Stack <Type> typesStack)
        {
            if (propertyInfo.GetCustomAttribute <SwaggerWcfHiddenAttribute>() != null ||
                propertyInfo.GetCustomAttributes <SwaggerWcfTagAttribute>()
                .Select(t => t.TagName)
                .Any(hiddenTags.Contains))
            {
                return(null);
            }

            TypeFormat typeFormat = Helpers.MapSwaggerType(propertyInfo.PropertyType, null);

            DefinitionProperty prop = new DefinitionProperty {
                Title = propertyInfo.Name
            };

            DataMemberAttribute dataMemberAttribute = propertyInfo.GetCustomAttribute <DataMemberAttribute>();

            if (dataMemberAttribute != null)
            {
                if (!string.IsNullOrEmpty(dataMemberAttribute.Name))
                {
                    prop.Title = dataMemberAttribute.Name;
                }

                prop.Required = dataMemberAttribute.IsRequired;
            }

            // Special case - if it came out required, but we unwrapped a null-able type,
            // then it's necessarily not required.  Ideally this would only set the default,
            // but we can't tell the difference between an explicit declaration of
            // IsRequired =false on the DataMember attribute and no declaration at all.
            if (prop.Required && propertyInfo.PropertyType.IsGenericType &&
                propertyInfo.PropertyType.GetGenericTypeDefinition() == typeof(Nullable <>))
            {
                prop.Required = false;
            }

            DescriptionAttribute descriptionAttribute = propertyInfo.GetCustomAttribute <DescriptionAttribute>();

            if (descriptionAttribute != null)
            {
                prop.Description = descriptionAttribute.Description;
            }

            SwaggerWcfRegexAttribute regexAttr = propertyInfo.GetCustomAttribute <SwaggerWcfRegexAttribute>();

            if (regexAttr != null)
            {
                prop.Pattern = regexAttr.Regex;
            }

            prop.TypeFormat = typeFormat;

            if (prop.TypeFormat.Type == ParameterType.Object)
            {
                typesStack.Push(propertyInfo.PropertyType);

                prop.Ref = propertyInfo.PropertyType.GetModelName();

                return(prop);
            }

            if (prop.TypeFormat.Type == ParameterType.Array)
            {
                Type subType = DefinitionsBuilder.GetEnumerableType(propertyInfo.PropertyType);
                if (subType != null)
                {
                    TypeFormat subTypeFormat = Helpers.MapSwaggerType(subType, null);

                    if (subTypeFormat.Type == ParameterType.Object)
                    {
                        typesStack.Push(subType);
                    }

                    prop.Items = new ParameterItems
                    {
                        TypeFormat = subTypeFormat
                    };
                }
            }

            if ((prop.TypeFormat.Type == ParameterType.Integer && prop.TypeFormat.Format == "enum") || (prop.TypeFormat.Type == ParameterType.Array && prop.Items.TypeFormat.Format == "enum"))
            {
                prop.Enum = new List <string>();

                Type propType = propertyInfo.PropertyType;

                if (propType.IsGenericType && (propType.GetGenericTypeDefinition() == typeof(Nullable <>) || propType.GetGenericTypeDefinition() == typeof(IEnumerable <>)))
                {
                    propType = propType.GenericTypeArguments.FirstOrDefault() ?? propType.GetEnumerableType();
                }

                string        enumDescription = "";
                List <string> listOfEnumNames = propType.GetEnumNames().ToList();
                foreach (string enumName in listOfEnumNames)
                {
                    var    enumMemberItem        = Enum.Parse(propType, enumName, true);
                    string enumMemberDescription = DefinitionsBuilder.GetEnumDescription((Enum)enumMemberItem);
                    enumMemberDescription = (string.IsNullOrWhiteSpace(enumMemberDescription)) ? "" : $"({enumMemberDescription})";
                    string enumMemberValue = DefinitionsBuilder.GetEnumMemberValue(propType, enumName);
                    if (prop.Description != null)
                    {
                        prop.Enum.Add(enumMemberValue);
                    }
                    enumDescription += $"    {enumName}{System.Web.HttpUtility.HtmlEncode(" = ")}{enumMemberValue} {enumMemberDescription}\r\n";
                }

                if (enumDescription != "")
                {
                    prop.Description += $"\r\n\r\n{enumDescription}";
                }
            }

            // Apply any options set in a [SwaggerWcfProperty]
            DefinitionsBuilder.ApplyAttributeOptions(propertyInfo, prop);

            return(prop);
        }
Пример #23
0
        /// <summary>
        /// Constructor
        /// </summary>
        static ReverserBase()
        {
            Type enumType = typeof(T);

            if (!enumType.IsEnum)
            {
                throw (new ArgumentException("T"));
            }

            // Get type and size from underlying type
            Type enumTypeBase = Enum.GetUnderlyingType(enumType);

            OpCodeSize  = Marshal.SizeOf(enumTypeBase);
            OpCodeCache = new Dictionary <string, OpCodeArgumentAttribute>();

            foreach (object t in Enum.GetValues(enumType))
            {
                // Get enumn member
                MemberInfo[] memInfo = enumType.GetMember(t.ToString());
                if (memInfo == null || memInfo.Length != 1)
                {
                    throw (new FormatException());
                }

                DescriptionAttribute    desc = memInfo[0].GetCustomAttribute <DescriptionAttribute>();
                OpCodeArgumentAttribute opa  = memInfo[0].GetCustomAttribute <OpCodeArgumentAttribute>();

                if (opa == null)
                {
                    throw (new FormatException());
                }

                if (desc != null && string.IsNullOrEmpty(opa.Description))
                {
                    opa.Description = desc.Description;
                }

                opa.OpCode = t.ToString();

                //  Get byte array from underlying type type
                byte[] d;
                object value = Convert.ChangeType(t, enumTypeBase);

                switch (Type.GetTypeCode(value.GetType()))
                {
                case TypeCode.Byte: d = new byte[] { (byte)value }; break;

                case TypeCode.Int16: d = ((short)value).ToByteArray(); break;

                case TypeCode.UInt16: d = ((ushort)value).ToByteArray(); break;

                case TypeCode.Int32: d = ((int)value).ToByteArray(); break;

                case TypeCode.UInt32: d = ((uint)value).ToByteArray(); break;

                case TypeCode.Int64: d = ((long)value).ToByteArray(); break;

                case TypeCode.UInt64: d = ((ulong)value).ToByteArray(); break;

                default: throw (new ArgumentException("T"));
                }

                // Append to cache
                OpCodeCache.Add(d.ToHexString(), opa);
            }
        }
Пример #24
0
        /// <summary>
        /// If the specified Enum has a System.ComponentModel.DescriptionAttribute defined, the defined description is returned. Otherwise call ToString() on the Enum value.
        /// </summary>
        /// <param name="source">Source enum.</param>
        /// <returns>Description string.</returns>
        public static string ToDescriptionString(this Enum source)
        {
            DescriptionAttribute descriptionAttribute = source.GetType().GetField(source.ToString()).GetCustomAttributes(typeof(DescriptionAttribute), false).FirstOrDefault() as DescriptionAttribute;

            return((descriptionAttribute != null) ? descriptionAttribute.Description : source.ToString());
        }
Пример #25
0
        private ModelDescription GenerateComplexTypeModelDescription(Type modelType)
        {
            ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription
            {
                Name          = ModelNameHelper.GetModelName(modelType),
                ModelType     = modelType,
                Documentation = CreateDefaultDocumentation(modelType)
            };

            GeneratedModels.Add(complexModelDescription.Name, complexModelDescription);
            bool hasDataContractAttribute = modelType.GetCustomAttribute <DataContractAttribute>() != null;

            PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
            foreach (PropertyInfo property in properties)
            {
                if (ShouldDisplayMember(property, hasDataContractAttribute))
                {
                    ParameterDescription propertyModel = new ParameterDescription
                    {
                        Name = GetMemberName(property, hasDataContractAttribute)
                    };

                    if (DocumentationProvider != null)
                    {
                        //以下用Description特性显示当前实体的字段解释
                        DescriptionAttribute myattribute       = (DescriptionAttribute)Attribute.GetCustomAttribute(property, typeof(DescriptionAttribute));
                        RequiredAttribute    requiredAttribute = (RequiredAttribute)Attribute.GetCustomAttribute(property, typeof(RequiredAttribute));
                        if (myattribute != null)
                        {
                            propertyModel.Documentation = myattribute.Description;
                        }
                        else
                        {
                            propertyModel.Documentation = DocumentationProvider.GetDocumentation(property);
                        }

                        if (requiredAttribute != null)
                        {
                            propertyModel.Documentation = propertyModel.Documentation + " 必填";
                        }
                    }

                    GenerateAnnotations(property, propertyModel);
                    complexModelDescription.Properties.Add(propertyModel);
                    propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType);
                }
            }

            FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance);
            foreach (FieldInfo field in fields)
            {
                if (ShouldDisplayMember(field, hasDataContractAttribute))
                {
                    ParameterDescription propertyModel = new ParameterDescription
                    {
                        Name = GetMemberName(field, hasDataContractAttribute)
                    };


                    if (DocumentationProvider != null)
                    {
                        //以下用Description特性显示当前实体的字段解释
                        DescriptionAttribute myattribute       = (DescriptionAttribute)Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute));
                        RequiredAttribute    requiredAttribute = (RequiredAttribute)Attribute.GetCustomAttribute(field, typeof(RequiredAttribute));
                        if (myattribute != null)
                        {
                            propertyModel.Documentation = myattribute.Description;
                        }
                        else
                        {
                            propertyModel.Documentation = DocumentationProvider.GetDocumentation(field);
                        }

                        if (requiredAttribute != null)
                        {
                            propertyModel.Documentation = propertyModel.Documentation + " 必填";
                        }
                    }

                    complexModelDescription.Properties.Add(propertyModel);
                    propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType);
                }
            }

            return(complexModelDescription);
        }
Пример #26
0
        /// <summary>
        /// 获取类型的Description特性描述信息
        /// </summary>
        /// <param name="type">类型对象</param>
        /// <param name="inherit">是否搜索类型的继承链以查找描述特性</param>
        /// <returns>返回Description特性描述信息,如不存在则返回类型的全名</returns>
        public static string GetDescription(this Type type, bool inherit = false)
        {
            DescriptionAttribute desc = type.GetAttribute <DescriptionAttribute>(inherit);

            return(desc == null ? type.FullName : desc.Description);
        }
Пример #27
0
        /// <summary>
        /// Function to retrieve any attributes from this property.
        /// </summary>
        private void GetAttributes()
        {
            DefaultValueAttribute      defaultValue  = null;
            ReadOnlyAttribute          readOnly      = null;
            RefreshPropertiesAttribute refresh       = null;
            DescriptionAttribute       description   = null;
            CategoryAttribute          category      = null;
            EditorAttribute            editor        = null;
            TypeConverterAttribute     typeConverter = null;
            DisplayNameAttribute       displayName   = null;

            foreach (Attribute attribute in _descriptor.Attributes.Cast <Attribute>())
            {
                if (defaultValue == null)
                {
                    defaultValue = attribute as DefaultValueAttribute;
                }

                if (readOnly == null)
                {
                    readOnly = attribute as ReadOnlyAttribute;
                }

                if (refresh == null)
                {
                    refresh = attribute as RefreshPropertiesAttribute;
                }

                if (description == null)
                {
                    description = attribute as DescriptionAttribute;
                }

                if (category == null)
                {
                    category = attribute as CategoryAttribute;
                }

                if (editor == null)
                {
                    editor = attribute as EditorAttribute;
                }

                if (typeConverter == null)
                {
                    typeConverter = attribute as TypeConverterAttribute;
                }

                if (displayName == null)
                {
                    displayName = attribute as DisplayNameAttribute;
                }
            }

            if (defaultValue != null)
            {
                DefaultValue = defaultValue.Value;
            }

            if (readOnly != null)
            {
                IsReadOnly = readOnly.IsReadOnly;
            }

            if (refresh != null)
            {
                RefreshProperties = refresh.RefreshProperties;
            }

            if (description != null)
            {
                Description = description.Description;
            }

            if (category != null)
            {
                Category = category.Category;
            }

            if (editor != null)
            {
                _editorBase = editor.EditorBaseTypeName;
                Editor      = editor.EditorTypeName;
            }

            if (displayName != null)
            {
                DisplayName = displayName.DisplayName;
            }

            if (typeConverter != null)
            {
                Converter = typeConverter.ConverterTypeName;
            }
        }
Пример #28
0
 public void CategoryNames(DescriptionAttribute attribute, string name)
 {
     Assert.Equal(name, attribute.Description);
 }
        /// <summary>
        ///  获取成员元数据的Description特性描述信息
        /// </summary>
        /// <param name="member">成员元数据对象</param>
        /// <param name="inherit">是否搜索成员的继承链以查找描述特性</param>
        /// <returns>返回Description特性描述信息,如不存在则返回成员的名称</returns>
        public static string ToDescription(this MemberInfo member, bool inherit = false)
        {
            DescriptionAttribute desc = member.GetAttribute <DescriptionAttribute>(inherit);

            return(desc == null ? null : desc.Description);
        }
Пример #30
0
        /// <summary>
        /// 根据枚举变量获取对应枚举类型的所有值的 Description 、 DisplayName 或 Display(Name= 特性值
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="spliter"></param>
        /// <returns></returns>
        public static string GetMutiEnumDescription(this object obj, string spliter = ",")
        {
            if (obj == null)
            {
                return(string.Empty);
            }
            try
            {
                Type type = obj.GetType();

                if (type.IsEnum)
                {
                    var flagValues = Enum.GetValues(type);
                    Dictionary <object, string> vd = new Dictionary <object, string>();
                    DescriptionAttribute        da = null;
                    //FieldInfo fi = type.GetField(Enum.GetName(type, obj));
                    //    da = (DescriptionAttribute)Attribute.GetCustomAttribute(fi, typeof(DescriptionAttribute));
                    foreach (var v in flagValues)
                    {
                        FieldInfo fi    = type.GetField(Enum.GetName(type, obj));
                        var       attrs = fi.GetCustomAttributes(false);

                        if (attrs.Any(i => i.GetType() == typeof(DescriptionAttribute)))
                        {
                            DescriptionAttribute desc = (DescriptionAttribute)attrs.Find(i => i.GetType() == typeof(DescriptionAttribute));
                            vd.Add(v, desc.Description);
                        }
                        else if (attrs.Any(i => i.GetType() == typeof(DisplayNameAttribute)))
                        {
                            DisplayNameAttribute desc = (DisplayNameAttribute)attrs.Find(i => i.GetType() == typeof(DisplayNameAttribute));
                            vd.Add(v, desc.DisplayName);
                        }
                        else if (attrs.Any(i => i.GetType() == typeof(DisplayAttribute)))
                        {
                            DisplayAttribute desc = (DisplayAttribute)attrs.Find(i => i.GetType() == typeof(DisplayAttribute));
                            vd.Add(v, desc.Name);
                        }
                    }
                    List <string> descs     = new List <string>();
                    int           realValue = (int)obj;
                    foreach (var x in flagValues)
                    {
                        var temp = (int)x;
                        if ((realValue & temp) == temp)
                        {
                            if (vd.ContainsKey(x))
                            {
                                descs.Add(vd[x]);
                            }
                            else
                            {
                                descs.Add(x.ToString());
                            }
                        }
                    }
                    return(descs.Aggregate((s, r) => { return string.Format("{0}{1}{2}", s, spliter, r); }));
                }
            }
            catch
            {
            }
            return(string.Empty);
        }
        /// <ToBeCompleted></ToBeCompleted>
        protected Attribute[] GetPropertyAttributes(IPropertyController controller, PropertyDescriptor descriptor)
        {
            if (controller == null)
            {
                throw new ArgumentNullException("controller");
            }
            if (descriptor == null)
            {
                throw new ArgumentNullException("descriptor");
            }
            try {
                int attrCount = descriptor.Attributes.Count;
                BrowsableAttribute          browsableAttr          = descriptor.Attributes[typeof(BrowsableAttribute)] as BrowsableAttribute;
                ReadOnlyAttribute           readOnlyAttr           = descriptor.Attributes[typeof(ReadOnlyAttribute)] as ReadOnlyAttribute;
                DescriptionAttribute        descriptionAttr        = descriptor.Attributes[typeof(DescriptionAttribute)] as DescriptionAttribute;
                RequiredPermissionAttribute requiredPermissionAttr = descriptor.Attributes[typeof(RequiredPermissionAttribute)] as RequiredPermissionAttribute;

                if (requiredPermissionAttr != null)
                {
                    object     propertyOwner = GetPropertyOwner(descriptor);
                    Permission permission    = requiredPermissionAttr.Permission;
                    // Check if property is viewable
                    if (!IsGranted(controller, permission, SecurityAccess.Modify, propertyOwner))
                    {
                        // Hide if PropertyDisplayMode is 'Hidden' and 'View' access is not granted,
                        // otherwise set peroperty to readonly
                        if (controller.PropertyDisplayMode == NonEditableDisplayMode.Hidden &&
                            !IsGranted(controller, permission, SecurityAccess.View, propertyOwner))
                        {
                            browsableAttr = BrowsableAttribute.No;
                        }
                        else
                        {
                            readOnlyAttr    = ReadOnlyAttribute.Yes;
                            descriptionAttr = GetNotGrantedDescription(descriptionAttr, permission);
                        }
                    }
                }

                // Now copy all attributes
                int cnt = descriptor.Attributes.Count;
                List <Attribute> result = new List <Attribute>(attrCount);
                // Add stored/modified attributes first
                if (browsableAttr != null)
                {
                    result.Add(browsableAttr);
                }
                if (readOnlyAttr != null)
                {
                    result.Add(readOnlyAttr);
                }
                if (descriptionAttr != null)
                {
                    result.Add(descriptionAttr);
                }
                if (requiredPermissionAttr != null)
                {
                    result.Add(requiredPermissionAttr);
                }
                // Copy all other attributes
                foreach (Attribute attribute in descriptor.Attributes)
                {
                    // Skip stored/modified attributes
                    if (attribute is BrowsableAttribute)
                    {
                        continue;
                    }
                    else if (attribute is ReadOnlyAttribute)
                    {
                        continue;
                    }
                    else if (attribute is DescriptionAttribute)
                    {
                        continue;
                    }
                    else if (attribute is EditorAttribute)
                    {
                        if (readOnlyAttr != null && readOnlyAttr.IsReadOnly)
                        {
                            continue;
                        }
                    }
                    result.Add(attribute);
                }
                return(result.ToArray());
            } catch (Exception) {
                throw;
            }
        }
Пример #32
0
        /// <summary>
        /// 枚举Lsit信息获取
        /// </summary>
        /// <param name="enumType"></param>
        /// <param name="flgRemoveAll">如果不想要All,设置为true</param>
        /// <returns></returns>
        public static List <EnumItem> GetList(this Type enumType, bool flgRemoveAll = false, EnumLanguage lan = EnumLanguage.CN)
        {
            // 返回值
            List <EnumItem> result = new List <EnumItem>();

            // 枚举遍历
            foreach (var e in Enum.GetValues(enumType))
            {
                EnumItem item = new EnumItem();

                // 获取Index
                item.Index = (int)e;
                // 是否加入All枚举
                if (flgRemoveAll && item.Index == 0)
                {
                    continue;
                }

                // 获取描述
                object[] objArr;
                switch (lan)
                {
                // 中文
                case EnumLanguage.CN:
                    objArr = e.GetType().GetField(e.ToString()).GetCustomAttributes(typeof(DescriptionAttribute), true);
                    if (objArr != null && objArr.Length > 0)
                    {
                        // 中文获取Description特性
                        DescriptionAttribute da = objArr[0] as DescriptionAttribute;
                        item.Description = da.Description;
                    }
                    break;

                // 英文
                case EnumLanguage.EN:
                    objArr = e.GetType().GetField(e.ToString()).GetCustomAttributes(typeof(EnglishAttribute), true);
                    if (objArr != null && objArr.Length > 0)
                    {
                        // 英文获取Description特性
                        EnglishAttribute da = objArr[0] as EnglishAttribute;
                        item.Description = da.Value;
                    }
                    break;

                // 日文
                default:
                    objArr = e.GetType().GetField(e.ToString()).GetCustomAttributes(typeof(JapaneseAttribute), true);
                    if (objArr != null && objArr.Length > 0)
                    {
                        // 日文获取Japanese特性
                        JapaneseAttribute da = objArr[0] as JapaneseAttribute;
                        item.Description = da.Value;
                    }
                    break;
                }

                // 获取Value值
                object[] dbValueArr = e.GetType().GetField(e.ToString()).GetCustomAttributes(typeof(ValueAttribute), true);
                if (dbValueArr != null && dbValueArr.Length > 0)
                {
                    ValueAttribute da = dbValueArr[0] as ValueAttribute;
                    item.Value = da.Value;
                }

                result.Add(item);
            }
            return(result);
        }
Пример #33
0
        /// <summary>
        /// Get Description attribute value
        /// </summary>
        /// <param name="fieldInstance"></param>
        /// <returns></returns>
        public static string GetDescriptionAttributeValue(this Enum fieldInstance)
        {
            DescriptionAttribute descAttrib = GetAttributeForField <Enum, DescriptionAttribute>(fieldInstance);

            return(descAttrib.Description);
        }
Пример #34
0
        private void LoadParameter()
        {
            DescriptionAttribute da = mMethod.GetCustomAttribute <DescriptionAttribute>(false);

            if (da != null)
            {
                this.Remark = da.Description;
            }
            foreach (System.Reflection.ParameterInfo pi in mMethod.GetParameters())
            {
                ParameterBinder   pb       = new DefaultParameter();
                ParameterBinder[] customPB = (ParameterBinder[])pi.GetCustomAttributes(typeof(ParameterBinder), false);
                if (customPB != null && customPB.Length > 0)
                {
                    pb = customPB[0];
                }
                else if (pi.ParameterType == typeof(Boolean))
                {
                    pb = new BooleanParameter();
                }
                else if (pi.ParameterType == typeof(string))
                {
                    pb = new StringParameter();
                }
                else if (pi.ParameterType == typeof(DateTime))
                {
                    pb = new DateTimeParameter();
                }

                else if (pi.ParameterType == typeof(Decimal))
                {
                    pb = new DecimalParameter();
                }
                else if (pi.ParameterType == typeof(float))
                {
                    pb = new FloatParameter();
                }
                else if (pi.ParameterType == typeof(double))
                {
                    pb = new DoubleParameter();
                }
                else if (pi.ParameterType == typeof(short))
                {
                    pb = new ShortParameter();
                }
                else if (pi.ParameterType == typeof(int))
                {
                    pb = new IntParameter();
                }
                else if (pi.ParameterType == typeof(long))
                {
                    pb = new LongParameter();
                }
                else if (pi.ParameterType == typeof(ushort))
                {
                    pb = new UShortParameter();
                }
                else if (pi.ParameterType == typeof(uint))
                {
                    pb = new UIntParameter();
                }
                else if (pi.ParameterType == typeof(ulong))
                {
                    pb = new ULongParameter();
                }
                else if (pi.ParameterType == typeof(HttpRequest))
                {
                    pb = new RequestParameter();
                }
                else if (pi.ParameterType == typeof(IHttpContext))
                {
                    pb = new HttpContextParameter();
                }
                else if (pi.ParameterType == typeof(IDataContext))
                {
                    pb = new DataContextParameter();
                }
                else if (pi.ParameterType == typeof(HttpApiServer))
                {
                    pb = new HttpApiServerParameter();
                }
                else if (pi.ParameterType == typeof(HttpResponse))
                {
                    pb = new ResponseParameter();
                }
                else if (pi.ParameterType == typeof(PostFile))
                {
                    pb = new PostFileParameter();
                }
                else
                {
                    pb = HttpApiServer.ActionFactory.GetParameterBinder(pi.ParameterType);
                    if (pb == null)
                    {
                        if (HttpApiServer.ActionFactory.HasParameterBindEvent)
                        {
                            pb = new ParamterEventBinder(HttpApiServer.ActionFactory);
                        }
                        else
                        {
                            pb = new DefaultParameter();
                        }
                    }
                }
                pb.ActionHandler = this;
                pb.ParameterInfo = pi;
                pb.Name          = pi.Name;
                pb.Type          = pi.ParameterType;
                pb.Validations   = pi.GetCustomAttributes <Validations.ValidationBase>(false).ToArray();
                if (!HasValidation)
                {
                    HasValidation = pb.Validations != null && pb.Validations.Length > 0;
                }
                pb.CacheKey = pi.GetCustomAttribute <CacheKeyParameter>(false);
                Parameters.Add(pb);
            }
        }