Exemplo n.º 1
0
        public void CreateFilterRule3dGrid(Document doc, out ParameterFilterElement parameterFilterElement)
        {
            if (CheckFilter(doc, out parameterFilterElement))
            {
            }
            else
            {
                List <ElementId> categories = new List <ElementId>();
                categories.Add(new ElementId(BuiltInCategory.OST_GenericModel));
                List <FilterRule> filterRules = new List <FilterRule>();
                // Create filter element assocated to the input categories
                parameterFilterElement = ParameterFilterElement.Create(doc, "Grid 3D", categories);
                var            collector      = (from x in new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_GenericModel).OfClass(typeof(FamilyInstance)).Cast <FamilyInstance>() where x.Name.Contains("650mm Bubble - Single") select x).ToList();
                FamilyInstance familyInstance = collector.First();

                if (familyInstance != null)
                {
                    ElementId sharedParamId = familyInstance.get_Parameter(BuiltInParameter.ALL_MODEL_FAMILY_NAME).Id;

                    filterRules.Add(ParameterFilterRuleFactory.CreateContainsRule(sharedParamId, "3D Grid", true));
                }

                parameterFilterElement.SetRules(filterRules);
                // Apply filter to view
                //doc.ActiveView.AddFilter(parameterFilterElement.Id);
                //doc.ActiveView.SetFilterVisibility(parameterFilterElement.Id, false);
            }
        }
Exemplo n.º 2
0
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            // get UIdocument
            UIDocument uidoc = commandData.Application.ActiveUIDocument;
            //get document
            Document doc = uidoc.Document;

            //create filter
            List <ElementId> cats = new List <ElementId>();

            cats.Add(new ElementId(BuiltInCategory.OST_Sections));

            ElementParameterFilter filter = new ElementParameterFilter(ParameterFilterRuleFactory.CreateContainsRule(new ElementId(BuiltInParameter.VIEW_NAME), "wip", false));

            try
            {
                using (Transaction trans = new Transaction(doc, "create plan view"))
                {
                    trans.Start();
                    //apply filter
                    ParameterFilterElement filterElement = ParameterFilterElement.Create(doc, "My First Filter", cats, filter);
                    doc.ActiveView.AddFilter(filterElement.Id);
                    doc.ActiveView.SetFilterVisibility(filterElement.Id, false);
                    trans.Commit();
                }

                return(Result.Succeeded);
            }
            catch (Exception e)
            {
                message = e.Message;
                return(Result.Failed);
            }
        }
Exemplo n.º 3
0
        private void CreateFilterForPipeSystem(Document doc, Element sysNameParam, string systemName)
        {
            using var tr = new Transaction(doc, "Создание фильтра для: " + systemName);
            tr.Start();
            var view       = _uiDoc.ActiveView;
            var categories = new List <ElementId>
            {
                new ElementId(BuiltInCategory.OST_PipeAccessory),
                new ElementId(BuiltInCategory.OST_PipeCurves),
                new ElementId(BuiltInCategory.OST_PipeFitting),
                new ElementId(BuiltInCategory.OST_PipeInsulations),
                new ElementId(BuiltInCategory.OST_PlumbingFixtures),
                new ElementId(BuiltInCategory.OST_FlexPipeCurves),
                new ElementId(BuiltInCategory.OST_PlaceHolderPipes),
                new ElementId(BuiltInCategory.OST_GenericModel),
                new ElementId(BuiltInCategory.OST_MechanicalEquipment),
                new ElementId(BuiltInCategory.OST_Sprinklers)
            };
            var rule = ParameterFilterRuleFactory.CreateNotContainsRule(sysNameParam.Id, systemName, true);
            var epf  = new ElementParameterFilter(rule);
            var ef   = (ElementFilter)epf;
            ParameterFilterElement filter;

            try
            {
                filter = ParameterFilterElement.Create(doc, "ADSK_Трубопровод_" + systemName, categories, ef);
            }
            catch (ArgumentException)
            {
                var filter1 = new FilteredElementCollector(doc)
                              .OfClass(typeof(ParameterFilterElement))
                              .FirstOrDefault(f => f.Name == "ADSK_Трубопровод_" + systemName);
                filter = filter1 as ParameterFilterElement;
                filter?.SetElementFilter(ef);
            }

            var eView = new FilteredElementCollector(doc)
                        .OfClass(typeof(View))
                        .WhereElementIsNotElementType()
                        .FirstOrDefault(v => v.Name == $"{view.Name}_{systemName}");

            if (null == eView)
            {
                var copyViewId = view.Duplicate(ViewDuplicateOption.Duplicate);
                if (doc.GetElement(copyViewId) is View copiedView)
                {
                    copiedView.Name = $"{view.Name}_{systemName}";
                    if (filter != null)
                    {
                        copiedView.AddFilter(filter.Id);
                        copiedView.SetFilterVisibility(filter.Id, false);
                    }
                }
            }

            tr.Commit();
        }
Exemplo n.º 4
0
        private IList <ElementId> CreateFiltersIfMissing(Document doc)
        {
            bool[] array = new bool[4];
            FilteredElementCollector val = new FilteredElementCollector(doc);

            val.OfClass(typeof(ParameterFilterElement));
            ICollection <ElementId> collection = val.ToElementIds();

            foreach (ElementId item2 in collection)
            {
                Element val2 = doc.GetElement(item2);
                for (int i = 0; i < filterNames.Length; i++)
                {
                    if (val2.get_Name() == filterNames[i])
                    {
                        array[i] = true;
                    }
                }
            }
            if (array.Any((bool b) => !b))
            {
                ElementId         val3 = LODapp.GetLODparameter(doc, "Current_LOD").get_Id();
                IList <ElementId> list = (from cat in LODapp.lodCatArray
                                          where (int)cat != -2000220
                                          select new ElementId(cat)).ToList();
                Transaction val4 = new Transaction(doc, "Create LOD filters");
                try
                {
                    val4.Start();
                    for (int j = 0; j < filterNames.Length; j++)
                    {
                        if (!array[j])
                        {
                            ParameterFilterElement val5 = ParameterFilterElement.Create(doc, filterNames[j], (ICollection <ElementId>)list);
                            FilterRule             item = ParameterFilterRuleFactory.CreateEqualsRule(val3, lodValues[j]);
                            val5.SetRules((IList <FilterRule>) new List <FilterRule>(1)
                            {
                                item
                            });
                        }
                    }
                    val4.Commit();
                }
                catch (Exception innerException)
                {
                    val4.RollBack();
                    throw new Exception("Failed to create filters.", innerException);
                }
            }
            return(GetLODfilters(doc));
        }
Exemplo n.º 5
0
        public static void CreateViewFilter(Document doc, View view)
        {
            List <ElementId> categories = new List <ElementId>();

            categories.Add(new ElementId(BuiltInCategory.OST_Walls));
            List <FilterRule> filterRules = new List <FilterRule>();

            try
            {
                // Create filter element associated to the input categories
                ParameterFilterElement parameterFilterElement = ParameterFilterElement.Create(doc, "Example view filter", categories);

                // Criterion 1 - wall type Function is "Exterior"
                ElementId exteriorParamId = new ElementId(BuiltInParameter.FUNCTION_PARAM);
                filterRules.Add(ParameterFilterRuleFactory.CreateEqualsRule(exteriorParamId, (int)WallFunction.Exterior));

                // Criterion 2 - wall height > some number
                ElementId lengthId = new ElementId(BuiltInParameter.CURVE_ELEM_LENGTH);
                filterRules.Add(ParameterFilterRuleFactory.CreateGreaterOrEqualRule(lengthId, 28.0, 0.0001));

                // Criterion 3 - custom shared parameter value matches string pattern
                // Get the id for the shared parameter - the ElementId is not hardcoded, so we need to get an instance of this type to find it
                Guid spGuid = new Guid("96b00b61-7f5a-4f36-a828-5cd07890a02a");
                FilteredElementCollector collector = new FilteredElementCollector(doc);
                collector.OfClass(typeof(Wall));
                Wall wall = collector.FirstElement() as Wall;

                if (wall != null)
                {
                    Parameter sharedParam   = wall.get_Parameter(spGuid);
                    ElementId sharedParamId = sharedParam.Id;

                    filterRules.Add(ParameterFilterRuleFactory.CreateBeginsWithRule(sharedParamId, "15.", true));
                }

                parameterFilterElement.SetRules(filterRules);

                // Apply filter to view
                view.AddFilter(parameterFilterElement.Id);
                view.SetFilterVisibility(parameterFilterElement.Id, false);
            }
            catch
            {
            }
        }
Exemplo n.º 6
0
        // Создание или переопределение фильтра
        private ParameterFilterElement CreateFilterElement(Document doc, string name, List <ElementId> categoriesIds, ElementFilter elementFilter)
        {
            ElementClassFilter       filter    = new ElementClassFilter(typeof(ParameterFilterElement));
            FilteredElementCollector collector = new FilteredElementCollector(doc);

            collector.WherePasses(filter).ToElements()
            .Cast <ParameterFilterElement>().ToList <ParameterFilterElement>();

            var result =
                from item in collector
                where item.Name.Equals(name)
                select item;

            ParameterFilterElement filterElement;

            if (result.Count() == 0)
            {
                using (Transaction t = new Transaction(doc, "CreateFilterElement"))
                {
                    t.Start();
                    filterElement = ParameterFilterElement.Create(doc, name, categoriesIds, elementFilter);
                    t.Commit();
                }
            }
            else
            {
                filterElement = result.First() as ParameterFilterElement;
                using (Transaction t = new Transaction(doc, "SetCategoriesFilterElement"))
                {
                    t.Start();
                    filterElement.SetCategories(categoriesIds);
                    filterElement.SetElementFilter(elementFilter);
                    t.Commit();
                }
            }
            if (filterElement != null)
            {
                return(filterElement);
            }
            else
            {
                throw new Exception();
            }
        }
        protected override Result ProcessCommand(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            // Create Category
            var cats = new List <ElementId>();

            cats.Add(new ElementId(BuiltInCategory.OST_Sections));
            var sectionFilter = ParameterFilterRuleFactory.CreateContainsRule(new ElementId(BuiltInParameter.VIEW_NAME), "Section 1", false);
            var elementFilter = new ElementParameterFilter(sectionFilter);

            using (Transaction trans = new Transaction(_activeDocument, "Create Filter"))
            {
                trans.Start();

                var filter = ParameterFilterElement.Create(_activeDocument, "Wall Filter", cats, elementFilter);
                _activeDocument.ActiveView.AddFilter(filter.Id);
                _activeDocument.ActiveView.SetFilterVisibility(filter.Id, false);
                trans.Commit();
            }
            return(Result.Succeeded);
        }
Exemplo n.º 8
0
        public static ParameterFilterElement createSimpleFilter(Document doc, List <ElementId> catsIds, string filterName, MyParameter mp, CriteriaType ctype)
        {
            List <ParameterFilterElement> filters = new FilteredElementCollector(doc)
                                                    .OfClass(typeof(ParameterFilterElement))
                                                    .Cast <ParameterFilterElement>()
                                                    .ToList();

            FilterRule rule = null;
            List <ParameterFilterElement> checkFilters = filters.Where(f => f.Name == filterName).ToList();
            ParameterFilterElement        filter       = null;

            if (checkFilters.Count != 0)
            {
                filter = checkFilters[0];
            }
            else
            {
                rule = FilterCreator.CreateRule(mp, ctype);


                if (rule == null)
                {
                    return(null);
                }

                List <FilterRule> filterRules = new List <FilterRule> {
                    rule
                };
                try
                {
                    filter = ParameterFilterElement.Create(doc, filterName, catsIds);
#if R2017 || R2018
                    filter.SetRules(filterRules);
#else
                    filter.SetElementFilter(new ElementParameterFilter(filterRules));
#endif
                }
                catch { }
            }
            return(filter);
        }
Exemplo n.º 9
0
        public static ParameterFilterElement CreateConstrFilter(Document doc, List <ElementId> catsIds, Parameter markParam, string mark, string filterNamePrefix)
        {
            string filterName = filterNamePrefix + "_Конструкция " + mark;

            ParameterFilterElement filter = DocumentGetter.GetFilterByName(doc, filterName);

            if (filter != null)
            {
                return(filter);
            }

            FilterRule markEquals = ParameterFilterRuleFactory.CreateEqualsRule(markParam.Id, mark, true);

#if R2017 || R2018
            filter = ParameterFilterElement.Create(doc, filterName, catsIds);
            filter.SetRules(new List <FilterRule> {
                markEquals
            });
#else
            ElementParameterFilter epf = new ElementParameterFilter(markEquals);
            filter = ParameterFilterElement.Create(doc, filterName, catsIds, epf);
#endif
            return(filter);
        }
Exemplo n.º 10
0
        /// <summary>
        /// Creates a filter in a Revit Document from a custom FilterST class instance.
        /// </summary>
        /// <param name="doc">The Revit Document Object.</param>
        /// <param name="fRaw">A FilterST object.</param>
        public static void CreateViewFilterFromObject(Document doc, FilterST fRaw)
        {
            string filterName = fRaw.Name;
            ICollection <ElementId> categories  = fRaw.Categories;
            List <FilterRule>       filterRules = fRaw.FilterRules;

            try
            {
                using (Transaction t = new Transaction(doc, "Add View Filter"))
                {
                    t.Start();

                    ParameterFilterElement parameterFilterElement = ParameterFilterElement.Create(doc, filterName, categories);
                    parameterFilterElement.SetRules(filterRules);

                    t.Commit();
                    t.Dispose();
                }
            }
            catch (Exception filterException)
            {
                MessageBox.Show(filterException.Message);
            }
        }
Exemplo n.º 11
0
        /// <summary>
        /// Update ParameterFilterElement within document with
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void okButton_Click(object sender, EventArgs e)
        {
            // Reserve how many Revit filters need to be updated/removed
            ICollection <String>     updatedFilters = new List <String>();
            ICollection <ElementId>  deleteElemIds  = new List <ElementId>();
            FilteredElementCollector collector      = new FilteredElementCollector(m_doc);
            ICollection <Element>    oldFilters     = collector.OfClass(typeof(ParameterFilterElement)).ToElements();
            //
            // Start transaction to update filters now
            Transaction tran = new Transaction(m_doc, "Update View Filter");

            tran.Start();
            try
            {
                // 1. Update existing filters
                foreach (ParameterFilterElement filter in oldFilters)
                {
                    FilterData filterData;
                    bool       bExist = m_dictFilters.TryGetValue(filter.Name, out filterData);
                    if (!bExist)
                    {
                        deleteElemIds.Add(filter.Id);
                        continue;
                    }
                    //
                    // Update Filter categories and filter rules for this filter
                    ICollection <ElementId> newCatIds = filterData.GetCategoryIds();
                    if (!ListCompareUtility <ElementId> .Equals(filter.GetCategories(), newCatIds))
                    {
                        filter.SetCategories(newCatIds);
                    }
                    IList <FilterRule> newRules = new List <FilterRule>();
                    foreach (FilterRuleBuilder ruleData in filterData.RuleData)
                    {
                        newRules.Add(ruleData.AsFilterRule());
                    }
                    filter.SetRules(newRules);
                    updatedFilters.Add(filter.Name);
                }
                //
                // 2. Delete some filters
                if (deleteElemIds.Count > 0)
                {
                    m_doc.Delete(deleteElemIds);
                }
                //
                // 3. Create new filters(if have)
                foreach (KeyValuePair <String, FilterData> myFilter in m_dictFilters)
                {
                    // If this filter is updated, do nothing
                    if (updatedFilters.Contains(myFilter.Key))
                    {
                        continue;
                    }
                    //
                    // Create new filter now if filter not exist yet
                    IList <FilterRule> rules = new List <FilterRule>();
                    foreach (FilterRuleBuilder ruleData in myFilter.Value.RuleData)
                    {
                        rules.Add(ruleData.AsFilterRule());
                    }
                    ParameterFilterElement.Create(
                        m_doc, myFilter.Key, myFilter.Value.GetCategoryIds(), rules);
                }
                //
                // Commit change now
                tran.Commit();
            }
            catch (Exception ex)
            {
                String failMsg = String.Format("Revit filters update failed and was aborted: " + ex.ToString());
                MyMessageBox(failMsg);
                tran.RollBack();
            }
        }
Exemplo n.º 12
0
        /// <summary>
        /// Update ParameterFilterElements in the Revit document with data from the dialog box.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void okButton_Click(object sender, EventArgs e)
        {
            // Reserve how many Revit filters need to be updated/removed
            ICollection <String>     updatedFilters = new List <String>();
            ICollection <ElementId>  deleteElemIds  = new List <ElementId>();
            FilteredElementCollector collector      = new FilteredElementCollector(m_doc);
            ICollection <Element>    oldFilters     = collector.OfClass(typeof(ParameterFilterElement)).ToElements();
            //
            // Start transaction to update filters now
            Transaction tran = new Transaction(m_doc, "Update View Filter");

            tran.Start();
            try
            {
                // 1. Update existing filters
                foreach (ParameterFilterElement filter in oldFilters)
                {
                    FilterData filterData;
                    bool       bExist = m_dictFilters.TryGetValue(filter.Name, out filterData);
                    if (!bExist)
                    {
                        deleteElemIds.Add(filter.Id);
                        continue;
                    }
                    //
                    // Update Filter categories for this filter
                    ICollection <ElementId> newCatIds = filterData.GetCategoryIds();
                    if (!ListCompareUtility <ElementId> .Equals(filter.GetCategories(), newCatIds))
                    {
                        filter.SetCategories(newCatIds);
                    }

                    // Update filter rules for this filter
                    IList <FilterRule> newRules = new List <FilterRule>();
                    foreach (FilterRuleBuilder ruleData in filterData.RuleData)
                    {
                        newRules.Add(ruleData.AsFilterRule());
                    }

                    ElementFilter elemFilter = FiltersUtil.CreateElementFilterFromFilterRules(newRules);
                    // Set this filter's list of rules.
                    filter.SetElementFilter(elemFilter);

                    // Remember that we updated this filter so that we do not try to create it again below.
                    updatedFilters.Add(filter.Name);
                }
                //
                // 2. Delete some filters
                if (deleteElemIds.Count > 0)
                {
                    m_doc.Delete(deleteElemIds);
                }
                //
                // 3. Create new filters(if have)
                foreach (KeyValuePair <String, FilterData> myFilter in m_dictFilters)
                {
                    // If this filter was updated in the previous step, do nothing.
                    if (updatedFilters.Contains(myFilter.Key))
                    {
                        continue;
                    }

                    // Create a new filter.
                    // Collect the FilterRules, create an ElementFilter representing the
                    // conjunction ("ANDing together") of the FilterRules, and use the ElementFilter
                    // to create a ParameterFilterElement
                    IList <FilterRule> rules = new List <FilterRule>();
                    foreach (FilterRuleBuilder ruleData in myFilter.Value.RuleData)
                    {
                        rules.Add(ruleData.AsFilterRule());
                    }
                    ElementFilter elemFilter = FiltersUtil.CreateElementFilterFromFilterRules(rules);

                    // Check that the ElementFilter is valid for use by a ParameterFilterElement.
                    IList <ElementId> categoryIdList = myFilter.Value.GetCategoryIds();
                    ISet <ElementId>  categoryIdSet  = new HashSet <ElementId>(categoryIdList);
                    if (!ParameterFilterElement.ElementFilterIsAcceptableForParameterFilterElement(
                            m_doc, categoryIdSet, elemFilter))
                    {
                        // In case the UI allowed invalid rules, issue a warning to the user.
                        MyMessageBox("The combination of filter rules is not acceptable for a View Filter.");
                    }
                    else
                    {
                        ParameterFilterElement.Create(m_doc, myFilter.Key, categoryIdSet, elemFilter);
                    }
                }
                //
                // Commit change now
                tran.Commit();
            }
            catch (Exception ex)
            {
                String failMsg = String.Format("Revit filters update failed and was aborted: " + ex.ToString());
                MyMessageBox(failMsg);
                tran.RollBack();
            }
        }
Exemplo n.º 13
0
        public static String LinkLevelGrid(Boolean Hide = true)
        {
            String  ifilter    = "LinkLevelGrid_QuasarPackage";
            var     doc        = DocumentManager.Instance.CurrentDBDocument;
            var     activeView = doc.ActiveView;
            Boolean found      = false;
            Boolean hide       = Hide == true ? false : true;

            TransactionManager.Instance.EnsureInTransaction(doc);

            var allFilters = new FilteredElementCollector(doc).OfClass(typeof(FilterElement)).ToElements();

            var           viewFilters     = activeView.GetFilters();
            List <String> viewFiltersName = new List <String>();

            foreach (var v in viewFilters)
            {
                viewFiltersName.Add(doc.GetElement(v).Name.ToString());
            }

            foreach (var fter in allFilters)
            {
                if (ifilter == fter.Name.ToString() && !viewFiltersName.Contains(ifilter))
                {
                    activeView.AddFilter(fter.Id);
                    activeView.SetFilterVisibility(fter.Id, hide);
                    found = true;
                }
                if (ifilter == fter.Name.ToString() && viewFiltersName.Contains(ifilter))
                {
                    activeView.SetFilterVisibility(fter.Id, hide);
                    found = true;
                }
            }

            if (!found)
            {
                var grids   = new FilteredElementCollector(doc).OfClass(typeof(Autodesk.Revit.DB.Grid)).ToElements();
                var levels  = new FilteredElementCollector(doc).OfClass(typeof(Autodesk.Revit.DB.Level)).ToElements();
                var cateIds = new List <ElementId> {
                    grids.First().Category.Id, levels.First().Category.Id
                };
                var gridTypeIds  = new HashSet <ElementId>();
                var levelTypeIds = new HashSet <ElementId>();
                foreach (var i in grids.Zip(levels, Tuple.Create))
                {
                    gridTypeIds.Add(i.Item1.GetTypeId()); levelTypeIds.Add(i.Item2.GetTypeId());
                }

                var gtypeElements = new List <Autodesk.Revit.DB.Element>();
                var ltypeElements = new List <Autodesk.Revit.DB.Element>();
                foreach (var i in gridTypeIds.Zip(levelTypeIds, Tuple.Create))
                {
                    gtypeElements.Add(doc.GetElement(i.Item1)); ltypeElements.Add(doc.GetElement(i.Item2));
                }
                gtypeElements.AddRange(ltypeElements);

                foreach (var e in gtypeElements)
                {
                    if (!e.LookupParameter("Type Name").AsString().Contains("_quasar"))
                    {
                        e.Name = e.LookupParameter("Type Name").AsString() + "_quasar";
                    }
                }
                var paramId     = gtypeElements.First().LookupParameter("Type Name").Id;
                var ruleSet     = new List <FilterRule>();
                var notEndsWith = ParameterFilterRuleFactory.CreateNotEndsWithRule(paramId, "_quasar", false);
                ruleSet.Add(notEndsWith);
                var paramFilterElem = ParameterFilterElement.Create(doc, ifilter, cateIds, ruleSet);
                var ogs             = new OverrideGraphicSettings();
                activeView.SetFilterOverrides(paramFilterElem.Id, ogs);
                activeView.SetFilterVisibility(paramFilterElem.Id, hide);
            }
            TransactionManager.Instance.TransactionTaskDone();

            return("DONE!");
        }
Exemplo n.º 14
0
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            Document doc = commandData.Application.ActiveUIDocument.Document;

            AppBatchFilterCreation.assemblyPath = System.Reflection.Assembly.GetExecutingAssembly().Location;
            string dllPath = Path.GetDirectoryName(AppBatchFilterCreation.assemblyPath);

            OpenFileDialog openCsvDialog = new OpenFileDialog();

            openCsvDialog.Filter           = "CSV file|*.csv";
            openCsvDialog.Title            = "Выберите файл CSV (v2018.10.17)";
            openCsvDialog.Multiselect      = false;
            openCsvDialog.InitialDirectory = dllPath;

            if (openCsvDialog.ShowDialog() != DialogResult.OK)
            {
                return(Result.Cancelled);
            }
            ;

            //считываю файл
            string          path = openCsvDialog.FileName;
            List <string[]> data = ReadDataFromCSV.Read(path);

            string msg         = "";
            int    filterCount = 0;

            //одна строка в файле - один фильтр
            foreach (string[] line in data)
            {
                FilterSourceInfo filterSource = new FilterSourceInfo(line);
                string           filterName   = filterSource.FilterName;

                //Добавляю категории
                List <ElementId> catIds = new List <ElementId>();
                foreach (string stringCat in filterSource.Categories)
                {
                    BuiltInCategory cat = GetBuiltinCategory.GetCategoryByRussianName(stringCat);
                    catIds.Add(new ElementId(cat));
                }


                //добавляю критерии фильтрации
                List <FilterRule> filterRules = new List <FilterRule>();

                foreach (string[] sourceRule in filterSource.SourceRules)
                {
                    string paramName = sourceRule[0];
                    string function  = sourceRule[1];
                    string value     = sourceRule[2];


                    BuiltInCategory cat = GetBuiltinCategory.GetCategoryByRussianName(filterSource.Categories[0]);
                    if (cat == BuiltInCategory.OST_Sections || cat == BuiltInCategory.OST_Elev || cat == BuiltInCategory.OST_Callouts)
                    {
                        cat = BuiltInCategory.OST_Views;
                    }

                    FilteredElementCollector collector = new FilteredElementCollector(doc).OfCategory(cat);

                    Parameter param = null;
                    try
                    {
                        foreach (Element elem in collector)
                        {
                            param = elem.LookupParameter(paramName);
                            if (param == null)
                            {
                                continue;
                            }
                            break;
                        }
                    }
                    catch { }

                    if (collector.Count() == 0 || param == null)
                    {
                        message  = "Ошибка при создании фильтра: " + filterName;
                        message += "\nУстановите как минимум один элемент в категории: " + filterSource.Categories[0];
                        message += "\nТребуемый параметр: " + paramName;
                        return(Result.Failed);
                    }

                    FilterRule rule = FilterCreator.CreateRule2(param, function, value);
                    filterRules.Add(rule);
                }

                try
                {
                    using (Transaction t = new Transaction(doc))
                    {
                        t.Start("Создание фильтра" + filterName);
                        ParameterFilterElement filter = ParameterFilterElement.Create(doc, filterName, catIds);
#if R2017 || R2018
                        filter.SetRules(filterRules);
#else
                        ElementParameterFilter epf = new ElementParameterFilter(filterRules);
                        filter.SetElementFilter(epf);
#endif
                        filterCount++;
                        t.Commit();
                    }
                }
                catch
                {
                    msg += filterName + "\n";
                }
            }
            string finalMessage = "Создано фильтров: " + filterCount.ToString() + "\n";
            if (msg.Length != 0)
            {
                finalMessage += "Не удалось создать: \n" + msg;
            }

            TaskDialog.Show("Batch filter create", finalMessage);
            return(Result.Succeeded);
        }
Exemplo n.º 15
0
        public static ParameterFilterElement CreateRebarHostFilter(
            Document doc, List <ElementId> rebarCatsIds, Parameter rebarIsFamilyParam, Parameter rebarHostParam, Parameter rebarMrkParam,
            string hostMark, string filterNamePrefix, RebarFilterMode filterMode)
        {
            string filterName = filterNamePrefix + "_Арм Конструкции " + hostMark;

            if (filterMode == RebarFilterMode.IfcMode)
            {
                filterName += " IFC";
            }
            ParameterFilterElement filter = DocumentGetter.GetFilterByName(doc, filterName);

            if (filter != null)
            {
                return(filter);
            }

            FilterRule ruleHostEquals = ParameterFilterRuleFactory.CreateEqualsRule(rebarHostParam.Id, hostMark, true);

            if (filterMode == RebarFilterMode.SingleMode)
            {
#if R2017 || R2018
                filter = ParameterFilterElement.Create(doc, filterName, rebarCatsIds);
                filter.SetRules(new List <FilterRule> {
                    ruleHostEquals
                });
#else
                ElementParameterFilter epf = new ElementParameterFilter(ruleHostEquals);
                filter = ParameterFilterElement.Create(doc, filterName, rebarCatsIds, epf);
#endif
                return(filter);
            }

            FilterRule ruleIsNotFamily = ParameterFilterRuleFactory.CreateEqualsRule(rebarIsFamilyParam.Id, 0);
            FilterRule ruleIsFamily    = ParameterFilterRuleFactory.CreateEqualsRule(rebarIsFamilyParam.Id, 1);
            FilterRule ruleMrkEquals   = ParameterFilterRuleFactory.CreateEqualsRule(rebarMrkParam.Id, hostMark, true);


#if R2017 || R2018
            if (filterMode == RebarFilterMode.StandardRebarMode)
            {
                filter = ParameterFilterElement.Create(doc, filterName, rebarCatsIds);
                filter.SetRules(new List <FilterRule> {
                    ruleIsNotFamily, ruleHostEquals
                });
                return(filter);
            }
            else if (filterMode == RebarFilterMode.IfcMode)
            {
                filter = ParameterFilterElement.Create(doc, filterName, rebarCatsIds);
                filter.SetRules(new List <FilterRule> {
                    ruleIsFamily, ruleMrkEquals
                });
                return(filter);
            }
#else
            if (filterMode == RebarFilterMode.DoubleMode)
            {
                ElementParameterFilter filterByStandardArm = new ElementParameterFilter(new List <FilterRule> {
                    ruleIsNotFamily, ruleHostEquals
                });
                ElementParameterFilter filterForIfcArm = new ElementParameterFilter(new List <FilterRule> {
                    ruleIsFamily, ruleMrkEquals
                });
                LogicalOrFilter orfilter = new LogicalOrFilter(filterByStandardArm, filterForIfcArm);
                filter = ParameterFilterElement.Create(doc, filterName, rebarCatsIds, orfilter);
                return(filter);
            }
#endif
            return(null);
        }