コード例 #1
0
        public void Constructor_PopulatesFilterCollections()
        {
            // Arrange
            IActionFilter expectedActionFilter = CreateDummyActionFilter();
            IAuthorizationFilter expectedAuthorizationFilter = CreateDummyAuthorizationFilter();
            IAuthenticationFilter expectedAuthenticationFilter = CreateDummyAuthenticationFilter();
            IExceptionFilter expectedExceptionFilter = CreateDummyExceptionFilter();
            IResultFilter expectedResultFilter = CreateDummyResultFilter();

            List<Filter> filters = new List<Filter>()
            {
                CreateFilter(expectedActionFilter),
                CreateFilter(expectedAuthorizationFilter),
                CreateFilter(expectedAuthenticationFilter),
                CreateFilter(expectedExceptionFilter),
                CreateFilter(expectedResultFilter),
            };

            // Act
            FilterInfo filterInfo = new FilterInfo(filters);

            // Assert
            Assert.Same(expectedActionFilter, filterInfo.ActionFilters.SingleOrDefault());
            Assert.Same(expectedAuthorizationFilter, filterInfo.AuthorizationFilters.SingleOrDefault());
            Assert.Same(expectedAuthenticationFilter, filterInfo.AuthenticationFilters.SingleOrDefault());
            Assert.Same(expectedExceptionFilter, filterInfo.ExceptionFilters.SingleOrDefault());
            Assert.Same(expectedResultFilter, filterInfo.ResultFilters.SingleOrDefault());
        }
コード例 #2
0
        public void Constructor_PopulatesFilterCollections()
        {
            // Arrange
            Mock<IActionFilter> actionFilterMock = new Mock<IActionFilter>();
            Mock<IAuthorizationFilter> authorizationFilterMock = new Mock<IAuthorizationFilter>();
            Mock<IExceptionFilter> exceptionFilterMock = new Mock<IExceptionFilter>();
            Mock<IResultFilter> resultFilterMock = new Mock<IResultFilter>();

            List<Filter> filters = new List<Filter>()
            {
                CreateFilter(actionFilterMock),
                CreateFilter(authorizationFilterMock),
                CreateFilter(exceptionFilterMock),
                CreateFilter(resultFilterMock),
            };

            // Act
            FilterInfo filterInfo = new FilterInfo(filters);

            // Assert
            Assert.Equal(actionFilterMock.Object, filterInfo.ActionFilters.SingleOrDefault());
            Assert.Equal(authorizationFilterMock.Object, filterInfo.AuthorizationFilters.SingleOrDefault());
            Assert.Equal(exceptionFilterMock.Object, filterInfo.ExceptionFilters.SingleOrDefault());
            Assert.Equal(resultFilterMock.Object, filterInfo.ResultFilters.SingleOrDefault());
        }
コード例 #3
0
 public object GetAllInfo(int start, int limit, SortInfo[] sort, FilterInfo[] filter)
 {
     return new {
         Root = _tasks.Skip(start).Take(limit).Select(t => new { t.Id, t.Number, t.Title, t.Description, t.State }),
         Total = _tasks.Count()
     };
 }
コード例 #4
0
 public FilterInfo SaveFilter(FilterInfo objFilter) {
     if (objFilter.FilterId > 0) {
        UpdateFilter(objFilter);
     } else {
        objFilter.FilterId = AddFilter(objFilter);
     }
     return GetFilter(objFilter.FilterId);
 }
        public void GetFilters_should_merge_filters_in_correct_order()
        {
            var controller = new FakeController();

            var decoratedAuthorizationFilter = new DummyFilter1{ Order = 2 };
            var decoratedActionFilter = new DummyFilter2{ Order = 2 };
            var decoratedResultFilter = new DummyFilter3{ Order = 2 };
            var decoratedExceptionFilter = new DummyFilter4{ Order = 2 };

            var decoratedFilters = new FilterInfo();

            decoratedFilters.AuthorizationFilters.Add(decoratedAuthorizationFilter);
            decoratedFilters.ActionFilters.Add(decoratedActionFilter);
            decoratedFilters.ResultFilters.Add(decoratedResultFilter);
            decoratedFilters.ExceptionFilters.Add(decoratedExceptionFilter);

            decoratedFilters.AuthorizationFilters.Add(controller);
            decoratedFilters.ActionFilters.Add(controller);
            decoratedFilters.ResultFilters.Add(controller);
            decoratedFilters.ExceptionFilters.Add(controller);

            var actionDescriptor = new Mock<ActionDescriptor>();
            actionDescriptor.Setup(ad => ad.GetFilters()).Returns(decoratedFilters);

            var registeredAuthorizationFilter = new DummyFilter5 { Order = 1 };
            var registeredActionFilter = new DummyFilter6 { Order = 1 };
            var registeredResultFilter = new DummyFilter7{ Order = 1 };
            var registeredExceptionFilter = new DummyFilter8{ Order = 1 };

            var registeredFilters = new FilterInfo();

            registeredFilters.AuthorizationFilters.Add(registeredAuthorizationFilter);
            registeredFilters.ActionFilters.Add(registeredActionFilter);
            registeredFilters.ResultFilters.Add(registeredResultFilter);
            registeredFilters.ExceptionFilters.Add(registeredExceptionFilter);

            filterRegistry.Setup(fr => fr.Matching(It.IsAny<ControllerContext>(), It.IsAny<ActionDescriptor>())).Returns(registeredFilters);

            var controllerContext = new ControllerContext(new RequestContext(new Mock<HttpContextBase>().Object, new RouteData()), new Mock<ControllerBase>().Object);

            var mergedFilters = controllerActionInvoker.PublicGetFilters(controllerContext, actionDescriptor.Object);

            Assert.Same(controller, mergedFilters.AuthorizationFilters[0]);
            Assert.Same(registeredAuthorizationFilter, mergedFilters.AuthorizationFilters[1]);
            Assert.Same(decoratedAuthorizationFilter, mergedFilters.AuthorizationFilters[2]);

            Assert.Same(controller, mergedFilters.ActionFilters[0]);
            Assert.Same(registeredActionFilter, mergedFilters.ActionFilters[1]);
            Assert.Same(decoratedActionFilter, mergedFilters.ActionFilters[2]);

            Assert.Same(controller, mergedFilters.ResultFilters[0]);
            Assert.Same(registeredResultFilter, mergedFilters.ResultFilters[1]);
            Assert.Same(decoratedResultFilter, mergedFilters.ResultFilters[2]);

            Assert.Same(controller, mergedFilters.ExceptionFilters[0]);
            Assert.Same(registeredExceptionFilter, mergedFilters.ExceptionFilters[1]);
            Assert.Same(decoratedExceptionFilter, mergedFilters.ExceptionFilters[2]);
        }
コード例 #6
0
        public static FilterInfo MergedWith(this FilterInfo target, FilterInfo source)
        {
            source.ActionFilters.ForEach(filter => target.ActionFilters.Add(filter));
            source.AuthorizationFilters.ForEach(filter => target.AuthorizationFilters.Add(filter));
            source.ResultFilters.ForEach(filter => target.ResultFilters.Add(filter));
            source.ExceptionFilters.ForEach(filter => target.ExceptionFilters.Add(filter));

            return target;
        }
コード例 #7
0
        public void Constructor_Default() {
            // Arrange + Act
            FilterInfo filterInfo = new FilterInfo();

            // Assert
            Assert.AreEqual(0, filterInfo.ActionFilters.Count);
            Assert.AreEqual(0, filterInfo.AuthorizationFilters.Count);
            Assert.AreEqual(0, filterInfo.ExceptionFilters.Count);
            Assert.AreEqual(0, filterInfo.ResultFilters.Count);
        }
コード例 #8
0
        public void Constructor_IteratesOverFiltersOnlyOnce() {
            // Arrange
            var filtersMock = new Mock<IEnumerable<Filter>>();
            filtersMock.Setup(f => f.GetEnumerator()).Returns(new List<Filter>().GetEnumerator());

            // Act
            FilterInfo filterInfo = new FilterInfo(filtersMock.Object);

            // Assert
            filtersMock.Verify(f => f.GetEnumerator(), Times.Once());
        }
コード例 #9
0
        public void Constructor_Default()
        {
            // Arrange + Act
            FilterInfo filterInfo = new FilterInfo();

            // Assert
            Assert.Empty(filterInfo.ActionFilters);
            Assert.Empty(filterInfo.AuthorizationFilters);
            Assert.Empty(filterInfo.ExceptionFilters);
            Assert.Empty(filterInfo.ResultFilters);
        }
コード例 #10
0
ファイル: FilterInfoTests.cs プロジェクト: mparsin/Elements
        public void FilterInfo_CreateNewInstance_PropertiesAreSet()
        {
            const string XmlValue = "<test></test>";
            TextReader txt = new StringReader(XmlValue);
            XmlReader reader = new XmlTextReader(txt);
            var dto = new FilterDto { FilterDefinition = new SqlXml(reader), Id = 1, Name = "name", ProcessId = 2 };
            var filter = new FilterInfo(dto);

            Assert.AreEqual(dto.Id, filter.Id);
            Assert.AreEqual(dto.Name, filter.Name);
            Assert.AreEqual(dto.FilterDefinition.Value, filter.FilterDefinition);
        }
コード例 #11
0
ファイル: FilterTab.cs プロジェクト: lgatto/proteowizard
 private void SetFilterInfo(DataGridViewRow row, FilterInfo filterInfo)
 {
     if (filterInfo.ColumnDescriptor == null)
     {
         row.Cells[colFilterColumn.Index].Value = filterInfo.FilterSpec.Column;
         row.Cells[colFilterColumn.Index].Style.Font = new Font(dataGridViewFilter.Font, FontStyle.Strikeout);
         row.Cells[colFilterColumn.Index].ToolTipText = Resources.CustomizeViewForm_SetFilterInfo_This_column_does_not_exist;
     }
     else
     {
         row.Cells[colFilterColumn.Index].Value = filterInfo.ColumnDescriptor.GetColumnCaption(ColumnCaptionType.localized);
         row.Cells[colFilterColumn.Index].Style.Font = dataGridViewFilter.Font;
         row.Cells[colFilterColumn.Index].ToolTipText = null;
     }
     var filterOpCell = (DataGridViewComboBoxCell)row.Cells[colFilterOperation.Index];
     row.Cells[colFilterOperand.Index].Value = filterInfo.FilterSpec.Operand;
     filterOpCell.Value = filterInfo.FilterSpec.Operation.DisplayName;
     var filterOpItems = FilterOperations.ListOperations()
         .Where(filterOp => filterOp == filterInfo.FilterSpec.Operation
                            || filterInfo.ColumnDescriptor == null
                            || filterOp.IsValidFor(filterInfo.ColumnDescriptor))
         .Select(filterOp => filterOp.DisplayName)
         .ToArray();
     filterOpCell.DataSource = filterOpItems;
     if (filterInfo.FilterSpec.Operation.GetOperandType(filterInfo.ColumnDescriptor) == null)
     {
         row.Cells[colFilterOperand.Index].ReadOnly = true;
         row.Cells[colFilterOperand.Index].Style.BackColor = Color.DarkGray;
     }
     else
     {
         row.Cells[colFilterOperand.Index].ReadOnly = false;
         row.Cells[colFilterOperand.Index].Style.BackColor = colFilterOperand.DefaultCellStyle.BackColor;
     }
     foreach (DataGridViewCell cell in row.Cells)
     {
         if (filterInfo.Error != null)
         {
             cell.Style.BackColor = Color.Red;
             cell.ToolTipText = filterInfo.Error;
         }
         else
         {
             cell.Style.BackColor = dataGridViewFilter.DefaultCellStyle.BackColor;
             cell.ToolTipText = null;
         }
     }
 }
コード例 #12
0
ファイル: ModuleUtils.cs プロジェクト: 40a/PowerShell
        /// <summary>
        /// Gets a list of matching commands
        /// </summary>
        /// <param name="pattern">command pattern</param>
        /// <param name="commandOrigin"></param>
        /// <param name="context"></param>
        /// <param name="rediscoverImportedModules"></param>
        /// <param name="moduleVersionRequired"></param>
        /// <returns></returns>
        internal static IEnumerable<CommandInfo> GetMatchingCommands(string pattern, ExecutionContext context, CommandOrigin commandOrigin, bool rediscoverImportedModules = false, bool moduleVersionRequired = false)
        {
            // Otherwise, if it had wildcards, just return the "AvailableCommand"
            // type of command info.
            WildcardPattern commandPattern = WildcardPattern.Get(pattern, WildcardOptions.IgnoreCase);

            CmdletInfo cmdletInfo = context.SessionState.InvokeCommand.GetCmdlet("Microsoft.PowerShell.Core\\Get-Module");
            PSModuleAutoLoadingPreference moduleAutoLoadingPreference = CommandDiscovery.GetCommandDiscoveryPreference(context, SpecialVariables.PSModuleAutoLoadingPreferenceVarPath, "PSModuleAutoLoadingPreference");

            if ((moduleAutoLoadingPreference != PSModuleAutoLoadingPreference.None) &&
                    ((commandOrigin == CommandOrigin.Internal) || ((cmdletInfo != null) && (cmdletInfo.Visibility == SessionStateEntryVisibility.Public))
                    )
                )
            {
                foreach (string modulePath in GetDefaultAvailableModuleFiles(true, false, context))
                {
                    // Skip modules that have already been loaded so that we don't expose private commands.
                    string moduleName = Path.GetFileNameWithoutExtension(modulePath);
                    var modules = context.Modules.GetExactMatchModules(moduleName, all: false, exactMatch: true);
                    PSModuleInfo tempModuleInfo = null;

                    if (modules.Count != 0)
                    {
                        // 1. We continue to the next module path if we don't want to re-discover those imported modules
                        // 2. If we want to re-discover the imported modules, but one or more commands from the module were made private, 
                        //    then we don't do re-discovery
                        if (!rediscoverImportedModules || modules.Exists(module => module.ModuleHasPrivateMembers))
                        {
                            continue;
                        }

                        if (modules.Count == 1)
                        {
                            PSModuleInfo psModule = modules[0];
                            tempModuleInfo = new PSModuleInfo(psModule.Name, psModule.Path, null, null);
                            tempModuleInfo.SetModuleBase(psModule.ModuleBase);

                            foreach (var entry in psModule.ExportedCommands)
                            {
                                if (commandPattern.IsMatch(entry.Value.Name))
                                {
                                    CommandInfo current = null;
                                    switch (entry.Value.CommandType)
                                    {
                                        case CommandTypes.Alias:
                                            current = new AliasInfo(entry.Value.Name, null, context);
                                            break;
                                        case CommandTypes.Workflow:
                                            current = new WorkflowInfo(entry.Value.Name, ScriptBlock.EmptyScriptBlock, context);
                                            break;
                                        case CommandTypes.Function:
                                            current = new FunctionInfo(entry.Value.Name, ScriptBlock.EmptyScriptBlock, context);
                                            break;
                                        case CommandTypes.Filter:
                                            current = new FilterInfo(entry.Value.Name, ScriptBlock.EmptyScriptBlock, context);
                                            break;
                                        case CommandTypes.Configuration:
                                            current = new ConfigurationInfo(entry.Value.Name, ScriptBlock.EmptyScriptBlock, context);
                                            break;
                                        case CommandTypes.Cmdlet:
                                            current = new CmdletInfo(entry.Value.Name, null, null, null, context);
                                            break;
                                        default:
                                            Dbg.Assert(false, "cannot be hit");
                                            break;
                                    }

                                    current.Module = tempModuleInfo;
                                    yield return current;
                                }
                            }

                            continue;
                        }
                    }

                    string moduleShortName = System.IO.Path.GetFileNameWithoutExtension(modulePath);
                    var exportedCommands = AnalysisCache.GetExportedCommands(modulePath, false, context);

                    if (exportedCommands == null) { continue; }

                    tempModuleInfo = new PSModuleInfo(moduleShortName, modulePath, null, null);
                    if (InitialSessionState.IsEngineModule(moduleShortName))
                    {
                        tempModuleInfo.SetModuleBase(Utils.GetApplicationBase(Utils.DefaultPowerShellShellID));
                    }

                    //moduleVersionRequired is bypassed by FullyQualifiedModule from calling method. This is the only place where guid will be involved.
                    if (moduleVersionRequired && modulePath.EndsWith(StringLiterals.PowerShellDataFileExtension, StringComparison.OrdinalIgnoreCase))
                    {
                        tempModuleInfo.SetVersion(ModuleIntrinsics.GetManifestModuleVersion(modulePath));
                        tempModuleInfo.SetGuid(ModuleIntrinsics.GetManifestGuid(modulePath));
                    }

                    foreach (var pair in exportedCommands)
                    {
                        var commandName = pair.Key;
                        var commandTypes = pair.Value;

                        if (commandPattern.IsMatch(commandName))
                        {
                            bool shouldExportCommand = true;

                            // Verify that we don't already have it represented in the initial session state.
                            if ((context.InitialSessionState != null) && (commandOrigin == CommandOrigin.Runspace))
                            {
                                foreach (SessionStateCommandEntry commandEntry in context.InitialSessionState.Commands[commandName])
                                {
                                    string moduleCompareName = null;

                                    if (commandEntry.Module != null)
                                    {
                                        moduleCompareName = commandEntry.Module.Name;
                                    }
                                    else if (commandEntry.PSSnapIn != null)
                                    {
                                        moduleCompareName = commandEntry.PSSnapIn.Name;
                                    }

                                    if (String.Equals(moduleShortName, moduleCompareName, StringComparison.OrdinalIgnoreCase))
                                    {
                                        if (commandEntry.Visibility == SessionStateEntryVisibility.Private)
                                        {
                                            shouldExportCommand = false;
                                        }
                                    }
                                }
                            }

                            if (shouldExportCommand)
                            {
                                if ((commandTypes & CommandTypes.Alias) == CommandTypes.Alias)
                                {
                                    yield return new AliasInfo(commandName, null, context)
                                    {
                                        Module = tempModuleInfo
                                    };
                                }
                                if ((commandTypes & CommandTypes.Cmdlet) == CommandTypes.Cmdlet)
                                {
                                    yield return new CmdletInfo(commandName, implementingType: null, helpFile: null, PSSnapin: null, context: context)
                                    {
                                        Module = tempModuleInfo
                                    };
                                }
                                if ((commandTypes & CommandTypes.Function) == CommandTypes.Function)
                                {
                                    yield return new FunctionInfo(commandName, ScriptBlock.EmptyScriptBlock, context)
                                    {
                                        Module = tempModuleInfo
                                    };
                                }
                                if ((commandTypes & CommandTypes.Configuration) == CommandTypes.Configuration)
                                {
                                    yield return new ConfigurationInfo(commandName, ScriptBlock.EmptyScriptBlock, context)
                                    {
                                        Module = tempModuleInfo
                                    };
                                }
                                if ((commandTypes & CommandTypes.Workflow) == CommandTypes.Workflow)
                                {
                                    yield return new WorkflowInfo(commandName, ScriptBlock.EmptyScriptBlock, context)
                                    {
                                        Module = tempModuleInfo
                                    };
                                }
                            }
                        }
                    }
                }
            }
        }
コード例 #13
0
        public void AccessPointEnabledEventTest()
        {
            EndpointReferenceType subscriptionReference = null;

            System.DateTime subscribeStarted = System.DateTime.MaxValue;

            int timeout = 60;

            RunTest(
                () =>
            {
                // Topic for current test
                // tns1:AccessPoint/State/Enabled
                TopicInfo topicInfo = ConstructTopic(new string[] { "AccessPoint", "State", "Enabled" });

                //3.	Get complete list of access points from the DUT (see Annex A.1).
                List <AccessPointInfo> fullAccessPointsList = GetAccessPointInfoList();

                List <AccessPointInfo> accessPoints =
                    fullAccessPointsList.Where(A => A.Capabilities != null && A.Capabilities.DisableAccessPoint).ToList();

                //4.	ONVIF Client will invoke GetEventPropertiesRequest message to retrieve all events supported by the DUT.
                //5.	Verify the GetEventPropertiesResponse message from the DUT.
                //6.	Check if there is an event with Topic tns1:AccessControl/AccessPoint/Enabled. If there is no event with such Topic skip other steps, fail the test and go to the next test.
                // Get topic description from the DUT.
                XmlElement topicElement = GetTopicElement(topicInfo);

                Assert(topicElement != null,
                       string.Format("Topic {0} not supported", topicInfo.GetDescription()),
                       "Check that the event topic is supported");

                //7.	Check that this event is a Property event (MessageDescription.IsProperty="true").
                //8.	Check that this event contains Source.SimpleItemDescription item with Name="AccessPointToken" and Type="pt:ReferenceToken".
                //9.	Check that this event contains Data.SimpleItemDescription item with Name="Enabled" and Type=" xs:boolean".
                //10.	Check that this event contains Data.SimpleItemDescription item with Name="Reason" and Type=" xs:string".

                XmlElement messageDescription = topicElement.GetMessageDescription();
                ValidateAccessPointEnabledTopic(messageDescription, topicInfo);

                FilterInfo filter = CreateFilter(topicInfo, messageDescription);

                //11.	ONVIF Client will invoke SubscribeRequest message with tns1:AccessControl/AccessPoint/Enabled Topic as Filter and an InitialTerminationTime of 60s to ensure that the SubscriptionManager is deleted after one minute.
                //12.	Verify that the DUT sends a SubscribeResponse message.

                //13.	Verify that DUT sends Notify message(s)

                Dictionary <NotificationMessageHolderType, XmlElement> notifications = new Dictionary <NotificationMessageHolderType, XmlElement>();

                subscriptionReference =
                    ReceiveMessages(filter.Filter,
                                    timeout,
                                    new Action(() => { }),
                                    fullAccessPointsList.Count,
                                    notifications,
                                    out subscribeStarted);

                //14.	Verify received Notify messages  (correct value for UTC time, TopicExpression and wsnt:Message).
                //15.	Verify that TopicExpression is equal to tns1:AccessControl/AccessPoint/Enabled
                // for all received Notify messages.
                //16.	Verify that each notification contains Source.SimpleItem item with Name="AccessPointToken"
                // and Value is equal to one of existing Access Point Tokens (e.g. complete list of access points contains Access Point with the same token). Verify that there are Notification messages for each Access Point.
                //17.	Verify that each notification contains Data.SimpleItem item with Name="Enabled" and
                // Value with type is equal to xs:boolean.
                //18.	Verify that each notification which contains Data.SimpleItem item with Name="Reason" contains
                // Value with type is equal to xs:string.
                //19.	Verify that Notify PropertyOperation="Initialized".

                ValidateMessages(notifications, topicInfo, OnvifMessage.INITIALIZED, accessPoints, ValidateAccessPointEnabledMessage);

                Dictionary <string, NotificationMessageHolderType> accessPointsMessages = new Dictionary <string, NotificationMessageHolderType>();
                ValidateMessagesSet(notifications.Keys, accessPoints, accessPointsMessages);

                //20.	ONVIF Client will invoke GetAccessPointStateRequest message for each Access Point
                // with corresponding tokens.
                //21.	Verify the GetAccessPointStateResponse messages from the DUT. Verify that Data.SimpleItem
                // item with Name="Enabled" from Notification message has the same value with Enabled elements
                // from corresponding GetAccessPointStateResponse messages for each AccessPoint.

                foreach (string accessPointToken in accessPointsMessages.Keys)
                {
                    AccessPointState state = GetAccessPointState(accessPointToken);

                    string expectedState = state.Enabled.ToString().ToLower();

                    XmlElement messageElement = accessPointsMessages[accessPointToken].Message;

                    // Simple Items must be OK by that moment
                    Dictionary <string, string> dataSimpleItems = messageElement.GetMessageDataSimpleItems();

                    string notificationState = dataSimpleItems["State"];

                    Assert(expectedState == notificationState,
                           string.Format("State is different ({0} in GetAccessPointStateResponse, {1} in Notification)", expectedState, notificationState),
                           "Check that state is the same in Notification and in GetAccessPointStateResponse");
                }
            },
                () =>
            {
                ReleaseSubscription(subscribeStarted, subscriptionReference, timeout);
            });
        }
コード例 #14
0
ファイル: FilterInfo.cs プロジェクト: 40a/PowerShell
        } // FilterInfo ctor

        /// <summary>
        /// This is a copy constructor, used primarily for get-command.
        /// </summary>
        internal FilterInfo(FilterInfo other)
            : base(other)
        {
        }
コード例 #15
0
ファイル: FilterInfo.cs プロジェクト: 40a/PowerShell
 /// <summary>
 /// Create a copy of commandInfo for GetCommandCommand so that we can generate parameter
 /// sets based on an argument list (so we can get the dynamic parameters.)
 /// </summary>
 internal override CommandInfo CreateGetCommandCopy(object[] arguments)
 {
     FilterInfo copy = new FilterInfo(this);
     copy.IsGetCommandCopy = true;
     copy.Arguments = arguments;
     return copy;
 }
コード例 #16
0
 public async void BeginDelayFilter()
 {
     var text = this.FilterText;
     await Task.Delay(400);
     if (text == this.filterText)
     {
         this.filter = new FilterInfo(this.IsOnlyTracking, this.FilterText);
         this.VideosView.View.Refresh();
     }
 }
コード例 #17
0
        /// <summary>
        /// 查询模型列表并分页SQL语句
        /// </summary>
        /// <param name="pageIndex">页码</param>
        /// <param name="pageSize">每页记录数</param>
        /// <param name="parameters">参数</param>
        /// <param name="filter">筛选</param>
        /// <param name="propertyNames">属性名称集合</param>
        /// <returns>SQL语句</returns>
        protected override string SelectPageSql(int pageIndex, int pageSize, out DynamicParameters parameters, FilterInfo filter = null, string[] propertyNames = null)
        {
            StringBuilder whereSql = MergeWhereSql(filter, out parameters);
            string        sortSql  = GetSelectPageSortSql(filter, GetSelectSortNamePfx(filter));

            return($"{SelectSql(appendFieldSqls: AppendSelectPageFieldsSql(), propertyNames: propertyNames)} {GetSelectPageJoinSql(parameters, filter)} {whereSql.ToString()} {sortSql} {GetPartPageSql(pageIndex, pageSize)}");
        }
コード例 #18
0
 /// <summary>
 /// 过滤信息前
 /// </summary>
 /// <param name="filter">过滤</param>
 protected virtual void BeforeFilterInfo(FilterInfo filter)
 {
 }
コード例 #19
0
 protected BaseFilterGroup(IToken groupToken, IDependency[] dependencies, FilterInfo info) 
     : base(info)
 {
     GroupDependencies = dependencies;
     NodeToken = groupToken;
 }
コード例 #20
0
        /// <summary>
        /// 查询模型列表并分页
        /// </summary>
        /// <param name="pageIndex">页码</param>
        /// <param name="pageSize">每页记录数</param>
        /// <param name="propertyNames">属性名称集合</param>
        /// <param name="filter">筛选</param>
        /// <param name="connectionId">连接ID</param>
        /// <returns>分页信息</returns>
        public virtual PagingInfo <ModelT> SelectPage(int pageIndex, int pageSize, string[] propertyNames, FilterInfo filter = null, string connectionId = null)
        {
            BeforeFilterInfo(filter);
            PagingInfo <ModelT> result = null;

            DbConnectionManager.BrainpowerExecute(connectionId, this, (connId, dbConn) =>
            {
                result = SelectPage(pageIndex, pageSize, dbConn, filter, GetDbTransaction(connId, AccessMode.SLAVE), propertyNames);
            }, AccessMode.SLAVE);

            return(result);
        }
コード例 #21
0
 /// <summary>
 /// 查询模型列表并分页
 /// </summary>
 /// <param name="pageIndex">页码</param>
 /// <param name="pageSize">每页记录数</param>
 /// <param name="dbConnection">数据库连接</param>
 /// <param name="filter">筛选</param>
 /// <param name="dbTransaction">数据库事务</param>
 /// <param name="propertyNames">属性名称集合</param>
 /// <returns>分页信息</returns>
 protected abstract PagingInfo <ModelT> SelectPage(int pageIndex, int pageSize, IDbConnection dbConnection, FilterInfo filter = null, IDbTransaction dbTransaction = null, string[] propertyNames = null);
コード例 #22
0
        public virtual IAsyncResult BeginInvokeAction(
            ControllerContext controllerContext,
            string actionName,
            AsyncCallback callback,
            object state
            )
        {
            if (controllerContext == null)
            {
                throw new ArgumentNullException("controllerContext");
            }

            Contract.Assert(controllerContext.RouteData != null);
            if (
                String.IsNullOrEmpty(actionName) &&
                !controllerContext.RouteData.HasDirectRouteMatch()
                )
            {
                throw Error.ParameterCannotBeNullOrEmpty("actionName");
            }

            ControllerDescriptor controllerDescriptor = GetControllerDescriptor(controllerContext);
            ActionDescriptor     actionDescriptor     = FindAction(
                controllerContext,
                controllerDescriptor,
                actionName
                );

            if (actionDescriptor != null)
            {
                FilterInfo filterInfo   = GetFilters(controllerContext, actionDescriptor);
                Action     continuation = null;

                BeginInvokeDelegate beginDelegate = delegate(
                    AsyncCallback asyncCallback,
                    object asyncState
                    )
                {
                    try
                    {
                        AuthenticationContext authenticationContext = InvokeAuthenticationFilters(
                            controllerContext,
                            filterInfo.AuthenticationFilters,
                            actionDescriptor
                            );
                        if (authenticationContext.Result != null)
                        {
                            // An authentication filter signaled that we should short-circuit the request. Let all
                            // authentication filters contribute to an action result (to combine authentication
                            // challenges). Then, run this action result.
                            AuthenticationChallengeContext challengeContext =
                                InvokeAuthenticationFiltersChallenge(
                                    controllerContext,
                                    filterInfo.AuthenticationFilters,
                                    actionDescriptor,
                                    authenticationContext.Result
                                    );
                            continuation = () =>
                                           InvokeActionResult(
                                controllerContext,
                                challengeContext.Result ?? authenticationContext.Result
                                );
                        }
                        else
                        {
                            AuthorizationContext authorizationContext = InvokeAuthorizationFilters(
                                controllerContext,
                                filterInfo.AuthorizationFilters,
                                actionDescriptor
                                );
                            if (authorizationContext.Result != null)
                            {
                                // An authorization filter signaled that we should short-circuit the request. Let all
                                // authentication filters contribute to an action result (to combine authentication
                                // challenges). Then, run this action result.
                                AuthenticationChallengeContext challengeContext =
                                    InvokeAuthenticationFiltersChallenge(
                                        controllerContext,
                                        filterInfo.AuthenticationFilters,
                                        actionDescriptor,
                                        authorizationContext.Result
                                        );
                                continuation = () =>
                                               InvokeActionResult(
                                    controllerContext,
                                    challengeContext.Result ?? authorizationContext.Result
                                    );
                            }
                            else
                            {
                                if (controllerContext.Controller.ValidateRequest)
                                {
                                    ValidateRequest(controllerContext);
                                }

                                IDictionary <string, object> parameters = GetParameterValues(
                                    controllerContext,
                                    actionDescriptor
                                    );
                                IAsyncResult asyncResult = BeginInvokeActionMethodWithFilters(
                                    controllerContext,
                                    filterInfo.ActionFilters,
                                    actionDescriptor,
                                    parameters,
                                    asyncCallback,
                                    asyncState
                                    );
                                continuation = () =>
                                {
                                    ActionExecutedContext postActionContext =
                                        EndInvokeActionMethodWithFilters(asyncResult);
                                    // The action succeeded. Let all authentication filters contribute to an action
                                    // result (to combine authentication challenges; some authentication filters need
                                    // to do negotiation even on a successful result). Then, run this action result.
                                    AuthenticationChallengeContext challengeContext =
                                        InvokeAuthenticationFiltersChallenge(
                                            controllerContext,
                                            filterInfo.AuthenticationFilters,
                                            actionDescriptor,
                                            postActionContext.Result
                                            );
                                    InvokeActionResultWithFilters(
                                        controllerContext,
                                        filterInfo.ResultFilters,
                                        challengeContext.Result ?? postActionContext.Result
                                        );
                                };
                                return(asyncResult);
                            }
                        }
                    }
                    catch (ThreadAbortException)
                    {
                        // This type of exception occurs as a result of Response.Redirect(), but we special-case so that
                        // the filters don't see this as an error.
                        throw;
                    }
                    catch (Exception ex)
                    {
                        // something blew up, so execute the exception filters
                        ExceptionContext exceptionContext = InvokeExceptionFilters(
                            controllerContext,
                            filterInfo.ExceptionFilters,
                            ex
                            );
                        if (!exceptionContext.ExceptionHandled)
                        {
                            throw;
                        }

                        continuation = () =>
                                       InvokeActionResult(controllerContext, exceptionContext.Result);
                    }

                    return(BeginInvokeAction_MakeSynchronousAsyncResult(asyncCallback, asyncState));
                };

                EndInvokeDelegate <bool> endDelegate = delegate(IAsyncResult asyncResult)
                {
                    try
                    {
                        continuation();
                    }
                    catch (ThreadAbortException)
                    {
                        // This type of exception occurs as a result of Response.Redirect(), but we special-case so that
                        // the filters don't see this as an error.
                        throw;
                    }
                    catch (Exception ex)
                    {
                        // something blew up, so execute the exception filters
                        ExceptionContext exceptionContext = InvokeExceptionFilters(
                            controllerContext,
                            filterInfo.ExceptionFilters,
                            ex
                            );
                        if (!exceptionContext.ExceptionHandled)
                        {
                            throw;
                        }
                        InvokeActionResult(controllerContext, exceptionContext.Result);
                    }

                    return(true);
                };

                return(AsyncResultWrapper.Begin(
                           callback,
                           state,
                           beginDelegate,
                           endDelegate,
                           _invokeActionTag
                           ));
            }
            else
            {
                // Notify the controller that no action was found.
                return(BeginInvokeAction_ActionNotFound(callback, state));
            }
        }
コード例 #23
0
        public List <Module> Find(int skip = 0, int?take = null, List <SortingInfo> sortings = null, FilterInfo filters = null, string filterLogic = null)
        {
            IQueryable <Module> modules = context.Modules;

            if (filters != null && (filters.Filters != null && filters.Filters.Count > 0))
            {
                filters.FormatFieldToUnderscore();
                GridHelper.ProcessFilters <Business.Entities.Module>(filters, ref modules);
            }

            if (sortings != null && sortings.Count > 0)
            {
                foreach (var s in sortings)
                {
                    string sortOn = this.MapSort(s.SortOn);
                    modules = modules.OrderBy(sortOn + " " + s.SortOrder);
                }
            }
            else
            {
                modules = modules.OrderBy("ModuleName asc");
            }

            var takeModules = modules;

            if (take != null)
            {
                takeModules = modules.Skip(skip).Take((int)take);
            }

            List <Module> moduleList = takeModules.ToList();

            return(moduleList);
        }
コード例 #24
0
 public FilterInfoItem(FilterInfo filterInfo)
 {
     this.FilterInfo = filterInfo;
 }
コード例 #25
0
        public List <MonitoringVehicle> FindAll(int?skip = null, int?take = null, List <SortingInfo> sortings = null, FilterInfo filters = null)
        {
            IQueryable <MonitoringVehicle> list = context.MonitoringVehicle;

            if (filters != null && (filters.Filters != null && filters.Filters.Count > 0))
            {
                GridHelper.ProcessFilters <MonitoringVehicle>(filters, ref list);
            }

            if (sortings != null && sortings.Count > 0)
            {
                foreach (var s in sortings)
                {
                    list = list.OrderBy <MonitoringVehicle>(s.SortOn + " " + s.SortOrder);
                }
            }
            else
            {
                list = list.OrderBy <MonitoringVehicle>("VehicleNo"); //default, wajib ada atau EF error
            }

            //take & skip
            var takeList = list;

            if (skip != null && skip != 0)
            {
                takeList = takeList.Skip(skip.Value);
            }
            if (take != null && take != 0)
            {
                takeList = takeList.Take(take.Value);
            }
            //return result
            //var sql = takeList.ToString();
            List <MonitoringVehicle> result = takeList.ToList();

            return(result);
        }
コード例 #26
0
        /// <summary>
        /// 异步查询模型列表并分页
        /// </summary>
        /// <param name="pageIndex">页码</param>
        /// <param name="pageSize">每页记录数</param>
        /// <param name="propertyNames">属性名称集合</param>
        /// <param name="connectionId">连接ID</param>
        /// <param name="filter">筛选</param>
        /// <param name="comData">通用数据</param>
        /// <returns>分页信息任务</returns>
        public virtual Task <PagingInfo <ModelT> > SelectPageAsync(int pageIndex, int pageSize, string[] propertyNames, ref string connectionId, FilterInfo filter = null, CommonUseData comData = null)
        {
            Task <PagingInfo <ModelT> > task = null;

            DbConnectionManager.BrainpowerExecuteAsync(ref connectionId, this, (connId, isClose, dbConn) =>
            {
                task = ExecAsync <PagingInfo <ModelT> >(connId, isClose, dbConn, (dbTrans) =>
                {
                    return(SelectPage(pageIndex, pageSize, dbConn, filter, propertyNames: propertyNames, dbTransaction: dbTrans, comData: comData));
                }, AccessMode.SLAVE);
            }, accessMode: AccessMode.SLAVE);

            return(task);
        }
コード例 #27
0
 private void DisplayProperties(FilterInfo filterInfo)
 {
     this._eventAggregator.GetEvent <FilterInfoSelectedEvent>().Publish(filterInfo);
 }
コード例 #28
0
        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            try
            {
                if (bindingContext.ModelType != typeof(GridQuery))
                {
                    return(false);
                }
                var request = controllerContext.HttpContext.Request;

                GridQuery model = new GridQuery();
                foreach (string key in request.QueryString.Keys)
                {
                    if (!model.PostData.ContainsKey(key))
                    {
                        model.PostData.Add(key, request.QueryString[key]);
                    }
                }
                foreach (string key in request.Form)
                {
                    if (!model.PostData.ContainsKey(key))
                    {
                        model.PostData.Add(key, request.Form[key]);
                    }
                }

                model.HasFilter = bool.Parse(request["_search"] ?? "false");
                model.PageIndex = int.Parse(request["page"] ?? "1");
                model.PageSize  = int.Parse(request["rows"] ?? "10");
                var sidx = request["sidx"];
                if (!string.IsNullOrEmpty(sidx))
                {
                    model.HasSort = true;
                    var list = sidx.Split(',');
                    foreach (var item in list)
                    {
                        if (item.IndexOf("asc") > -1)
                        {
                            model.SortInfos.Add(new SortInfo {
                                Name = item.Replace("asc", "").Trim(), Type = SortType.Asc
                            });
                        }
                        else if (item.IndexOf("desc") > -1)
                        {
                            model.SortInfos.Add(new SortInfo {
                                Name = item.Replace("desc", "").Trim(), Type = SortType.Desc
                            });
                        }
                        else
                        {
                            SortType type = SortType.Asc;
                            if (request["sord"] == "desc")
                            {
                                type = SortType.Desc;
                            }
                            model.SortInfos.Add(new SortInfo {
                                Name = item.Trim(), Type = type
                            });
                        }
                    }
                }

                var filters = request["filters"];
                if (!string.IsNullOrEmpty(filters))
                {
                    JToken            token       = JToken.Parse(filters);
                    var               groupOp     = (JValue)token.SelectToken("groupOp");
                    FilterComposeType composeType = FilterComposeType.And;
                    if ((string)groupOp.Value == "OR")
                    {
                        composeType = FilterComposeType.Or;
                    }

                    var rules = token.SelectToken("rules");
                    foreach (JToken item in rules)
                    {
                        FilterInfo filterInfo = new FilterInfo();
                        filterInfo.ComposeType = composeType;
                        var field = (JValue)item.SelectToken("field");
                        filterInfo.Name = (string)field.Value;
                        var op          = (JValue)item.SelectToken("op");
                        var operateType = (FilterOperateType)Enum.Parse(typeof(FilterOperateType), (string)op.Value, true);
                        filterInfo.OperateType = operateType;
                        var data = item.SelectToken("data");
                        if (data.Type == JTokenType.Array)
                        {
                            filterInfo.HasMultipleValue = true;
                            foreach (JToken vItem in data.Children())
                            {
                                filterInfo.Values.Add((string)((JValue)vItem).Value);
                            }
                        }
                        else
                        {
                            filterInfo.Value = (string)((JValue)data).Value;
                        }
                        model.FilterInfos.Add(filterInfo);
                    }
                }
                return(model);
            }
            catch
            {
                return(null);
            }
        }
コード例 #29
0
        public override async Task RefreshAsync()
        {
            var source = await this.GetSourceAsync();

            if (source != null)
            {
                this.filter = new FilterInfo(this.IsOnlyTracking, this.FilterText);
                this.VideosView.View.CustomSort = null;
                this.VideosView.View.GroupDescriptions?.Clear();
                this.VideosView.Collection.Reset(source);
                if (this.IsOnlyTracking)
                {
                    this.VideosView.View.CustomSort = new VideoInfoViewModel.DayOfWeekComparer();
                    this.VideosView.View.GroupDescriptions?.Add(new PropertyGroupDescription(nameof(VideoInfoViewModel.GroupTitle)));
                }
                else
                {
                    this.VideosView.View.CustomSort = new VideoInfoViewModel.DefaultComparer();
                }
            }
        }
コード例 #30
0
        public List <DataBorongan> FindAll(int?skip = null, int?take = null, List <SortingInfo> sortings = null, FilterInfo filters = null)
        {
            IQueryable <DataBorongan> list = context.DataBorongan;

            if (filters != null && (filters.Filters != null && filters.Filters.Count > 0))
            {
                GridHelper.ProcessFilters <DataBorongan>(filters, ref list);
            }

            if (sortings != null && sortings.Count > 0)
            {
                foreach (var s in sortings)
                {
                    list = list.OrderBy <DataBorongan>(s.SortOn + " " + s.SortOrder);
                }
            }
            else
            {
                list = list.OrderBy <DataBorongan>("id"); //default, wajib ada atau EF error
            }

            //take & skip
            var takeList = list;

            if (skip != null)
            {
                takeList = takeList.Skip(skip.Value);
            }
            if (take != null)
            {
                takeList = takeList.Take(take.Value);
            }

            //return result
            List <DataBorongan> result = takeList.ToList().ToList();

            return(result);
        }
コード例 #31
0
        /// <summary>
        /// 根据筛选信息统计模型数SQL语句
        /// </summary>
        /// <param name="filter">筛选信息</param>
        /// <param name="parameters">参数</param>
        /// <returns>SQL语句</returns>
        protected override string CountByFilterSql(FilterInfo filter, out DynamicParameters parameters)
        {
            StringBuilder whereSql = MergeWhereSql(filter, out parameters);

            return($"{CountSql()} {GetSelectPageJoinSql(parameters, filter)} {whereSql.ToString()}");
        }
コード例 #32
0
        public void ShouldThrowFilterInfoExpressionExceptionWhenFilterSingleItemAndWithInvalidArguments(string fieldName, FilterType filterType, object value)
        {
            var filter = FilterInfo.CreateItem(fieldName, filterType, value);

            CreateTestUsers().WhereCondition(filter).ToList();
        }
コード例 #33
0
 private bool CanDisplayProperties(FilterInfo filterInfo)
 {
     return(filterInfo != null);
 }
コード例 #34
0
 /// <summary>
 /// 获取查询分页连接SQL
 /// </summary>
 /// <param name="parameters">参数</param>
 /// <param name="filter">筛选</param>
 /// <returns>连接SQL语句</returns>
 protected virtual string GetSelectPageJoinSql(DynamicParameters parameters, FilterInfo filter = null) => null;
コード例 #35
0
ファイル: FilterInfo.cs プロジェクト: 40a/PowerShell
 /// <summary>
 /// This is a copy constructor, used primarily for get-command.
 /// </summary>
 internal FilterInfo(string name, FilterInfo other)
     : base(name, other)
 {
 }
コード例 #36
0
 /// <summary>
 /// 追加查询分页条件SQL
 /// </summary>
 /// <param name="whereSql">where语句</param>
 /// <param name="parameters">参数</param>
 /// <param name="filter">筛选</param>
 protected virtual void AppendSelectPageWhereSql(StringBuilder whereSql, DynamicParameters parameters, FilterInfo filter = null)
 {
 }
コード例 #37
0
ファイル: OrGroup.cs プロジェクト: repinvv/TestingContext
 public OrGroup(IDependency[] dependencies, FilterInfo info) 
     : base(new GroupToken(typeof(OrGroup)), dependencies, info)
 { }
コード例 #38
0
        /// <summary> build the capture graph for grabber. </summary>
        bool SetupGraph()
        {
            int  hr;
            IPin pin1, pin2;

            try
            {
                hr = capGraph.SetFiltergraph(graphBuilder);
                if (hr < 0)
                {
                    Marshal.ThrowExceptionForHR(hr);
                }

                if (atiTVCardFound)
                {
                    SetupVideoCrossbar();
                    AddFilter(atiCrossbar, "ATI Crossbar");
                    AddFilter(capFilter, "Analog Capture Device");
                    AddFilter(wmVideoDecoder, "AVI Decompressor");
                    AddFilter(stretchVideo, "Stretch Video");
                    AddFilter(colorConverter, "Color Space Converter");
                }
                else if (videoSource.Equals("File"))
                {
                    graphBuilder.AddSourceFilter(filePath, "WM ASF Reader", out capFilter);
                    AddFilter(modFrameRate, "Modify Frame Rate");
                    AddFilter(stretchVideo, "Stretch Video");
                    AddFilter(colorConverter, "Color Space Converter");
                }
                else
                {
                    int state;
                    if (capFilter.GetState(100, out state) == 0)
                    {
                        AddFilter(capFilter, "Capture Filter");
                    }
                }

                AddFilter(sampleGrabber, "Sample Grabber"); // make sure samples grabbed have 32 bits per pixel to work with Ge Force 7900

                AddFilter(baseGrabFlt, "Vector Grabber");
                AddFilter(motionVector, "Motion Flow Vector Filter");

                if (videoPreview)
                {
                    AddFilter(teeSplitter, "Smart Tee Splitter");
                    AddFilter(colorConverter, "Color Space Converter");
                    AddFilter(videoRenderer, "Video Renderer");
                }

#if false // Attempt to use VMR9 abandoned for now
                IVMRFilterConfig9 vmrConfig = videoRenderer as IVMRFilterConfig9;
                hr = vmrConfig.SetRenderingMode(VMR9Mode.Renderless);
                if (hr < 0)
                {
                    Marshal.ThrowExceptionForHR(hr);
                }
                IVMRSurfaceAllocatorNotify9 vmrAllocNotify = videoRenderer as IVMRSurfaceAllocatorNotify9;
                vmrAllocNotify.AdviseSurfaceAllocator(userID, vmrAllocator);
                vmrAllocator.AdviseNotify(vmrAllocNotify);
#endif

                // connect the pins
                if (videoSource.Equals("File"))
                {
                    ConnectPins(capFilter, "Raw Video 1", modFrameRate, "In");
                    ConnectPins(modFrameRate, "Out", stretchVideo, "In");
                    //ConnectPins(wmVideoDecoder, "out0", stretchVideo, "In");
                    ConnectPins(stretchVideo, "Out", colorConverter, "In");
                    ConnectPins(colorConverter, "Out", sampleGrabber, "In");
                }
                else
                {
                    if (atiTVCardFound)
                    {
                        ConnectPins(atiCrossbar, "0: Video Decoder Out", capFilter, "0");
                        ConnectPins(capFilter, "2", wmVideoDecoder, "In");
                        ConnectPins(wmVideoDecoder, "Out", stretchVideo, "In");
                        ConnectPins(stretchVideo, "Out", colorConverter, "In");
                        ConnectPins(colorConverter, "Out", sampleGrabber, "In");
                    }
                    else // webcam case
                    {
                        //ConnectPins(capFilter, "CapturePin", stretchVideo, "In");
                        ConnectPins(capFilter, "CapturePin", sampleGrabber, "In");
                    }
                }


                if (videoPreview)
                {
                    ConnectPins(sampleGrabber, "Out", teeSplitter, "Input");
                    //ConnectPins(teeSplitter, "0", videoRenderer, "In");
                    ConnectPins(teeSplitter, "Preview", colorConverter, "In");
                    ConnectPins(colorConverter, "Out", videoRenderer, "VMR Input0");
                    ConnectPins(teeSplitter, "Capture", motionVector, "In");
                }
                else
                {
                    ConnectPins(sampleGrabber, "Out", motionVector, "In");
                }
                ConnectPins(motionVector, "Out", baseGrabFlt, "In");

                // check that all filters are accounted for
                // there must be a total of 7 filters if source is "File"
                IEnumFilters enumFilters;
                graphBuilder.EnumFilters(out enumFilters);
                enumFilters.Reset();
                IBaseFilter[] filters = new IBaseFilter[1];
                int           count   = 0;
                int           total   = 0;
                while (0 == (hr = enumFilters.Next(1, filters, out count)))
                {
                    FilterInfo info = new FilterInfo();
                    hr = filters[0].QueryFilterInfo(info);
                    if (hr < 0)
                    {
                        Marshal.ThrowExceptionForHR(hr);
                    }
                    LogInfo(LogGroups.Console, info.achName);
                    IPin[]    pins = new IPin[1];
                    IEnumPins enumPins;
                    filters[0].EnumPins(out enumPins);
                    while (0 == (hr = enumPins.Next(1, pins, out count)))
                    {
                        IPin pin;
                        hr = pins[0].ConnectedTo(out pin);
                        if (pin != null)
                        {
                            string pinID;
                            hr = pin.QueryId(out pinID);
                            LogInfo(LogGroups.Console, pinID);
                        }
                    }
                    Marshal.ReleaseComObject(filters[0]);
                    total++;
                }
                Marshal.ReleaseComObject(enumFilters);

                SetupVideoGrabber();

                SetupVectorGrabber();

                return(true);
            }
            catch (Exception ee)
            {
                LogInfo(LogGroups.Console, "Could not setup graph\r\n" + ee.Message);
                return(false);
            }
        }
コード例 #39
0
ファイル: Wrap.cs プロジェクト: yindongfei/bridge.lua
 public TypeDefinitionBuilder(string libWhite, string libBlack) {
     whiteFilter_ = new FilterInfo(libWhite);
     blackFilter_ = new FilterInfo(libBlack);
 }
コード例 #40
0
        public void AccessPointTamperingTest()
        {
            EndpointReferenceType subscriptionReference = null;

            System.DateTime subscribeStarted = System.DateTime.MaxValue;

            int timeout = 60;

            RunTest(
                () =>
            {
                //3.	Get complete list of access points from the DUT (see Annex A.1).
                List <AccessPointInfo> fullAccessPointsList = GetAccessPointInfoList();

                //4.	Check that there is at least one Access Point with Capabilities.Tamper = “true”.
                // Otherwise skip other steps and go to the next test.

                List <AccessPointInfo> accessPointsList =
                    fullAccessPointsList.Where(A => A.Capabilities != null && A.Capabilities.TamperSpecified && A.Capabilities.Tamper).ToList();

                if (accessPointsList.Count == 0)
                {
                    LogTestEvent("No AccessPoints with required Capabilities found, exit the test." + Environment.NewLine);
                    return;
                }

                // Topic for current test
                // tns1:AccessPoint/State/Tampering
                TopicInfo topicInfo = ConstructTopic(new string[] { "AccessPoint", "State", "Tampering" });

                //5.	ONVIF Client will invoke GetEventPropertiesRequest message to retrieve all events supported by the DUT.
                //6.	Verify the GetEventPropertiesResponse message from the DUT.
                //7.	Check if there is an event with Topic tns1:AccessControl/AccessPoint/Tampering. If there is no event with such Topic skip other steps, fail the test and go to the next test.
                XmlElement topicElement = GetTopicElement(topicInfo);

                Assert(topicElement != null,
                       string.Format("Topic {0} not supported", topicInfo.GetDescription()),
                       "Check that the event topic is supported");

                //8.	Check that this event is a Property event (MessageDescription.IsProperty="true").
                //9.	Check that this event contains Source.SimpleItemDescription item with
                // Name="AccessPointToken" and Type="pt:ReferenceToken".
                //10.	Check that this event contains Data.SimpleItemDescription item with Name="Active"
                // and Type=" xs:boolean".
                //11.	Check that this event contains Data.SimpleItemDescription item with Name="Reason"
                // and Type=" xs:string".

                XmlElement messageDescription = topicElement.GetMessageDescription();
                ValidateAccessPointTamperingTopic(messageDescription, topicInfo);

                //12.	ONVIF Client will invoke SubscribeRequest message with tns1:AccessControl/AccessPoint/Tampering Topic as Filter and an InitialTerminationTime of 60s to ensure that the SubscriptionManager is deleted after one minute.
                //13.	Verify that the DUT sends a SubscribeResponse message.
                //14.	Verify that DUT sends Notify message(s)

                FilterInfo filter = CreateFilter(topicInfo, messageDescription);

                Dictionary <NotificationMessageHolderType, XmlElement> notifications = new Dictionary <NotificationMessageHolderType, XmlElement>();

                subscriptionReference =
                    ReceiveMessages(filter.Filter,
                                    timeout,
                                    new Action(() => { }),
                                    fullAccessPointsList.Count,
                                    notifications,
                                    out subscribeStarted);

                //15.	Verify received Notify messages (correct value for UTC time, TopicExpression and
                // wsnt:Message).
                //16.	Verify that TopicExpression is equal to tns1:AccessControl/AccessPoint/Tampering
                // for all received Notify messages.
                //17.	Verify that each notification contains Source.SimpleItem item with Name="AccessPointToken"
                // and Value is equal to one of existing Access Point Tokens with Capabilities.Tamper = “true”
                // (e.g. complete list of access points contains Access Point with the same token). Verify that
                // there are Notification messages for each Access Point with Capabilities.Tamper = “true”.
                // Verify that there are no Notification messages for each Access Point with Capabilities.Tamper
                // = “false”.
                //18.	Verify that each notification contains Data.SimpleItem item with Name="Active" and Value
                // with type is equal to xs:boolean.
                //19.	Verify that each notification which contains Data.SimpleItem item with Name="Reason"
                // contains Value with type is equal to xs:boolean.
                //20.	Verify that Notify PropertyOperation="Initialized".

                ValidateMessages(notifications,
                                 topicInfo,
                                 OnvifMessage.INITIALIZED,
                                 accessPointsList,
                                 ValidateAccessPointTamperingMessage);

                // check that there is a notification for each access point
                Dictionary <string, NotificationMessageHolderType> accessPointsMessages = new Dictionary <string, NotificationMessageHolderType>();
                ValidateMessagesSet(notifications.Keys, accessPointsList, accessPointsMessages);
            },
                () =>
            {
                ReleaseSubscription(subscribeStarted, subscriptionReference, timeout);
            });
        }
コード例 #41
0
ファイル: Filter.aspx.cs プロジェクト: paopaofeng/dp2
    // 根据记录数量的多少,少的时候可以立即返回结果,多的时候用线程后台处理,然后可以随时查询状态
    // 线程用线程池,避免过多耗用线程数目

    // 根据结果集名,提取全部书目XML记录,然后批处理经过MarcFilter过滤,创建若干个子结果集
    // 最基本的功能是返回子结果集的显示名,文件名,包含记录数量,供前端显示在界面上
    // 较为深入的功能是,将子结果集按照key排序归并,而显示出二级条目和数量。二级结果集是子结果集的子结果集

    // TODO: 如何及时清理Task对象,避免内存过度膨胀? 是否仅保存最新10个Task对象?
    void GetFilterInfo(
        string strResultsetName,
        string strSelected,
        string strLang)
    {
        string strError = "";
        GetFilterInfo result_info = new GetFilterInfo();

        if (string.IsNullOrEmpty(strResultsetName) == true)
        {
            strError = "结果集名不应为空";
            goto ERROR1;
        }
#if NO
        Hashtable result_table = null;
        string strFilterFileName = PathUtil.MergePath(app.DataDir, "cfgs/facet.fltx");
        int nRet = ResultsetFilter.DoFilter(
            app,
            sessioninfo.Channel,
            strResultsetName,
            strFilterFileName,
            1000,
            ref result_table,
            out strError);
        if (nRet == -1)
            goto ERROR1;
#endif
        FilterTask t = sessioninfo.FindFilterTask(strResultsetName);    // Task对象是利用Session内结果集名来进行管理的
        if (t == null)
        {
            // 如果一个结果集还没有被后台任务处理,就立即启动一个后台任务
            t = new FilterTask();
            sessioninfo.SetFilterTask(strResultsetName, t);

            string strGlobalResultSetName = "";
            bool bShare = false;

            if (strResultsetName[0] == '#')
                strGlobalResultSetName = strResultsetName.Substring(1);
            else
            {
                // 构造全局结果集名
                strGlobalResultSetName = sessioninfo.GetHashCode() + "_" + strResultsetName;

                // 先把结果集共享
                // 管理结果集
                // parameters:
                //      strAction   share/remove 分别表示共享为全局结果集对象/删除全局结果集对象
                long lRet = sessioninfo.Channel.ManageSearchResult(
                    null,
                    "share",
                    strResultsetName,
                    strGlobalResultSetName,
                    out strError);
                if (lRet == -1)
                    goto ERROR1;

                bShare = true;
            }

            FilterTaskInput i = new FilterTaskInput();
            i.App = app;
            i.FilterFileName = PathUtil.MergePath(app.DataDir, "cfgs/facet.fltx");
            i.ResultSetName = strGlobalResultSetName;
            i.ShareResultSet = bShare;
            i.SessionInfo = sessioninfo;
            i.TaskName = strResultsetName;  // Task对象是利用Session内结果集名来进行管理的
            i.MaxCount = 1000;
            // i.aggregation_names = new List<string>() {"author"};

            XmlDocument def_dom = GetFacetDefDom(out strError);
            if (def_dom == null)
                goto ERROR1;
            i.DefDom = def_dom;

            ThreadPool.QueueUserWorkItem(t.ThreadPoolCallBack, i);
            strError = "#pending";  // 表示正在处理,希望前端稍后重新访问
            goto ERROR1;
        }
        else
        {
            if (t.TaskState == TaskState.Processing)
            {
                if (t.ProgressRange != 0)
                    result_info.ProgressValue = (int)(((double)t.ProgressValue / (double)t.ProgressRange) * 100);
                strError = "#pending";  // 表示正在处理,希望前端稍后重新访问
                goto ERROR1;
            }
            if (string.IsNullOrEmpty(t.ErrorInfo) == false)
            {
                strError = t.ErrorInfo;
                goto ERROR1;
            }

#if NO
            string[] names = new string[t.ResultTable.Keys.Count];
            t.ResultTable.Keys.CopyTo(names, 0);
            Array.Sort(names);

            List<FilterInfo> infos = new List<FilterInfo>();
            foreach (string strName in names)
            {
                KeyValueCollection items = (KeyValueCollection)t.ResultTable[strName];
                FilterInfo info = new FilterInfo();
                info.Name = strName;
                if (items != null)
                    info.Count = items.Count.ToString();
                else
                    info.Count = "0";

                infos.Add(info);
            }
            result_info.Items = new FilterInfo[infos.Count];
            infos.CopyTo(result_info.Items);
#endif

#if NO
            Hashtable keyname_table = null;
            // 获得名称对照表
            // parameters:
            //      keyname_table   keyname --> 当前语言的名称
            int nRet = ResultsetFilter.GetKeyNameTable(
                app,
                PathUtil.MergePath(app.DataDir, "cfgs/facet.fltx"),
                t.ResultItems,
                string.IsNullOrEmpty(strLang) == true ? Thread.CurrentThread.CurrentUICulture.Name : strLang,
                out keyname_table,
                out strError);
            if (nRet == -1)
                goto ERROR1;
#endif

            long lHitCount = MyWebPage.GetServerResultCount(sessioninfo, strResultsetName);

            XmlDocument def_dom = GetFacetDefDom(out strError);
            if (def_dom == null)
                goto ERROR1;
            this.m_facetDom = def_dom;

            this.m_strLang = strLang;

            try
            {
                // 创建FilterInfo数组
                result_info.Items = ResultsetFilter.BuildFilterInfos(
                    strResultsetName,
                    lHitCount,
                    strSelected,
                    GetKeyNameCaption,
                    t.ResultItems,
                    sessioninfo.GetTempDir(),
                    10);
            }
            catch (Exception ex)
            {
                strError = ex.Message;
                goto ERROR1;
            }

            if (t.HitCount > 1000)
            {
                result_info.Comment = "分面导航只提取了当前结果集的前 1000 条记录";
            }
        }


        // 返回一级节点的名字和包含记录数量
        this.Response.Write(MyWebPage.GetResultString(result_info));
        this.Response.End();
        return;
    ERROR1:
        result_info.ErrorString = strError;
        this.Response.Write(MyWebPage.GetResultString(result_info));
        this.Response.End();
    }
コード例 #42
0
		private void FilterSave()
		{
			FilterInfo filter = new FilterInfo();
			filter.FilterId = -1;
			filter.ModuleId = ModuleId;
			filter.PortalId = PortalId;
			if (Params.ContainsKey("FilterId"))
			{
				filter.FilterId = Convert.ToInt32(Params["FilterId"]);
			}
			if (Params.ContainsKey("Find"))
			{
				filter.Find = Params["Find"].ToString();
			}
			if (Params.ContainsKey("Replacement"))
			{
				filter.Replace = Params["Replacement"].ToString();
			}
			if (Params.ContainsKey("FilterType"))
			{
				filter.FilterType = Params["FilterType"].ToString();
			}

			FilterController fc = new FilterController();
			filter = fc.Filter_Save(filter);
		}
コード例 #43
0
        // Display property page for the specified object
        private void DisplayPropertyPage( IntPtr parentWindow, object sourceObject )
        {
            try
            {
                // retrieve ISpecifyPropertyPages interface of the device
                ISpecifyPropertyPages pPropPages = (ISpecifyPropertyPages) sourceObject;

                // get property pages from the property bag
                CAUUID caGUID;
                pPropPages.GetPages( out caGUID );

                // get filter info
                FilterInfo filterInfo = new FilterInfo( deviceMoniker );

                // create and display the OlePropertyFrame
                Win32.OleCreatePropertyFrame( parentWindow, 0, 0, filterInfo.Name, 1, ref sourceObject, caGUID.cElems, caGUID.pElems, 0, 0, IntPtr.Zero );

                // release COM objects
                Marshal.FreeCoTaskMem( caGUID.pElems );
            }
            catch
            {
            }
        }
コード例 #44
0
        public virtual string FilterString( FilterInfo fi )
        {
            object oVal = fi.Value;
            string v = serializeValueForSearch( fi.Value );

            if( fi.Operation == FilterOperation.Equals && oVal == null ||
                fi.Operation == FilterOperation.DoesNotEqual && oVal == null )
            {
                throw new NotImplementedException("Cannot filter for null in DefaultSearchFilterFormatter");
            }
            else if( fi.Operation == FilterOperation.Contains || fi.Operation == FilterOperation.NotContains )
            {
                v = v + "*";
            }
            else if( fi.Operation == FilterOperation.NotContains )
            {

            }
            else if( fi.Operation == FilterOperation.In )
            {
                if( oVal is IRecordList )
                {
                    IRecordList irl = (IRecordList)oVal;
                    FilterSet inSet = new FilterSet(FilterJoinOperator.Or);
                    foreach( IRecord r in irl )
                    {
                        inSet.Rules.Add( new FilterInfo(fi.ColumnName, r.Id ) );
                    }
                    v = string.Format("({0})", FilterString(inSet) );
                }
                else if( oVal is IList )
                {
                    IList il = (IList)oVal;
                    FilterSet inSet = new FilterSet(FilterJoinOperator.Or);
                    foreach( object o in il )
                    {
                        inSet.Rules.Add( new FilterInfo(fi.ColumnName, o ) );
                    }
                    v = string.Format("({0})", FilterString(inSet) );
                }
            }
            else if (fi.Operation == FilterOperation.GreaterThan)
            {
                return String.Format("{0}:[{1} TO *]", fi.ColumnName, v);
            }
            else if (fi.Operation == FilterOperation.GreaterThanOrEqual)
            {
                return String.Format("{0}:{{{1} TO *}}", fi.ColumnName, v);
            }
            else if (fi.Operation == FilterOperation.LessThan)
            {
                return String.Format("{0}:[* TO {1}]", fi.ColumnName, v);
            }
            else if (fi.Operation == FilterOperation.LessThanOrEqual)
            {
                return String.Format("{0}:{{* TO {1}}}", fi.ColumnName, v);
            }
            else if (fi.Operation == FilterOperation.Equals)
            {
                return string.Format("{0}:{1}", fi.ColumnName, v);
            }
            else if (fi.Operation != FilterOperation.Equals)
            {
                throw new NotImplementedException("Operation " + fi.Operation + " not in DefaultSearchFilterFormatter");
            }

            return string.Format("{0}:{2}", fi.ColumnName, FilterInfo.FilterOperationToString(fi.Operation), v);
        }
コード例 #45
0
 private static FilterInfo GetFilterInfo(string ext)
 {
     FilterInfo info = null;
     if (!FilterCache.TryGetValue(ext, out info))
     {
         string str2;
         string str3;
         string persistentHandlerClass = GetPersistentHandlerClass(ext, true);
         if (!string.IsNullOrEmpty(persistentHandlerClass) && GetFilterDllAndClassFromPersistentHandler(persistentHandlerClass, out str2, out str3))
         {
             Microsoft.Win32.SafeHandles.SafeLibraryHandle hModule = Windows.LoadLibrary(str2);
             if (!hModule.IsInvalid)
             {
                 IntPtr procAddress = Windows.GetProcAddress(hModule, "DllGetClassObject");
                 if (procAddress != IntPtr.Zero)
                 {
                     DllGetClassObject delegateForFunctionPointer = (DllGetClassObject) Marshal.GetDelegateForFunctionPointer(procAddress, typeof(DllGetClassObject));
                     info = new FilterInfo(hModule, new Guid(str3), delegateForFunctionPointer);
                 }
             }
         }
         FilterCache.Add(ext, info);
     }
     return info;
 }
コード例 #46
0
        /// <summary>
        /// Gets a list of matching commands
        /// </summary>
        /// <param name="pattern">Command pattern.</param>
        /// <param name="commandOrigin"></param>
        /// <param name="context"></param>
        /// <param name="rediscoverImportedModules"></param>
        /// <param name="moduleVersionRequired"></param>
        /// <returns></returns>
        internal static IEnumerable <CommandInfo> GetMatchingCommands(string pattern, ExecutionContext context, CommandOrigin commandOrigin, bool rediscoverImportedModules = false, bool moduleVersionRequired = false)
        {
            // Otherwise, if it had wildcards, just return the "AvailableCommand"
            // type of command info.
            WildcardPattern commandPattern = WildcardPattern.Get(pattern, WildcardOptions.IgnoreCase);

            CmdletInfo cmdletInfo = context.SessionState.InvokeCommand.GetCmdlet("Microsoft.PowerShell.Core\\Get-Module");
            PSModuleAutoLoadingPreference moduleAutoLoadingPreference = CommandDiscovery.GetCommandDiscoveryPreference(context, SpecialVariables.PSModuleAutoLoadingPreferenceVarPath, "PSModuleAutoLoadingPreference");

            if ((moduleAutoLoadingPreference != PSModuleAutoLoadingPreference.None) &&
                ((commandOrigin == CommandOrigin.Internal) || ((cmdletInfo != null) && (cmdletInfo.Visibility == SessionStateEntryVisibility.Public))
                )
                )
            {
                foreach (string modulePath in GetDefaultAvailableModuleFiles(isForAutoDiscovery: false, context))
                {
                    // Skip modules that have already been loaded so that we don't expose private commands.
                    string moduleName                  = Path.GetFileNameWithoutExtension(modulePath);
                    List <PSModuleInfo> modules        = context.Modules.GetExactMatchModules(moduleName, all: false, exactMatch: true);
                    PSModuleInfo        tempModuleInfo = null;

                    if (modules.Count != 0)
                    {
                        // 1. We continue to the next module path if we don't want to re-discover those imported modules
                        // 2. If we want to re-discover the imported modules, but one or more commands from the module were made private,
                        //    then we don't do re-discovery
                        if (!rediscoverImportedModules || modules.Exists(module => module.ModuleHasPrivateMembers))
                        {
                            continue;
                        }

                        if (modules.Count == 1)
                        {
                            PSModuleInfo psModule = modules[0];
                            tempModuleInfo = new PSModuleInfo(psModule.Name, psModule.Path, context: null, sessionState: null);
                            tempModuleInfo.SetModuleBase(psModule.ModuleBase);

                            foreach (KeyValuePair <string, CommandInfo> entry in psModule.ExportedCommands)
                            {
                                if (commandPattern.IsMatch(entry.Value.Name))
                                {
                                    CommandInfo current = null;
                                    switch (entry.Value.CommandType)
                                    {
                                    case CommandTypes.Alias:
                                        current = new AliasInfo(entry.Value.Name, definition: null, context);
                                        break;

                                    case CommandTypes.Function:
                                        current = new FunctionInfo(entry.Value.Name, ScriptBlock.EmptyScriptBlock, context);
                                        break;

                                    case CommandTypes.Filter:
                                        current = new FilterInfo(entry.Value.Name, ScriptBlock.EmptyScriptBlock, context);
                                        break;

                                    case CommandTypes.Configuration:
                                        current = new ConfigurationInfo(entry.Value.Name, ScriptBlock.EmptyScriptBlock, context);
                                        break;

                                    case CommandTypes.Cmdlet:
                                        current = new CmdletInfo(entry.Value.Name, implementingType: null, helpFile: null, PSSnapin: null, context);
                                        break;

                                    default:
                                        Dbg.Assert(false, "cannot be hit");
                                        break;
                                    }

                                    current.Module = tempModuleInfo;
                                    yield return(current);
                                }
                            }

                            continue;
                        }
                    }

                    string moduleShortName = System.IO.Path.GetFileNameWithoutExtension(modulePath);

                    IDictionary <string, CommandTypes> exportedCommands = AnalysisCache.GetExportedCommands(modulePath, testOnly: false, context);

                    if (exportedCommands == null)
                    {
                        continue;
                    }

                    tempModuleInfo = new PSModuleInfo(moduleShortName, modulePath, sessionState: null, context: null);
                    if (InitialSessionState.IsEngineModule(moduleShortName))
                    {
                        tempModuleInfo.SetModuleBase(Utils.DefaultPowerShellAppBase);
                    }

                    //moduleVersionRequired is bypassed by FullyQualifiedModule from calling method. This is the only place where guid will be involved.
                    if (moduleVersionRequired && modulePath.EndsWith(StringLiterals.PowerShellDataFileExtension, StringComparison.OrdinalIgnoreCase))
                    {
                        tempModuleInfo.SetVersion(ModuleIntrinsics.GetManifestModuleVersion(modulePath));
                        tempModuleInfo.SetGuid(ModuleIntrinsics.GetManifestGuid(modulePath));
                    }

                    foreach (KeyValuePair <string, CommandTypes> pair in exportedCommands)
                    {
                        string       commandName  = pair.Key;
                        CommandTypes commandTypes = pair.Value;

                        if (commandPattern.IsMatch(commandName))
                        {
                            bool shouldExportCommand = true;

                            // Verify that we don't already have it represented in the initial session state.
                            if ((context.InitialSessionState != null) && (commandOrigin == CommandOrigin.Runspace))
                            {
                                foreach (SessionStateCommandEntry commandEntry in context.InitialSessionState.Commands[commandName])
                                {
                                    string moduleCompareName = null;

                                    if (commandEntry.Module != null)
                                    {
                                        moduleCompareName = commandEntry.Module.Name;
                                    }
                                    else if (commandEntry.PSSnapIn != null)
                                    {
                                        moduleCompareName = commandEntry.PSSnapIn.Name;
                                    }

                                    if (string.Equals(moduleShortName, moduleCompareName, StringComparison.OrdinalIgnoreCase))
                                    {
                                        if (commandEntry.Visibility == SessionStateEntryVisibility.Private)
                                        {
                                            shouldExportCommand = false;
                                        }
                                    }
                                }
                            }

                            if (shouldExportCommand)
                            {
                                if ((commandTypes & CommandTypes.Alias) == CommandTypes.Alias)
                                {
                                    yield return(new AliasInfo(commandName, null, context)
                                    {
                                        Module = tempModuleInfo
                                    });
                                }

                                if ((commandTypes & CommandTypes.Cmdlet) == CommandTypes.Cmdlet)
                                {
                                    yield return(new CmdletInfo(commandName, implementingType: null, helpFile: null, PSSnapin: null, context: context)
                                    {
                                        Module = tempModuleInfo
                                    });
                                }

                                if ((commandTypes & CommandTypes.Function) == CommandTypes.Function)
                                {
                                    yield return(new FunctionInfo(commandName, ScriptBlock.EmptyScriptBlock, context)
                                    {
                                        Module = tempModuleInfo
                                    });
                                }

                                if ((commandTypes & CommandTypes.Configuration) == CommandTypes.Configuration)
                                {
                                    yield return(new ConfigurationInfo(commandName, ScriptBlock.EmptyScriptBlock, context)
                                    {
                                        Module = tempModuleInfo
                                    });
                                }
                            }
                        }
                    }
                }
            }
        }
コード例 #47
0
        // Collect filters of specified category
		private void CollectFilters( Guid category )
		{
			object			comObj = null;
			ICreateDevEnum	enumDev = null;
			IEnumMoniker	enumMon = null;
			IMoniker[]		devMon = new IMoniker[1];
			int				hr;

            try
            {
                // Get the system device enumerator
                Type srvType = Type.GetTypeFromCLSID( Clsid.SystemDeviceEnum );
                if ( srvType == null )
                    throw new ApplicationException( "Failed creating device enumerator" );

                // create device enumerator
                comObj = Activator.CreateInstance( srvType );
                enumDev = (ICreateDevEnum) comObj;

                // Create an enumerator to find filters of specified category
                hr = enumDev.CreateClassEnumerator( ref category, out enumMon, 0 );
                if ( hr != 0 )
                    throw new ApplicationException( "No devices of the category" );

                // Collect all filters
                IntPtr n = IntPtr.Zero;
                while ( true )
                {
                    // Get next filter
                    hr = enumMon.Next( 1, devMon, n );
                    if ( ( hr != 0 ) || ( devMon[0] == null ) )
                        break;

                    // Add the filter
                    FilterInfo filter = new FilterInfo( devMon[0] );
                    InnerList.Add( filter );

                    // Release COM object
                    Marshal.ReleaseComObject( devMon[0] );
                    devMon[0] = null;
                }

                // Sort the collection
                InnerList.Sort( );
            }
            catch
            {
            }
			finally
			{
				// release all COM objects
				enumDev = null;
				if ( comObj != null )
				{
					Marshal.ReleaseComObject( comObj );
					comObj = null;
				}
				if ( enumMon != null )
				{
					Marshal.ReleaseComObject( enumMon );
					enumMon = null;
				}
				if ( devMon[0] != null )
				{
					Marshal.ReleaseComObject( devMon[0] );
					devMon[0] = null;
				}
			}
		}
コード例 #48
0
		public int AddFilter(FilterInfo objFilter)
		{
			return dataProvider.AddFilter(objFilter.PortalId, objFilter.ModuleId, objFilter.ForumId, objFilter.Find, objFilter.Replace, objFilter.FilterType, objFilter.ApplyOnSave, objFilter.ApplyOnRender);
		}
コード例 #49
0
 public FilterRecord(FilterInfo fi)
 {
     this.columnName = fi.ColumnName;
     this.operation = fi.Operation;
     this.testObject = fi.Value;
 }
コード例 #50
0
		public void UpdateFilter(FilterInfo objFilter)
		{
			dataProvider.UpdateFilter(objFilter.FilterId, objFilter.PortalId, objFilter.ModuleId, objFilter.ForumId, objFilter.Find, objFilter.Replace, objFilter.FilterType, objFilter.ApplyOnSave, objFilter.ApplyOnRender);
			//Caching.ClearFilterCache(filterId, portalId);
		}
コード例 #51
0
        /// <summary>
        /// Gets the filter recursive.
        /// </summary>
        /// <param name="filterList">The filter list.</param>
        /// <param name="filter">The filter.</param>
        /// <param name="reportEntityType">Type of the report entity.</param>
        private void GetFilterListRecursive( List<FilterInfo> filterList, DataViewFilter filter, EntityType reportEntityType )
        {
            var result = new Dictionary<Guid, string>();

            var entityType = EntityTypeCache.Read( filter.EntityTypeId ?? 0 );
            var reportEntityTypeCache = EntityTypeCache.Read( reportEntityType );
            var reportEntityTypeModel = reportEntityTypeCache.GetEntityType();

            var filterInfo = new FilterInfo();
            filterInfo.Guid = filter.Guid;
            filterInfo.FilterExpressionType = filter.ExpressionType;
            filterInfo.ParentFilter = filter.ParentId.HasValue ? filterList.FirstOrDefault( a => a.Guid == filter.Parent.Guid ) : null;
            if ( entityType != null )
            {
                var component = Rock.Reporting.DataFilterContainer.GetComponent( entityType.Name );
                if ( component != null )
                {
                    if ( component is Rock.Reporting.DataFilter.EntityFieldFilter )
                    {
                        var entityFieldFilter = component as Rock.Reporting.DataFilter.EntityFieldFilter;
                        var fieldName = entityFieldFilter.GetSelectedFieldName( filter.Selection );
                        if ( !string.IsNullOrWhiteSpace( fieldName ) )
                        {
                            var entityFields = EntityHelper.GetEntityFields( reportEntityTypeModel );
                            var entityField = entityFields.Where( a => a.Name == fieldName ).FirstOrDefault();
                            if ( entityField != null )
                            {
                                filterInfo.Title = entityField.Title;
                            }
                            else
                            {
                                filterInfo.Title = fieldName;
                            }
                        }
                    }
                    else
                    {
                        filterInfo.Title = component.GetTitle( reportEntityType.GetType() );
                    }

                    filterInfo.Summary = component.FormatSelection( reportEntityTypeModel, filter.Selection );

                }
            }

            filterList.Add( filterInfo );

            foreach ( var childFilter in filter.ChildFilters )
            {
                GetFilterListRecursive( filterList, childFilter, reportEntityType );
            }
        }
コード例 #52
0
 void IGlobalFilterProvider.AddFilters(FilterInfo filterInfo)
 {
     AddFilters(filterInfo);
 }