Exemple #1
0
 /// <summary cref="IFilterTarget.IsInView" />
 public bool IsInView(
     FilterContext context, 
     NodeId        viewId)
 {
     // events instances are not in any view.
     return false;
 }
Exemple #2
0
        /// <summary cref="IFilterTarget.GetAttributeValue" />
        public virtual object GetAttributeValue(
            FilterContext        context,
            NodeId               typeDefinitionId,
            IList<QualifiedName> relativePath,
            uint                 attributeId,
            NumericRange         indexRange)
        {
            if (context == null) throw new ArgumentNullException("context");
            
            // read the attribute value.
            DataValue dataValue = ReadAttributeValue(
                context,
                typeDefinitionId,
                relativePath,
                attributeId,
                indexRange);

            if (StatusCode.IsBad(dataValue.StatusCode))
            {
                return dataValue.StatusCode;
            }
                        
            // return the value.
            return dataValue.Value;
        }
Exemple #3
0
 /// <summary cref="IFilterTarget.IsTypeOf" />
 public bool IsTypeOf(
     FilterContext context, 
     NodeId        typeDefinitionId)
 {
     if (context == null) throw new ArgumentNullException("context");
     
     return context.TypeTree.IsTypeOf(TypeDefinitionId, typeDefinitionId);
 }
Exemple #4
0
 /// <summary cref="IFilterTarget.IsRelatedTo" />
 public virtual bool IsRelatedTo(
     FilterContext context, 
     NodeId        source,
     NodeId        targetTypeId,
     NodeId        referenceTypeId,
     int           hops)
 {
     // events instances do not have any relationships to other nodes.
     return false;
 }
        protected string GetUrl(FilterContext context)
        {
            FilterContext castedContext;
            var url = string.Empty;
            if (context.GetType().ToString() == "ResultExecutingContext")
            {
                url = ((ResultExecutingContext)context).Controller.GetType() + "|" + context.ActionDescriptor.DisplayName + "|" + string.Join(",", context.ActionDescriptor.Properties.Values.Select(x => x.ToString()).ToList());
            }
            else
            {
                url = ((ResultExecutedContext)context).Controller.GetType() + "|" + context.ActionDescriptor.DisplayName + "|" + string.Join(",",context.ActionDescriptor.Properties.Values.Select(x=>x.ToString()).ToList());
            }

            return url;
        }
        public string getVersionedId(string assetId)
        {
            Asset asset = null;

            FilterContext filterContext = new FilterContext(this._context.Cache, null, FilterState.Discovery, new AssetPrefixFilter(assetId));

            foreach (Asset a in this._context.AssetExplorer.Discover(this._assembly, filterContext))
            {
                if (StringComparer.Ordinal.Equals(a.Id.AssetId, assetId))
                {
                    asset = a;
                    break;
                }
            }

            if (asset == null)
            {
                foreach (var asm in this._context.AssetExplorer.GetReferences(this._assembly))
                {
                    Debug.WriteLine(asm.ToString());

                    foreach (Asset a in this._context.AssetExplorer.Discover(asm, filterContext))
                    {
                        if (StringComparer.Ordinal.Equals(a.Id.AssetId, assetId))
                        {
                            asset = a;
                            break;
                        }
                    }
                }
            }

            if (asset != null)
            {
                TraceSources.AssetResolverSource.TraceVerbose("Resolved {0} to version: {1}", assetId, asset.Id.Version);
                this._context.AddReference(asset);
                assetId = asset.Id.ToString();
            }
            else
            {
                TraceSources.AssetResolverSource.TraceWarning("Failed to resolve {0}", assetId);
            }

            return assetId;
        }
        public void ApplyFilter(FilterContext context)
        {
            var userList = (String)context.State.Users;

            if (userList == null)
            {
                return;
            }

            var userIds = UsersFilterForms.GetUserIds(userList);

            if (!userIds.Any())
            {
                return;
            }

            Action <IAliasFactory>         selector = alias => alias.ContentPartRecord <CommonPartRecord>();
            Action <IHqlExpressionFactory> filter   = x => x.InG("OwnerId", userIds);

            context.Query.Where(selector, filter);
        }
Exemple #8
0
        public void Wrap(FilterContext context)
        {
            JsonResult jsonResult = null;

            switch (context)
            {
            case ResultExecutingContext resultExecutingContext:
                jsonResult = resultExecutingContext.Result as JsonResult;
                break;
            }

            if (jsonResult == null)
            {
                throw new ArgumentException("Action Result should be JsonResult!");
            }

            if (!(jsonResult.Value is JsonResponseBase))
            {
                jsonResult.Value = new JsonResponse(jsonResult.Value);
            }
        }
        private async Task ExecuteSearchAsync()
        {
            try
            {
                IsLoading = true;

                var sw = System.Diagnostics.Stopwatch.StartNew();

                await Task.Run(() =>
                {
                    var filter      = new FilterContext(Filter, ComboMatchVM.GetSelectedValues(), ComboObjectsVM.GetSelectedValues(), SchemaObjectsVM.GetSelectedValues());
                    SearchResultsVM = FilterResultService.Filter(_allDdResults, filter).Select(p => new SearchFilterResultVM(p, filter)).ToList();
                }).ConfigureAwait(false);

                Message = $"{SearchResultsVM.Count} Result(s) in {sw.ElapsedMilliseconds} ms";
            }
            finally
            {
                IsLoading = false;
            }
        }
Exemple #10
0
        /// <inheritdoc/>
        public override ValueTask <string> BuildAsync(FilterContext filterContext, StringBuilder keyBuilder)
        {
            var query = filterContext.HttpContext.Request.Query;

            foreach (var queryKey in _queryKeys)
            {
                if (query.TryGetValue(queryKey, out var value))
                {
                    keyBuilder.Append(CombineChar);
                    keyBuilder.Append(value);
                }
                else
                {
                    if (!ProcessKeyNotFind(queryKey))
                    {
                        return(new ValueTask <string>());
                    }
                }
            }
            return(base.BuildAsync(filterContext, keyBuilder));
        }
Exemple #11
0
        private async Task ApplyFilters(Func <IFilterAsyncHandler, Func <FilterContext, Task> > action, FilterContext context, bool swallowExceptions = false)
        {
            foreach (IFilterAsyncHandler handler in this.filters)
            {
                try
                {
                    await action(handler)(context).ConfigureAwait(false);
                }
                catch (Exception ex)
                {
                    if (!swallowExceptions)
                    {
                        FilterContext exceptionContext = new FilterContext(context.Connection, context.Command, ex, context.SourceObject);

                        await this.ApplyFilters(h => h.OnExceptionAsync, exceptionContext, swallowExceptions : true).ConfigureAwait(false);

                        throw;
                    }
                }
            }
        }
Exemple #12
0
        public void ApplyFilter(FilterContext context)
        {
            var currentContent = _currentContentAccessor.CurrentContentItem;

            if (currentContent == null)
            {
                return;
            }

            var commonPart = currentContent.As <CommonPart>();

            if (commonPart == null)
            {
                return;
            }

            Action <IAliasFactory>         selector = alias => alias.ContentPartRecord <CommonPartRecord>();
            Action <IHqlExpressionFactory> filter   = x => x.Eq("OwnerId", commonPart.Owner.Id);

            context.Query.Where(selector, filter);
        }
        protected override Task Validate(FilterContext <DeleteIdeaCommentCommand> context)
        {
            if (!context.Message.IsValid())
            {
                throw new ArgumentException(nameof(context.Message));
            }

            var comment = _repository.GetOne <IdeaComment>(context.Message.CommentId);

            if (comment == null)
            {
                throw new InvalidOperationException("invalid comment");
            }

            if (comment.OwnerId != _userIdentityProvider.GetUserId())
            {
                throw new UnauthorizedAccessException();
            }

            return(Task.CompletedTask);
        }
Exemple #14
0
        /// <summary>
        /// Checks controller authority, returns false if unauthorized
        /// </summary>
        private bool CheckControllerAuthority(RouteMatch match, FilterContext context, HttpResponse response)
        {
            if (!match.Route.HasControllerAuthorizeFilter)
            {
                return(true);
            }

            AuthorizeAttribute filter = (AuthorizeAttribute)match.Route.ControllerType.GetCustomAttribute(typeof(AuthorizeAttribute));

            if (filter != null)
            {
                filter.VerifyAuthority(Mvc, null, context);
                if (context.Result != null)
                {
                    WriteResponse(response, context.Result);
                    return(false);
                }
            }

            return(true);
        }
Exemple #15
0
        private void ApplyFilters(Func <IFilterHandler, Action <FilterContext> > action, FilterContext context, bool swallowExceptions = false)
        {
            foreach (IFilterHandler handler in this.filters)
            {
                try
                {
                    action(handler)(context);
                }
                catch (Exception ex)
                {
                    if (!swallowExceptions)
                    {
                        FilterContext exceptionContext = new FilterContext(context.Connection, context.Command, ex, context.SourceObject);

                        this.ApplyFilters(h => h.OnException, exceptionContext, swallowExceptions: true);

                        throw;
                    }
                }
            }
        }
        static void ResolveActionScopedFilter <TFilter, TWrapper>(
            FilterContext filterContext, MethodInfo methodInfo, Func <FilterMetadata, TWrapper> wrapperFactory, string metadataKey)
            where TFilter : class
            where TWrapper : IFilter
        {
            var filters = filterContext.LifetimeScope.Resolve <IEnumerable <Meta <Lazy <TFilter> > > >();

            foreach (var filter in filters.Where(a => a.Metadata.ContainsKey(metadataKey) && a.Metadata[metadataKey] is FilterMetadata))
            {
                var metadata = (FilterMetadata)filter.Metadata[metadataKey];

                if (!FilterMatchesAction(filterContext, methodInfo, metadataKey, metadata))
                {
                    continue;
                }

                var wrapper = wrapperFactory(metadata);
                filterContext.Filters.Add(new FilterInfo(wrapper, metadata.FilterScope));
                filterContext.AddedFilters[metadataKey].Add(metadata);
            }
        }
Exemple #17
0
        protected override async Task Validate(FilterContext <UpdateTaskItemTypeCommand> context)
        {
            var taskBoard = await _repository.GetOneAsync <TaskBoard>(context.Message.Type.TaskBoardId);

            if (taskBoard == null)
            {
                throw new LogicalException(ErrorCategory.InvalidInput, "Invalid board");
            }

            var team = await _repository.GetOneAsync <Team>(taskBoard.TeamId);

            if (team == null)
            {
                throw new LogicalException(ErrorCategory.InvalidInput, "Invalid team");
            }

            if (!team.Members.Any(i => i.MemberUserId == _userIdentityProvider.GetUserId()))
            {
                throw new LogicalException(ErrorCategory.UnAuthorized);
            }
        }
        public static Task <Piracystring> FindTriggerAsync(FilterContext ctx, string str)
        {
            if (string.IsNullOrEmpty(str))
            {
                return(Task.FromResult((Piracystring)null));
            }

            if (!filters.TryGetValue(ctx, out var matcher))
            {
                return(Task.FromResult((Piracystring)null));
            }

            Piracystring result = null;

            matcher?.ParseText(str, h =>
            {
                if (string.IsNullOrEmpty(h.Value.ValidatingRegex) || Regex.IsMatch(str, h.Value.ValidatingRegex, RegexOptions.IgnoreCase | RegexOptions.Multiline))
                {
                    result = h.Value;
                    return(h.Value.Actions.HasFlag(FilterAction.RemoveContent));
                }
                return(true);
            });

            if (result is null && ctx == FilterContext.Chat)
            {
                str = str.StripInvisibleAndDiacritics().ToCanonicalForm();
                matcher?.ParseText(str, h =>
                {
                    if (string.IsNullOrEmpty(h.Value.ValidatingRegex) || Regex.IsMatch(str, h.Value.ValidatingRegex, RegexOptions.IgnoreCase | RegexOptions.Multiline))
                    {
                        result = h.Value;
                        return(h.Value.Actions.HasFlag(FilterAction.RemoveContent));
                    }
                    return(true);
                });
            }

            return(Task.FromResult(result));
        }
        private bool IsShip(FilterContext context)
        {
            var controllerActionDescriptor = context.ActionDescriptor as ControllerActionDescriptor;

            if (controllerActionDescriptor != null)
            {
                var isskip = controllerActionDescriptor.ControllerTypeInfo.GetCustomAttributes(inherit: true)
                             .Any(a => a.GetType().Equals(typeof(IgnoreLogFilterAttribute)));
                if (isskip)
                {
                    return(true);
                }
                isskip = controllerActionDescriptor.MethodInfo.GetCustomAttributes(inherit: true)
                         .Any(a => a.GetType().Equals(typeof(IgnoreLogFilterAttribute)));
                if (isskip)
                {
                    return(true);
                }
            }
            else
            {
                var compiledPageActionDescriptor = context.ActionDescriptor as ControllerActionDescriptor;
                if (compiledPageActionDescriptor != null)
                {
                    var isskip = compiledPageActionDescriptor.ControllerTypeInfo.GetCustomAttributes(inherit: true)
                                 .Any(a => a.GetType().Equals(typeof(IgnoreLogFilterAttribute)));
                    if (isskip)
                    {
                        return(true);
                    }
                    isskip = compiledPageActionDescriptor.MethodInfo.GetCustomAttributes(inherit: true)
                             .Any(a => a.GetType().Equals(typeof(IgnoreLogFilterAttribute)));
                    if (isskip)
                    {
                        return(true);
                    }
                }
            }
            return(false);
        }
        /// <summary>
        /// Validate report
        /// </summary>
        /// <param name="context">Context info</param>
        /// <returns>Recommendation</returns>
        public FilterResult Validate(FilterContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }
            if (string.IsNullOrEmpty(ContextName))
            {
                foreach (var ctx in context.ErrorReport.ContextCollections)
                {
                    if (ctx.Properties.Any(property => Matches(PropertyValue, property.Value)))
                    {
                        return(ResultToUse);
                    }
                }

                return(FilterResult.NotMatched);
            }

            var errContext =
                context.ErrorReport.ContextCollections.FirstOrDefault(
                    x => x.Name.Equals(ContextName, StringComparison.CurrentCultureIgnoreCase));

            if (errContext == null)
            {
                return(FilterResult.NotMatched);
            }

            var prop = errContext.Properties.Where(
                x => x.Key.Equals(PropertyName, StringComparison.CurrentCultureIgnoreCase))
                       .Select(x => x.Value)
                       .FirstOrDefault();

            if (prop == null)
            {
                return(FilterResult.NotMatched);
            }

            return(Matches(PropertyValue, prop) ? ResultToUse : FilterResult.NotMatched);
        }
Exemple #21
0
        /// <summary>
        /// 获取更新文件路径
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        private string GetOutputFilePath(FilterContext context)
        {
            string dir = OutputFolder;

            if (string.IsNullOrEmpty(dir))
            {
                dir          = Path.Combine(Path.GetDirectoryName(typeof(HtmlStaticFileAttribute).Assembly.Location), "html");
                OutputFolder = dir;
            }

            var t = context.HttpContext.Request.Path.ToString().Replace("//", Path.DirectorySeparatorChar.ToString()).Replace("/", Path.DirectorySeparatorChar.ToString());

            if (t.EndsWith(Path.DirectorySeparatorChar))
            {
                t += "index";
            }
            if (UseQueryString)
            {
                var list = new HashSet <string>();
                foreach (var item in context.HttpContext.Request.Query.Keys)
                {
                    if (item != UpdateFileQueryString)
                    {
                        var value = context.HttpContext.Request.Query[item];
                        if (string.IsNullOrEmpty(value))
                        {
                            list.Add($"{list}_");
                        }
                        else
                        {
                            list.Add($"{list}_{value}");
                        }
                    }
                }
                t += Regex.Replace(string.Join(",", list), "[^0-9_a-zA-Z\u4E00-\u9FCB\u3400-\u4DB5\u3007]", "_");
            }

            t = t.TrimStart(Path.DirectorySeparatorChar);
            return(Path.Combine(dir, t) + ".html");
        }
        public static async Task RemoveFilterAsync(string name, FilterTypeEnum type)
        {
            try
            {
                using (FilterContext db = new FilterContext())
                {
                    var itemToRemove = await db.filterTables.AsQueryable().FirstOrDefaultAsync(x => x.FilterPattern.ToLower() == name.ToLower()
                                                                                               & x.FilterType == type);

                    if (itemToRemove != null)
                    {
                        db.filterTables.Remove(itemToRemove);
                        await db.SaveChangesAsync();
                    }
                }
            }
            catch (Exception ex)
            {
                ExceptionManager.HandleException(ErrMessages.StorageException, ex);
                throw;
            }
        }
        public static async Task AddFilterAsync(string name, string pattern, FilterTypeEnum type)
        {
            try
            {
                using (FilterContext db = new FilterContext())
                {
                    await db.AddAsync(new FilterTable()
                    {
                        FilterName    = name,
                        FilterPattern = pattern,
                        FilterType    = type
                    });

                    await db.SaveChangesAsync();
                }
            }
            catch (Exception ex)
            {
                ExceptionManager.HandleException(ErrMessages.StorageException, ex);
                throw;
            }
        }
Exemple #24
0
        protected override void ConfigureOverride(FilterContext context, ITimestampedDataSerializationOptions options)
        {
            string timestampFieldName = options.TimestampFieldName;

            context.IO
            .Formats
            .GetOrDefault(FileFormat.JSON)?
            .Configurations
            .Add
            (
                new JsonTimestampedDataSerializationConfiguration(timestampFieldName)
            );

            context.IO
            .Formats
            .GetOrDefault(FileFormat.CSV)?
            .Configurations
            .Add
            (
                new CsvTimestampedDataSerializationConfiguration(timestampFieldName)
            );
        }
Exemple #25
0
        private static void OnExecuting(FilterContext context)
        {
            if (context.HttpContext.Request.Method == "GET")
            {
                return;
            }

            var keyValueManager = context.HttpContext.RequestServices.GetService <IKeyValueManager>();
            var ms        = keyValueManager?.HttpPostsMinimumIntervalMilliseconds() ?? 300;
            var principal = context.HttpContext.RequestServices.GetRequiredService <IPrincipalUser>();
            var blocker   = new AntiViolenceDefender(principal);

            if (blocker.GetTimer().AddMilliseconds(ms) < DateTime.Now)
            {
                blocker.SetTimer();
            }
            else
            {
                blocker.SetTimer(DateTime.Now.AddMilliseconds(ms));
                context.ModelState.AddModelError("", "太快了,慢一点儿");
            }
        }
Exemple #26
0
        public void ApplyFilter(FilterContext context)
        {
            string format  = context.State.Format;
            int    quality = context.State.Quality;

            var settings = new ResizeSettings {
                Quality = quality,
                Format  = format
            };

            var result = new MemoryStream();

            if (context.Media.CanSeek)
            {
                context.Media.Seek(0, SeekOrigin.Begin);
            }

            ImageBuilder.Current.Build(context.Media, result, settings);

            context.FilePath = Path.ChangeExtension(context.FilePath, format);
            context.Media    = result;
        }
Exemple #27
0
            protected override Boolean OnExecute(FilterContext context)
            {
                var pk = context.Packet;
                var ss = Session;

                if (ss.IsWebSocket)
                {
                    pk = HttpHelper.MakeWS(pk);
                }
                else
                {
                    pk = ss.Response.Build(pk);
                }
                ss.Response = null;

                context.Packet = pk;
#if DEBUG
                //Session.WriteLog(pk.ToStr());
#endif

                return(true);
            }
        public LocalizedString DisplayFilter(FilterContext context)
        {
            var terms = (string)context.State.TermIds;

            if (String.IsNullOrEmpty(terms))
            {
                return(T("Any term"));
            }

            int op = Convert.ToInt32(context.State.Operator);

            switch (op)
            {
            case 0:
                return(T("Categorized with one of {0}", terms));

            case 1:
                return(T("Categorized with all of {0}", terms));
            }

            return(T("Categorized with {0}", terms));
        }
Exemple #29
0
        protected override void ConfigureOverride(FilterContext context, ITimestampSerializationOptions options)
        {
            ITimestampStringConverter timestampConverter = TimestampStringConverterResolver.Default.Resolve(options.TimestampFormat);

            context.IO
            .Formats
            .GetOrDefault(FileFormat.JSON)?
            .Configurations
            .Add
            (
                new JsonTimestampSerializationConfiguration(timestampConverter)
            );

            context.IO
            .Formats
            .GetOrDefault(FileFormat.CSV)?
            .Configurations
            .Add
            (
                new CsvTimestampSerializationConfiguration(timestampConverter)
            );
        }
        public void Wrap(FilterContext context)
        {
            ObjectResult objectResult = null;

            switch (context)
            {
            case ResultExecutingContext resultExecutingContext:
                objectResult = resultExecutingContext.Result as ObjectResult;
                break;
            }

            if (objectResult == null)
            {
                throw new ArgumentException("Action Result should be JsonResult!");
            }

            if (!(objectResult.Value is JsonResponseBase))
            {
                objectResult.Value        = new JsonResponse(objectResult.Value);
                objectResult.DeclaredType = typeof(JsonResponse);
            }
        }
Exemple #31
0
        protected virtual bool AuthorizeCore(FilterContext context, object controller)
        {
            if (!context.HttpContext.User.Identity.IsAuthenticated)
            {
                return(false);
            }
            if (Roles.Length == 0)
            {
                return(true);
            }
            var authenticationProvider = context.HttpContext.RequestServices.GetRequiredService <IAuthenticationProvider>();
            var authentication         = authenticationProvider.GetAuthentication();

            if (Mode == AuthenticationRequiredMode.All)
            {
                return(Roles.All(t => authentication.IsInRole(t)));
            }
            else
            {
                return(Roles.Any(t => authentication.IsInRole(t)));
            }
        }
Exemple #32
0
        /// <inheritdoc />
        public FilterContext Create(
            HttpRequest request,
            string criteriaQueryStringKey = QueryStringKeys.Criteria,
            string orderQueryStringKey    = QueryStringKeys.Order,
            string skipQueryStringKey     = QueryStringKeys.Skip,
            string takeQueryStringKey     = QueryStringKeys.Take)
        {
            var result = new FilterContext
            {
                Criterias = this.BuildCriterias(request, criteriaQueryStringKey),
                Orders    = this.BuildOrders(request, orderQueryStringKey),
                Skip      = request?.Query?.FirstOrDefault(p => p.Key.Equals(skipQueryStringKey, StringComparison.OrdinalIgnoreCase)).Value.FirstOrDefault().ToNullableInt(),
                Take      = request?.Query?.FirstOrDefault(p => p.Key.Equals(takeQueryStringKey, StringComparison.OrdinalIgnoreCase)).Value.FirstOrDefault().ToNullableInt()
            };

            if (this.accessor != null)
            {
                this.accessor.Context = result;
            }

            return(result);
        }
Exemple #33
0
        public FilterContext <Mast, FilterMastParam> GetMast(int pageSize = 2, int pageNumber = 1, int?lon = null, int?lat = null)
        {
            IEnumerable <Mast> filterd;

            filterd = dbContext.Masts;
            if (lon != null)
            {
                filterd = filterd.Where(x => x.Lon == lon);
            }
            if (lat != null)
            {
                filterd = filterd.Where(x => x.Lat == lat);
            }
            FilterContext <Mast, FilterMastParam> masts = new FilterContext <Mast, FilterMastParam>(filterd, pageSize, pageNumber);

            masts.FilterParams = new FilterMastParam
            {
                Lat = lat,
                Lon = lon
            };
            return(masts);
        }
Exemple #34
0
        public static string GetActionDescription(FilterContext actionContext)
        {
            var cad = (ControllerActionDescriptor)actionContext.ActionDescriptor;

            var action = cad.ControllerName + "." + cad.ActionName;

            if (cad == null)
            {
                var attr = cad.MethodInfo.GetCustomAttributes(true).OfType <ProfilerActionSplitterAttribute>().FirstOrDefault();
                if (attr != null)
                {
                    var obj = attr.RequestKey == null ? null : actionContext.ActionDescriptor.RouteValues.GetOrThrow(attr.RequestKey, "Argument '{0}' not found in: " + cad.MethodInfo.MethodSignature());

                    if (obj != null)
                    {
                        action += " " + obj.ToString();
                    }
                }
            }

            return(action);
        }
        private static void ResolveActionScopedOverrideFilter(FilterContext filterContext, MethodInfo methodInfo, string metadataKey)
        {
            var filters = filterContext.LifetimeScope.Resolve <IEnumerable <Meta <IOverrideFilter> > >();

            foreach (var filter in filters)
            {
                var metadata = filter.Metadata.TryGetValue(metadataKey, out var metadataAsObject)
                    ? metadataAsObject as FilterMetadata
                    : null;

                if (metadata != null)
                {
                    if (!FilterMatchesAction(filterContext, methodInfo, metadataKey, metadata))
                    {
                        continue;
                    }

                    filterContext.Filters.Add(new FilterInfo(filter.Value, metadata.FilterScope));
                    filterContext.AddedFilters[metadataKey].Add(metadata);
                }
            }
        }
Exemple #36
0
        /// <summary>
        /// Checks action authority, returns false if unauthorized
        /// </summary>
        private bool CheckActionAuthority(RouteMatch match, FilterContext context, HttpResponse response, ActionDescriptor descriptor)
        {
            if (!match.Route.HasActionAuthorizeFilter)
            {
                return(true);
            }

            //check action authorize attribute
            AuthorizeAttribute filter = (AuthorizeAttribute)match.Route.ActionType.GetCustomAttribute(typeof(AuthorizeAttribute));

            if (filter != null)
            {
                filter.VerifyAuthority(Mvc, descriptor, context);
                if (context.Result != null)
                {
                    WriteResponse(response, context.Result);
                    return(false);
                }
            }

            return(true);
        }
Exemple #37
0
        public override Resultset Get(QueryContext queryContext, object[] parameters)
        {
            if (ChildNodes.Count < 1)
                throw new InvalidOperationException();

            Resultset rs = ChildNodes[0].Get(queryContext, parameters);
            FilterContext context = new FilterContext(this, rs, FilterPredicate, queryContext, parameters);
            return new Resultset(rs.RowType, context);
        }
Exemple #38
0
        /// <summary cref="IFilterTarget.GetAttributeValue" />
        public override object GetAttributeValue(
            FilterContext        context,
            NodeId               typeDefinitionId,
            IList<QualifiedName> relativePath,
            uint                 attributeId,
            NumericRange         indexRange)
        {
            if (context == null) throw new ArgumentNullException("context");

            // check type definition.
            if (!Server.TypeTree.IsTypeOf(this.TypeDefinitionId, typeDefinitionId))
            {
                return null;
            }

            // lookup extended properties.
            if (relativePath == null || relativePath.Count == 1)
            {
                object value = null;

                if (m_values.TryGetValue(relativePath[0], out value))
                {
                    return value;
                }
            }

            // read the attribute value.
            DataValue dataValue = ReadAttributeValue(
                context,
                typeDefinitionId,
                relativePath,
                attributeId,
                indexRange);

            if (StatusCode.IsBad(dataValue.StatusCode))
            {
                return dataValue.StatusCode;
            }
                        
            // return the value.
            return dataValue.Value;
        }
 public override bool OnFilter(FilterContext filterContext)
 {
     return Array.Exists(_requestMethods, s => s.Equals(WebAppContext.Request.RequestType,StringComparison.InvariantCultureIgnoreCase));
 }
        /// <summary>
		/// Adds an event to the queue.
		/// </summary>
        public virtual void QueueEvent(IFilterTarget instance, bool bypassFilter)
        {
            if (instance == null) throw new ArgumentNullException("instance");
         
            lock (m_lock)
			{
                // this method should only be called for objects or views. 
                if ((m_typeMask & MonitoredItemTypeMask.Events) == 0)
                {
                    throw new ServiceResultException(StatusCodes.BadInternalError);
                }
                
                // can't do anything if queuing is disabled.
                if (m_events == null)
                {
                    return;
                }

                // check for duplicate instances being reported via multiple paths.
                for (int ii = 0; ii < m_events.Count; ii++)
                {
                    EventFieldList processedEvent = m_events[ii] as EventFieldList;

                    if (processedEvent != null)
                    {
                        if (Object.ReferenceEquals(instance, processedEvent.Handle))
                        {
                            return;
                        }
                    }
                }

                // check for space in the queue.
                if (m_events.Count >= m_queueSize)
                {
                    if (!m_discardOldest)
                    {
                        m_overflow = true;
                        return;
                    }
                }
                
                // construct the context to use for the event filter.
                FilterContext context = new FilterContext(m_server.NamespaceUris, m_server.TypeTree, m_session.PreferredLocales);

                // event filter must be specified.
                EventFilter filter = m_filterToUse as EventFilter;

                if (filter == null)
                {
                    throw new ServiceResultException(StatusCodes.BadInternalError);
                }
                
                // apply filter.
                if (!bypassFilter)
                {
                    if (!filter.WhereClause.Evaluate(context, instance))
                    {
                        return;
                    }
                }
                
                // fetch the event fields.
                EventFieldList fields = GetEventFields(context, filter, instance);
                QueueEvent(fields);
			}
        }
        private void UpdateKeepFilterTurnedOnButtonDepressedState(FilterContext? ADepressButton = null)
        {
            Control[] ControlsArrayStdFltr = pnlFilterControls.Controls.Find(BTN_KEEP_FILTER_TURNED_ON_NAME, false);
            Control[] ControlsArrayExtraFltr = pnlExtraFilterControls.Controls.Find(BTN_KEEP_FILTER_TURNED_ON_NAME, false);

            FKeepFilterTurnedOnButtonDepressed = FilterContext.None;

            // If a 'Keep Filter Turned On' Button is shown: check whether it is checked
            if (ControlsArrayStdFltr.Length != 0)
            {
                if (((CheckBox)ControlsArrayStdFltr[0]).Checked)
                {
                    if (ControlsArrayExtraFltr.Length != 0)
                    {
                        if (((CheckBox)ControlsArrayExtraFltr[0]).Checked)
                        {
                            FKeepFilterTurnedOnButtonDepressed = FilterContext.StandardAndExtraFilter;

                            return;
                        }
                        else
                        {
                            FKeepFilterTurnedOnButtonDepressed = FilterContext.StandardFilterOnly;

                            return;
                        }
                    }
                    else
                    {
                        FKeepFilterTurnedOnButtonDepressed = FilterContext.StandardFilterOnly;

                        return;
                    }
                }
                else
                {
                    if ((ADepressButton != null)
                        && ((ADepressButton == FilterContext.StandardFilterOnly)
                            || (ADepressButton == FilterContext.StandardAndExtraFilter)))
                    {
                        ((CheckBox)ControlsArrayStdFltr[0]).Checked = true;
                    }
                }
            }

            // Now Check the Extra Filter Panel
            ControlsArrayExtraFltr = pnlExtraFilterControls.Controls.Find(BTN_KEEP_FILTER_TURNED_ON_NAME, false);

            // If a 'Keep Filter Turned On' Button is shown: check whether it is checked
            if (ControlsArrayExtraFltr.Length != 0)
            {
                if (((CheckBox)ControlsArrayExtraFltr[0]).Checked)
                {
                    FKeepFilterTurnedOnButtonDepressed = FilterContext.ExtraFilterOnly;

                    return;
                }
                else
                {
                    FKeepFilterTurnedOnButtonDepressed = FilterContext.None;

                    if ((ADepressButton != null)
                        && ((ADepressButton == FilterContext.ExtraFilterOnly)
                            || (ADepressButton == FilterContext.StandardAndExtraFilter)))
                    {
                        ((CheckBox)ControlsArrayExtraFltr[0]).Checked = true;
                    }
                }
            }
        }
 public abstract bool OnFilter(FilterContext filterContext);
        /// <summary>
        /// Switches the 'Keep Filter Turned On' Button to the 'on'/'depressed' state.
        /// </summary>
        /// <param name="AFilterContext">Filter Context in which to switch the Button on.</param>
        public void SwitchOnKeepFilterTurnedOn(FilterContext AFilterContext)
        {
            Control[] ControlsArray = pnlFilterControls.Controls.Find(BTN_KEEP_FILTER_TURNED_ON_NAME, false);

            // If a 'Keep Filter Turned On' Button is shown: check whether it is checked
            if (ControlsArray.Length != 0)
            {
                UpdateKeepFilterTurnedOnButtonDepressedState(AFilterContext);
                FKeepFilterTurnedOnButtonDepressed = AFilterContext;
            }
        }
        /// <summary>
        /// Adds a 'Filter Always Turned On' Label to a Filter Panel (if it isn't already there).
        /// </summary>
        /// <param name="AFilterPanel">The Filter Panel to add the Label to.</param>
        private void AddLabelFilterIsAlwaysTurnedOn(Panel AFilterPanel)
        {
            Control[] ControlsArray;
            Label LblFilterIsAlwaysTurnedOn;

            ControlsArray = AFilterPanel.Controls.Find(LBL_FILTER_IS_ALWAYS_TURNED_ON_NAME, false);

            if (ControlsArray.Length == 0)
            {
                LblFilterIsAlwaysTurnedOn = new Label();
                LblFilterIsAlwaysTurnedOn.Name = LBL_FILTER_IS_ALWAYS_TURNED_ON_NAME;

                LblFilterIsAlwaysTurnedOn.Left = 5;
                LblFilterIsAlwaysTurnedOn.Height = 20;
                LblFilterIsAlwaysTurnedOn.BackColor = System.Drawing.Color.Transparent;
                LblFilterIsAlwaysTurnedOn.Tag = TSingleLineFlow.BeginGroupIndicator;
                LblFilterIsAlwaysTurnedOn.Font = new System.Drawing.Font("Verdana", 8.0f, FontStyle.Italic);
                LblFilterIsAlwaysTurnedOn.Text = Catalog.GetString("Filter Always Turned On");
                LblFilterIsAlwaysTurnedOn.TextAlign = ContentAlignment.MiddleCenter;

                tipGeneral.SetToolTip(LblFilterIsAlwaysTurnedOn, "This filter will be kept active even\r\nwhen the Filter Panel is closed!");

                AFilterPanel.Controls.Add(LblFilterIsAlwaysTurnedOn);

                ControlsArray = AFilterPanel.Controls.Find(BTN_APPLY_FILTER_NAME, false);

                // Ensure that this Control is...
                if (ControlsArray.Length == 0)
                {
                    // ... always the bottommost of the Controls in the Panel in case there is no 'Apply Filter' Button
                    if (AFilterPanel.Controls.GetChildIndex(LblFilterIsAlwaysTurnedOn) != AFilterPanel.Controls.Count - 1)
                    {
                        AFilterPanel.Controls.SetChildIndex(LblFilterIsAlwaysTurnedOn, AFilterPanel.Controls.Count - 1);
                    }
                }
                else
                {
                    // ... always one up from the bottommost of the Controls in the Panel in case there is a 'Apply Filter' Button (which is always the bottommost Control)
                    if (AFilterPanel.Controls.GetChildIndex(LblFilterIsAlwaysTurnedOn) == AFilterPanel.Controls.Count - 1)
                    {
                        ControlsArray[0].Tag = ""; // remove any TSingleLineFlow.BeginGroupIndicator!
                        AFilterPanel.Controls.SetChildIndex(LblFilterIsAlwaysTurnedOn, AFilterPanel.Controls.Count - 2);
//                        AFilterPanel.Refresh();
                    }
                }
            }

            //
            // Ensure that no 'Keep Filter Turned On' Button is left on the Panel as it is mutually exclusive to the 'Filter Always Turned On' Label
            //
            ControlsArray = AFilterPanel.Controls.Find(BTN_KEEP_FILTER_TURNED_ON_NAME, false);

            if (ControlsArray.Length != 0)
            {
                RemoveButtonKeepFilterTurnedOn(AFilterPanel);

                if (FShowKeepFilterTurnedOnButton == FilterContext.StandardAndExtraFilter)
                {
                    if (AFilterPanel == pnlFilterControls)
                    {
                        FShowKeepFilterTurnedOnButton = FilterContext.ExtraFilterOnly;
                    }
                    else
                    {
                        FShowKeepFilterTurnedOnButton = FilterContext.StandardFilterOnly;
                    }
                }
                else if ((FShowKeepFilterTurnedOnButton == FilterContext.StandardFilterOnly)
                         || (FShowKeepFilterTurnedOnButton == FilterContext.ExtraFilterOnly))
                {
                    FShowKeepFilterTurnedOnButton = FilterContext.None;
                }
            }

            UpdateKeepFilterTurnedOnButtonDepressedState();
        }
        /// <summary>
        /// Constructor.
        /// </summary>
        public TUcoFilterAndFind(List <Panel>AFilterControls, List <Panel>AExtraFilterControls, List <Panel>AFindControls,
            FilterContext AShowApplyFilterButton = FilterContext.None,
            FilterContext AShowKeepFilterTurnedOnButton = FilterContext.None,
            FilterContext AShowFilterIsAlwaysOnLabel = FilterContext.None,
            int AWidth = 150)
        {
            //
            // The InitializeComponent() call is required for Windows Forms designer support.
            //
            InitializeComponent();

            FFilterControls = AFilterControls;
            FExtraFilterControls = AExtraFilterControls;
            FFindControls = AFindControls;

            FShowApplyFilterButton = AShowApplyFilterButton;
            FShowKeepFilterTurnedOnButton = AShowKeepFilterTurnedOnButton;
            FShowFilterIsAlwaysTurnedOnLabel = AShowFilterIsAlwaysOnLabel;

            this.Width = AWidth;
            FInitialWidth = AWidth;

            InitUserControlInternal();
        }
 /// <summary>
 /// Constructor.
 /// </summary>
 /// <param name="AFilterAndFindInitialWidth">Initial Width of the Filter and Find Panel.</param>
 /// <param name="AFilterAndFindInitiallyExpanded">Wether the Filter and Find Panel are shown when the containing Form/UserControl
 /// is opened/shown.</param>
 /// <param name="AApplyFilterButtonContext">The context in which an 'Apply Filter' Button is shown (if any).</param>
 /// <param name="AShowKeepFilterTurnedOnButtonContext">The context in which a 'Keep Filter Turned On' Button is shown (if any).</param>
 /// <param name="AShowFilterIsAlwaysOnLabelContext">The context in which a 'Filter Is Always On' Label is shown (if any).</param>
 public FilterAndFindParameters(int AFilterAndFindInitialWidth, bool AFilterAndFindInitiallyExpanded,
     FilterContext AApplyFilterButtonContext, FilterContext AShowKeepFilterTurnedOnButtonContext,
     FilterContext AShowFilterIsAlwaysOnLabelContext)
 {
     FFilterAndFindInitialWidth = AFilterAndFindInitialWidth;
     FFilterAndFindInitiallyExpanded = AFilterAndFindInitiallyExpanded;
     FApplyFilterButtonContext = AApplyFilterButtonContext;
     FShowKeepFilterTurnedOnButtonContext = AShowKeepFilterTurnedOnButtonContext;
     FShowFilterIsAlwaysOnLabelContext = AShowFilterIsAlwaysOnLabelContext;
 }
        /// <summary>
        /// Fetches the event fields from the event.
        /// </summary>
        private EventFieldList GetEventFields(FilterContext context, EventFilter filter, IFilterTarget instance)
        {
            // fetch the event fields.
            EventFieldList fields = new EventFieldList();

            fields.ClientHandle = m_clientHandle;
            fields.Handle = instance;

            foreach (SimpleAttributeOperand clause in filter.SelectClauses)
            {
                // get the value of the attribute (apply localization).
                object value = instance.GetAttributeValue(
                    context, 
                    clause.TypeDefinitionId, 
                    clause.BrowsePath, 
                    clause.AttributeId, 
                    clause.ParsedIndexRange);

                // add the value to the list of event fields.
                if (value != null)
                {
                    // translate any localized text.
                    LocalizedText text = value as LocalizedText;

                    if (text != null)
                    {
                        value = m_server.ResourceManager.Translate(m_session.PreferredLocales, text);
                    }

                    // add value.
                    fields.EventFields.Add(new Variant(value));
                }

                // add a dummy entry for missing values.
                else
                {
                    fields.EventFields.Add(Variant.Null);
                }
            }

            return fields;
        }
        /// <summary>
        /// Adds a 'Keep Filter Turned On' Button to a Filter Panel (if it isn't already there).
        /// </summary>
        /// <param name="AFilterPanel">The Filter Panel to add the Button to.</param>
        private void AddButtonKeepFilterTurnedOn(Panel AFilterPanel)
        {
            Control[] ControlsArray;
            CheckBox BtnKeepFilterTurnedOn;

            ControlsArray = AFilterPanel.Controls.Find(BTN_KEEP_FILTER_TURNED_ON_NAME, false);

            if (ControlsArray.Length == 0)
            {
                BtnKeepFilterTurnedOn = new CheckBox();
                BtnKeepFilterTurnedOn.Name = BTN_KEEP_FILTER_TURNED_ON_NAME;

                BtnKeepFilterTurnedOn.Left = 5;
                BtnKeepFilterTurnedOn.Height = 22;
                BtnKeepFilterTurnedOn.Font = new System.Drawing.Font("Verdana", 8.0f);
                BtnKeepFilterTurnedOn.Text = Catalog.GetString("Kee&p Filter Turned On");
                BtnKeepFilterTurnedOn.Tag = CommonTagString.SUPPRESS_CHANGE_DETECTION + ";" + TSingleLineFlow.BeginGroupIndicator;
                BtnKeepFilterTurnedOn.FlatStyle = FlatStyle.System;               // this is set so that the Button doesn't let the background colour shine through, but uses the system's colours and uses a gradient!
                BtnKeepFilterTurnedOn.Appearance = Appearance.Button;
                BtnKeepFilterTurnedOn.TextAlign = ContentAlignment.MiddleCenter;  // Same as 'real' Button
                BtnKeepFilterTurnedOn.MinimumSize = new Size(75, 22);             // To prevent shrinkage!
                BtnKeepFilterTurnedOn.Click += delegate(object sender, EventArgs e) {
                    OnKeepFilterTurnedOnClicked(sender, e);
                };

                tipGeneral.SetToolTip(BtnKeepFilterTurnedOn, "Depress to keep the filter active\r\neven when the Filter Panel is closed");

                AFilterPanel.Controls.Add(BtnKeepFilterTurnedOn);

                ControlsArray = AFilterPanel.Controls.Find(BTN_APPLY_FILTER_NAME, false);

                // Ensure that this Control is...
                if (ControlsArray.Length == 0)
                {
                    // ... always the bottommost of the Controls in the Panel in case there is no 'Apply Filter' Button
                    if (AFilterPanel.Controls.GetChildIndex(BtnKeepFilterTurnedOn) != AFilterPanel.Controls.Count - 1)
                    {
                        AFilterPanel.Controls.SetChildIndex(BtnKeepFilterTurnedOn, AFilterPanel.Controls.Count - 1);
                    }
                }
                else
                {
                    // ... always one up from the bottommost of the Controls in the Panel in case there is a 'Apply Filter' Button (which is always the bottommost Control)
                    if (AFilterPanel.Controls.GetChildIndex(BtnKeepFilterTurnedOn) == AFilterPanel.Controls.Count - 1)
                    {
                        ControlsArray[0].Tag = ""; // remove any TSingleLineFlow.BeginGroupIndicator!
                        AFilterPanel.Controls.SetChildIndex(BtnKeepFilterTurnedOn, AFilterPanel.Controls.Count - 2);
                    }
                }
            }

            //
            // Ensure that no 'Filter Always Turned On' Label is left on the Panel as it is mutually exclusive to the 'Keep Filter Turned On' Button
            //
            ControlsArray = AFilterPanel.Controls.Find(LBL_FILTER_IS_ALWAYS_TURNED_ON_NAME, false);

            if (ControlsArray.Length != 0)
            {
                RemoveLabelFilterIsAlwaysTurnedOn(AFilterPanel);

                if (FShowFilterIsAlwaysTurnedOnLabel == FilterContext.StandardAndExtraFilter)
                {
                    if (AFilterPanel == pnlFilterControls)
                    {
                        FShowFilterIsAlwaysTurnedOnLabel = FilterContext.ExtraFilterOnly;
                    }
                    else
                    {
                        FShowFilterIsAlwaysTurnedOnLabel = FilterContext.StandardFilterOnly;
                    }
                }
                else if ((FShowFilterIsAlwaysTurnedOnLabel == FilterContext.StandardFilterOnly)
                         || (FShowFilterIsAlwaysTurnedOnLabel == FilterContext.ExtraFilterOnly))
                {
                    FShowFilterIsAlwaysTurnedOnLabel = FilterContext.None;
                }
            }

            UpdateKeepFilterTurnedOnButtonDepressedState();
        }