/// <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); }
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); }
/// <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); }
protected MethodBinding(MethodDispatch dispatch) { if (dispatch == null) { throw new ArgumentNullException(nameof(dispatch)); } Dispatcher = dispatch; AddFilters(FilterAttribute.GetFilters(Dispatcher.Method)); }
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); }
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; }
/// <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; }
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); }
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)); } }); } } } }
/// <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; } }
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); }
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); }
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); }
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))); }
/// <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); }
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); }
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); }
/// <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"); } }
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)); }
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); }
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; }
/// <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; * } */ } }
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); } }
/// <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); }
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); }
/// <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(); }
private IEnumerable<object> ExecutedActionFiltersOf(FilterAttribute attribute) { return ActionFiltersOf(attribute).OrderByDescending((dynamic filter) => filter.Order); }
private IEnumerable<IActionFilter> ExecutedActionFiltersOf(FilterAttribute attribute) { return ActionFiltersOf(attribute).OrderByDescending(filter => filter.Order); }
private IEnumerable<IActionFilter> ActionFiltersOf(FilterAttribute attribute) { var filterType = typeof (IActionFilter<>).MakeGenericType(attribute.GetType()); return _serviceProvider.Invoke(filterType); }
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("')"); }
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()); }