public void DisplayAttribute_Resourced_Properties() {
            DisplayAttribute attr = new DisplayAttribute();

            attr.ResourceType = typeof(DisplayAttribute_Resources);

            Assert.IsNull(attr.GetShortName());
            Assert.IsNull(attr.GetName());
            Assert.IsNull(attr.GetPrompt());
            Assert.IsNull(attr.GetDescription());
            Assert.IsNull(attr.GetGroupName());

            attr.ShortName = "Resource1";
            attr.Name = "Resource2";
            attr.Prompt = "Resource3";
            attr.Description = "Resource4";
            attr.GroupName = "Resource5";

            Assert.AreEqual("string1", attr.GetShortName());
            Assert.AreEqual("string2", attr.GetName());
            Assert.AreEqual("string3", attr.GetPrompt());
            Assert.AreEqual("string4", attr.GetDescription());
            Assert.AreEqual("string5", attr.GetGroupName());

            Assert.AreEqual("Resource1", attr.ShortName);
            Assert.AreEqual("Resource2", attr.Name);
            Assert.AreEqual("Resource3", attr.Prompt);
            Assert.AreEqual("Resource4", attr.Description);
            Assert.AreEqual("Resource5", attr.GroupName);
        }
Пример #2
0
        public void Name_Get_Set(string value)
        {
            DisplayAttribute attribute = new DisplayAttribute();
            attribute.Name = value;

            Assert.Equal(value, attribute.Name);
            Assert.Equal(value == null, attribute.GetName() == null);

            // Set again, to cover the setter avoiding operations if the value is the same
            attribute.Name = value;
            Assert.Equal(value, attribute.Name);
        }
Пример #3
0
        public void Ctor()
        {
            DisplayAttribute attribute = new DisplayAttribute();
            Assert.Null(attribute.ShortName);
            Assert.Null(attribute.GetShortName());

            Assert.Null(attribute.Name);
            Assert.Null(attribute.GetName());

            Assert.Null(attribute.Description);
            Assert.Null(attribute.GetDescription());

            Assert.Null(attribute.Prompt);
            Assert.Null(attribute.GetPrompt());

            Assert.Null(attribute.GroupName);
            Assert.Null(attribute.GetGroupName());

            Assert.Null(attribute.ResourceType);
        }
        public void DisplayAttribute_Literal_Properties() {
            DisplayAttribute attr = new DisplayAttribute();

            Assert.IsNull(attr.ResourceType);
            Assert.IsNull(attr.ShortName);
            Assert.IsNull(attr.Name);
            Assert.IsNull(attr.Prompt);
            Assert.IsNull(attr.Description);
            Assert.IsNull(attr.GroupName);

            Assert.IsNull(attr.GetShortName());
            Assert.IsNull(attr.GetName());
            Assert.IsNull(attr.GetPrompt());
            Assert.IsNull(attr.GetDescription());
            Assert.IsNull(attr.GetGroupName());

            attr.ShortName = "theShortName";
            attr.Name = "theName";
            attr.Prompt = "thePrompt";
            attr.Description = "theDescription";
            attr.GroupName = "theGroupName";

            Assert.AreEqual("theShortName", attr.GetShortName());
            Assert.AreEqual("theName", attr.GetName());
            Assert.AreEqual("thePrompt", attr.GetPrompt());
            Assert.AreEqual("theDescription", attr.GetDescription());
            Assert.AreEqual("theGroupName", attr.GetGroupName());

            attr.ShortName = String.Empty;
            attr.Name = String.Empty;
            attr.Prompt = String.Empty;
            attr.Description = String.Empty;
            attr.GroupName = String.Empty;

            Assert.AreEqual(String.Empty, attr.GetShortName());
            Assert.AreEqual(String.Empty, attr.GetName());
            Assert.AreEqual(String.Empty, attr.GetPrompt());
            Assert.AreEqual(String.Empty, attr.GetDescription());
            Assert.AreEqual(String.Empty, attr.GetGroupName());
        }
        public void DisplayAttribute_AutoGenerateFilter_Is_Optional() {
            DisplayAttribute attr = new DisplayAttribute();

            ExceptionHelper.ExpectException<InvalidOperationException>(delegate() {
                attr.AutoGenerateFilter.ToString();
            }, String.Format(CultureInfo.CurrentCulture, Resources.DataAnnotationsResources.DisplayAttribute_PropertyNotSet, "AutoGenerateFilter", "GetAutoGenerateFilter"));

            Assert.IsNull(attr.GetOrder(), "GetAutoGenerateFilter should be null by default");
        }
 public void DisplayAttribute_Order_Can_Be_Set_And_Retrieved() {
     DisplayAttribute attr = new DisplayAttribute { Order = 1 };
     Assert.AreEqual(1, attr.Order, "The Order getter should return what was set");
     Assert.AreEqual(1, attr.GetOrder().Value, "The GetOrder method should return what was set for the Order property");
 }
Пример #7
0
        internal static bool ValidateMethodCall(string methodName,
                                                ValidationContext validationContext, object[] parameters,
                                                List <ValidationResult> validationResults, bool performTypeValidation)
        {
            if (string.IsNullOrEmpty(methodName))
            {
                throw new ArgumentNullException("methodName");
            }

            if (validationContext == null)
            {
                throw new ArgumentNullException("validationContext");
            }

            if (validationContext.ObjectInstance == null)
            {
                throw new ArgumentException(DataResource.ValidationUtilities_ContextInstance_CannotBeNull, "validationContext");
            }

            MethodInfo        method        = GetMethod(validationContext.ObjectInstance, methodName, parameters);
            ValidationContext methodContext = CreateValidationContext(validationContext.ObjectInstance, validationContext);

            methodContext.MemberName = method.Name;

            DisplayAttribute display = GetDisplayAttribute(method);

            if (display != null)
            {
                methodContext.DisplayName = display.GetName();
            }

            string memberPath = string.Empty;

            if (performTypeValidation)
            {
                memberPath = method.Name + ".";
            }

            IEnumerable <ValidationAttribute> validationAttributes = method.GetCustomAttributes(typeof(ValidationAttribute), true).Cast <ValidationAttribute>();
            bool success = ValidationUtilities.ValidateValue(validationContext.ObjectInstance, methodContext, validationResults, validationAttributes, string.Empty);

            ParameterInfo[] parameterInfos = method.GetParameters();

            for (int paramIndex = 0; paramIndex < parameterInfos.Length; paramIndex++)
            {
                ParameterInfo methodParameter = parameterInfos[paramIndex];
                object        value           = (parameters.Length > paramIndex ? parameters[paramIndex] : null);

                ValidationContext parameterContext = ValidationUtilities.CreateValidationContext(validationContext.ObjectInstance, validationContext);
                parameterContext.MemberName = methodParameter.Name;

                string paramName = methodParameter.Name;

                display = GetDisplayAttribute(methodParameter);

                if (display != null)
                {
                    paramName = display.GetName();
                }

                parameterContext.DisplayName = paramName;

                string parameterPath = memberPath;
                if (performTypeValidation)
                {
                    parameterPath += methodParameter.Name;
                }

                IEnumerable <ValidationAttribute> parameterAttributes = methodParameter.GetCustomAttributes(typeof(ValidationAttribute), false).Cast <ValidationAttribute>();
                bool parameterSuccess = ValidationUtilities.ValidateValue(value, parameterContext, validationResults,
                                                                          parameterAttributes, ValidationUtilities.NormalizeMemberPath(parameterPath, methodParameter.ParameterType));

                if (parameterSuccess && performTypeValidation && value != null)
                {
                    Type parameterType = methodParameter.ParameterType;

                    // If the user expects an exception we perform shallow validation only.
                    if (validationResults == null)
                    {
                        if (TypeUtility.IsComplexType(parameterType))
                        {
                            ValidationContext context = ValidationUtilities.CreateValidationContext(value, parameterContext);
                            context.DisplayName = paramName;
                            Validator.ValidateObject(value, context, /*validateAllProperties*/ true);
                        }
                    }
                    // Else we are able to report fully recursive validation errors to the user, perform deep validation.
                    else
                    {
                        if (TypeUtility.IsComplexType(parameterType))
                        {
                            parameterSuccess = ValidationUtilities.ValidateObjectRecursive(value, parameterPath, validationContext, validationResults);
                        }
                        else if (TypeUtility.IsComplexTypeCollection(parameterType))
                        {
                            parameterSuccess = ValidationUtilities.ValidateComplexCollection(value as IEnumerable, parameterPath, validationContext, validationResults);
                        }
                    }
                }

                success &= parameterSuccess;
            }

            return(success);
        }
        private void DiscoverObject()
        {
            this.displays.Clear();
            this.properties.Clear();
            this.bindables.Clear();
            this.bindings.Clear();
#if !SILVERLIGHT
            this.rules.Clear();
#endif
            this.controls.Clear();
            this.validations.Clear();

            if (this.CurrentItem == null)
            {
                return;
            }

            Type           dataType = this.CurrentItem.GetType();
            PropertyInfo[] properties;

            //Code for dynamic Types....

            /*var meta = this.CurrentItem as IDynamicMetaObjectProvider;
             * if (meta != null)
             * {
             *  List<PropertyInfo> tmpLst = new List<PropertyInfo>();
             *  var metaObject = meta.GetMetaObject(System.Linq.Expressions.Expression.Constant(this.CurrentItem));
             *  var membernames = metaObject.GetDynamicMemberNames();
             *  foreach (var membername in membernames)
             *  {
             *      var binder = Microsoft.CSharp.RuntimeBinder.Binder.GetMember(CSharpBinderFlags.None, membername, dataType, new[] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null) });
             *      var callsite = CallSite<Func<CallSite, object, object>>.Create(binder);
             *      var item = callsite.Target(callsite, this.CurrentItem);
             *  }
             * }
             * else*/
            {
                properties = GetPropertyInfos(dataType);
            }

            BindableAttribute bindable = ((BindableAttribute[])dataType.GetCustomAttributes(typeof(System.ComponentModel.BindableAttribute), true)).FirstOrDefault();

            foreach (PropertyInfo property in properties)
            {
                BindableAttribute propBindable = ((BindableAttribute[])property.GetCustomAttributes(typeof(System.ComponentModel.BindableAttribute), true)).FirstOrDefault();

                // Check if Readable
                if (!property.CanRead)
                {
                    continue;
                }

                // Check if Bindable
                if ((bindable != null && !bindable.Bindable && propBindable == null) || (bindable != null && !bindable.Bindable && propBindable != null && !propBindable.Bindable) || (propBindable != null && !propBindable.Bindable))
                {
                    continue;
                }


                DisplayAttribute           propDisplay  = ((DisplayAttribute[])Attribute.GetCustomAttributes(property, typeof(DisplayAttribute), true)).FirstOrDefault();
                EditableAttribute          propEditable = ((EditableAttribute[])Attribute.GetCustomAttributes(property, typeof(EditableAttribute), true)).FirstOrDefault();
                List <ValidationAttribute> validations  = new List <ValidationAttribute>((ValidationAttribute[])Attribute.GetCustomAttributes(property, typeof(ValidationAttribute), true));

                if (propDisplay == null)
                {
                    propDisplay = new DisplayAttribute()
                    {
                        AutoGenerateField = true, Name = property.Name, ShortName = property.Name, Order = 10000, Prompt = null, GroupName = null, Description = null
                    }
                }
                ;
                if (propEditable == null)
                {
                    propEditable = new EditableAttribute(!this.DefaultReadOnly)
                    {
                        AllowInitialValue = true
                    }
                }
                ;

                bool setPrivate = true;
                if (property.GetSetMethod(true) != null)
                {
                    setPrivate = !property.GetSetMethod(true).IsPublic;
                }

                if (propDisplay.GetAutoGenerateField().HasValue&& !propDisplay.AutoGenerateField)
                {
                    continue;
                }

                if (PropertyDisplayInformations != null)
                {
                    var prpDisplay = PropertyDisplayInformations.FirstOrDefault(x => x.Name == property.Name);
                    if (prpDisplay == null || !prpDisplay.Visible)
                    {
                        continue;
                    }
                    propDisplay.Order = prpDisplay.Order;
                }


                if (bindable != null && propBindable == null)
                {
                    if ((!property.CanWrite || !propEditable.AllowEdit || setPrivate) && bindable.Direction == BindingDirection.TwoWay)
                    {
                        this.bindables.Add(property.Name, new BindableAttribute(true, BindingDirection.OneWay));
                    }
                    else
                    {
                        this.bindables.Add(property.Name, new BindableAttribute(true, bindable.Direction));
                    }
                }
                else if (propBindable != null)
                {
                    if ((!property.CanWrite || !propEditable.AllowEdit || setPrivate) && propBindable.Direction == BindingDirection.TwoWay)
                    {
                        this.bindables.Add(property.Name, new BindableAttribute(true, BindingDirection.OneWay));
                    }
                    else
                    {
                        this.bindables.Add(property.Name, new BindableAttribute(true, propBindable.Direction));
                    }
                }
                else
                {
                    if (!this.bindables.ContainsKey(property.Name))
                    {
                        if (!property.CanWrite || !propEditable.AllowEdit || setPrivate)
                        {
                            this.bindables.Add(property.Name, new BindableAttribute(true, BindingDirection.OneWay));
                        }
                        else
                        {
                            this.bindables.Add(property.Name, new BindableAttribute(true, BindingDirection.TwoWay));
                        }
                    }
                }

                if (!this.validations.ContainsKey(property.Name))
                {
                    this.validations.Add(property.Name, validations);
                    this.displays.Add(property.Name, propDisplay);
                    this.properties.Add(property.Name, property);
                }
            }
        }
        public void DisplayAttribute_Resourced_Properties_Wrong_Keys() {
            DisplayAttribute attr = new DisplayAttribute();

            attr.ResourceType = typeof(DisplayAttribute_Resources);

            attr.ShortName = "notAKey1";
            attr.Name = "notAKey2";
            attr.Prompt = "notAKey3";
            attr.Description = "notAKey4";
            attr.GroupName = "notAKey5";

            Assert.AreEqual("notAKey1", attr.ShortName);
            Assert.AreEqual("notAKey2", attr.Name);
            Assert.AreEqual("notAKey3", attr.Prompt);
            Assert.AreEqual("notAKey4", attr.Description);
            Assert.AreEqual("notAKey5", attr.GroupName);

            string shortNameError = String.Format(CultureInfo.CurrentCulture, Resources.DataAnnotationsResources.LocalizableString_LocalizationFailed, "ShortName", attr.ResourceType.FullName, attr.ShortName);
            string nameError = String.Format(CultureInfo.CurrentCulture, Resources.DataAnnotationsResources.LocalizableString_LocalizationFailed, "Name", attr.ResourceType.FullName, attr.Name);
            string promptError = String.Format(CultureInfo.CurrentCulture, Resources.DataAnnotationsResources.LocalizableString_LocalizationFailed, "Prompt", attr.ResourceType.FullName, attr.Prompt);
            string descriptionError = String.Format(CultureInfo.CurrentCulture, Resources.DataAnnotationsResources.LocalizableString_LocalizationFailed, "Description", attr.ResourceType.FullName, attr.Description);
            string groupNameError = String.Format(CultureInfo.CurrentCulture, Resources.DataAnnotationsResources.LocalizableString_LocalizationFailed, "GroupName", attr.ResourceType.FullName, attr.GroupName);

            ExceptionHelper.ExpectException<InvalidOperationException>(() => { string s = attr.GetShortName(); }, shortNameError);
            ExceptionHelper.ExpectException<InvalidOperationException>(() => { string s = attr.GetName(); }, nameError);
            ExceptionHelper.ExpectException<InvalidOperationException>(() => { string s = attr.GetPrompt(); }, promptError);
            ExceptionHelper.ExpectException<InvalidOperationException>(() => { string s = attr.GetDescription(); }, descriptionError);
            ExceptionHelper.ExpectException<InvalidOperationException>(() => { string s = attr.GetGroupName(); }, groupNameError);
        }
Пример #10
0
        public static string GetDisplayName(this System.Type type, string fieldName)
        {
            DisplayAttribute displayAttribute = type.GetField(fieldName).GetCustomAttributes(typeof(DisplayAttribute), false).FirstOrDefault <object>() as DisplayAttribute;

            return((displayAttribute != null) ? displayAttribute.Name : fieldName);
        }
        /// <summary>
        /// Configures the localizable strings to the <see cref="PageInfo"/> in the tree path
        /// created from the current request. Uses <see cref="DisplayAttribute"/> and/or the
        /// <see cref="PageMetadataAttribute"/>.
        /// </summary>
        /// <param name="currentPageTree">Current page tree to apply</param>
        private void ApplyAttributes(PageTree currentPageTree)
        {
            PageInfo   currentPage = currentPageTree.Page;
            MethodInfo pageAction  = currentPage.Action;

            //detect and apply the display attribute
            DisplayAttribute displayAttribute = pageAction.GetCustomAttribute <DisplayAttribute>();

            if (displayAttribute != null)
            {
                if (displayAttribute.ResourceType != null)
                {
                    var rs = new ResourceManager(displayAttribute.ResourceType);
                    currentPage.Caption = rs.GetString(displayAttribute.Name);
                }
                else
                {
                    currentPage.Caption = displayAttribute.Name;
                }
            }

            //detect and apply the page metadata attribute
            PageMetadataAttribute pageMetadataAttribute = pageAction.GetCustomAttribute <PageMetadataAttribute>();

            if (pageMetadataAttribute != null)
            {
                if (pageMetadataAttribute.ResourceType != null)
                {
                    var rs = new ResourceManager(pageMetadataAttribute.ResourceType);

                    if (!String.IsNullOrEmpty(pageMetadataAttribute.Caption))
                    {
                        currentPage.Caption = rs.GetString(pageMetadataAttribute.Caption);
                    }

                    if (!String.IsNullOrEmpty(pageMetadataAttribute.Header))
                    {
                        currentPage.Header = rs.GetString(pageMetadataAttribute.Header);
                    }
                }
                else
                {
                    currentPage.Caption = pageMetadataAttribute.Caption;
                    currentPage.Header  = pageMetadataAttribute.Header;
                }

                currentPage.RenderHeader  = pageMetadataAttribute.RenderHeader;
                currentPage.RenderCaption = pageMetadataAttribute.RenderCaption;
            }

            //translate template variables from route data
            if (!String.IsNullOrEmpty(currentPage.Caption))
            {
                currentPage.Caption = TranslateParameters(currentPage.Caption);
            }

            if (!String.IsNullOrEmpty(currentPage.Header))
            {
                currentPage.Header = TranslateParameters(currentPage.Header);
            }

            var urlHelper = new UrlHelper(actionContextAccessor.ActionContext);

            //build url for the items in the page tree using the existing route values
            var routeValues = new Dictionary <string, object>();

            foreach (KeyValuePair <string, object> routeValue in actionContextAccessor.ActionContext.RouteData.Values)
            {
                //detecting a variable template with "{" should be enough
                if (currentPage.UrlTemplate.Contains("{" + routeValue.Key))
                {
                    routeValues.Add(routeValue.Key, routeValue.Value);
                }
            }

            currentPage.CurrentUrl = urlHelper.Action(new UrlActionContext()
            {
                Action     = currentPage.Action.Name,
                Controller = currentPage.Action.DeclaringType.Name.Replace("controller", "", StringComparison.InvariantCultureIgnoreCase),
                Values     = routeValues
            });
        }
Пример #12
0
        public static string GetDescription(this AbilityId prop)
        {
            DisplayAttribute description = prop.GetAttributeOfType <DisplayAttribute>();

            return(description?.Description ?? prop.ToString());
        }
Пример #13
0
        /*
         *   ViewBag.FleetTypeList = new List<SelectListItem>{
         *  new SelectListItem { Text="17 Truck", Value="1"},
         *  new SelectListItem { Text="20 Truck", Value="2"},
         *  new SelectListItem { Text="Something else", Value="0"}
         * };
         * and in the view
         *
         * @Html.DropDownListFor(m => m.FleetType, ViewBag.FleetTypeList as List<SelectListItem>
         *          , new { @class = "btn btn-primary btn-lg dropdown-toggle" })
         */

        public static MvcHtmlString DropDownListModel <TModel>(this HtmlHelper <IEnumerable <TModel> > helper, SelectList ListaValores = null, object htmlAttributes = null)
        {
            //a ideia aqui é dado um selectList / list montar a lista e retornar; caso contrário, procurar os atributos customizados
            //if (ListaValores != null)
            //{

            //}

            PropertyInfo[] Props = typeof(TModel).GetProperties(BindingFlags.Public | BindingFlags.Instance);


            //Get column headers
            bool isDisplayGridHeader       = false;
            bool isDisplayAttributeDefined = false;

            List <string> nomesPropriedades = new List <string>();

            StringBuilder tags = new StringBuilder();

            TagBuilder tagBuilder = new TagBuilder("select");

            tagBuilder.Attributes.Add("name", "pesquisaDropList");
            tagBuilder.Attributes.Add("id", "pesquisaDropListId");

            StringBuilder options = new StringBuilder();

            options.AppendLine("<option value='-1'> Selecione uma opção </option>");


            foreach (PropertyInfo prop in Props)
            {
                nomesPropriedades.Add(prop.Name);
                var displayName = "";

                isDisplayAttributeDefined = Attribute.IsDefined(prop, typeof(DisplayAttribute));

                if (isDisplayAttributeDefined)
                {
                    DisplayAttribute dna = (DisplayAttribute)Attribute.GetCustomAttribute(prop, typeof(DisplayAttribute));
                    if (dna != null)
                    {
                        displayName = dna.Description;
                    }
                }
                else
                {
                    displayName = prop.Name;
                }

                isDisplayGridHeader = Attribute.IsDefined(prop, typeof(DisplayGridHeader));

                if (isDisplayGridHeader)
                {
                    DisplayGridHeader dgh = (DisplayGridHeader)Attribute.GetCustomAttribute(prop, typeof(DisplayGridHeader));
                    if (dgh != null)
                    {
                        if (!string.IsNullOrEmpty(dgh.Descricao))
                        {
                            displayName = dgh.Descricao;
                        }

                        if (dgh.FiltroPesquisa)
                        {
                            string dynamicTypeJSfilter = "text";

                            if (prop.PropertyType == typeof(int))
                            {
                                dynamicTypeJSfilter = "number";
                            }
                            else if (prop.PropertyType == typeof(DateTime) || prop.PropertyType == typeof(DateTime?))
                            {
                                dynamicTypeJSfilter = "date";
                            }


                            string singleOption = "<option value = '" + dynamicTypeJSfilter + '|' + prop.Name + "'>" + displayName + "</option>";
                            options.AppendLine(singleOption);
                        }
                    }
                }
            }

            tagBuilder.InnerHtml = options.ToString();
            foreach (PropertyDescriptor prop in TypeDescriptor.GetProperties(htmlAttributes))
            {
                tagBuilder.MergeAttribute(prop.Name.Replace('_', '-'), prop.GetValue(htmlAttributes).ToString(), true);
            }

            return(MvcHtmlString.Create(tagBuilder.ToString()));
        }
Пример #14
0
        /// <summary>
        /// Display components that are tagged with the <see cref="DisplayAttribute"/>.
        /// </summary>
        /// <param name="context">Context of the view model.</param>
        /// <param name="viewModel">The current view model</param>
        /// <param name="component">The entity component to display</param>
        private void AutoDisplayComponent(ViewModelContext context, IViewModelNode viewModel, EntityComponent component)
        {
            var displayComp = DisplayAttribute.GetDisplay(component.GetType());

            if (displayComp == null)
            {
                return;
            }

            var componentViewModel = viewModel.GetChildrenByName("Component");

            if (componentViewModel == null)
            {
                return;
            }

            // Change the name of the component being displayed
            if (!string.IsNullOrEmpty(displayComp.Name))
            {
                var componentName = viewModel.GetChildrenByName("PropertyKeyName");
                if (componentName != null)
                {
                    componentName.Value = displayComp.Name;
                }
            }

            var propertyToDisplay = new List <Tuple <DisplayAttribute, ViewModelNode> >();
            var memberInfos       = new List <MemberInfo>();

            memberInfos.AddRange(component.GetType().GetProperties());
            memberInfos.AddRange(component.GetType().GetFields());

            // Process fields and properties
            foreach (var property in memberInfos)
            {
                var display = DisplayAttribute.GetDisplay(property);
                if (display == null)
                {
                    continue;
                }

                IViewModelContent modelContent = null;
                object            modelValue   = null;

                var propertyInfo = property as PropertyInfo;
                if (propertyInfo != null)
                {
                    if (typeof(ParameterCollection).IsAssignableFrom(propertyInfo.PropertyType))
                    {
                        modelValue = propertyInfo.GetValue(component, null);
                    }
                    else
                    {
                        modelContent = new PropertyInfoViewModelContent(new ParentNodeValueViewModelContent(), propertyInfo);
                    }
                }

                var fieldInfo = property as FieldInfo;
                if (fieldInfo != null)
                {
                    if (typeof(ParameterCollection).IsAssignableFrom(fieldInfo.FieldType))
                    {
                        modelValue = fieldInfo.GetValue(component);
                    }
                    else
                    {
                        modelContent = new FieldInfoViewModelContent(new ParentNodeValueViewModelContent(), fieldInfo);
                    }
                }

                var propertyViewModel = modelValue != null ? new ViewModelNode(display.Name ?? property.Name, modelValue) : new ViewModelNode(display.Name ?? property.Name, modelContent);
                propertyViewModel.GenerateChildren(context);
                propertyToDisplay.Add(new Tuple <DisplayAttribute, ViewModelNode>(display, propertyViewModel));
            }

            foreach (var item in propertyToDisplay.OrderBy((left) => left.Item1.Order))
            {
                componentViewModel.Children.Add(item.Item2);
            }
        }
Пример #15
0
        public static MvcHtmlString DisplayGridModel <TModel, TValue>(this HtmlHelper <IPagedList <TModel> > helper, TValue valores, string classTable = "", string classTr = "", string classTh = "", string classTd = "")
        {
            var url = new UrlHelper(helper.ViewContext.RequestContext);

            var controller = helper.ViewContext.RouteData.Values["controller"].ToString();


            var listaOrder = (List <string>)helper.ViewBag.Orders;



            //System.Reflection.MemberInfo info = typeof(TModel);
            //Get properties
            PropertyInfo[] Props = typeof(TModel).GetProperties(BindingFlags.Public | BindingFlags.Instance);

            //Get column headers
            bool isDisplayGridHeader       = false;
            bool isDisplayAttributeDefined = false;


            List <string> nomesPropriedades = new List <string>();

            StringBuilder tags = new StringBuilder();

            tags.Append("<table").Append(classTable.Length > 0 ? string.Format(" {0}\"{1}\"", "class=", classTable) : "").Append(">");
            tags.Append("<tr").Append(classTr.Length > 0 ? string.Format(" {0}\"{1}\"", "class=", classTr) : "").Append(">");

            foreach (PropertyInfo prop in Props)
            {
                var displayName = "";

                isDisplayAttributeDefined = Attribute.IsDefined(prop, typeof(DisplayAttribute));

                if (isDisplayAttributeDefined)
                {
                    DisplayAttribute dna = (DisplayAttribute)Attribute.GetCustomAttribute(prop, typeof(DisplayAttribute));
                    if (dna != null)
                    {
                        displayName = dna.Description;
                    }
                }
                else
                {
                    displayName = prop.Name;
                }

                isDisplayGridHeader = Attribute.IsDefined(prop, typeof(DisplayGridHeader));

                if (isDisplayGridHeader)
                {
                    DisplayGridHeader dgh = (DisplayGridHeader)Attribute.GetCustomAttribute(prop, typeof(DisplayGridHeader));
                    if (dgh != null)
                    {
                        if (dgh.VisivelGrid)
                        {
                            if (!string.IsNullOrEmpty(dgh.Descricao))
                            {
                                displayName = dgh.Descricao;
                            }

                            if (!dgh.OrdenaColuna)
                            {
                                tags.Append("<th").Append(classTh.Length > 0 ? string.Format(" {0}\"{1}\"", "class=", classTh) : "").Append(">").Append(displayName).Append("</th>");
                            }
                            else
                            {
                                var ordemColumn = "";
                                for (int i = 0; i < listaOrder.Count; i++)
                                {
                                    if (listaOrder[i].StartsWith(prop.Name))
                                    {
                                        ordemColumn = listaOrder[i];
                                        break;
                                    }
                                }

                                if (!string.IsNullOrEmpty(ordemColumn))
                                {
                                    var anchorBuilderEdit = new TagBuilder("a");
                                    //Importante toda lista deve ter um id!!!!
                                    anchorBuilderEdit.MergeAttribute("href", url.Action("Lista", controller, new { sortOrder = ordemColumn }));
                                    anchorBuilderEdit.SetInnerText(displayName);
                                    var linkOrder = anchorBuilderEdit.ToString(TagRenderMode.Normal);

                                    tags.Append("<th").Append(classTh.Length > 0 ? string.Format(" {0}\"{1}\"", "class=", classTh) : "").Append(">").Append(linkOrder).Append("</th>");
                                }
                                else
                                {
                                    tags.Append("<th").Append(classTh.Length > 0 ? string.Format(" {0}\"{1}\"", "class=", classTh) : "").Append(">").Append(displayName).Append("</th>");
                                }
                            }

                            nomesPropriedades.Add(prop.Name);
                        }
                    }
                }
            }

            tags.Append("<th></th>");


            //Montagem da grid
            dynamic lista = valores;



            foreach (var item in lista)
            {
                tags.Append("<tr").Append(classTr.Length > 0 ? string.Format(" {0}\"{1}\"", "class=", classTr) : "").Append(">");

                foreach (var column in nomesPropriedades)
                {
                    dynamic conteudo = item.GetType().GetProperty(column).GetValue(item, null);
                    if (conteudo != null)
                    {
                        tags.Append("<td").Append(classTd.Length > 0 ? string.Format(" {0}\"{1}\"", "class=", classTd) : "").Append(">").Append(conteudo).Append("</td>");
                    }
                    else
                    {
                        tags.Append("<td").Append(classTd.Length > 0 ? string.Format(" {0}\"{1}\"", "class=", classTd) : "").Append(">").Append("</td>");
                    }
                }

                var anchorBuilderEdit = new TagBuilder("a");
                //Importante toda lista deve ter um id!!!!
                anchorBuilderEdit.MergeAttribute("href", url.Action("UpInsert", controller, new { modeid = "UPD|" + item.id }));
                anchorBuilderEdit.SetInnerText("Editar");
                var linkEdit = anchorBuilderEdit.ToString(TagRenderMode.Normal);

                tags.Append("<td").Append(classTd.Length > 0 ? string.Format(" {0}\"{1}\"", "class=", classTd) : "").Append(">").Append(linkEdit).Append("</td>");

                var anchorBuilderDel = new TagBuilder("a");
                //Importante toda lista deve ter um id!!!!
                anchorBuilderDel.MergeAttribute("href", url.Action("UpInsert", controller, new { modeid = "DEL|" + item.id }));
                anchorBuilderDel.SetInnerText("Remover");
                var linkRemover = anchorBuilderDel.ToString(TagRenderMode.Normal);

                tags.Append("<td").Append(classTd.Length > 0 ? string.Format(" {0}\"{1}\"", "class=", classTd) : "").Append(">").Append(linkRemover).Append("</td>");

                tags.Append("</tr>");
            }

            tags.Append("</tr>");
            tags.Append("</table>");

            return(MvcHtmlString.Create(tags.ToString()));
        }
Пример #16
0
 private static string GetDisplayAttributeName(Type containerType, string propertyName, DisplayAttribute displayAttribute)
 {
     if (containerType != null)
     {
         if (String.IsNullOrEmpty(displayAttribute.Name))
         {
             // check to see that resource key exists.
             string resourceKey = GetResourceKey(containerType, propertyName);
             if (displayAttribute.ResourceType.PropertyExists(resourceKey))
             {
                 return(resourceKey);
             }
             else
             {
                 return(propertyName);
             }
         }
     }
     return(null);
 }
Пример #17
0
 protected override void OnInitialized()
 {
     base.OnInitialized();
     Display = typeof(TModel).GetType().GetCustomAttribute <DisplayAttribute>();
 }
 public void DisplayAttribute_GetShortName_Falls_Back_Onto_NonLocalized_Name() {
     DisplayAttribute attr = new DisplayAttribute { Name = "Name" };
     Assert.AreEqual("Name", attr.GetShortName(), "GetShortName should return the Name when ShortName is null");
 }
Пример #19
0
        public static string GetName(this WealthRating?prop)
        {
            DisplayAttribute description = prop.GetAttributeOfType <DisplayAttribute>();

            return(description?.Name ?? prop?.ToString() ?? "");
        }
 public void DisplayAttribute_GetGroupName_Does_Not_Fall_Back() {
     DisplayAttribute attr = new DisplayAttribute { ShortName = "ShortName", Name = "Name", Description = "Description", Prompt = "Prompt" };
     Assert.IsNull(attr.GetGroupName(), "GetGroupName should NOT fall back onto any other values");
 }
Пример #21
0
 public static bool CanSupplyDisplayName(this DisplayAttribute attribute)
 {
     return(attribute != null &&
            attribute.ResourceType != null &&
            !string.IsNullOrEmpty(attribute.Name));
 }
Пример #22
0
 private void SetMetaFromDisplayAttribute(DisplayAttribute displayAttribute)
 {
     PropertyDisplayName = displayAttribute.Name;
     PropertyDescription = displayAttribute.Description;
 }
Пример #23
0
 public Boolean HasAttribute(DisplayAttribute attr)
 {
     return((attr & attributes) == attr);
 }
Пример #24
0
        internal static bool TryValidateMethodCall(DomainOperationEntry operationEntry, ValidationContext validationContext, object[] parameters, List <ValidationResult> validationResults)
        {
            bool breakOnFirstError = validationResults == null;

            ValidationContext methodContext = CreateValidationContext(validationContext.ObjectInstance, validationContext);

            methodContext.MemberName = operationEntry.Name;

            DisplayAttribute display = (DisplayAttribute)operationEntry.Attributes[typeof(DisplayAttribute)];

            if (display != null)
            {
                methodContext.DisplayName = display.GetName();
            }

            string methodPath = string.Empty;

            if (operationEntry.Operation == DomainOperation.Custom)
            {
                methodPath = operationEntry.Name + ".";
            }

            IEnumerable <ValidationAttribute> validationAttributes = operationEntry.Attributes.OfType <ValidationAttribute>();
            bool success = Validator.TryValidateValue(validationContext.ObjectInstance, methodContext, validationResults, validationAttributes);

            if (!breakOnFirstError || success)
            {
                for (int paramIndex = 0; paramIndex < operationEntry.Parameters.Count; paramIndex++)
                {
                    DomainOperationParameter methodParameter = operationEntry.Parameters[paramIndex];
                    object value = (parameters.Length > paramIndex ? parameters[paramIndex] : null);

                    ValidationContext parameterContext = ValidationUtilities.CreateValidationContext(validationContext.ObjectInstance, validationContext);
                    parameterContext.MemberName = methodParameter.Name;

                    string paramName = methodParameter.Name;

                    AttributeCollection parameterAttributes = methodParameter.Attributes;
                    display = (DisplayAttribute)parameterAttributes[typeof(DisplayAttribute)];

                    if (display != null)
                    {
                        paramName = display.GetName();
                    }

                    parameterContext.DisplayName = paramName;

                    string parameterPath = string.Empty;
                    if (!string.IsNullOrEmpty(methodPath) && paramIndex > 0)
                    {
                        parameterPath = methodPath + methodParameter.Name;
                    }

                    IEnumerable <ValidationAttribute> parameterValidationAttributes = parameterAttributes.OfType <ValidationAttribute>();
                    bool parameterSuccess = ValidationUtilities.ValidateValue(value, parameterContext, validationResults, parameterValidationAttributes,
                                                                              ValidationUtilities.NormalizeMemberPath(parameterPath, methodParameter.ParameterType));

                    // Custom methods run deep validation as well as parameter validation.
                    // If parameter validation has already failed, stop further validation.
                    if (parameterSuccess && operationEntry.Operation == DomainOperation.Custom && value != null)
                    {
                        Type parameterType = methodParameter.ParameterType;

                        if (TypeUtility.IsComplexType(parameterType))
                        {
                            parameterSuccess = ValidationUtilities.ValidateObjectRecursive(value, parameterPath, parameterContext, validationResults);
                        }
                        else if (TypeUtility.IsComplexTypeCollection(parameterType))
                        {
                            parameterSuccess = ValidationUtilities.ValidateComplexCollection(value as IEnumerable, parameterPath, parameterContext, validationResults);
                        }
                    }

                    success &= parameterSuccess;

                    if (breakOnFirstError && !success)
                    {
                        break;
                    }
                }
            }

            return(success);
        }
 private static string GetSharedRendererDisplayName(ISharedRenderer sharedRenderer) => $"Shared: {DisplayAttribute.GetDisplayName(sharedRenderer.GetType())}";
        protected override ModelMetadata CreateMetadata(IEnumerable <Attribute> attributes, Type containerType, Func <object> modelAccessor, Type modelType, string propertyName)
        {
            List <Attribute>             attributeList          = new List <Attribute>(attributes);
            DisplayColumnAttribute       displayColumnAttribute = attributeList.OfType <DisplayColumnAttribute>().FirstOrDefault();
            DataAnnotationsModelMetadata result = new DataAnnotationsModelMetadata(this, containerType, modelAccessor, modelType, propertyName, displayColumnAttribute);

            // Do [HiddenInput] before [UIHint], so you can override the template hint
            HiddenInputAttribute hiddenInputAttribute = attributeList.OfType <HiddenInputAttribute>().FirstOrDefault();

            if (hiddenInputAttribute != null)
            {
                result.TemplateHint        = "HiddenInput";
                result.HideSurroundingHtml = !hiddenInputAttribute.DisplayValue;
            }

            // We prefer [UIHint("...", PresentationLayer = "MVC")] but will fall back to [UIHint("...")]
            IEnumerable <UIHintAttribute> uiHintAttributes = attributeList.OfType <UIHintAttribute>();
            UIHintAttribute uiHintAttribute = uiHintAttributes.FirstOrDefault(a => String.Equals(a.PresentationLayer, "MVC", StringComparison.OrdinalIgnoreCase))
                                              ?? uiHintAttributes.FirstOrDefault(a => String.IsNullOrEmpty(a.PresentationLayer));

            if (uiHintAttribute != null)
            {
                result.TemplateHint = uiHintAttribute.UIHint;
            }

            EditableAttribute editable = attributes.OfType <EditableAttribute>().FirstOrDefault();

            if (editable != null)
            {
                result.IsReadOnly = !editable.AllowEdit;
            }
            else
            {
                ReadOnlyAttribute readOnlyAttribute = attributeList.OfType <ReadOnlyAttribute>().FirstOrDefault();
                if (readOnlyAttribute != null)
                {
                    result.IsReadOnly = readOnlyAttribute.IsReadOnly;
                }
            }

            DataTypeAttribute      dataTypeAttribute      = attributeList.OfType <DataTypeAttribute>().FirstOrDefault();
            DisplayFormatAttribute displayFormatAttribute = attributeList.OfType <DisplayFormatAttribute>().FirstOrDefault();

            SetFromDataTypeAndDisplayAttributes(result, dataTypeAttribute, displayFormatAttribute);

            ScaffoldColumnAttribute scaffoldColumnAttribute = attributeList.OfType <ScaffoldColumnAttribute>().FirstOrDefault();

            if (scaffoldColumnAttribute != null)
            {
                result.ShowForDisplay = result.ShowForEdit = scaffoldColumnAttribute.Scaffold;
            }

            DisplayAttribute display = attributes.OfType <DisplayAttribute>().FirstOrDefault();
            string           name    = null;

            if (display != null)
            {
                result.Description      = display.GetDescription();
                result.ShortDisplayName = display.GetShortName();
                result.Watermark        = display.GetPrompt();
                result.Order            = display.GetOrder() ?? ModelMetadata.DefaultOrder;

                name = display.GetName();
            }

            if (name != null)
            {
                result.DisplayName = name;
            }
            else
            {
                DisplayNameAttribute displayNameAttribute = attributeList.OfType <DisplayNameAttribute>().FirstOrDefault();
                if (displayNameAttribute != null)
                {
                    result.DisplayName = displayNameAttribute.DisplayName;
                }
            }

            RequiredAttribute requiredAttribute = attributeList.OfType <RequiredAttribute>().FirstOrDefault();

            if (requiredAttribute != null)
            {
                result.IsRequired = true;
            }

            return(result);
        }
Пример #27
0
        /// <summary>
        /// 返回属性的数据规则和约束条件
        /// </summary>
        /// <param name="prop"></param>
        /// <returns></returns>
        CatalogExtAttribute GetAdvDataRule(PropertyInfo prop)
        {
            var attrs = prop.GetCustomAttributes(true);

            CatalogExtAttribute extAttr = attrs.FirstOrDefault(attr => attr is CatalogExtAttribute) as CatalogExtAttribute;

            if (extAttr == null)
            {
                extAttr = new CatalogExtAttribute();
                if (prop.Name == "Id")
                {
                    extAttr.Editable = false;
                    extAttr.DataType = ExtDataType.SingleLineText;
                }
                if (prop.PropertyType.IsValueType && !prop.PropertyType.IsNullableType())
                {
                    extAttr.AllowNull = false;
                }
            }

            if (extAttr.Name.IsEmpty())
            {
                extAttr.Name = prop.Name;
            }

            RequiredAttribute required = attrs.FirstOrDefault(attr => attr is RequiredAttribute) as RequiredAttribute;

            if (required != null)
            {
                extAttr.AllowNull = false;
            }

            StringLengthAttribute stringLen = attrs.FirstOrDefault(attr => attr is StringLengthAttribute) as StringLengthAttribute;

            if (stringLen != null)
            {
                extAttr.MaxLength = stringLen.MaximumLength;
                extAttr.MinLength = stringLen.MinimumLength;
            }

            DisplayColumnAttribute displayProp = attrs.FirstOrDefault(attr => attr is DisplayColumnAttribute) as DisplayColumnAttribute;

            if (displayProp != null)
            {
                extAttr.DisplayProperty = displayProp.DisplayColumn;
            }

            DisplayFormatAttribute displayFmt = attrs.FirstOrDefault(attr => attr is DisplayFormatAttribute) as DisplayFormatAttribute;

            if (displayFmt != null)
            {
                extAttr.DisplayFormat = displayFmt.DataFormatString;
            }

            RegularExpressionAttribute reg = attrs.FirstOrDefault(attr => attr is RegularExpressionAttribute) as RegularExpressionAttribute;

            if (reg != null)
            {
                extAttr.RegExpr = reg.Pattern;
            }

            RangeAttribute rng = attrs.FirstOrDefault(attr => attr is RangeAttribute) as RangeAttribute;

            if (rng != null)
            {
                extAttr.MinValue = rng.Minimum;
                extAttr.MaxValue = rng.Maximum;
            }

            DisplayAttribute dsp = attrs.FirstOrDefault(attr => attr is DisplayAttribute) as DisplayAttribute;

            if (dsp != null)
            {
                extAttr.Name = dsp.Name;
            }

            BrowsableAttribute brw = attrs.FirstOrDefault(attr => attr is BrowsableAttribute) as BrowsableAttribute;

            if (brw != null)
            {
                extAttr.Browsable = brw.Browsable;
            }
            if (extAttr.DataType == ExtDataType.Auto)
            {
                Type type = prop.PropertyType;
                if (type.IsNullableType())
                {
                    type = type.GetGenericArguments()[0];
                }
                if (type.IsEnum)
                {
                }
                else if (type == typeof(DateTime))
                {
                    extAttr.DataType = ExtDataType.Date;
                }
                else if (type == typeof(bool))
                {
                    extAttr.DataType = ExtDataType.Bool;
                }
                else if (type == typeof(decimal))
                {
                    extAttr.DataType = ExtDataType.Currency;
                }
                else if (type == typeof(float) || type == typeof(double))
                {
                    extAttr.DataType = ExtDataType.FloatNumber;
                }
                else if (type.IsValueType)
                {
                    extAttr.DataType = ExtDataType.SingleNumber;
                }
            }
            if (!extAttr.LinkedProperty.IsEmpty() && extAttr.DisplayProperty.IsEmpty())
            {
                extAttr.DisplayProperty = extAttr.Name;
            }

            if (extAttr.DisplayFormat == null)
            {
                switch (extAttr.DataType)
                {
                case ExtDataType.Date:
                    extAttr.DisplayFormat = "yyyy-MM-dd";
                    break;

                case ExtDataType.DateAndTime:
                    extAttr.DisplayFormat = "yyyy-MM-dd HH:mm:ss";
                    break;

                case ExtDataType.FloatNumber:
                    extAttr.DisplayFormat = "#0.00";
                    //extAttr.MaxValue = int.MaxValue;
                    break;

                case ExtDataType.SingleNumber:
                    extAttr.DisplayFormat = "#0";
                    //extAttr.MaxValue = int.MaxValue;
                    break;

                case ExtDataType.Currency:
                    char currChar = 100.ToString("C")[0];
                    extAttr.DisplayFormat = currChar + "#0.00";
                    //extAttr.MaxValue = int.MaxValue;
                    break;

                case ExtDataType.Percent:
                    extAttr.DisplayFormat = "p2";
                    //extAttr.MaxValue = 1;
                    break;

                case ExtDataType.Time:
                    extAttr.DisplayFormat = "H:mm";
                    break;
                }
            }
            if (extAttr.InputFormat == null)
            {
                extAttr.InputFormat = extAttr.DisplayFormat;
            }
            switch (extAttr.DataType)
            {
            case ExtDataType.FloatNumber:
            case ExtDataType.SingleNumber:
            case ExtDataType.Currency:
            case ExtDataType.Percent:
                if (extAttr.MaxValue == null && extAttr.MinValue == null)
                {
                    extAttr.MinValue = 0;
                    extAttr.MaxValue = int.MaxValue;
                }
                break;
            }
            extAttr.Property = prop;
            return(extAttr);
        }
Пример #28
0
        private void DiscoverRecordFields(Type recordType, string declaringMember, bool optIn = false)
        {
            if (!recordType.IsDynamicType())
            {
                Type pt         = null;
                int  startIndex = 0;
                int  size       = 0;

                if (optIn) //ChoTypeDescriptor.GetProperties(recordType).Where(pd => pd.Attributes.OfType<ChoFixedLengthRecordFieldAttribute>().Any()).Any())
                {
                    foreach (PropertyDescriptor pd in ChoTypeDescriptor.GetProperties(recordType))
                    {
                        pt = pd.PropertyType.GetUnderlyingType();
                        if (!pt.IsSimple() && !typeof(IEnumerable).IsAssignableFrom(pt))
                        {
                            DiscoverRecordFields(pt, declaringMember == null ? pd.Name : "{0}.{1}".FormatString(declaringMember, pd.Name), optIn);
                        }
                        else if (pd.Attributes.OfType <ChoFixedLengthRecordFieldAttribute>().Any())
                        {
                            var obj = new ChoFixedLengthRecordFieldConfiguration(pd.Name, pd.Attributes.OfType <ChoFixedLengthRecordFieldAttribute>().First(), pd.Attributes.OfType <Attribute>().ToArray());
                            obj.FieldType          = pt;
                            obj.PropertyDescriptor = pd;
                            obj.DeclaringMember    = declaringMember == null ? null : "{0}.{1}".FormatString(declaringMember, pd.Name);
                            if (!FixedLengthRecordFieldConfigurations.Any(c => c.Name == pd.Name))
                            {
                                FixedLengthRecordFieldConfigurations.Add(obj);
                            }
                        }
                    }
                }
                else
                {
                    foreach (PropertyDescriptor pd in ChoTypeDescriptor.GetProperties(recordType))
                    {
                        pt = pd.PropertyType.GetUnderlyingType();
                        if (pt != typeof(object) && !pt.IsSimple() && !typeof(IEnumerable).IsAssignableFrom(pt))
                        {
                            DiscoverRecordFields(pt, declaringMember == null ? pd.Name : "{0}.{1}".FormatString(declaringMember, pd.Name), optIn);
                        }
                        else
                        {
                            if (FixedLengthFieldDefaultSizeConfiguation == null)
                            {
                                size = ChoFixedLengthFieldDefaultSizeConfiguation.Instance.GetSize(pd.PropertyType);
                            }
                            else
                            {
                                size = FixedLengthFieldDefaultSizeConfiguation.GetSize(pd.PropertyType);
                            }

                            var obj = new ChoFixedLengthRecordFieldConfiguration(pd.Name, startIndex, size);
                            obj.FieldType          = pt;
                            obj.PropertyDescriptor = pd;
                            obj.DeclaringMember    = declaringMember == null ? null : "{0}.{1}".FormatString(declaringMember, pd.Name);
                            StringLengthAttribute slAttr = pd.Attributes.OfType <StringLengthAttribute>().FirstOrDefault();
                            if (slAttr != null && slAttr.MaximumLength > 0)
                            {
                                obj.Size = slAttr.MaximumLength;
                            }
                            DisplayAttribute dpAttr = pd.Attributes.OfType <DisplayAttribute>().FirstOrDefault();
                            if (dpAttr != null)
                            {
                                if (!dpAttr.ShortName.IsNullOrWhiteSpace())
                                {
                                    obj.FieldName = dpAttr.ShortName;
                                }
                                else if (!dpAttr.Name.IsNullOrWhiteSpace())
                                {
                                    obj.FieldName = dpAttr.Name;
                                }
                            }
                            DisplayFormatAttribute dfAttr = pd.Attributes.OfType <DisplayFormatAttribute>().FirstOrDefault();
                            if (dfAttr != null && !dfAttr.DataFormatString.IsNullOrWhiteSpace())
                            {
                                obj.FormatText = dfAttr.DataFormatString;
                            }
                            if (dfAttr != null && !dfAttr.NullDisplayText.IsNullOrWhiteSpace())
                            {
                                obj.NullValue = dfAttr.NullDisplayText;
                            }
                            if (!FixedLengthRecordFieldConfigurations.Any(c => c.Name == pd.Name))
                            {
                                FixedLengthRecordFieldConfigurations.Add(obj);
                            }

                            startIndex += size;
                        }
                    }
                }
            }
        }
Пример #29
0
 private void DiscoverRecordFields(Type recordType, string declaringMember, bool optIn = false)
 {
     if (!recordType.IsDynamicType())
     {
         Type pt = null;
         if (ChoTypeDescriptor.GetProperties(recordType).Where(pd => pd.Attributes.OfType <ChoJSONRecordFieldAttribute>().Any()).Any())
         {
             foreach (PropertyDescriptor pd in ChoTypeDescriptor.GetProperties(recordType))
             {
                 pt = pd.PropertyType.GetUnderlyingType();
                 bool optIn1 = ChoTypeDescriptor.GetProperties(pt).Where(pd1 => pd1.Attributes.OfType <ChoJSONRecordFieldAttribute>().Any()).Any();
                 if (optIn1 && !pt.IsSimple() && !typeof(IEnumerable).IsAssignableFrom(pt) && FlatToNestedObjectSupport)
                 {
                     DiscoverRecordFields(pt, declaringMember == null ? pd.Name : "{0}.{1}".FormatString(declaringMember, pd.Name), optIn1);
                 }
                 else if (pd.Attributes.OfType <ChoJSONRecordFieldAttribute>().Any())
                 {
                     var obj = new ChoJSONRecordFieldConfiguration(pd.Name, pd.Attributes.OfType <ChoJSONRecordFieldAttribute>().First(), pd.Attributes.OfType <Attribute>().ToArray());
                     obj.FieldType          = pt;
                     obj.PropertyDescriptor = pd;
                     obj.DeclaringMember    = declaringMember == null ? null : "{0}.{1}".FormatString(declaringMember, pd.Name);
                     if (!JSONRecordFieldConfigurations.Any(c => c.Name == pd.Name))
                     {
                         JSONRecordFieldConfigurations.Add(obj);
                     }
                 }
             }
         }
         else
         {
             foreach (PropertyDescriptor pd in ChoTypeDescriptor.GetProperties(recordType))
             {
                 pt = pd.PropertyType.GetUnderlyingType();
                 if (pt != typeof(object) && !pt.IsSimple() && !typeof(IEnumerable).IsAssignableFrom(pt) && FlatToNestedObjectSupport)
                 {
                     DiscoverRecordFields(pt, declaringMember == null ? pd.Name : "{0}.{1}".FormatString(declaringMember, pd.Name), optIn);
                 }
                 else
                 {
                     var obj = new ChoJSONRecordFieldConfiguration(pd.Name, (string)null);
                     obj.FieldType          = pt;
                     obj.PropertyDescriptor = pd;
                     obj.DeclaringMember    = declaringMember == null ? null : "{0}.{1}".FormatString(declaringMember, pd.Name);
                     StringLengthAttribute slAttr = pd.Attributes.OfType <StringLengthAttribute>().FirstOrDefault();
                     if (slAttr != null && slAttr.MaximumLength > 0)
                     {
                         obj.Size = slAttr.MaximumLength;
                     }
                     ChoUseJSONSerializationAttribute sAttr = pd.Attributes.OfType <ChoUseJSONSerializationAttribute>().FirstOrDefault();
                     if (sAttr != null)
                     {
                         obj.UseJSONSerialization = true;
                     }
                     DisplayAttribute dpAttr = pd.Attributes.OfType <DisplayAttribute>().FirstOrDefault();
                     if (dpAttr != null)
                     {
                         if (!dpAttr.ShortName.IsNullOrWhiteSpace())
                         {
                             obj.FieldName = dpAttr.ShortName;
                         }
                         else if (!dpAttr.Name.IsNullOrWhiteSpace())
                         {
                             obj.FieldName = dpAttr.Name;
                         }
                     }
                     DisplayFormatAttribute dfAttr = pd.Attributes.OfType <DisplayFormatAttribute>().FirstOrDefault();
                     if (dfAttr != null && !dfAttr.DataFormatString.IsNullOrWhiteSpace())
                     {
                         obj.FormatText = dfAttr.DataFormatString;
                     }
                     if (dfAttr != null && !dfAttr.NullDisplayText.IsNullOrWhiteSpace())
                     {
                         obj.NullValue = dfAttr.NullDisplayText;
                     }
                     if (!JSONRecordFieldConfigurations.Any(c => c.Name == pd.Name))
                     {
                         JSONRecordFieldConfigurations.Add(obj);
                     }
                 }
             }
         }
     }
 }
        public void DisplayAttribute_Fail_No_Getter_Resource() {
            DisplayAttribute attr = new DisplayAttribute();
            attr.ResourceType = typeof(DisplayAttribute_Resources);
            attr.ShortName = "NoGetter";
            attr.Name = "NoGetter";
            attr.Prompt = "NoGetter";
            attr.Description = "NoGetter";
            attr.GroupName = "NoGetter";

            string shortNameError = String.Format(CultureInfo.CurrentCulture, Resources.DataAnnotationsResources.LocalizableString_LocalizationFailed, "ShortName", attr.ResourceType.FullName, attr.ShortName);
            string nameError = String.Format(CultureInfo.CurrentCulture, Resources.DataAnnotationsResources.LocalizableString_LocalizationFailed, "Name", attr.ResourceType.FullName, attr.Name);
            string promptError = String.Format(CultureInfo.CurrentCulture, Resources.DataAnnotationsResources.LocalizableString_LocalizationFailed, "Prompt", attr.ResourceType.FullName, attr.Prompt);
            string descriptionError = String.Format(CultureInfo.CurrentCulture, Resources.DataAnnotationsResources.LocalizableString_LocalizationFailed, "Description", attr.ResourceType.FullName, attr.Description);
            string groupNameError = String.Format(CultureInfo.CurrentCulture, Resources.DataAnnotationsResources.LocalizableString_LocalizationFailed, "GroupName", attr.ResourceType.FullName, attr.GroupName);

            ExceptionHelper.ExpectException<InvalidOperationException>(() => { string s = attr.GetShortName(); }, shortNameError);
            ExceptionHelper.ExpectException<InvalidOperationException>(() => { string s = attr.GetName(); }, nameError);
            ExceptionHelper.ExpectException<InvalidOperationException>(() => { string s = attr.GetPrompt(); }, promptError);
            ExceptionHelper.ExpectException<InvalidOperationException>(() => { string s = attr.GetDescription(); }, descriptionError);
            ExceptionHelper.ExpectException<InvalidOperationException>(() => { string s = attr.GetGroupName(); }, groupNameError);
        }
Пример #31
0
        private Type DiscoverRecordFields(Type recordType, string declaringMember, bool optIn = false,
                                          List <ChoYamlRecordFieldConfiguration> recordFieldConfigurations = null, bool isTop = false)
        {
            if (recordType == null)
            {
                return(recordType);
            }
            if (!recordType.IsDynamicType())
            {
                Type pt = null;
                if (ChoTypeDescriptor.GetProperties(recordType).Where(pd => pd.Attributes.OfType <ChoYamlRecordFieldAttribute>().Any()).Any())
                {
                    foreach (PropertyDescriptor pd in ChoTypeDescriptor.GetProperties(recordType))
                    {
                        pt = pd.PropertyType.GetUnderlyingType();
                        bool optIn1 = ChoTypeDescriptor.GetProperties(pt).Where(pd1 => pd1.Attributes.OfType <ChoYamlRecordFieldAttribute>().Any()).Any();
                        if (optIn1 && !pt.IsSimple() && !typeof(IEnumerable).IsAssignableFrom(pt) && FlatToNestedObjectSupport)
                        {
                            DiscoverRecordFields(pt, declaringMember == null ? pd.Name : "{0}.{1}".FormatString(declaringMember, pd.Name), optIn1, recordFieldConfigurations, false);
                        }
                        else if (pd.Attributes.OfType <ChoYamlRecordFieldAttribute>().Any())
                        {
                            var obj = new ChoYamlRecordFieldConfiguration(pd.Name, pd.Attributes.OfType <ChoYamlRecordFieldAttribute>().First(), pd.Attributes.OfType <Attribute>().ToArray());
                            obj.FieldType          = pt;
                            obj.PropertyDescriptor = pd;
                            obj.DeclaringMember    = declaringMember == null ? pd.Name : "{0}.{1}".FormatString(declaringMember, pd.Name);
                            if (recordFieldConfigurations != null)
                            {
                                if (!recordFieldConfigurations.Any(c => c.Name == pd.Name))
                                {
                                    recordFieldConfigurations.Add(obj);
                                }
                            }
                        }
                    }
                }
                else
                {
                    if (isTop)
                    {
                        if (typeof(IList).IsAssignableFrom(recordType))
                        {
                            throw new ChoParserException("Record type not supported.");
                        }
                        else if (typeof(IDictionary <string, object>).IsAssignableFrom(recordType))
                        {
                            recordType = typeof(ExpandoObject);
                            return(recordType);
                        }
                        else if (typeof(IDictionary).IsAssignableFrom(recordType))
                        {
                            recordType = typeof(ExpandoObject);
                            return(recordType);
                        }
                    }

                    if (recordType.IsSimple())
                    {
                        var obj = new ChoYamlRecordFieldConfiguration("Value", "$.Value");
                        obj.FieldType = recordType;

                        recordFieldConfigurations.Add(obj);
                        return(recordType);
                    }

                    foreach (PropertyDescriptor pd in ChoTypeDescriptor.GetProperties(recordType))
                    {
                        ChoYamlIgnoreAttribute jiAttr = pd.Attributes.OfType <ChoYamlIgnoreAttribute>().FirstOrDefault();
                        if (jiAttr != null)
                        {
                            continue;
                        }

                        pt = pd.PropertyType.GetUnderlyingType();
                        if (pt != typeof(object) && !pt.IsSimple() && !typeof(IEnumerable).IsAssignableFrom(pt) && FlatToNestedObjectSupport)
                        {
                            DiscoverRecordFields(pt, declaringMember == null ? pd.Name : "{0}.{1}".FormatString(declaringMember, pd.Name), optIn, recordFieldConfigurations, false);
                        }
                        else
                        {
                            var obj = new ChoYamlRecordFieldConfiguration(pd.Name, (string)null);
                            obj.FieldType          = pt;
                            obj.PropertyDescriptor = pd;
                            obj.DeclaringMember    = declaringMember == null ? pd.Name : "{0}.{1}".FormatString(declaringMember, pd.Name);
                            StringLengthAttribute slAttr = pd.Attributes.OfType <StringLengthAttribute>().FirstOrDefault();
                            if (slAttr != null && slAttr.MaximumLength > 0)
                            {
                                obj.Size = slAttr.MaximumLength;
                            }
                            //ChoUseYamlSerializationAttribute sAttr = pd.Attributes.OfType<ChoUseYamlSerializationAttribute>().FirstOrDefault();
                            //if (sAttr != null)
                            //    obj.UseYamlSerialization = sAttr.Flag;
                            ChoYamlPathAttribute jpAttr = pd.Attributes.OfType <ChoYamlPathAttribute>().FirstOrDefault();
                            if (jpAttr != null)
                            {
                                obj.YamlPath = jpAttr.YamlPath;
                            }

                            ChoYamPropertyAttribute jAttr = pd.Attributes.OfType <ChoYamPropertyAttribute>().FirstOrDefault();
                            if (jAttr != null && !jAttr.PropertyName.IsNullOrWhiteSpace())
                            {
                                obj.FieldName = jAttr.PropertyName;
                            }
                            else
                            {
                                DisplayNameAttribute dnAttr = pd.Attributes.OfType <DisplayNameAttribute>().FirstOrDefault();
                                if (dnAttr != null && !dnAttr.DisplayName.IsNullOrWhiteSpace())
                                {
                                    obj.FieldName = dnAttr.DisplayName.Trim();
                                }
                                else
                                {
                                    DisplayAttribute dpAttr = pd.Attributes.OfType <DisplayAttribute>().FirstOrDefault();
                                    if (dpAttr != null)
                                    {
                                        if (!dpAttr.ShortName.IsNullOrWhiteSpace())
                                        {
                                            obj.FieldName = dpAttr.ShortName;
                                        }
                                        else if (!dpAttr.Name.IsNullOrWhiteSpace())
                                        {
                                            obj.FieldName = dpAttr.Name;
                                        }

                                        obj.Order = dpAttr.Order;
                                    }
                                    else
                                    {
                                        ColumnAttribute clAttr = pd.Attributes.OfType <ColumnAttribute>().FirstOrDefault();
                                        if (clAttr != null)
                                        {
                                            obj.Order = clAttr.Order;
                                            if (!clAttr.Name.IsNullOrWhiteSpace())
                                            {
                                                obj.FieldName = clAttr.Name;
                                            }
                                        }
                                    }
                                }
                            }
                            DisplayFormatAttribute dfAttr = pd.Attributes.OfType <DisplayFormatAttribute>().FirstOrDefault();
                            if (dfAttr != null && !dfAttr.DataFormatString.IsNullOrWhiteSpace())
                            {
                                obj.FormatText = dfAttr.DataFormatString;
                            }
                            if (dfAttr != null && !dfAttr.NullDisplayText.IsNullOrWhiteSpace())
                            {
                                obj.NullValue = dfAttr.NullDisplayText;
                            }

                            if (recordFieldConfigurations != null)
                            {
                                if (!recordFieldConfigurations.Any(c => c.Name == pd.Name))
                                {
                                    recordFieldConfigurations.Add(obj);
                                }
                            }
                        }
                    }
                }
            }
            return(recordType);
        }
        public void DisplayAttribute_Order_Accepts_Negative_Values() {
            DisplayAttribute attr = new DisplayAttribute();

            attr.Order = Int32.MinValue;
            Assert.AreEqual(Int32.MinValue, attr.GetOrder());

            attr.Order = -1;
            Assert.AreEqual(-1, attr.GetOrder());

            attr.Order = 0;
            Assert.AreEqual(0, attr.GetOrder());

            attr.Order = 1;
            Assert.AreEqual(1, attr.GetOrder());

            attr.Order = Int32.MaxValue;
            Assert.AreEqual(Int32.MaxValue, attr.GetOrder());
        }
Пример #33
0
        public static List <Property> GetProperties(Type type)
        {
            List <Property> properties = new List <Property>();

            List <PropertyInfo> _properties = type.GetProperties().ToList();

            for (var i = 0; i < _properties.Count(); i++)
            {
                DisplayAttribute _display = (DisplayAttribute)_properties.ElementAt(i).GetCustomAttributes(typeof(DisplayAttribute), true).FirstOrDefault();

                if (_display != null)
                {
                    Property property = new Property()
                    {
                        Description        = _display.Description,
                        Name               = _display.Name,
                        AutoGenerateField  = _display.AutoGenerateField,
                        Order              = _display.Order,
                        Minimum            = 0,
                        Maximum            = Int64.MaxValue,
                        Required           = false,
                        Type_Description   = "",
                        AutoGenerateFilter = _display.AutoGenerateFilter
                    };

                    property.Name = property.Name[0].ToString().ToLower() + property.Name.Substring(1);
                    RequiredAttribute required = (RequiredAttribute)_properties.ElementAt(i).GetCustomAttributes(typeof(RequiredAttribute), true).FirstOrDefault();

                    if (required != null)
                    {
                        property.Required = true;
                    }
                    else
                    {
                        property.Required = false;
                    }

                    StringLengthAttribute stringLength = (StringLengthAttribute)_properties.ElementAt(i).GetCustomAttributes(typeof(StringLengthAttribute), true).FirstOrDefault();

                    if (stringLength != null)
                    {
                        property.Minimum = stringLength.MinimumLength;
                        property.Maximum = stringLength.MaximumLength;
                    }

                    switch (Type.GetTypeCode(_properties.ElementAt(i).PropertyType))
                    {
                    case TypeCode.String:
                        property.Type_Description = "string";
                        break;

                    case TypeCode.Int16:
                    case TypeCode.Int32:
                    case TypeCode.Int64:
                    case TypeCode.UInt16:
                    case TypeCode.UInt32:
                    case TypeCode.UInt64:
                        property.Type_Description = "int";
                        break;

                    case TypeCode.Boolean:
                        property.Type_Description = "boolean";
                        break;

                    case TypeCode.Char:
                        property.Type_Description = "char";
                        break;

                    case TypeCode.DateTime:
                        property.Type_Description = "datetime";
                        break;

                    case TypeCode.Decimal:
                    case TypeCode.Double:
                    case TypeCode.Single:
                        property.Type_Description = "decimal";
                        break;

                    case TypeCode.Object:

                        List <Type> int_types = new List <Type>();
                        int_types.Add(typeof(Nullable <Int16>));
                        int_types.Add(typeof(Nullable <Int32>));
                        int_types.Add(typeof(Nullable <Int64>));
                        int_types.Add(typeof(Nullable <UInt16>));
                        int_types.Add(typeof(Nullable <UInt32>));
                        int_types.Add(typeof(Nullable <UInt64>));

                        List <Type> decimal_types = new List <Type>();
                        decimal_types.Add(typeof(Nullable <Decimal>));
                        decimal_types.Add(typeof(Nullable <Double>));
                        decimal_types.Add(typeof(Nullable <Single>));

                        if (int_types.Contains(_properties.ElementAt(i).PropertyType))
                        {
                            property.Type_Description = "int";
                        }

                        if (decimal_types.Contains(_properties.ElementAt(i).PropertyType))
                        {
                            property.Type_Description = "decimal";
                        }

                        if (_properties.ElementAt(i).PropertyType == typeof(Nullable <DateTime>))
                        {
                            property.Type_Description = "datetime";
                        }


                        if (property.Type_Description.Length == 0)
                        {
                            property.Type_Description = _properties.ElementAt(i).PropertyType.ToString();
                        }

                        break;
                    }

                    ReadOnlyAttribute isreadonly = (ReadOnlyAttribute)_properties.ElementAt(i).GetCustomAttributes(typeof(ReadOnlyAttribute), true).FirstOrDefault();

                    if (isreadonly != null)
                    {
                        property.ReadOnly = isreadonly.IsReadOnly;
                    }
                    else
                    {
                        property.ReadOnly = false;
                    }
                    properties.Add(property);
                }
            }

            return(properties.OrderBy(e => e.Order).ToList());
        }
        public void DisplayAttribute_AutoGenerateFilter_Can_Be_Set_And_Retrieved() {
            DisplayAttribute attr = new DisplayAttribute { AutoGenerateFilter = true };
            Assert.IsTrue(attr.AutoGenerateFilter, "AutoGenerateFilter should be true after setting it to true");
            Assert.IsTrue(attr.GetAutoGenerateFilter().Value, "GetAutoGenerateFilter should be true after setting it to true");

            attr = new DisplayAttribute { AutoGenerateFilter = false };
            Assert.IsFalse(attr.AutoGenerateFilter, "AutoGenerateFilter should be false after setting it to false");
            Assert.IsFalse(attr.GetAutoGenerateFilter().Value, "GetAutoGenerateFilter should be false after setting it to false");
        }
Пример #35
0
        public void ResourceType_Get_Set(Type value)
        {
            DisplayAttribute attribute = new DisplayAttribute();
            attribute.ResourceType = value;
            Assert.Equal(value, attribute.ResourceType);

            // Set again, to cover the setter avoiding operations if the value is the same
            attribute.ResourceType = value;
            Assert.Equal(value, attribute.ResourceType);
        }
 public void DisplayAttribute_GetShortName_Falls_Back_Onto_Localized_Name() {
     DisplayAttribute attr = new DisplayAttribute { ResourceType = typeof(DisplayAttribute_Resources), Name = "Resource1" };
     Assert.AreEqual(DisplayAttribute_Resources.Resource1, attr.GetShortName(), "GetShortName should return the localized Name when ShortName is null");
 }
Пример #37
0
        public void Order_Get_Set(int value)
        {
            DisplayAttribute attribute = new DisplayAttribute();

            attribute.Order = value;
            Assert.Equal(value, attribute.Order);
            Assert.Equal(value, attribute.GetOrder());
        }
 SortableColumn CreateColumnHeader(System.Reflection.PropertyInfo propertyInfo, DisplayAttribute attr)
 {
     return(CreateColumnHeader(propertyInfo.Name, attr.Name, 0.15, true, new ColumnCellText(null, true)));
 }
Пример #39
0
 public void Order_Get_NotSet_ThrowsInvalidOperationException()
 {
     DisplayAttribute attribute = new DisplayAttribute();
     Assert.Throws<InvalidOperationException>(() => attribute.Order);
     Assert.Null(attribute.GetOrder());
 }
Пример #40
0
 protected override void OnInitialized()
 {
     display = Prop.GetCustomAttribute <DisplayAttribute>();
 }
Пример #41
0
        public List <DataAnnotationsDetails> GetDataAnnotationsDetailsList(string className)
        {
            object currentClassInstance = CreateClassByName(className);

            PropertyDescriptorCollection  properties       = TypeDescriptor.GetProperties(currentClassInstance, true);
            List <DataAnnotationsDetails> listFieldDetails = new List <DataAnnotationsDetails>();

            foreach (PropertyDescriptor property in properties)
            {
                AttributeCollection attributes = property.Attributes;

                RequiredAttribute      requiredAttribute = (RequiredAttribute)attributes[typeof(RequiredAttribute)];
                DisplayAttribute       displayAttribute = (DisplayAttribute)attributes[typeof(DisplayAttribute)];
                DisplayFormatAttribute displayFormatAttribute = (DisplayFormatAttribute)attributes[typeof(DisplayFormatAttribute)];
                string displayName = "", shortName = "", prompt = "", description = "", groupName = "", dataFormatString = "", nullDisplayText = "", attributeList = "";
                displayName = property.DisplayName;

                if (displayAttribute != null)
                {
                    // DisplayName and Description both have single purpose attributes
                    displayName = displayAttribute.Name ?? displayName;
                    description = displayAttribute.Description ?? description;
                    shortName   = displayAttribute.ShortName ?? "";
                    prompt      = displayAttribute.Prompt ?? "";
                    groupName   = displayAttribute.GroupName ?? "";
                }

                if (displayFormatAttribute != null)
                {
                    dataFormatString = displayFormatAttribute.DataFormatString ?? "";
                    nullDisplayText  = displayFormatAttribute.NullDisplayText ?? "";
                }
                foreach (Attribute attr in property.Attributes)
                {
                    attributeList += attr.GetType().Name + ",";
                }

                DataAnnotationsDetails dad = new DataAnnotationsDetails
                {
                    Name                    = property.Name,
                    DisplayName             = displayName,
                    ShortName               = shortName,
                    Prompt                  = prompt,
                    GroupName               = groupName,
                    Description             = description,
                    Category                = property.Category,
                    DataFormatString        = dataFormatString,
                    NullDisplayText         = nullDisplayText,
                    Required                = (requiredAttribute != null),
                    Attributes              = attributeList.TrimEnd(','),
                    Browsable               = property.IsBrowsable,
                    PropertyType            = property.PropertyType.Name,
                    SerializationVisibility = property.SerializationVisibility.ToString()
                };
                if (requiredAttribute != null)
                {
                    dad.ErrorMessage = requiredAttribute.ErrorMessage;
                }
                listFieldDetails.Add(dad);
            }
            return(listFieldDetails);
        }
Пример #42
0
        public void AutoGenerateFilter_Get_Set(bool value)
        {
            DisplayAttribute attribute = new DisplayAttribute();

            attribute.AutoGenerateFilter = value;
            Assert.Equal(value, attribute.AutoGenerateFilter);
            Assert.Equal(value, attribute.GetAutoGenerateFilter());
        }
Пример #43
0
        public void TestGetAttribute()
        {
            DisplayAttribute attribute = Lambda.GetAttribute <Sample, string, DisplayAttribute>(t => t.StringValue);

            Assert.Equal("字符串值", attribute.Name);
        }
Пример #44
0
 public void AutoGenerateField_Get_NotSet_ThrowsInvalidOperationException()
 {
     DisplayAttribute attribute = new DisplayAttribute();
     Assert.Throws<InvalidOperationException>(() => attribute.AutoGenerateField);
     Assert.Null(attribute.GetAutoGenerateField());
 }
Пример #45
0
        internal ChoJSONRecordFieldConfiguration(string name, ChoJSONRecordFieldAttribute attr = null, Attribute[] otherAttrs = null) : base(name, attr, otherAttrs)
        {
            //IsArray = false;
            FieldName = name;
            if (attr != null)
            {
                Order                = attr.Order;
                JSONPath             = attr.JSONPath;
                UseJSONSerialization = attr.UseJSONSerializationInternal;
                FieldName            = attr.FieldName.IsNullOrWhiteSpace() ? Name.NTrim() : attr.FieldName.NTrim();
            }
            if (otherAttrs != null)
            {
                var sa = otherAttrs.OfType <ChoSourceTypeAttribute>().FirstOrDefault();
                if (sa != null)
                {
                    SourceType = sa.Type;
                }

                StringLengthAttribute slAttr = otherAttrs.OfType <StringLengthAttribute>().FirstOrDefault();
                if (slAttr != null && slAttr.MaximumLength > 0)
                {
                    Size = slAttr.MaximumLength;
                }
                ChoUseJSONSerializationAttribute sAttr = otherAttrs.OfType <ChoUseJSONSerializationAttribute>().FirstOrDefault();
                if (sAttr != null)
                {
                    UseJSONSerialization = sAttr.Flag;
                }
                ChoJSONPathAttribute jpAttr = otherAttrs.OfType <ChoJSONPathAttribute>().FirstOrDefault();
                if (jpAttr != null)
                {
                    JSONPath = jpAttr.JSONPath;
                }

                JsonPropertyAttribute jAttr = otherAttrs.OfType <JsonPropertyAttribute>().FirstOrDefault();
                if (jAttr != null && !jAttr.PropertyName.IsNullOrWhiteSpace())
                {
                    FieldName = jAttr.PropertyName;
                    JSONPath  = jAttr.PropertyName;
                    Order     = jAttr.Order;
                }
                else
                {
                    DisplayNameAttribute dnAttr = otherAttrs.OfType <DisplayNameAttribute>().FirstOrDefault();
                    if (dnAttr != null && !dnAttr.DisplayName.IsNullOrWhiteSpace())
                    {
                        FieldName = dnAttr.DisplayName.Trim();
                    }
                    else
                    {
                        DisplayAttribute dpAttr = otherAttrs.OfType <DisplayAttribute>().FirstOrDefault();
                        if (dpAttr != null)
                        {
                            if (!dpAttr.ShortName.IsNullOrWhiteSpace())
                            {
                                FieldName = dpAttr.ShortName;
                            }
                            else if (!dpAttr.Name.IsNullOrWhiteSpace())
                            {
                                FieldName = dpAttr.Name;
                            }

                            Order = dpAttr.Order;
                        }
                        else
                        {
                            ColumnAttribute clAttr = otherAttrs.OfType <ColumnAttribute>().FirstOrDefault();
                            if (clAttr != null)
                            {
                                Order = clAttr.Order;
                                if (!clAttr.Name.IsNullOrWhiteSpace())
                                {
                                    FieldName = clAttr.Name;
                                }
                            }
                        }
                    }
                }
                DisplayFormatAttribute dfAttr = otherAttrs.OfType <DisplayFormatAttribute>().FirstOrDefault();
                if (dfAttr != null && !dfAttr.DataFormatString.IsNullOrWhiteSpace())
                {
                    FormatText = dfAttr.DataFormatString;
                }
                if (dfAttr != null && !dfAttr.NullDisplayText.IsNullOrWhiteSpace())
                {
                    NullValue = dfAttr.NullDisplayText;
                }
            }
        }
Пример #46
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.Where(i => i.GetType() == typeof(DescriptionAttribute)).FirstOrDefault();
                            vd.Add(v, desc.Description);
                        }
                        else if (attrs.Any(i => i.GetType() == typeof(DisplayNameAttribute)))
                        {
                            DisplayNameAttribute desc = (DisplayNameAttribute)attrs.Where(i => i.GetType() == typeof(DisplayNameAttribute)).FirstOrDefault();
                            vd.Add(v, desc.DisplayName);
                        }
                        else if (attrs.Any(i => i.GetType() == typeof(DisplayAttribute)))
                        {
                            DisplayAttribute desc = (DisplayAttribute)attrs.Where(i => i.GetType() == typeof(DisplayAttribute)).FirstOrDefault();
                            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);
        }
Пример #47
0
        public static string GetDescription(this TreasureClass?prop)
        {
            DisplayAttribute description = prop.GetAttributeOfType <DisplayAttribute>();

            return(description?.Description ?? prop?.ToString() ?? "");
        }