/// <summary>
		/// Initializes a new instance of the <see cref="FilterDescriptor"/> class.
		/// </summary>
		/// <param name="filterType">Type of the filter.</param>
		/// <param name="when">The flag that defines when it should run.</param>
		/// <param name="executionOrder">The execution order.</param>
		/// <param name="attribute">The attribute.</param>
		public FilterDescriptor(Type filterType, ExecuteWhen when, int executionOrder, FilterAttribute attribute)
		{
			this.filterType = filterType;
			this.when = when;
			this.executionOrder = executionOrder;
			this.attribute = attribute;
		}
		/// <summary>
		/// Initializes a new instance of the <see cref="FilterDescriptor"/> class 
		/// from a <see cref="FilterAttribute"/> instance.
		/// </summary>
		public FilterDescriptor(FilterAttribute attribute) 
			: this(
				attribute.FilterType, 
				attribute.When, 
				attribute.ExecutionOrder, 
				attribute
			){}
        internal void SetFilter(LocationInfo locationInfo, FilterAttribute filter)
        {
            if ( this.frozen )
                throw new InvalidOperationException();

            this.filteredMembers.Add(locationInfo, filter);
        }
Exemplo n.º 4
0
        public void Should_Infer_Result_Filter_Generic_Types()
        {
            var handler  = new FilterResolver();
            var provider = new FilterAttribute(typeof(RequestFilterRes <>));
            var filter   = provider.GetFilters(typeof(string), typeof(int), handler)
                           .ToArray();

            Assert.AreEqual(typeof(RequestFilterRes <int>), handler.RequestedType);
        }
Exemplo n.º 5
0
 /// <summary>
 /// Initializes a new instance of the <see cref="FilterDescriptor"/> class
 /// from a <see cref="FilterAttribute"/> instance.
 /// </summary>
 public FilterDescriptor(FilterAttribute attribute)
     : this(
         attribute.FilterType,
         attribute.When,
         attribute.ExecutionOrder,
         attribute
         )
 {
 }
        internal void SetFilter(LocationInfo locationInfo, FilterAttribute filter)
        {
            if (frozen)
            {
                throw new InvalidOperationException();
            }

            filteredMembers.Add(locationInfo, filter);
        }
Exemplo n.º 7
0
 protected MethodBinding(MethodDispatch dispatch)
 {
     if (dispatch == null)
     {
         throw new ArgumentNullException(nameof(dispatch));
     }
     Dispatcher = dispatch;
     AddFilters(FilterAttribute.GetFilters(Dispatcher.Method));
 }
Exemplo n.º 8
0
        private static ActionDescriptor CreateActionDescriptor(object filter)
        {
            Mock <ActionDescriptor> mock      = new Mock <ActionDescriptor>(MockBehavior.Strict);
            FilterAttribute         attribute = filter as FilterAttribute;

            mock.Setup(d => d.GetFilterAttributes(It.IsAny <bool>()))
            .Returns(attribute != null ? new FilterAttribute[] { attribute } : new FilterAttribute[0]);
            mock.Setup(d => d.ControllerDescriptor).Returns(new Mock <ControllerDescriptor>().Object);
            return(mock.Object);
        }
Exemplo n.º 9
0
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            FilterAttribute ignoreFilterAttribute = filterContext.ActionDescriptor.GetFilterAttributes(false).FirstOrDefault(s => s.GetType() == typeof(GoogleAnalyticsIgnoreAttribute));
            bool            isIgnore = ignoreFilterAttribute != null;

            if (isIgnore)
            {
                return;
            }
            IncludeAnalyticsScript();
        }
        internal void SetFilter(ParameterInfo parameter, FilterAttribute filter)
        {
            if (_filters[parameter.Position] != null)
            {
                // If you want to support more than 1 filter, you will need a more complex data structure and to cope with priorities.
                Message.Write(parameter, SeverityType.Error, "MY01", "There cannot be more than 1 filter on parameter {0}.",
                              parameter);
                return;
            }

            _filters[parameter.Position] = filter;
        }
Exemplo n.º 11
0
        /// <summary>
        /// Builds the where statement.
        /// </summary>
        /// <typeparam name="T">The Entity type</typeparam>
        /// <param name="baseFilterDto">The filtering DTO</param>
        /// <returns>The where statement</returns>
        public static Expression <Func <T, bool> > BuildWhere <T>(BaseFilterDto baseFilterDto) where T : IBaseEntity
        {
            ParameterExpression parameterExpression = Expression.Parameter(typeof(T), EXPRESSION_PARAMETER);
            List <Expression>   whereParts          = new List <Expression>();

            foreach (IGrouping <string, PropertyInfo> searchPropertyGroup in GetGroupedSearchedPropertiesInfo(baseFilterDto))
            {
                List <Expression> expressionGroupedOrWhereParts  = new List <Expression>();
                List <Expression> expressionGroupedAndWhereParts = new List <Expression>();
                foreach (PropertyInfo searchPropertyInfo in searchPropertyGroup)
                {
                    FilterAttribute searchAttribute     = (FilterAttribute)searchPropertyInfo.GetCustomAttribute(typeof(FilterAttribute));
                    object          value               = searchPropertyInfo.GetValue(baseFilterDto);
                    Expression      expressionWherePart = null;
                    //if (value is bool && searchAttribute.EnumAttribute != null)
                    //{
                    //    if ((bool)value == true)
                    //    {
                    //        expressionWherePart = BuildWherePart<T>(parameterExpression, searchAttribute, searchAttribute.EnumAttribute);
                    //        if (expressionWherePart != null)
                    //        {
                    //            expressionGroupedOrWhereParts.Add(expressionWherePart);
                    //        }
                    //    }
                    //}
                    //else
                    {
                        expressionWherePart = BuildWherePart <T>(parameterExpression, searchAttribute, value);
                        if (expressionWherePart != null)
                        {
                            expressionGroupedAndWhereParts.Add(expressionWherePart);
                        }
                    }
                }
                Expression finalGroupedOrWhereParts  = JoinOrWhereParts(expressionGroupedOrWhereParts);
                Expression finalGroupedAndWhereParts = JoinAndWhereParts(expressionGroupedAndWhereParts);
                if (finalGroupedOrWhereParts != null)
                {
                    whereParts.Add(finalGroupedOrWhereParts);
                }
                if (finalGroupedAndWhereParts != null)
                {
                    whereParts.Add(finalGroupedAndWhereParts);
                }
            }

            if (whereParts.Count == 0)
            {
                return(x => true);
            }

            return(Expression.Lambda <Func <T, bool> >(JoinAndWhereParts(whereParts), parameterExpression));
        }
        internal void SetFilter(ParameterInfo parameter, FilterAttribute filter)
        {
            if ( this.filters[parameter.Position] != null )
            {
                // If you want to support more than 1 filter, you will need a more complex data structure and to cope with priorities.
                Message.Write(parameter, SeverityType.Error, "MY01", "There cannot be more than 1 filter on parameter {0}.", parameter);
                return;
            }

            this.filters[parameter.Position] = filter;

        }
Exemplo n.º 13
0
        public static TypeSelectorWindow ShowAsNew(Rect rect,
                                                   FilterAttribute filter,
                                                   Action <MemberData[]> selectCallback,
                                                   params TypeItem[] targetType)
        {
            TypeSelectorWindow window = CreateInstance(typeof(TypeSelectorWindow)) as TypeSelectorWindow;

            window.targetType     = targetType;
            window.filter         = filter;
            window.selectCallback = selectCallback;
            window.Init(rect);
            return(window);
        }
Exemplo n.º 14
0
        private void EditType(Type type, FilterAttribute filter, int deepLevel, Action <Type> onChange)
        {
            string tName = type.PrettyName();
            Rect   rect  = GUILayoutUtility.GetRect(new GUIContent(tName), "Button");

            rect.x     += 15 * deepLevel;
            rect.width -= 15 * deepLevel;
            if (GUI.Button(rect, new GUIContent(tName, type.FullName)))
            {
                if (Event.current.button == 0)
                {
                    ItemSelector.ShowAsNew(targetObject, filter, delegate(MemberData value) {
                        onChange(value.Get <Type>());
                    }, true).ChangePosition(rect.ToScreenRect());
                }
                else
                {
                    CommandWindow.CreateWindow(uNodeGUIUtility.GUIToScreenRect(rect), (items) => {
                        var member = CompletionEvaluator.CompletionsToMemberData(items);
                        if (member != null)
                        {
                            onChange(member.Get <Type>());
                            return(true);
                        }
                        return(false);
                    }, new CompletionEvaluator.CompletionSetting()
                    {
                        validCompletionKind = CompletionKind.Type | CompletionKind.Namespace | CompletionKind.Keyword,
                    });
                }
            }
            if (type.IsGenericType)
            {
                var gType = type.GetGenericArguments();
                if (gType.Length > 0)
                {
                    for (int i = 0; i < gType.Length; i++)
                    {
                        var current = i;
                        EditType(gType[i], filter, deepLevel + 1, (t) => {
                            if (t != null)
                            {
                                var typeDefinition = type.GetGenericTypeDefinition();
                                gType[current]     = t;
                                onChange(typeDefinition.MakeGenericType(gType));
                            }
                        });
                    }
                }
            }
        }
Exemplo n.º 15
0
        /// <summary>
        /// Processes a type if its a Filter
        /// </summary>
        /// <param name="type">The type.</param>
        /// <returns></returns>
        private void ProcessFilter(Type type, Dictionary <string, Type> dtoMap)
        {
            FilterAttribute filterAttribute = AttributeUtil.GetAttributeFrom <FilterAttribute>(type);

            if (filterAttribute == null)
            {
                return;
            }
            if (filterAttribute.DtoType != null)
            {
                this.Parent.BOManager.AddFilterType(filterAttribute.DtoType, type);
                return;
            }
            string name = string.IsNullOrEmpty(filterAttribute.Name) ? type.Name : filterAttribute.Name;

            if (name.IndexOf('.') > -1)
            {
                Type dtoType = TypesManager.ResolveType(name);
                if (dtoType != null)
                {
                    this.Parent.BOManager.AddFilterType(dtoType, type);
                }
                return;
            }
            if (dtoMap.ContainsKey(name))
            {
                this.Parent.BOManager.AddFilterType(dtoMap[name], type);
                return;
            }
            string testname = this.DtoPreffix + name + this.DtoSuffix;

            if (dtoMap.ContainsKey(testname))
            {
                this.Parent.BOManager.AddFilterType(dtoMap[testname], type);
                return;
            }
            testname = name;
            testname = this.RemovePreffix(testname, this.FilterPreffix);
            testname = this.RemoveSuffix(testname, this.FilterSuffix);
            if (dtoMap.ContainsKey(testname))
            {
                this.Parent.BOManager.AddFilterType(dtoMap[testname], type);
                return;
            }
            testname = this.DtoPreffix + testname + this.DtoSuffix;
            if (dtoMap.ContainsKey(testname))
            {
                this.Parent.BOManager.AddFilterType(dtoMap[testname], type);
                return;
            }
        }
Exemplo n.º 16
0
        public IEnumerable <Book> GetBooks(string searchBy, string filterBy, string orderBy)
        {
            using (SqlConnection conn = new SqlConnection(this.DBString))
            {
                using (SqlCommand cmd = new SqlCommand("spGetBooks", conn)
                {
                    CommandType = CommandType.StoredProcedure
                })
                {
                    cmd.Parameters.AddWithValue("@search", searchBy.Trim().ToLower());
                    cmd.Parameters.AddWithValue("@filter", FilterAttribute.GetAttribute(filterBy));
                    cmd.Parameters.AddWithValue("@order", OrderAttribute.GetAttribute(orderBy));

                    try
                    {
                        conn.Open();
                        SqlDataReader rdr = cmd.ExecuteReader();
                        if (rdr.HasRows)
                        {
                            List <Book> bookList = new List <Book>();
                            while (rdr.Read())
                            {
                                bookList.Add(new Book
                                {
                                    id             = Convert.ToInt32(rdr["id"]),
                                    authorName     = rdr["auther_name"].ToString(),
                                    bookDetail     = rdr["book_detail"].ToString(),
                                    bookImageSrc   = rdr["book_image_src"].ToString(),
                                    bookName       = rdr["book_name"].ToString(),
                                    bookPrice      = Convert.ToInt32(rdr["book_price"]),
                                    isbnNumber     = rdr["isbn_number"].ToString(),
                                    noOfCopies     = Convert.ToInt32(rdr["no_of_copies"]),
                                    publishingYear = Convert.ToInt32(rdr["publishing_year"])
                                });
                            }
                            return(bookList);
                        }
                    }
                    catch
                    {
                        return(null);
                    }
                    finally
                    {
                        conn.Close();
                    }
                }
            }
            return(null);
        }
Exemplo n.º 17
0
        private bool Invoke(object target, object callback,
                            IHandler composer, Type resultType, Func <object, bool> results,
                            out object result)
        {
            var args = Rule.ResolveArgs(this, callback, composer);

            if (callback is INoFiltersCallback)
            {
                result = Dispatcher.Invoke(target, args, resultType);
                return(true);
            }

            Type callbackType;
            var  dispatcher     = Dispatcher.CloseDispatch(args, resultType);
            var  actualCallback = GetCallbackInfo(
                callback, args, dispatcher, out callbackType);
            var returnType  = dispatcher.ReturnType;
            var logicalType = dispatcher.LogicalReturnType;

            var filters = composer
                          .GetOrderedFilters(callbackType, logicalType, Filters,
                                             FilterAttribute.GetFilters(target.GetType(), true),
                                             Policy.Filters)
                          .ToArray();

            if (filters.Length == 0)
            {
                result = dispatcher.Invoke(target, args, resultType);
            }
            else if (!MethodPipeline.GetPipeline(callbackType, logicalType)
                     .Invoke(this, target, actualCallback, comp => dispatcher.Invoke(
                                 target, GetArgs(callback, args, composer, comp),
                                 resultType), composer, filters, out result))
            {
                return(false);
            }

            var accepted = Policy.AcceptResult?.Invoke(result, this)
                           ?? result != null;

            if (accepted && (result != null) && !Dispatcher.IsVoid)
            {
                var asyncCallback = callback as IAsyncCallback;
                result = CoerceResult(result, returnType, asyncCallback?.WantsAsync);
                return(results?.Invoke(result) != false);
            }

            return(accepted);
        }
Exemplo n.º 18
0
 public static TypeSelectorWindow ShowWindow(Vector2 pos,
                                             FilterAttribute filter,
                                             Action <MemberData[]> selectCallback,
                                             params TypeItem[] targetType)
 {
     if (window == null)
     {
         window = CreateInstance(typeof(TypeSelectorWindow)) as TypeSelectorWindow;
     }
     window.targetType = targetType;
     window.filter     = filter;
     window.Init(pos);
     window.selectCallback = selectCallback;
     return(window);
 }
Exemplo n.º 19
0
        public Task <FilterResult> FilterAsync(FilterAttribute attribute, MiddlewareData data)
        {
            var principal = data.Features.RequireOne <AuthenticationFeature>().Principal;

            if (!principal.Is​Authenticated())
            {
                var message = new BaseOutMessage()
                {
                    Text = "Unauthorized access"
                };
                var result = FilterResult.BreakExecution(data.AddRenderMessageFeature(message));
                return(Task.FromResult(result));
            }
            return(Task.FromResult(FilterResult.NextFilter(data)));
        }
Exemplo n.º 20
0
 /// <summary>
 /// Get the filter of this port or create new if none.
 /// </summary>
 /// <returns></returns>
 public FilterAttribute GetFilter()
 {
     if (filter == null)
     {
         Type t = getPortType();
         if (t != null)
         {
             filter = new FilterAttribute(t);
         }
         else
         {
             filter = new FilterAttribute(typeof(object));
         }
     }
     return(filter);
 }
Exemplo n.º 21
0
        public PortView AddInputValuePort(string fieldName, FilterAttribute filter, string portName = null)
        {
            FieldInfo field = targetNode.GetType().GetField(fieldName);

            return(AddPort(Orientation.Horizontal, Direction.Input, new PortData()
            {
                portID = fieldName,
                getPortName = () => portName ?? ObjectNames.NicifyVariableName(field.Name),
                getPortValue = () => field.GetValueOptimized(targetNode),
                onValueChanged = (o) => {
                    RegisterUndo();
                    field.SetValueOptimized(targetNode, o);
                },
                filter = filter,
            }));
        }
        public static bool ValidateField(FilterAttribute filter, FieldInfo field)
        {
            bool valid = true;

            // Validate type based on field type
            valid &= ValidateMemberType(filter, field.FieldType);

            // Exclude constants (literal) and readonly (init) fields if
            // the filter rejects read-only fields.
            if (!filter.ReadOnly)
            {
                valid &= !field.IsLiteral || !field.IsInitOnly;
            }

            return(valid);
        }
Exemplo n.º 23
0
        private static Expression BuildWherePart <T>(Parameter parameter, FilterAttribute filterAttribute, object value)
        {
            if (value == null)
            {
                return(null);
            }

            if (CompareOperator.IS_IN_COLLECTION.Equals(filterAttribute.Operator))
            {
                return(COMPARE_OPERATOR_TO_EXPRESSION_OPERATOR_MAP[filterAttribute.Operator].Generate(parameter, null, null, filterAttribute, value));
            }

            LeftExpression  left  = LeftExpression.Create(parameter, filterAttribute);
            RightExpression right = RightExpression.Create(value, left);

            return(COMPARE_OPERATOR_TO_EXPRESSION_OPERATOR_MAP[filterAttribute.Operator].Generate(parameter, left, right, filterAttribute, value));
        }
        /// <inheritdoc />
        protected override void Update(SerializedProperty property)
        {
            // Update the targeted drawer
            base.Update(property);

            // Assign the property and sub-properties
            this.property     = property;
            componentProperty = property.FindPropertyRelative("_component");
            nameProperty      = property.FindPropertyRelative("_name");

            // Fetch the filter
            filter = (FilterAttribute)fieldInfo.GetCustomAttributes(typeof(FilterAttribute), true).FirstOrDefault() ?? DefaultFilter();

            // Find the targets
            targets    = FindTargets();
            targetType = DetermineTargetType();
        }
        public static bool ValidateProperty(FilterAttribute filter, PropertyInfo property)
        {
            bool valid = true;

            // Validate type based on property type
            valid &= ValidateMemberType(filter, property.PropertyType);

            // Exclude read-only and write-only properties
            if (!filter.ReadOnly)
            {
                valid &= property.CanWrite;
            }
            if (!filter.WriteOnly)
            {
                valid &= property.CanRead;
            }

            return(valid);
        }
Exemplo n.º 26
0
        /// <summary>used to show the connection</summary>
        /// <param name="context">see documentation on ITypeDescriptorContext</param>
        /// <param name="provider">see documentation on IServiceProvider</param>
        /// <param name="value">the value prior to editing</param>
        /// <returns>the new connection string after editing</returns>
        public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value)
        {
            if (value is string)
            {
                FilterAttribute filterAtt = (FilterAttribute)context.PropertyDescriptor.Attributes[typeof(FilterAttribute)];

                string filter = null;
                if (filterAtt != null)
                {
                    filter = filterAtt.Filter;
                }

                return(EditValue(value as string, filter));
            }
            else
            {
                throw new Exception("Invalid type");
            }
        }
Exemplo n.º 27
0
        private static Expression AnyCall(ParameterExpression parameterExpression, FilterAttribute filterAttribute, object value)
        {
            Expression collectionExpression = Expression.PropertyOrField(parameterExpression, filterAttribute.TargetProperty);
            Type       collectionType       = collectionExpression.Type;
            Type       elemType             = collectionType.GetGenericArguments()[0];
            Type       predType             = typeof(Func <,>).MakeGenericType(elemType, typeof(bool));

            MethodInfo anyMethod = typeof(Enumerable).GetMethods().Single(x => x.Name == "Any" && x.GetParameters().Count() == 2).MakeGenericMethod(new Type[] { elemType });

            ParameterExpression p2          = Expression.Parameter(elemType, "y");
            Expression          left        = Expression.Property(p2, elemType.GetProperty(filterAttribute.SourceJoinProperty));
            Expression          InnerLambda = Expression.Equal(left, GetValueExpression(value, left.Type));

            //Expression<Func<IBaseEntity, bool>> innerFunction = Expression.Lambda<Func<IBaseEntity, bool>>(InnerLambda, p2);
            var        innerFunction   = typeof(Func <,>).MakeGenericType(elemType, typeof(bool));
            Expression innerExpression = Expression.Lambda(innerFunction, InnerLambda, p2);


            return(Expression.Call(anyMethod, collectionExpression, innerExpression));
        }
Exemplo n.º 28
0
        public static ItemSelector ShowAsNew(
            UnityEngine.Object targetObject,
            FilterAttribute filter,
            Action <MemberData> selectCallback = null,
            bool onlyGetType = false,
            List <CustomItem> customItems = null)
        {
            ItemSelector window = ScriptableObject.CreateInstance(typeof(ItemSelector)) as ItemSelector;

            window.targetObject = targetObject;
            window.filter       = filter;
            window.onlyGetType  = onlyGetType;
            window.Init();
            window.selectCallback = selectCallback;
            if (customItems != null)
            {
                window.customItems = customItems;
            }
            return(window);
        }
Exemplo n.º 29
0
        private LeftExpression(Parameter parameter, FilterAttribute filterAttribute)
        {
            string[]   leftExpressionProperties = GetLeftExpressionProperties(filterAttribute.TargetProperty);
            Expression previousExpression       = null;
            Expression nextExpression           = null;

            foreach (string leftExpressionProperty in leftExpressionProperties)
            {
                if (previousExpression == null)
                {
                    nextExpression = Expression.Property(parameter.GetExpression(), leftExpressionProperty);
                }
                else
                {
                    nextExpression = Expression.Property(previousExpression, leftExpressionProperty);
                }
                previousExpression = nextExpression;
            }
            _expression = nextExpression;
        }
Exemplo n.º 30
0
        /// <summary>
        /// Set whether the $filter can be applied on those properties of this structural type.
        /// </summary>
        /// <param name="edmTypeConfiguration">The structural type to configure.</param>
        /// <param name="model">The edm model that this type belongs to.</param>
        /// <param name="attribute">The <see cref="Attribute"/> found on this type.</param>
        public override void Apply(StructuralTypeConfiguration edmTypeConfiguration, ODataConventionModelBuilder model,
                                   Attribute attribute)
        {
            if (edmTypeConfiguration == null)
            {
                throw Error.ArgumentNull("edmTypeConfiguration");
            }

            if (model == null)
            {
                throw Error.ArgumentNull("model");
            }

            if (!edmTypeConfiguration.AddedExplicitly)
            {
                FilterAttribute filterAttribute = attribute as FilterAttribute;

                /*
                 * ModelBoundQuerySettings querySettings =
                 *  edmTypeConfiguration.QueryConfiguration.GetModelBoundQuerySettingsOrDefault();
                 * if (querySettings.FilterConfigurations.Count == 0)
                 * {
                 *  querySettings.CopyFilterConfigurations(
                 *      filterAttribute.FilterConfigurations);
                 * }
                 * else
                 * {
                 *  foreach (var property in filterAttribute.FilterConfigurations.Keys)
                 *  {
                 *      querySettings.FilterConfigurations[property] =
                 *          filterAttribute.FilterConfigurations[property];
                 *  }
                 * }
                 *
                 * if (filterAttribute.FilterConfigurations.Count == 0)
                 * {
                 *  querySettings.DefaultEnableFilter = filterAttribute.DefaultEnableFilter;
                 * }
                 */
            }
        }
Exemplo n.º 31
0
 public void Execute()
 {
     if (mFirstInvoke)
     {
         mFirstInvoke = false;
         ((Implement.Application)Application).OnMethodProcess(new Events.EventMethodProcessArgs {
             Session = Session, Application = Application, Method = this
         });
     }
     FilterAttribute[] filters = Handler.Filters;
     if (filters == null || filters.Length == 0 || mIndex >= filters.Length)
     {
         Result = Handler.Execute(this, Parameters);
     }
     else
     {
         FilterAttribute filter = filters[mIndex];
         mIndex++;
         filter.Execute(this);
     }
 }
Exemplo n.º 32
0
        /// <inheritdoc />
        protected override void Update(SerializedProperty property)
        {
            // Update the targeted drawer
            base.Update(property);

            // Assign the property and sub-properties
            this.property          = property;
            componentProperty      = property.FindPropertyRelative("_component");
            nameProperty           = property.FindPropertyRelative("_name");
            parameterTypesProperty = property.FindPropertyRelative("_parameterTypes");

            // Fetch the filter
            filter = filterOverride ?? (FilterAttribute)fieldInfo.GetCustomAttributes(typeof(FilterAttribute), true).FirstOrDefault() ?? new FilterAttribute();

            // Check for the label type after attribute
            labelTypeAfter = labelTypeAfterOverride ?? fieldInfo.IsDefined(typeof(LabelTypeAfterAttribute), true);

            // Find the targets
            targets    = FindTargets();
            targetType = DetermineTargetType();
        }
        public static bool ValidateMethod(FilterAttribute filter, MethodInfo method)
        {
            bool valid = true;

            // Validate type based on return type
            valid &= ValidateMemberType(filter, method.ReturnType);

            // Exclude special compiler methods
            valid &= !method.IsSpecialName;

            // Exclude generic methods
            // TODO: Generic type (de)serialization
            valid &= !method.ContainsGenericParameters;

            // Exclude methods with parameters
            if (!filter.Parameters)
            {
                valid &= method.GetParameters().Length == 0;
            }

            return(valid);
        }
Exemplo n.º 34
0
 public static ItemSelector ShowWindow(
     UnityEngine.Object targetObject,
     MemberData variable,
     FilterAttribute filter,
     Action <MemberData> selectCallback = null,
     List <CustomItem> customItems      = null)
 {
     if (window == null)
     {
         window = ScriptableObject.CreateInstance(typeof(ItemSelector)) as ItemSelector;
     }
     window.targetObject    = targetObject;
     window.reflectionValue = variable;
     window.filter          = filter;
     window.selectCallback  = selectCallback;
     window.Init();
     if (customItems != null)
     {
         window.customItems = customItems;
     }
     return(window);
 }
        /// <inheritdoc />
        protected override void Update(SerializedProperty property)
        {
            // Update the targeted drawer
            base.Update(property);

            // Assign the property and sub-properties
            this.property = property;
            componentProperty = property.FindPropertyRelative("_component");
            nameProperty = property.FindPropertyRelative("_name");
            parameterTypesProperty = property.FindPropertyRelative("_parameterTypes");

            // Fetch the filter
            filter = filterOverride ?? (FilterAttribute)fieldInfo.GetCustomAttributes(typeof(FilterAttribute), true).FirstOrDefault() ?? new FilterAttribute();

            // Check for the label type after attribute
            labelTypeAfter = labelTypeAfterOverride ?? fieldInfo.IsDefined(typeof(LabelTypeAfterAttribute), true);

            // Find the targets
            targets = FindTargets();
            targetType = DetermineTargetType();
        }
Exemplo n.º 36
0
        /// <summary> Write a Filter XML Element from attributes in a member. </summary>
        public virtual void WriteFilter(System.Xml.XmlWriter writer, System.Reflection.MemberInfo member, FilterAttribute attribute, BaseAttribute parentAttribute, System.Type mappedClass)
        {
            writer.WriteStartElement( "filter" );
            // Attribute: <name>
            writer.WriteAttributeString("name", attribute.Name==null ? DefaultHelper.Get_Filter_Name_DefaultValue(member) : GetAttributeValue(attribute.Name, mappedClass));
            // Attribute: <condition>
            if(attribute.Condition != null)
            writer.WriteAttributeString("condition", GetAttributeValue(attribute.Condition, mappedClass));

            WriteUserDefinedContent(writer, member, null, attribute);

            // Write the content of this element (mixed="true")
            writer.WriteString(attribute.Content);

            writer.WriteEndElement();
        }
Exemplo n.º 37
0
 private IEnumerable<object> ExecutedActionFiltersOf(FilterAttribute attribute)
 {
     return ActionFiltersOf(attribute).OrderByDescending((dynamic filter) => filter.Order);
 }
Exemplo n.º 38
0
 private IEnumerable<IActionFilter> ExecutedActionFiltersOf(FilterAttribute attribute)
 {
     return ActionFiltersOf(attribute).OrderByDescending(filter => filter.Order);
 }
Exemplo n.º 39
0
        private IEnumerable<IActionFilter> ActionFiltersOf(FilterAttribute attribute)
        {
            var filterType = typeof (IActionFilter<>).MakeGenericType(attribute.GetType());

            return _serviceProvider.Invoke(filterType);
        }
Exemplo n.º 40
0
		public void OutputCurrentElementAsContent(ITemplateContext context, FilterAttribute filter)
		{
			context.AppendIndented("output.Write('");

			XmlReader reader = context.Reader;
			StringBuilder script = context.Script;

			if (reader.NodeType == XmlNodeType.Element)
			{
				if (reader.IsEmptyElement)
				{
					script.Append("<" + reader.LocalName);
					OutputAttributes(reader, script, filter);
					script.Append(" />");
				}
				else
				{
					script.Append("<");
					script.Append(reader.LocalName);
					OutputAttributes(reader, script, filter);
					script.Append(">");
				}
			}
			else if (reader.NodeType == XmlNodeType.EndElement)
			{
				script.Append("</");
				script.Append(reader.LocalName);
				script.Append(">");
			}
			else if (reader.NodeType == XmlNodeType.ProcessingInstruction)
			{
				script.Append("<?");
				script.Append(reader.LocalName);
				script.Append(' ');
				script.Append(reader.Value);
				script.Append(" ?>");
			}
			else if (reader.NodeType == XmlNodeType.Text ||
			         reader.NodeType == XmlNodeType.Whitespace)
			{
				script.Append(ConvertEscapes(reader.Value));
			}

			script.AppendLine("')");
		}
Exemplo n.º 41
0
		private void OutputAttributes(XmlReader reader, StringBuilder script, FilterAttribute filter)
		{
			if (!reader.HasAttributes) return;

			if (!reader.MoveToFirstAttribute()) return;

			do
			{
				String name = reader.LocalName;

				if (filter != null && !filter(name))
				{
					continue;
				}

				script.Append(' ');
				script.Append(name);
				script.Append('=');
				script.Append('\"');
				script.Append(reader.Value);
				script.Append('\"');
				
			} while(reader.MoveToNextAttribute());
		}