public void SetFilterItem(string name, FilterItem value)
 {
     if (FilterItems.ContainsKey(name))
     {
         FilterItems[name] = value;
     } else
     {
         FilterItems.Add(name, value);
     }
 }
        /// <summary>
        /// Create an instance of this form.
        /// </summary>
        /// <param name="items"></param>
        /// <param name="item">FilterItem object to edit, null if adding a new one.</param>
        /// <history>
        /// [Curtis_Beard]	   03/07/2012	ADD: 3131609, exclusions
        /// [Curtis_Beard]	   11/11/2014	CHG: use FilterItem, pass all FilterItems from display form
        /// </history>
        public frmAddEditExclusions(List<FilterItem> items, FilterItem item)
        {
            InitializeComponent();

             _item = item;

             defaultFilterTypes = FilterType.GetDefaultFilterTypes();

             filterItems = items;
        }
Exemple #3
0
 public IEnumerable <Item> GetFromQuality([FromQuery] FilterItem filter)
 {
     if (filter.HighQuantity != 0)
     {
         return(ItemListTemp.FindAll(i => i.Quantity >= filter.LowQuantity && i.Quantity <= filter.HighQuantity));
     }
     else
     {
         return(ItemListTemp.FindAll(i => i.Quantity > filter.LowQuantity));
     }
 }
        public async Task <ActionResult> Edit([Bind(Include = "Id,Title,GroupFilterId")] FilterItem filterItem)
        {
            if (ModelState.IsValid)
            {
                db.Entry(filterItem).State = EntityState.Modified;
                await db.SaveChangesAsync();

                return(RedirectToAction("Index"));
            }
            return(View(filterItem));
        }
Exemple #5
0
        protected override bool DoFind(object value)
        {
            FilterItem fItem = new FilterItem();

            fItem.Column         = ((DataGridViewColumn)(Fields_CB.SelectedItem)).Name;
            fItem.Value          = value;
            fItem.FilterProperty = FilterProperty;
            fItem.Operation      = _operation;
            _search_results      = Localize(fItem);
            return(_search_results != null);
        }
        public IActionResult RegistrarItem([FromQuery] FilterItem filter)
        {
            try
            {
                Item item = new Item
                {
                    Nome          = filter.Nome.Trim(),
                    Valor         = (Double)filter.Valor,
                    QtdDisponivel = filter.QtdDisponivel,
                    Predio        = _database.Predios.First(p => p.IdPredio == filter.Predio)
                };

                if (item.Predio == null)
                {
                    throw new ArgumentException("Predio indicado não encontrado!");
                }

                if (_database.Items.First(I => I.Nome == filter.Nome) != null)
                {
                    throw new ArgumentException("Item com esse nome já existe!");
                }

                if (String.IsNullOrEmpty(item.Nome))
                {
                    throw new ArgumentException("Nome não pode estar vazio");
                }

                if (item.Valor < 0)
                {
                    throw new ArgumentException("Valor não pode ser negativo!");
                }

                if (item.QtdDisponivel < 0)
                {
                    throw new ArgumentException("Quantidade não pode ser negativa!");
                }

                _database.Items.Add(item);
                _database.SaveChanges();

                Response.StatusCode = 201;
                return(new ObjectResult(""));
            }
            catch (ArgumentException ae)
            {
                Response.StatusCode = 400;
                return(new ObjectResult(ae.Message));
            }
            catch (Exception)
            {
                Response.StatusCode = 400;
                return(new ObjectResult(""));
            }
        }
        /// <summary>
        /// Finds references for specific assets.
        /// </summary>
        /// <param name="assets">Specific assets.</param>
        /// <param name="showResults">Shows results in %Maintainer window if true.</param>
        /// <returns>Array of ProjectReferenceItem for the TreeView buildup or manual parsing.</returns>
        public static ProjectReferenceItem[] FindAssetsReferences(string[] assets, bool showResults = true)
        {
            var assetsFilters = new FilterItem[assets.Length];

            for (var i = 0; i < assets.Length; i++)
            {
                assetsFilters[i] = FilterItem.Create(assets[i], FilterKind.Path);
            }

            return(ProjectScopeReferencesFinder.FindAssetsReferences(assetsFilters, false, showResults));
        }
Exemple #8
0
 public AddDevice(FilterItem task)
 {
     InitializeComponent();
     bt_change_cam.LookAndFeel.Style = DevExpress.LookAndFeel.LookAndFeelStyle.Flat;
     bt_change_cam.LookAndFeel.UseDefaultLookAndFeel = false;
     bt_change_cam.LookAndFeel.Style = DevExpress.LookAndFeel.LookAndFeelStyle.Flat;
     //  bt_selected_tab.LookAndFeel.UseDefaultLookAndFeel = false;
     //   bt_selected_tab.Tag = 0;
     CurTask = task;
     IniTaskDevice();
 }
Exemple #9
0
        protected new SortedBindingList <ClasePracticaInfo> Localize(FilterItem item)
        {
            SortedBindingList <ClasePracticaInfo> list = null;
            ClasePracticaList sourceList = null;

            switch (FilterType)
            {
            case IFilterType.None:
                if (List == null)
                {
                    MessageBox.Show(Face.Resources.Messages.NO_RESULTS);
                    return(null);
                }
                sourceList = List;
                break;

            case IFilterType.Filter:
                if (FilteredList == null)
                {
                    MessageBox.Show(Face.Resources.Messages.NO_RESULTS);
                    return(null);
                }
                sourceList = FilteredList;
                break;

            default:
                sourceList = List;
                break;
            }

            if (item.FilterProperty == IFilterProperty.All)
            {
                FCriteria criteria = GetCriteria(string.Empty, item.Value, null, item.Operation);
                list = sourceList.GetSortedSubList(criteria, _properties_list);
            }
            else
            {
                FCriteria criteria = GetCriteria(item.Column, item.Value, null, item.Operation);
                list = sourceList.GetSortedSubList(criteria, _properties_list);
            }

            if (list.Count == 0)
            {
                MessageBox.Show(Face.Resources.Messages.NO_RESULTS);
                return(sourceList.GetSortedList());
            }

            DatosSearch.DataSource = list;
            DatosSearch.MoveFirst();

            AddFilterLabel(item);

            return(list);
        }
Exemple #10
0
        public override void LoadFrom(FilterItem value)
        {
            var binary = Get <BinaryFilterItem>(value);

            Left  = ValueExpressionBuilder.GetBuilder(binary.Left);
            Right = ValueExpressionBuilder.GetBuilder(binary.Right);

            var stringBinary = Get <StringBinaryFilterItem>(value);

            Operator = stringBinary.Operator;
        }
Exemple #11
0
 private void iniNames()
 {
     foreach (QcUser user in QcUser.Users)
     {
         FilterItem item = new FilterItem(user.姓名, 0, user.姓名);
         item.IsChecked = false;
         item.Tag       = user;
         users.Add(item);
     }
     GridCtlFilter.DataSource = users;
 }
        public TopCountFilterConfiguration(FilterItem filterItem)
        {
            HasName(filterItem.Name);
            Layout.HasConfig(new FilterItem {
                Name = filterItem.Name, ControlId = filterItem.ControlId, Label = "", IsVisible = true
            })
            .HasController <DropdownFilterLayoutController>();

            DataFlow.AddSource <RecordCountSource>();
            ModifyParameter(filterItem.ModifyParam);
        }
Exemple #13
0
        protected override bool DoFilter(FilterItem fItem)
        {
#if TRACE
            AppControllerBase.AppControler.Timer.Record("DoFilter - INI");
#endif
            FilterResults = Localize(fItem);
#if TRACE
            AppControllerBase.AppControler.Timer.Record("DoFilter - END");
#endif
            return(FilterResults != null);
        }
Exemple #14
0
        /// <summary>
        /// Adds new assets to the last selection if it existed and calls a GetReferences() with extended selection;
        /// </summary>
        /// <param name="selectedAssets">Additionally selected assets.</param>
        /// <param name="showResults">Shows results in %Maintainer window if true.</param>
        /// <returns>Array of ReferencesTreeElement for the TreeView buildup or manual parsing.</returns>
        public static ReferencesTreeElement[] AddToSelectionAndRun(string[] selectedAssets, bool showResults = true)
        {
            var additiveSelection = new FilterItem[selectedAssets.Length];

            for (var i = 0; i < selectedAssets.Length; i++)
            {
                additiveSelection[i] = FilterItem.Create(selectedAssets[i], FilterKind.Path);
            }

            return(AddToSelectionAndRun(additiveSelection, showResults));
        }
Exemple #15
0
        public void AddFilter(int opcode, bool fromServer)
        {
            FilterItem fItem = new FilterItem(opcode, fromServer);
            if (this.filter.ContainsKey(fItem.GetHashCode()))
            {
                return;
            }
            this.filter.Add(fItem.GetHashCode(), fItem);

            this.applyFilter();
        }
        protected override bool DoFilterByProperty(object value, object secondValue, string column_name)
        {
            Type type = TablaBase.Columns[column_name].ValueType;
            //string dataPropertyName = TablaBase.Columns[column_name].DataPropertyName;

            FilterItem fItem = BuildFilterItem(value, secondValue, column_name, type);

            _filter_property = IFilterProperty.ByParamenter;

            return(DoFilter(fItem));
        }
Exemple #17
0
 /// <summary>
 /// Start drawing A FilterItem and its content at a given position.
 /// </summary>
 /// <param name="g">SpriteBatch to draw on.</param>
 /// <param name="Filter">Filter to draw.</param>
 /// <param name="X">X Position to start drawing.</param>
 /// <param name="Y">Y Position to start drawing.</param>
 /// <returns></returns>
 private int DrawFilter(CustomSpriteBatch g, FilterItem Filter, int X, int Y, ref int Index)
 {
     if (Filter.IsOpen)
     {//Loop through every ShopItem.
         for (int i = 0; i < Filter.ListItem.Count; i++)
         {
             if (Index >= CursorIndexStart && Index < 32 + CursorIndexStart)
             {
                 //Draw the name,
                 g.DrawString(fntArial8, Filter.ListItem[i].RelativePath, new Vector2(X + 20, Y), Color.White);
                 //Draw the quantity related informations.
                 int QuantityOwned = 0;
                 if (Inventory.ListItems.ContainsKey(Filter.ListItem[i].RelativePath))
                 {
                     QuantityOwned = Inventory.ListItems[Filter.ListItem[i].RelativePath].Quantity;
                 }
                 g.DrawString(fntArial8, Filter.ListItem[i].QuantityToBuy + " / " + Filter.ListItem[i].Quantity + " (" + QuantityOwned + ")", new Vector2(Constants.Width - 60, Y), Color.Aqua);
                 //If the current ShopItem is selected, highlight it.
                 if (i == Filter.CursorIndex)
                 {
                     g.Draw(sprRectangle, new Rectangle(X + 16, Y, (int)fntArial8.MeasureString(Filter.ListItem[i].RelativePath).X + 10, fntArial8.LineSpacing), Color.FromNonPremultiplied(255, 255, 255, CursorAlpha));
                 }
                 Y += fntArial8.LineSpacing;
             }
             Index++;
         }
         //Loop through every FilterItem.
         for (int F = 0; F < Filter.ListFilter.Count; F++)
         {
             if (Index >= CursorIndexStart && Index < 32 + CursorIndexStart)
             {
                 //If it's open
                 if (Filter.ListFilter[F].IsOpen)
                 {
                     g.DrawString(fntArial8, "- " + Filter.ListFilter[F].Name, new Vector2(X + 20, Y), Color.White);
                 }
                 else
                 {
                     g.DrawString(fntArial8, "+ " + Filter.ListFilter[F].Name, new Vector2(X + 20, Y), Color.White);
                 }
                 //If the current FilterItem is selected, highlight it.
                 if (F == Filter.CursorIndex - Filter.ListItem.Count)
                 {
                     g.Draw(sprRectangle, new Rectangle(X + 16, Y, (int)fntArial8.MeasureString("+ " + Filter.ListFilter[F].Name).X + 10, fntArial8.LineSpacing), Color.FromNonPremultiplied(255, 255, 255, CursorAlpha));
                 }
                 Y += fntArial8.LineSpacing;
             }
             Index++;
             //Loop in the filter so it draws itself if open.
             Y = DrawFilter(g, Filter.ListFilter[F], X + 20, Y, ref Index);
         }
     }
     return(Y);
 }
        public async Task <ActionResult> Create([Bind(Include = "Id,Title,GroupFilterId")] FilterItem filterItem)
        {
            if (ModelState.IsValid)
            {
                db.FilterItems.Add(filterItem);
                await db.SaveChangesAsync();

                return(RedirectToAction("Index"));
            }

            return(View(filterItem));
        }
Exemple #19
0
        public void AddFilter(int opcode, bool fromServer)
        {
            FilterItem fItem = new FilterItem(opcode, fromServer);

            if (this.filter.ContainsKey(fItem.GetHashCode()))
            {
                return;
            }
            this.filter.Add(fItem.GetHashCode(), fItem);

            this.applyFilter();
        }
Exemple #20
0
 public virtual void ProvideFilter(FilterProviderContext context, FilterItem filterItem)
 {
     if (filterItem.Descriptor.Filter is AuthorizeFilter && (object)filterItem.Filter == null)
     {
         AuthorizeFilter val = filterItem.Descriptor.Filter as AuthorizeFilter;
         IEnumerable <IAuthorizeData> enumerable = val.AuthorizeData;
         if (enumerable == null && (object)val.Policy != null)
         {
             List <IAuthorizeData> list = new List <IAuthorizeData>();
             string text = val.Policy.AuthenticationSchemes.FirstOrDefault();
             if (!string.IsNullOrEmpty(text))
             {
                 List <IAuthorizeData> list2 = list;
                 MvcAuthorizeAttribute mvcAuthorizeAttribute = new MvcAuthorizeAttribute();
                 mvcAuthorizeAttribute.AuthenticationSchemes = text;
                 list2.Add(mvcAuthorizeAttribute);
             }
             enumerable = list;
         }
         filterItem.Filter     = new MvcAuthorizeFilter(enumerable).CreateInstance(context.ActionContext.HttpContext.RequestServices);
         filterItem.IsReusable = true;
     }
     if ((object)filterItem.Filter != null)
     {
         AuthorizeFilter    val2;
         MvcAuthorizeFilter mvcAuthorizeFilter = default(MvcAuthorizeFilter);
         if ((val2 = (filterItem.Filter as AuthorizeFilter)) != null && (mvcAuthorizeFilter = (filterItem.Descriptor.Filter as MvcAuthorizeFilter)) != null)
         {
             filterItem.Filter = mvcAuthorizeFilter.CreateInstance(context.ActionContext.HttpContext.RequestServices);
         }
     }
     else
     {
         IFilterMetadata val3 = filterItem.Descriptor.Filter;
         IFilterFactory  val4;
         if ((val4 = (val3 as IFilterFactory)) == null)
         {
             filterItem.Filter     = val3;
             filterItem.IsReusable = true;
         }
         else
         {
             IServiceProvider requestServices = context.ActionContext.HttpContext.RequestServices;
             filterItem.Filter     = val4.CreateInstance(requestServices);
             filterItem.IsReusable = val4.IsReusable;
             if ((object)filterItem.Filter == null)
             {
                 throw new InvalidOperationException("The 'CreateInstance' method of type '" + typeof(IFilterFactory).Name + "' cannot return a null value.");
             }
             ApplyFilterToContainer((object)filterItem.Filter, val4);
         }
     }
 }
Exemple #21
0
        public static FilterItem GetFilterItem(string name, string value, string parent, FilterType type = FilterType.Bool, bool active = true,
                                               bool selected       = false, FilterBelonging belongsTo = FilterBelonging.All, string parameter = "",
                                               string filterString = "", string displayName           = "", string displayType = FilterDisplayTypes.Checkbox, string tagName = "")
        {
            var fi = new FilterItem(name, value, type, parent, selected, parameter, filterString);

            fi.DisplayName = string.IsNullOrWhiteSpace(displayName) ? name : displayName;
            fi.TagName     = string.IsNullOrWhiteSpace(tagName) ? fi.DisplayName : tagName;
            fi.BelongsToId = (int)belongsTo;

            return(fi);
        }
        public IQueryable <Product> DynamicFieldSelection(FilterItem filter)
        {
            ParameterExpression p = Expression.Parameter(typeof(Product), "p");
            MemberExpression    fieldExpresion     = Expression.PropertyOrField(p, filter.FieldName);
            ConstantExpression  constantExpression = Expression.Constant(filter.Value, filter.ValueType);
            Expression          compare            = Expression.MakeBinary(ExpressionType.Equal, fieldExpresion, constantExpression);

            Expression <Func <Product, bool> > where = Expression.Lambda <Func <Product, bool> >(compare, new[] { p });
            var products = Products.Where(where);

            return(products);
        }
Exemple #23
0
 void StoreItemFilter_FilterUpdate(FilterItem updateFilter)
 {
     if (updateFilter.isActive && !activeFilters.Contains(updateFilter))
     {
         activeFilters.Add(updateFilter);
     }
     else if (!updateFilter.isActive && activeFilters.Contains(updateFilter))
     {
         activeFilters.Remove(updateFilter);
     }
     OrganizeStore();
 }
 void StoreItemFilter_FilterUpdate(FilterItem updateFilter)
 {
     if (updateFilter.isActive && !activeFilters.Contains(updateFilter))
     {
         activeFilters.Add(updateFilter);
     }
     else if (!updateFilter.isActive && activeFilters.Contains(updateFilter))
     {
         activeFilters.Remove(updateFilter);
     }
     OrganizeStore();
 }
Exemple #25
0
        /// <summary>
        /// Handles the selection change event from the filter popup
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SelectionChangedHandler(object sender, SelectionChangedEventArgs e)
        {
            // obtain the term to filter for
            ListView   filterListView = (ListView)sender;
            FilterItem filterItem     = (FilterItem)filterListView.SelectedItem;

            // navigate up to the header to obtain the filter property name
            GridViewColumnHeader header = (GridViewColumnHeader)UIHelpers.FindElementOfTypeUp(filterListView, typeof(GridViewColumnHeader));

            SortableGridViewColumn column = (SortableGridViewColumn)header.Column;
            String currentFilterProperty  = column.SortPropertyName;

            if (filterItem == null)
            {
                return;
            }

            // determine whether to clear the filter for this column
            if (filterItem.ItemView.Equals("Clear"))
            {
                if (currentFilters.ContainsKey(currentFilterProperty))
                {
                    FilterStruct filter = (FilterStruct)currentFilters[currentFilterProperty];
                    filter.button.ContentTemplate = (DataTemplate)dictionary["filterButtonInactiveTemplate"];
                    if (FilterButtonInactiveStyle != null)
                    {
                        filter.button.Style = FilterButtonInactiveStyle;
                    }
                    currentFilters.Remove(currentFilterProperty);
                }

                ApplyCurrentFilters();
            }
            else
            {
                // find the button and apply the active style
                Button button = (Button)UIHelpers.FindVisualElement(header, "filterButton");
                button.ContentTemplate = (DataTemplate)dictionary["filterButtonActiveTemplate"];

                if (FilterButtonActiveStyle != null)
                {
                    button.Style = FilterButtonActiveStyle;
                }

                AddFilter(currentFilterProperty, filterItem, button);
                ApplyCurrentFilters();
            }

            // navigate up to the popup and close it
            Popup popup = (Popup)UIHelpers.FindElementOfTypeUp(filterListView, typeof(Popup));

            popup.IsOpen = false;
        }
Exemple #26
0
        private void AddTimelineTreeNode(FilterItem _item)
        {
            TreeNode _treeNode = new TreeNode();

            _treeNode.Text = _item.Name;
            _treeNode.Tag  = _item;

            _treeNode.ImageIndex         = 1;
            _treeNode.SelectedImageIndex = 1;

            tvTimeline.Nodes.Add(_treeNode);
        }
Exemple #27
0
 private static void AssertSameFilterEntry(
     RegressionEnvironment env,
     string eventTypeName)
 {
     IDictionary<string, FilterItem> filters = SupportFilterServiceHelper.GetFilterSvcAllStmtForTypeSingleFilter(env.Runtime, eventTypeName);
     FilterItem s0 = filters.Get("s0");
     FilterItem s1 = filters.Get("s1");
     Assert.AreEqual(FilterOperator.REBOOL, s0.Op);
     Assert.IsNotNull(s0.Index);
     Assert.AreSame(s0.Index, s1.Index);
     Assert.AreSame(s0.OptionalValue, s1.OptionalValue);
 }
Exemple #28
0
        public override void ProvideFilter(FilterProviderContext context, FilterItem filterItem)
        {
            FilterRecord record;

            FilterCollectionExtensions.Records.TryGetValue(filterItem.Descriptor.Filter, out record);
            if (record != null && !record.Match(context))
            {
                return;
            }

            base.ProvideFilter(context, filterItem);
        }
Exemple #29
0
 public IEnumerable <Item> GetWithFilter([FromQuery] FilterItem filter)
 {
     if (filter.HighQuantity == 0)
     {
         filter.HighQuantity = double.MaxValue;
     }
     else
     {
         filter.HighQuantity = filter.HighQuantity;
     }
     return(_items.FindAll(i => i.Quantity > filter.LowQuantity && i.Quantity < filter.HighQuantity));
 }
Exemple #30
0
        public async Task <IActionResult> PutFilterItem(long id, FilterItem item)
        {
            if (id != item.Id)
            {
                return(BadRequest());
            }

            _context.Entry(item).State = EntityState.Modified;
            await _context.SaveChangesAsync();

            return(NoContent());
        }
        public static bool TryAddNewItemToFilters(ref FilterItem[] filters, FilterItem newItem)
        {
            foreach (var filterItem in filters)
            {
                if (filterItem.value == newItem.value)
                {
                    return(false);
                }
            }

            ArrayUtility.Add(ref filters, newItem);
            return(true);
        }
Exemple #32
0
        public FilterPairViewModel(FilterPair filterPair, Session session, ConfigurationViewModel configuration)
        {
            m_filterPair    = filterPair;
            m_session       = session;
            m_configuration = configuration;

            LeftFilterItem = filterPair.FilterItem.FirstOrDefault(x => string.Equals(x.MigrationSourceUniqueId, session.LeftMigrationSourceUniqueId));
            Debug.Assert(LeftFilterItem != null, "LeftFilterItem == null");
            RightFilterItem = filterPair.FilterItem.FirstOrDefault(x => string.Equals(x.MigrationSourceUniqueId, session.RightMigrationSourceUniqueId));
            Debug.Assert(RightFilterItem != null, "RightFilterItem == null");

            UpdateFilterStringExtensions();
        }
Exemple #33
0
        private RowFilter.ColumnFilter MakeColumnFilter(ComboBox comboOperation, TextBox text)
        {
            FilterItem filterItem = comboOperation.SelectedItem as FilterItem;

            if (null == filterItem || FilterOperations.OP_HAS_ANY_VALUE == filterItem.FilterOperation)
            {
                return(null);
            }
            var filterPredicate = FilterPredicate.CreateFilterPredicate(DataSchema, PropertyDescriptor.PropertyType,
                                                                        filterItem.FilterOperation, text.Text);

            return(new RowFilter.ColumnFilter(ColumnId.GetColumnId(PropertyDescriptor), filterPredicate));
        }
        /// <summary>
        /// Save the new/edit item.
        /// </summary>
        /// <param name="sender">system parameter</param>
        /// <param name="e">system parameter</param>
        /// <history>
        /// [Curtis_Beard]	   03/07/2012	ADD: 3131609, exclusions
        /// [Curtis_Beard]	   11/11/2014	CHG: use FilterItem
        /// </history>
        private void btnOK_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.None;
            FilterItem item = VerifyInterface();

            if (item != null)
            {
                _item = item;

                this.DialogResult = DialogResult.OK;
                this.Close();
            }
        }
Exemple #35
0
        /// <summary>
        /// Grep files for specified text.
        /// </summary>
        /// <param name="sourceDirectory">directory to begin grep</param>
        /// <param name="sourceDirectoryFilter">any directory specifications</param>
        /// <param name="sourceFileFilter">any file specifications</param>
        /// <remarks>Recursive algorithm</remarks>
        /// <history>
        /// [Curtis_Beard]      09/08/2005	Created
        /// [Curtis_Beard]      12/06/2005	CHG: skip any invalid directories
        /// [Curtis_Beard]      03/14/2006  CHG: catch any errors generated during a file search
        /// [Curtis_Beard]      07/03/2006  FIX: 1516774, ignore a thread abort exception
        /// [Curtis_Beard]      07/12/2006  CHG: make private
        /// [Curtis_Beard]      07/28/2006  ADD: check extension against exclusion list
        /// [Curtis_Beard]      01/27/2007  ADD: 1561584, check directories/files if hidden or system
        /// [Ed_Jakubowski]     05/20/2009  ADD: When a blank searchText is given only list files
        /// [Andrew_Radford]    13/08/2009  CHG: Remove searchtext param
        /// [Curtis_Beard]	   03/07/2012	ADD: 3131609, exclusions
        /// [Curtis_Beard]	   10/10/2012	CHG: 3131609, signal when directories are filtered out due to system/hidden flag
        /// [Curtis_Beard]      09/17/2013    FIX: 45, check against a specific extension when only 3 characters is defined (*.txt can return things like *.txtabc due to .net GetFiles)
        /// [Curtis_Beard]      09/20/2013    CHG: use EnumerateFiles and EnumerateDirectories instead of GetFiles,GetDirectories to not lock up on waiting for those methods.
        /// </history>
        private void Execute(DirectoryInfo sourceDirectory, string sourceDirectoryFilter, string sourceFileFilter)
        {
            // skip directory if matches an exclusion item
             if (FileFilterSpec != null && FileFilterSpec.FilterItems != null)
             {
            var dirFilterItems = from f in FileFilterSpec.FilterItems where f.FilterType.Category == FilterType.Categories.Directory select f;
            foreach (FilterItem item in dirFilterItems)
            {
               string filterValue = string.Empty;
               if (item.ShouldExcludeDirectory(sourceDirectory, out filterValue))
               {
                  OnDirectoryFiltered(sourceDirectory, item, filterValue);
                  return;
               }
            }
             }

             // Check for File Filter
             string filePattern = "*";
             if (sourceFileFilter != null)
            filePattern = sourceFileFilter.Trim();

             // Check for Folder Filter
             string dirPattern = "*";
             if (sourceDirectoryFilter != null)
            dirPattern = sourceDirectoryFilter.Trim();

             //Search Every File for search text
             foreach (FileInfo SourceFile in sourceDirectory.EnumerateFiles(filePattern))
             {
            bool processFile = true;
            if (sourceFileFilter != null && !StriktMatch(SourceFile.Extension, sourceFileFilter.Trim()))
            {
               processFile = false;

               string filterValue = SourceFile.Extension;
               FilterItem filterItem = new FilterItem(new FilterType(FilterType.Categories.File, FilterType.SubCategories.Extension), string.Empty, FilterType.ValueOptions.None, false, true);
               OnFileFiltered(SourceFile, filterItem, filterValue);
            }

            if (processFile)
            {
               SearchFile(SourceFile);
            }
             }

             if (SearchSpec.SearchInSubfolders)
             {
            //Recursively go through every subdirectory and it's files (according to folder filter)
            foreach (var sourceSubDirectory in sourceDirectory.EnumerateDirectories(dirPattern))
            {
               try
               {
                  Execute(sourceSubDirectory, sourceDirectoryFilter, sourceFileFilter);
               }
               catch
               {
                  //skip any invalid directory
               }
            }
             }
        }
Exemple #36
0
        /// <summary>
        /// Return true if the file does not pass the fileFilterSpec, i.e should be skipped
        /// </summary>
        /// <param name="file">FileInfo object of current file</param>
        /// <param name="fileFilterSpec">Current file filter settings</param>
        /// <param name="filterItem">Item causing filtering, null if none</param>
        /// <param name="filterValue">Output of actual filter value</param>
        /// <returns>true if file does not pass file filter settings, false otherwise</returns>
        /// <history>
        /// [Andrew_Radford]    13/08/2009  Created
        /// [Curtis_Beard]	   03/07/2012	ADD: 3131609, exclusions
        /// </history>
        private static bool ShouldFilterOut(FileInfo file, IFileFilterSpec fileFilterSpec, out FilterItem filterItem, out string filterValue)
        {
            filterItem = null;
             filterValue = string.Empty;

             if (fileFilterSpec.FilterItems != null && fileFilterSpec.FilterItems.Count > 0)
             {
            var fileFilterItems = from f in fileFilterSpec.FilterItems where f.FilterType.Category == FilterType.Categories.File select f;
            foreach (FilterItem item in fileFilterItems)
            {
               filterValue = string.Empty;
               if (item.ShouldExcludeFile(file, out filterValue))
               {
                  filterItem = item;
                  return true;
               }
            }
             }

             return false;
        }
 private FilterItem CreateFilterItem(string filterType)
 {
     var type = TypeHelper<Type>.GetTypeByFullName(filterType);
     var typeFilterAttribute = new TypeFilterAttribute(type) {Order = 0};
     var filterDescriptor = new FilterDescriptor(typeFilterAttribute, 0);
     var filterInstance = _serviceProvider.GetService(type);
     var filterMetaData = (IFilterMetadata) filterInstance;
     var fi = new FilterItem(filterDescriptor, filterMetaData);
     return fi;
 }
Exemple #38
0
 public void applyFilter()
 {
     // Clear the old list
     this.diplayedList.Clear();
     // neue Größe schonmal festlegen
     this.diplayedList.Capacity = this.packetList.Count;
     FilterItem f;
     foreach (L2Packet p in this.packetList)
     {
         f = new FilterItem(p.OpCode, (p is GameServerPacket));
         if (this.filter.ContainsKey(f.GetHashCode()))
         {
             continue;
         }
         this.diplayedList.Add(p);
     }
 }
    private List<FilterItem> CreateFilterItems()
    {
        try
        {
            GroupInfo info = GroupContext.GetGroupContext().CurrentGroupInfo.CurrentGroup.GroupInformation;
            GroupLayout layout = info.GetGroupLayout();

            List<FilterItem> items = new List<FilterItem>();
            foreach (GroupLayoutItem layoutItem in layout.Items)
            {
                if (!layoutItem.IsFilterable)
                    continue;

                FilterItem item = new FilterItem();
                item.Name = layoutItem.Caption;
                item.Alias = layoutItem.Alias;
                item.Hidden = _hiddenFilters.Contains(layoutItem.Alias);
                items.Add(item);
            }

            return items;
        }
        catch
        {
            return new List<FilterItem>();
        }
    }
        /// <summary>
        /// Handles the ShowFilter command to populate the filter list and display the popup
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ShowFilterCommand(object sender, ExecutedRoutedEventArgs e)
        {
            Button button = e.OriginalSource as Button;

            if (button != null)
            {
                // navigate up to the header
                GridViewColumnHeader header = (GridViewColumnHeader)UIHelpers.FindElementOfTypeUp(button, typeof(GridViewColumnHeader));

                // then down to the popup
                Popup popup = (Popup)UIHelpers.FindElementOfType(header, typeof(Popup));

                if (popup != null)
                {
                    // find the property name that we are filtering
                    SortableGridViewColumn column = (SortableGridViewColumn)header.Column;

                    IEnumerable filterValues = ((SortableGridViewColumn)column).FilterValues;

                    String propertyName = column.SortPropertyName;

                    // clear the previous filter
                    if (filterList == null)
                    {
                        filterList = new ArrayList();
                    }
                    filterList.Clear();

                    bool containsNull = false;

                    //PropertyDescriptor filterPropDesc = TypeDescriptor.GetProperties(typeof(Airport))[propertyName];

                    if (filterValues != null)
                    {
                        filterList.Add(new FilterItem(new FilterValue("All",0,Int32.MaxValue)));

                        foreach (FilterValue value in filterValues)
                        {
                            FilterItem filterItem = new FilterItem(value);

                            filterList.Add(filterItem);
                        }
                        ContentControl ccPopUp = (ContentControl)popup.Child;

                        ccPopUp.SetResourceReference(ContentControl.ContentTemplateProperty, "FixedFilteredPopUp");

                    }
                    else
                    {
                        if (IsPropertyFiltered(propertyName))
                        {
                            filterList.Add(new FilterItem("Clear"));
                        }
                        else
                        {
                            // iterate over all the objects in the list
                            foreach (Object item in Items)
                            {
                                object value = getPropertyValue(item, propertyName);

                                if (value != null)
                                {
                                    FilterItem filterItem = new FilterItem(value as IComparable);

                                    Boolean contains = filterList.Cast<FilterItem>().ToList().Exists(i => i.Item.ToString() == filterItem.Item.ToString());

                                    if (!filterList.Contains(filterItem) && !contains)
                                    {
                                        filterList.Add(filterItem);
                                    }

                                }
                                else
                                {
                                    containsNull = true;
                                }

                            }
                        }

                        filterList.Sort();

                        if (containsNull)
                        {
                            filterList.Add(new FilterItem(null));
                        }
                    }

                    // open the popup to display this list
                    popup.DataContext = filterList;
                    CollectionViewSource.GetDefaultView(filterList).Refresh();
                    popup.IsOpen = true;

                    if (filterValues != null)
                    {
                        Button btnOk = UIHelpers.FindChild<Button>(popup.Child, "btnOk");
                        btnOk.Click += btnFixedOk_Click;

                        Button btnCancel = UIHelpers.FindChild<Button>(popup.Child, "btnCancel");
                        btnCancel.Click += btnCancel_Click;
                    }
                    else
                    {
                        Button btnOk = UIHelpers.FindChild<Button>(popup.Child, "btnOk");
                        btnOk.Click += btnOk_Click;

                        Button btnCancel = UIHelpers.FindChild<Button>(popup.Child, "btnCancel");
                        btnCancel.Click += btnCancel_Click;
                    }

                    // connect to the selection change event
                    //ListView listView = UIHelpers.FindChild<ListView>(popup.Child, "filterList");
                    //listView.SelectionChanged += SelectionChangedHandler;

                }
            }
        }
 private void AddFilters(String property, FilterItem[] values, Button button)
 {
     if (currentFilters.ContainsKey(property))
     {
         currentFilters.Remove(property);
     }
     currentFilters.Add(property, new FilterStruct(property, button, values));
 }
 void ProxyManager_OnCapabilityAdded(GridProxy.CapInfo cap)
 {
     Application.Invoke((sender, e) =>
     {
         if (!CapFilterItems.ContainsKey(cap.CapType))
         {
             FilterItem item = new FilterItem() { Name = cap.CapType, Type = ItemType.Cap };
             item.FilterItemChanged += item_FilterItemChanged;
             item.Enabled = true;
             CapFilterItems[item.Name] = item;
             capStore.AppendValues(item);
         }
     });
 }
    void ProxyManager_OnEventMessageLog(GridProxy.CapsRequest req, GridProxy.CapsStage stage)
    {
        Application.Invoke((sender, e) =>
        {
            if (!CapFilterItems.ContainsKey(req.Info.CapType))
            {
                FilterItem item = new FilterItem() { Enabled = true, Name = req.Info.CapType, Type = ItemType.EQ };
                item.FilterItemChanged += item_FilterItemChanged;
                CapFilterItems[item.Name] = item;
                capStore.AppendValues(item);
            }

            ProxyManager_OnMessageLog(req, GridProxy.CapsStage.Response);
        });
    }
    void InitUDPFilters(OSDArray filters)
    {
        UDPFilterItems.Clear();
        udpStore.Clear();

        if (filters != null)
        {
            LoadFromOSD(UDPFilterItems, filters);
        }

        if (!UDPFilterItems.ContainsKey("Login Request"))
        {
            UDPFilterItems["Login Request"] = new FilterItem() { Enabled = true, Name = "Login Request", Type = ItemType.Login };
        }

        if (!UDPFilterItems.ContainsKey("Login Response"))
        {
            UDPFilterItems["Login Response"] = new FilterItem() { Enabled = true, Name = "Login Response", Type = ItemType.Login };
        }

        foreach (string name in Enum.GetNames(typeof(PacketType)))
        {
            if (!string.IsNullOrEmpty(name) && !UDPFilterItems.ContainsKey(name))
            {
                var item = new FilterItem() { Enabled = false, Name = name, Type = ItemType.UDP };
                UDPFilterItems[name] = item;
            }
        }

        List<string> keys = new List<string>(UDPFilterItems.Keys);
        keys.Sort((a, b) => { return string.Compare(a.ToLower(), b.ToLower()); });

        udpStore.AppendValues(UDPFilterItems["Login Request"]);
        udpStore.AppendValues(UDPFilterItems["Login Response"]);

        foreach (var key in keys)
        {
            UDPFilterItems[key].FilterItemChanged += item_FilterItemChanged;
            if (UDPFilterItems[key].Type == ItemType.Login) continue;
            udpStore.AppendValues(UDPFilterItems[key]);
        }
    }
Exemple #45
0
        /// <summary>
        /// Search a given file for the searchText.
        /// </summary>
        /// <param name="file">FileInfo object for file to search for searchText</param>
        /// <history>
        /// [Curtis_Beard]		09/08/2005	Created
        /// [Curtis_Beard]		11/21/2005	ADD: update hit count when actual line added
        /// [Curtis_Beard]		12/02/2005	CHG: use SearchingFile instead of StatusMessage
        /// [Curtis_Beard]		04/21/2006	CHG: use a regular expression match collection to get
        ///											correct count of hits in a line when using RegEx
        /// [Curtis_Beard]		07/03/2006	FIX: 1500174, use a FileStream to open the files readonly
        /// [Curtis_Beard]		07/07/2006	FIX: 1512029, RegEx use Case Sensitivity and WholeWords,
        ///											also use different whole word matching regex
        /// [Curtis_Beard]		07/26/2006	ADD: 1512026, column position
        /// [Curtis_Beard]		07/26/2006	FIX: 1530023, retrieve file with correct encoding
        /// [Curtis_Beard]		09/12/2006	CHG: Converted to C#
        /// [Curtis_Beard]		09/28/2006	FIX: check for any plugins before looping through them
        /// [Curtis_Beard]		05/18/2006	FIX: 1723815, use correct whole word matching regex
        /// [Curtis_Beard]		06/26/2007	FIX: correctly detect plugin extension support
        /// [Curtis_Beard]		06/26/2007	FIX: 1779270, increase array size holding context lines
        /// [Curtis_Beard]		10/09/2012	FIX: don't overwrite position when getting context lines
        /// [Curtis_Beard]		10/12/2012	FIX: get correct position when using whole word option
        /// [Curtis_Beard]		10/12/2012	CHG: 32, implement a hit count filter
        /// [Curtis_Beard]		10/31/2012	CHG: renamed to SearchFileContents, remove parameter searchText
        /// [Curtis_Beard]		08/19/2014	FIX: 57, escape search text when whole word is enabled but not regular expressions
        /// [Curtis_Beard]      10/27/2014	CHG: 85, remove leading white space, remove use of newline so each line is in hit object
        /// [Curtis_Beard]      02/09/2015	CHG: 92, support for specific file encodings
        /// [Curtis_Beard]		03/05/2015	FIX: 64/35, if whole word doesn't pass our check but does pass regex, make it fail.  Code cleanup.
        /// [Curtis_Beard]		04/02/2015	CHG: remove line number logic and always include line number in MatchResultLine.
        /// [Curtis_Beard]		05/18/2015	FIX: 72, don't grab file sample when detect encoding option is turned off.
        /// [Curtis_Beard]		05/18/2015	FIX: 69, use same stream to detect encoding and grep contents
        /// [Curtis_Beard]	   05/26/2015	FIX: 69, add performance setting for file detection
        /// [Curtis_Beard]		06/02/2015	FIX: 75, use sample size from performance setting
        /// [theblackbunny]		06/25/2015	FIX: 39, remove context lines that intersect with each other in different MatchResults
        /// </history>
        private void SearchFileContents(FileInfo file)
        {
            // Raise SearchFile Event
             OnSearchingFile(file);

             FileStream _stream = null;
             StreamReader _reader = null;
             int _lineNumber = 0;
             MatchResult match = null;
             Regex _regularExp;
             MatchCollection _regularExpCol = null;
             bool _hitOccurred = false;
             bool _fileNameDisplayed = false;
             int _maxContextLines = 0;
             var _context = new string[11];
             int _contextIndex = -1;
             int _lastHit = 0;
             int userFilterCount = 0;

             try
             {
            #region Plugin Processing

            if (Plugins != null)
            {
               for (int i = 0; i < Plugins.Count; i++)
               {
                  // find a valid plugin for this file type
                  if (Plugins[i].Enabled && Plugins[i].Plugin.IsAvailable)
                  {
                     // detect if plugin supports extension
                     bool isFound = Plugins[i].Plugin.IsFileSupported(file);

                     // if extension not supported try another plugin
                     if (!isFound)
                        continue;

                     Exception pluginEx = null;

                     // load plugin and perform grep
                     if (Plugins[i].Plugin.Load())
                     {
                        OnSearchingFileByPlugin(Plugins[i].Plugin.Name);
                        match = Plugins[i].Plugin.Grep(file, SearchSpec, ref pluginEx);
                     }
                     else
                     {
                        OnSearchError(file, new Exception(string.Format("Plugin {0} failed to load.", Plugins[i].Plugin.Name)));
                     }

                     Plugins[i].Plugin.Unload();

                     // if the plugin processed successfully
                     if (pluginEx == null)
                     {
                        // check for a hit
                        if (match != null)
                        {
                           match.FromPlugin = true;

                           // only perform is not using negation
                           if (!SearchSpec.UseNegation)
                           {
                              if (DoesPassHitCountCheck(match))
                              {
                                 match.Index = MatchResults.Count;
                                 MatchResults.Add(match);
                                 OnFileHit(file, match.Index);

                                 if (SearchSpec.ReturnOnlyFileNames)
                                    match.SetHitCount();

                                 OnLineHit(match, match.Index);
                              }
                           }
                        }
                        else if (SearchSpec.UseNegation)
                        {
                           // no hit but using negation so create one
                           match = new MatchResult(file) { Index = MatchResults.Count, FromPlugin = true };
                           MatchResults.Add(match);
                           OnFileHit(file, match.Index);
                        }
                     }
                     else
                     {
                        // the plugin had an error
                        OnSearchError(file, pluginEx);
                     }

                     return;
                  }
               }
            }
            #endregion

            // open stream to file to use in encoding detection if enabled and in grep logic
            _stream = file.Open(FileMode.Open, FileAccess.Read, FileShare.ReadWrite);

            #region Encoding Detection

            string usedEncoder = string.Empty;
            System.Text.Encoding encoding = null;

            //
            // User specified file encoding
            //
            FileEncoding fileEncoding = SearchSpec.FileEncodings != null && SearchSpec.FileEncodings.Count > 0 ?
               (from f in SearchSpec.FileEncodings where f.FilePath.Equals(file.FullName, StringComparison.InvariantCultureIgnoreCase) && f.Enabled select f).ToList().FirstOrDefault()
               :  null;
            if (fileEncoding != null)
            {
               usedEncoder = "User";
               encoding = fileEncoding.Encoding;
            }
            else
            {
               //
               // Detect file encoding if enabled
               //
               if (SearchSpec.EncodingDetectionOptions.DetectFileEncoding)
               {
                  // encoding cache check
                  var key = file.FullName;
                  if (SearchSpec.EncodingDetectionOptions.UseEncodingCache &&
                     EncodingCache.Instance.ContainsKey(key))
                  {
                     var value = EncodingCache.Instance.GetItem(key);

                     usedEncoder = value.DetectorName;
                     encoding = System.Text.Encoding.GetEncoding(value.CodePage);
                  }
                  else
                  {
                     byte[] sampleBytes;

                     //Check if can read first
                     try
                     {
                        int sampleSize = EncodingOptions.GetSampleSizeByPerformance(SearchSpec.EncodingDetectionOptions != null ? SearchSpec.EncodingDetectionOptions.PerformanceSetting : EncodingOptions.Performance.Default);
                        sampleBytes = EncodingTools.ReadFileContentSample(_stream, sampleSize);
                     }
                     catch (Exception ex)
                     {
                        // can't read file for sample bytes
                        OnSearchError(file, ex);
                        return;
                     }

                     // detect encoding based on user set performance level that determines what detectors are used
                     encoding = EncodingDetector.Detect(sampleBytes,
                        out usedEncoder,
                        EncodingOptions.GetEncodingDetectorOptionsByPerformance(SearchSpec.EncodingDetectionOptions != null ? SearchSpec.EncodingDetectionOptions.PerformanceSetting : EncodingOptions.Performance.Default),
                        System.Text.Encoding.Default);

                     // add to cache if enabled
                     if (encoding != null && SearchSpec.EncodingDetectionOptions.UseEncodingCache)
                     {
                        var value = new EncodingCacheItem() { CodePage = encoding.CodePage, DetectorName = usedEncoder };
                        EncodingCache.Instance.SetItem(key, value);
                     }
                  }
               }
               else
               {
                  // Use original encoding method before detect encoding option availalbe
                  usedEncoder = "Default";
                  encoding = System.Text.Encoding.Default;
               }
            }

            if (encoding == null)
            {
               // Could not detect file encoding
               OnSearchError(file, new Exception("Could not detect file encoding."));
               return;
            }

            OnFileEncodingDetected(file, encoding, usedEncoder);

            // process all encoding detectors and display results to output window
            //var values = EncodingDetector.DetectAll(sampleBytes);
            //if (values.Count > 0)
            //{
            //   System.Diagnostics.Debug.WriteLine(string.Format("File: {0}", file.FullName));
            //   foreach (var value in values)
            //   {
            //      System.Diagnostics.Debug.WriteLine(string.Format("Encoding: {0} ({1})", value.Encoding != null ? value.Encoding.EncodingName : "None", value.Option.ToString()));
            //   }
            //   System.Diagnostics.Debug.WriteLine(Environment.NewLine);
            //}

            #endregion

            // could have read some data for the encoding check, seek back to start of file
            if (_stream.CanSeek)
            {
               _stream.Seek(0, SeekOrigin.Begin);
            }
            _reader = new StreamReader(_stream, encoding);

            _maxContextLines = SearchSpec.ContextLines + 1;
            do
            {
               string textLine = _reader.ReadLine();

               if (textLine == null)
                  break;
               else
               {
                  _lineNumber += 1;

                  int _posInStr = -1;
                  if (SearchSpec.UseRegularExpressions)
                  {
                     if (textLine.Length > 0)
                     {
                        string pattern = string.Format("{0}{1}{0}", SearchSpec.UseWholeWordMatching ? "\\b" : string.Empty, SearchSpec.SearchText);
                        RegexOptions options = SearchSpec.UseCaseSensitivity ? RegexOptions.None : RegexOptions.IgnoreCase;
                        _regularExp = new Regex(pattern, options);
                        _regularExpCol = _regularExp.Matches(textLine);

                        if (_regularExpCol.Count > 0)
                        {
                           if (SearchSpec.UseNegation)
                           {
                              _hitOccurred = true;
                           }

                           _posInStr = 1;
                        }
                     }
                  }
                  else
                  {
                     // If we are looking for whole worlds only, perform the check.
                     if (SearchSpec.UseWholeWordMatching)
                     {
                        _regularExp = new Regex("\\b" + Regex.Escape(SearchSpec.SearchText) + "\\b", SearchSpec.UseCaseSensitivity ? RegexOptions.None : RegexOptions.IgnoreCase);

                        // if match is found, also check against our internal line hit count method to be sure they are in sync
                        Match mtc = _regularExp.Match(textLine);
                        if (mtc != null && mtc.Success && RetrieveLineMatches(textLine, SearchSpec).Count > 0)
                        {
                           if (SearchSpec.UseNegation)
                           {
                              _hitOccurred = true;
                           }

                           _posInStr = mtc.Index;
                        }
                     }
                     else
                     {
                        _posInStr = textLine.IndexOf(SearchSpec.SearchText, SearchSpec.UseCaseSensitivity ? StringComparison.Ordinal : StringComparison.OrdinalIgnoreCase);

                        if (SearchSpec.UseNegation && _posInStr > -1)
                        {
                           _hitOccurred = true;
                        }
                     }
                  }

                  //*******************************************
                  // We found an occurrence of our search text.
                  //*******************************************
                  if (_posInStr > -1)
                  {
                     //since we have a hit, check to see if negation is checked
                     if (SearchSpec.UseNegation)
                        break;

                     // create new hit and add to collection
                     if (match == null)
                     {
                        match = new MatchResult(file) { Index = MatchResults.Count, DetectedEncoding = encoding };
                        MatchResults.Add(match);
                     }

                     // don't show until passes count check
                     if (!_fileNameDisplayed && DoesPassHitCountCheck(match))
                     {
                        OnFileHit(file, match.Index);

                        _fileNameDisplayed = true;
                     }

                     // If we are only showing filenames, go to the next file.
                     if (SearchSpec.ReturnOnlyFileNames)
                     {
                        if (!_fileNameDisplayed)
                        {
                           OnFileHit(file, match.Index);

                           _fileNameDisplayed = true;
                        }

                        //notify that at least 1 hit is in file
                        match.SetHitCount();
                        OnLineHit(match, match.Index);

                        break;
                     }

                     // Display context lines if applicable.
                     if (SearchSpec.ContextLines > 0 && _lastHit <= 0)
                     {
                        if (match.Matches.Count > 0 && _lastHit < -_maxContextLines)
                        {
                           // Insert a blank space before the context lines.
                           var matchLine = new MatchResultLine() { Line = string.Empty, LineNumber = -1 };
                           match.Matches.Add(matchLine);
                           int _pos = match.Matches.Count - 1;

                           if (DoesPassHitCountCheck(match))
                           {
                              OnLineHit(match, _pos);
                           }
                        }

                        // Display preceding n context lines before the hit.
                        int tempContextLines = SearchSpec.ContextLines;
                        // But only output the context lines which are not part of the previous context
                        if(_lastHit >= -_maxContextLines)
                        {
                           tempContextLines = -_lastHit;
                        }
                        // Roll back the context index to get the first context line that needs to be displayed
                        _contextIndex = _contextIndex - tempContextLines;
                        if(_contextIndex < 0)
                        {
                           _contextIndex += _maxContextLines;
                        }
                        for (int tempPosInStr = tempContextLines; tempPosInStr >= 1; tempPosInStr--)
                        {
                           _contextIndex = _contextIndex + 1;
                           if (_contextIndex >= _maxContextLines)
                              _contextIndex = 0;

                           // If there is a match in the first one or two lines,
                           // the entire preceeding context may not be available.
                           if (_lineNumber > tempPosInStr)
                           {
                              // Add the context line.
                              var matchLine = new MatchResultLine() { Line = _context[_contextIndex], LineNumber = _lineNumber - tempPosInStr };
                              match.Matches.Add(matchLine);
                              int _pos = match.Matches.Count - 1;

                              if (DoesPassHitCountCheck(match))
                              {
                                 OnLineHit(match, _pos);
                              }
                           }
                        }
                     }

                     _lastHit = SearchSpec.ContextLines;

                     //
                     // Add the actual "hit".
                     //
                     var matchLineFound = new MatchResultLine() { Line = textLine, LineNumber = _lineNumber, HasMatch = true };

                     if (SearchSpec.UseRegularExpressions)
                     {
                        _posInStr = _regularExpCol[0].Index;
                        match.SetHitCount(_regularExpCol.Count);

                        foreach (Match regExMatch in _regularExpCol)
                        {
                           matchLineFound.Matches.Add(new MatchResultLineMatch(regExMatch.Index, regExMatch.Length));
                        }
                     }
                     else
                     {
                        var lineMatches = RetrieveLineMatches(textLine, SearchSpec);
                        match.SetHitCount(lineMatches.Count);
                        matchLineFound.Matches = lineMatches;
                     }
                     matchLineFound.ColumnNumber = _posInStr + 1;
                     match.Matches.Add(matchLineFound);
                     int _index = match.Matches.Count - 1;

                     if (DoesPassHitCountCheck(match))
                     {
                        OnLineHit(match, _index);
                     }
                  }
                  else if (SearchSpec.ContextLines > 0)
                  {
                     if(_lastHit > 0)
                     {
                        //***************************************************
                        // We didn't find a hit, but since lastHit is > 0, we
                        // need to display this context line.
                        //***************************************************
                        var matchLine = new MatchResultLine() { Line = textLine, LineNumber = _lineNumber };
                        match.Matches.Add(matchLine);
                        int _index = match.Matches.Count - 1;

                        if (DoesPassHitCountCheck(match))
                        {
                           OnLineHit(match, _index);
                        }
                     }
                     if(_lastHit >= -_maxContextLines)
                     {
                        //*****************************************************
                        // We continue keeping track of the number of potential
                        // context lines since the last displayed context line
                        // until we pass (-_maxContextLines).
                        //*****************************************************
                        _lastHit -= 1;
                     }

                  } // Found a hit or not.

                  // If we are showing context lines, keep the last n+1 lines.
                  if (SearchSpec.ContextLines > 0)
                  {
                     _contextIndex += 1;
                     if (_contextIndex >= _maxContextLines)
                        _contextIndex = 0;

                     _context[_contextIndex] = textLine;
                  }
               }
            }
            while (true);

            // send event file/line hit if we haven't yet but it should be
            if (!_fileNameDisplayed && match != null && DoesPassHitCountCheck(match))
            {
               // need to display it
               OnFileHit(file, match.Index);
               OnLineHit(match, match.Index);
            }

            // send event for file filtered if it fails the file hit count filter
            if (!SearchSpec.UseNegation && !SearchSpec.ReturnOnlyFileNames && match != null && !DoesPassHitCountCheck(match))
            {
               // remove from grep collection only if
               // not negation
               // not filenames only
               // actually have a hit
               // doesn't pass the hit count filter
               MatchResults.RemoveAt(MatchResults.Count - 1);

               string filterValue = match.HitCount.ToString();
               FilterItem filterItem = new FilterItem(new FilterType(FilterType.Categories.File, FilterType.SubCategories.MinimumHitCount), userFilterCount.ToString(), FilterType.ValueOptions.None, false, true);
               OnFileFiltered(file, filterItem, filterValue);
            }

            //
            // Check for no hits through out the file
            //
            if (SearchSpec.UseNegation && _hitOccurred == false)
            {
               //add the file to the hit list
               if (!_fileNameDisplayed)
               {
                  match = new MatchResult(file) { Index = MatchResults.Count, DetectedEncoding = encoding };
                  MatchResults.Add(match);
                  OnFileHit(file, match.Index);
               }
            }
             }
             finally
             {
            if (_reader != null)
               _reader.Close();

            if (_stream != null)
               _stream.Close();
             }
        }
 public FilterStruct(String property, Button button, FilterItem[] values)
 {
     this.values = values;
     this.button = button;
     this.property = property;
 }
 private static FilterItem CreateFilterItem(string filterType)
 {
     var authFilter = TypeHelper<Type>.GetTypeByFullName(filterType);
     var typeFilterAttribute = new TypeFilterAttribute(authFilter) {Order = -1};
     var filterDescriptor = new FilterDescriptor(typeFilterAttribute, -1);
     var filterMetaData = (IFilterMetadata) Activator.CreateInstance(authFilter);
     var fi = new FilterItem(filterDescriptor, filterMetaData);
     return fi;
 }
Exemple #48
0
 /// <summary>
 /// Handles the Grep object's FileFiltered event
 /// </summary>
 /// <param name="file">FileInfo object containg currently being search file</param>
 /// <param name="filterItem">FilterItem causing the filtering</param>
 /// <param name="filterValue">Value that caused the filtering</param>
 /// <history>
 /// [Curtis_Beard]	   03/07/2012	ADD: 3131609, exclusions
 /// [Curtis_Beard]	   11/11/2014	CHG: more descriptive exclusion information
 /// </history>
 private void ReceiveFileFiltered(System.IO.FileInfo file, FilterItem filterItem, string filterValue)
 {
     LogItems.Add(new LogItem(LogItem.LogItemTypes.Exclusion, file.FullName, string.Format("{0}~~{1}", filterItem.ToString(), filterValue)));
      SetStatusBarFilterCount(GetLogItemsCountByType(LogItem.LogItemTypes.Exclusion));
 }
Exemple #49
0
        /// <summary>
        /// Get the list view item from the given FilterItem object.
        /// </summary>
        /// <param name="item">FilterItem object</param>
        /// <returns>ListViewItem object</returns>
        /// <history>
        /// [Curtis_Beard]	   03/07/2012	ADD: 3131609, exclusions
        /// [Curtis_Beard]	   11/11/2014	CHG: use FilterItem
        /// </history>
        private ListViewItem GetListViewItem(FilterItem item)
        {
            ListViewItem listItem = new ListViewItem();
             listItem.Tag = item;
             listItem.Checked = item.Enabled;
             listItem.SubItems.Add(Language.GetGenericText("Exclusions." + item.FilterType.Category.ToString(), item.FilterType.Category.ToString()));
             listItem.SubItems.Add(Language.GetGenericText("Exclusions." + item.FilterType.SubCategory.ToString(), item.FilterType.SubCategory.ToString()));

             string valueText = item.Value;
             string optionText = Language.GetGenericText("Exclusions." + item.ValueOption.ToString());
             string additionalInfo = string.Empty;
             if (item.ValueIgnoreCase)
             {
            additionalInfo = Language.GetGenericText("Exclusions.IgnoreCase");
             }
             else if (item.FilterType.Category == FilterType.Categories.File && item.FilterType.SubCategory == FilterType.SubCategories.Size && !string.IsNullOrEmpty(item.ValueSizeOption))
             {
            valueText = string.Format("{0} {1}", AstroGrep.Core.Convertors.ConvertFileSizeForDisplay(item.Value, item.ValueSizeOption), item.ValueSizeOption);
             }

             listItem.SubItems.Add(valueText);
             listItem.SubItems.Add(string.Format("{0}{1}", optionText, additionalInfo));

             return listItem;
        }
 private bool TryFetchAuthFilterItem(FilterProviderContext context, out FilterItem filterItem)
 {
     if (RequiresAuth(context))
     {
         filterItem = TypeToFilterItem[_settings.Value.Authorization.Filter];
         return true;
     }
     filterItem = null;
     return false;
 }
    public override IEnumerable<string> Process()
    {
      if (!File.Exists(_options.BaseFilename) || new FileInfo(_options.BaseFilename).Length == 0)
      {
        base.Process();
      }
      else
      {
        Progress.SetMessage("Base file {0} exists, ignore pileup ...", _options.BaseFilename);
      }

      var filterOptions = options.GetFilterOptions();

      if (new FileInfo(_options.BaseFilename).Length > 0)
      {
        if (!filterOptions.PrepareOptions())
        {
          throw new Exception("Filter options failed: " + filterOptions.ParsingErrors.Merge("\n"));
        }

        new FilterProcessor(filterOptions).Process();

        var lines = File.ReadAllLines(filterOptions.ROutputFile).Skip(1).ToArray();
        var glmfailed = lines.Count(m => m.Contains("GLM_PVALUE"));
        var summarylines = File.ReadAllLines(_options.SummaryFilename).ToList();
        if (summarylines.Last().StartsWith("glm pvalue"))
        {
          summarylines.RemoveAt(summarylines.Count - 1);
        }
        summarylines.Add(string.Format("glm pvalue > {0}\t{1}\t{2}", options.GlmPvalue, glmfailed, lines.Length - glmfailed));
        File.WriteAllLines(_options.SummaryFilename, summarylines);
      }

      var mutationList = GetValidationList();
      var candidates = new MpileupFisherResultFileFormat().ReadFromFile(options.CandidatesFilename).ToDictionary(m => GenomeUtils.GetKey(m.Item.SequenceIdentifier, m.Item.Position));
      var items = new FilterItemTextFormat().ReadFromFile(filterOptions.ROutputFile).ToDictionary(m => GenomeUtils.GetKey(m.Chr, m.Start));

      var result = new List<FilterItem>();
      foreach (var mutation in mutationList.Items)
      {
        var key = GenomeUtils.GetKey(mutation.Chr, mutation.Pos);
        if (items.ContainsKey(key))
        {
          result.Add(items[key]);
        }
        else
        {
          var item = new FilterItem();
          item.Chr = mutation.Chr;
          item.Start = mutation.Pos;
          item.End = item.Start;
          item.FisherNormal = string.Empty;
          item.BrglmConverged = string.Empty;
          item.BrglmGroup = 1.0;
          item.BrglmGroupFdr = 1.0;
          item.BrglmScore = string.Empty;
          item.BrglmStrand = string.Empty;
          item.BrglmPosition = string.Empty;
          item.Identity = string.Empty;
          result.Add(item);

          if (candidates.ContainsKey(key))
          {
            var cand = candidates[key];
            item.ReferenceAllele = cand.Item.Nucleotide.ToString();
            item.MajorAllele = cand.Group.SucceedName;
            item.MinorAllele = cand.Group.FailedName;
            item.NormalMajorCount = cand.Group.Sample1.Succeed;
            item.NormalMinorCount = cand.Group.Sample1.Failed;
            item.TumorMajorCount = cand.Group.Sample2.Succeed;
            item.TumorMinorCount = cand.Group.Sample2.Failed;
            item.FisherGroup = cand.Group.PValue;
            item.Filter = cand.FailedReason;
            Console.WriteLine("In candidates : " + item.Filter);
          }
          else
          {
            item.NormalMajorCount = 0;
            item.NormalMinorCount = 0;
            item.TumorMajorCount = 0;
            item.TumorMinorCount = 0;
            item.Filter = "No coverage";
            Console.WriteLine("No read : " + item.Filter);
          }
        }
      }

      new FilterItemVcfWriter(filterOptions).WriteToFile(_options.OutputSuffix + ".vcf", result);
      new FilterItemTextFormat().WriteToFile(_options.OutputSuffix + ".tsv", result);

      return new string[] { _options.OutputSuffix + ".tsv", _options.OutputSuffix + ".vcf" };
    }
Exemple #52
0
 /// <summary>
 /// Raise directory filtered event.
 /// </summary>
 /// <param name="dir">DirectoryInfo object</param>
 /// <param name="filterItem">FilterItem directory was filtered on</param>
 /// <param name="value">Current value causing filtering</param>
 /// <history>
 /// [Curtis_Beard]	   03/07/2012	ADD: 3131609, exclusions
 /// </history>
 protected virtual void OnDirectoryFiltered(DirectoryInfo dir, FilterItem filterItem, string value)
 {
     if (DirectoryFiltered != null)
      {
     DirectoryFiltered(dir, filterItem, value);
      }
 }
Exemple #53
0
        public void RemoveFilter(int opcode, bool fromServer)
        {
            FilterItem fItem = new FilterItem(opcode, fromServer);
            this.filter.Remove(fItem.GetHashCode());

            this.applyFilter();
        }
Exemple #54
0
 /// <summary>
 /// Raise file filtered event.
 /// </summary>
 /// <param name="file">FileInfo object</param>
 /// <param name="filterItem">FilterItem file was filtered on</param>
 /// <param name="value">Current value causing filtering</param>
 /// <history>
 /// [Curtis_Beard]	   03/07/2012	ADD: 3131609, exclusions
 /// </history>
 protected virtual void OnFileFiltered(FileInfo file, FilterItem filterItem, string value)
 {
     if (FileFiltered != null)
      {
     FileFiltered(file, filterItem, value);
      }
 }
        /// <summary>
        /// Verify that the values selected are valid. [MessageBox displayed based on error]
        /// </summary>
        /// <returns>FilterItem object if valid, null if not.</returns>
        /// <history>
        /// [Curtis_Beard]	   03/07/2012	ADD: 3131609, exclusions
        /// [Curtis_Beard]	   11/11/2014	CHG: use FilterItem
        /// [Curtis_Beard]	   06/15/2015	CHG: use language string for replacement values instead of raw values for TypeCategoryLimit error.
        /// </history>
        private FilterItem VerifyInterface()
        {
            // needs to be a category
             if (cboCategories.SelectedIndex == -1)
             {
            MessageBox.Show(this, Language.GetGenericText("Exclusions.Error.NoCategory"), ProductInformation.ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            return null;
             }

             // needs to be a type
             if (cboTypes.SelectedIndex == -1)
             {
            MessageBox.Show(this, Language.GetGenericText("Exclusions.Error.NoType"), ProductInformation.ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            return null;
             }

             // create item and set type, value
             var item = new FilterItem();
             var cboTypeItem = cboTypes.SelectedItem as ComboBoxEntry;
             item.FilterType = cboTypeItem.Value as FilterType;
             item.Value = fvtValue.Value;
             item.ValueIgnoreCase = chkIgnoreCase.Checked;
             item.Enabled = true;

             // size needs size option
             if (item.FilterType.Category == FilterType.Categories.File && item.FilterType.SubCategory == FilterType.SubCategories.Size)
             {
            item.ValueSizeOption = fvtValue.GetSizeDropDown();
             }

             // get selected option
             if (cboOptions.SelectedIndex == -1)
             {
            item.ValueOption = FilterType.ValueOptions.None;
             }
             else
             {
            var cboOptionsItem = cboOptions.SelectedItem as ComboBoxEntry;
            item.ValueOption = (FilterType.ValueOptions)Enum.Parse(typeof(FilterType.ValueOptions), cboOptionsItem.ValueName);
             }

             // needs to be a value
             if (item.FilterType.ValueType != FilterType.ValueTypes.Null && string.IsNullOrEmpty(item.Value.Trim()))
             {
            MessageBox.Show(this, Language.GetGenericText("Exclusions.Error.NoValue"), ProductInformation.ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            return null;
             }

             // if options supported then options value must be something other than None
             if (item.ValueOption == FilterType.ValueOptions.None &&
            (item.FilterType.SupportedValueOptions != null && item.FilterType.SupportedValueOptions.Count > 0 && item.FilterType.SupportedValueOptions[0] != FilterType.ValueOptions.None))
             {
            MessageBox.Show(this, Language.GetGenericText("Exclusions.Error.InvalidOptions"), ProductInformation.ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            return null;
             }

             // check how many we can have
             if (!item.FilterType.SupportsMulitpleItems)
             {
            if (_item == null)
            {
               // adding
               if (filterItems != null)
               {
                  var existing = (from i in filterItems where i.FilterType.Category == item.FilterType.Category && i.FilterType.SubCategory == item.FilterType.SubCategory select i).ToList();
                  if (existing.Count > 0)
                  {
                     MessageBox.Show(this, string.Format(Language.GetGenericText("Exclusions.Error.TypeCategoryLimit"), Language.GetGenericText(string.Format("Exclusions.{0}", item.FilterType.SubCategory)), Language.GetGenericText(string.Format("Exclusions.{0}", item.FilterType.Category))), ProductInformation.ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                     return null;
                  }
               }
            }
            else if (_item.FilterType.Category != item.FilterType.Category || _item.FilterType.SubCategory != item.FilterType.SubCategory)
            {
               if (filterItems != null)
               {
                  var existing = (from i in filterItems where i.FilterType.Category == item.FilterType.Category && i.FilterType.SubCategory == item.FilterType.SubCategory select i).ToList();
                  if (existing.Count > 0)
                  {
                     MessageBox.Show(this, string.Format(Language.GetGenericText("Exclusions.Error.TypeCategoryLimit"), Language.GetGenericText(string.Format("Exclusions.{0}", item.FilterType.SubCategory)), Language.GetGenericText(string.Format("Exclusions.{0}", item.FilterType.Category))), ProductInformation.ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                     return null;
                  }
               }
            }
             }

             return item;
        }
        /// <summary>
        /// Save the new/edit item.
        /// </summary>
        /// <param name="sender">system parameter</param>
        /// <param name="e">system parameter</param>
        /// <history>
        /// [Curtis_Beard]	   03/07/2012	ADD: 3131609, exclusions
        /// [Curtis_Beard]	   11/11/2014	CHG: use FilterItem
        /// </history>
        private void btnOK_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.None;
             FilterItem item = VerifyInterface();

             if (item != null)
             {
            _item = item;

            this.DialogResult = DialogResult.OK;
            this.Close();
             }
        }