Beispiel #1
0
        /// <summary>
        /// Retrieve all supply air terminals from given document.
        /// Select all family instance elements of BuiltInCategory
        /// OST_DuctTerminal with system type equal to suppy air.
        /// </summary>
        public static FilteredElementCollector GetSupplyAirTerminals(Document doc)
        {
            FilteredElementCollector collector = new FilteredElementCollector(doc);

            collector.OfCategory(BuiltInCategory.OST_DuctTerminal);
            collector.OfClass(typeof(FamilyInstance));

            //int n1 = collector.ToElements().Count; // 61 in sample model

            // ensure that system type equals supply air:
            //
            // in Revit 2009 and 2010 API, this did it:
            //
            //ParameterFilter parameterFilter = a.Filter.NewParameterFilter(
            //  Bip.SystemType, CriteriaFilterType.Equal, ParameterValue.SupplyAir );

            // in Revit 2011, create an ElementParameter filter.
            // Create filter by provider and evaluator:

            ParameterValueProvider    provider  = new ParameterValueProvider(new ElementId(Bip.SystemType));
            FilterStringRuleEvaluator evaluator = new FilterStringEquals();
            string                 ruleString   = ParameterValue.SupplyAir;
            FilterRule             rule         = new FilterStringRule(provider, evaluator, ruleString, false);
            ElementParameterFilter filter       = new ElementParameterFilter(rule);

            collector.WherePasses(filter);

            //int n2 = collector.ToElements().Count; // 51 in sample model

            return(collector);
        }
Beispiel #2
0
        /// <summary>
        /// ElementParameterFilter参数过滤器 Creates an ElementParameter filter to find rooms whose area is greater than specified value
        /// </summary>
        /// <remarks>提示: 参数过滤条件可能比其他的类型过滤条件要快,但是这要视条件而定。毕竟这是一个慢过,使用时请按照过滤标准的复杂程度而异。</remarks>
        public void ElementParameterFilter_FindRooms(Document Document)
        {
            // 以下5个步骤演示了要进行参数过滤的完整过程。
            // provider
            ParameterValueProvider pvp = new ParameterValueProvider(new ElementId(BuiltInParameter.ROOM_AREA));
            // evaluator
            FilterNumericRuleEvaluator fnrv = new FilterNumericGreater();

            // 过滤规则 : 参数“房间面积”的值“大于”“100 Square Foot”。(浮点数比较的容差为0.000001)
            FilterRule fRule = new FilterDoubleRule(pvp, fnrv, 100, 0.000001);

            // Create an ElementParameter filter
            ElementParameterFilter filter = new ElementParameterFilter(fRule);

            // Apply the filter to the elements in the active document
            FilteredElementCollector collector = new FilteredElementCollector(Document);
            IList <Element>          rooms     = collector.WherePasses(filter).ToElements();

            // 反转过滤条件
            // Find rooms whose area is less than or equal to 100:
            // Use inverted filter to match elements
            ElementParameterFilter lessOrEqualFilter = new ElementParameterFilter(fRule, true);

            collector = new FilteredElementCollector(Document);
            IList <Element> lessOrEqualFounds = collector.WherePasses(lessOrEqualFilter).ToElements();
        }
Beispiel #3
0
        private bool CreateFiltersIfMissing(Document doc)
        {
            if (curLODfilter != null && tarLODfilter != null)
            {
                return(false);
            }
            ElementId val  = LODapp.GetLODparameter(doc, "Current_LOD").get_Id();
            ElementId val2 = LODapp.GetLODparameter(doc, "Target_LOD").get_Id();
            ParameterValueProvider     val3 = new ParameterValueProvider(val);
            ParameterValueProvider     val4 = new ParameterValueProvider(val2);
            FilterNumericRuleEvaluator val5 = new FilterNumericEquals();

            ElementParameterFilter[] array = (ElementParameterFilter[])new ElementParameterFilter[VALID_CURRENT_LOD_VALUES.Length];
            for (int i = 0; i < VALID_CURRENT_LOD_VALUES.Length; i++)
            {
                FilterIntegerRule val6 = new FilterIntegerRule(val3, val5, VALID_CURRENT_LOD_VALUES[i]);
                array[i] = new ElementParameterFilter(val6, true);
            }
            curLODfilter = new LogicalAndFilter((IList <ElementFilter>)array);
            ElementParameterFilter[] array2 = (ElementParameterFilter[])new ElementParameterFilter[VALID_TARGET_LOD_VALUES.Length];
            for (int j = 0; j < VALID_TARGET_LOD_VALUES.Length; j++)
            {
                FilterIntegerRule val7 = new FilterIntegerRule(val4, val5, VALID_TARGET_LOD_VALUES[j]);
                array2[j] = new ElementParameterFilter(val7, true);
            }
            tarLODfilter = new LogicalAndFilter((IList <ElementFilter>)array2);
            return(true);
        }
Beispiel #4
0
        protected internal virtual void initializeOutputParameter(CmmnElement element, CmmnActivity activity, CmmnHandlerContext context, CallableElement callableElement)
        {
            ExpressionManager expressionManager = context.ExpressionManager;

            IList <CamundaOut> outputs = getOutputs(element);

            foreach (CamundaOut output in outputs)
            {
                // create new parameter
                CallableElementParameter parameter = new CallableElementParameter();
                callableElement.addOutput(parameter);

                // all variables
                string variables = output.CamundaVariables;
                if ("all".Equals(variables))
                {
                    parameter.AllVariables = true;
                    continue;
                }

                // source/sourceExpression
                string source = output.CamundaSource;
                if (string.ReferenceEquals(source, null) || source.Length == 0)
                {
                    source = output.CamundaSourceExpression;
                }

                ParameterValueProvider sourceValueProvider = createParameterValueProvider(source, expressionManager);
                parameter.SourceValueProvider = sourceValueProvider;

                // target
                string target = output.CamundaTarget;
                parameter.Target = target;
            }
        }
Beispiel #5
0
        public Autodesk.Revit.UI.Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            Document   document         = commandData.Application.ActiveUIDocument.Document;
            UIDocument uidoc            = commandData.Application.ActiveUIDocument;
            ICollection <ElementId> ids = uidoc.Selection.GetElementIds();

            string prompt = "";

            BuiltInParameter volParam = BuiltInParameter.HOST_VOLUME_COMPUTED;
            // provider
            ParameterValueProvider pvp = new ParameterValueProvider(new ElementId((int)volParam));
            // evaluator
            FilterNumericRuleEvaluator fnrv = new FilterNumericGreater();
            // 篩選面體積大於500立方呎的元件
            double ruleValue = 500f;
            // rule 規則
            FilterRule fRule = new FilterDoubleRule(pvp, fnrv, ruleValue, 1E-6);
            // Create an ElementParameter filter 創建ElementParameter篩選器
            ElementParameterFilter filter = new ElementParameterFilter(fRule);
            // Apply the filter to the elements in the active document 使用這個篩選器到作用文件檔案中的元件
            FilteredElementCollector collector = new FilteredElementCollector(document);
            IList <Element>          elems     = collector.WherePasses(filter).ToElements();

            prompt += "篩選後的元件數量:" + elems.Count.ToString() + "\n";

            ElementCategoryFilter filterWall = new ElementCategoryFilter(BuiltInCategory.OST_Walls);
            IList <Element>       walls      = collector.WherePasses(filter).WherePasses(filterWall).ToElements();

            prompt += "篩選後的牆數量:" + walls.Count.ToString() + "\n";

            TaskDialog.Show("篩選", prompt);

            return(Autodesk.Revit.UI.Result.Succeeded);
        }
Beispiel #6
0
        public IList <Element> GetElementValueDouble(RevitParameter valRevitParameter, List <ElementId> valCategoryElementId, string valValue)
        {
            IList <Element> vResult = new List <Element>();

            foreach (var vCategoryId in valCategoryElementId)
            {
                BuiltInCategory        vBuiltInCategory = (BuiltInCategory)vCategoryId.IntegerValue;
                ParameterValueProvider vPovider         = new ParameterValueProvider(valRevitParameter.ElementId);
                string vRulestring = valValue;
                FilteredElementCollector vCollector = new FilteredElementCollector(_Doc);
                vCollector.OfCategory(vBuiltInCategory);
                LibNumeric insLibNumeric = new LibNumeric();
                double     ruleValDb     = 0.0;
                if (insLibNumeric.IsDouble(valValue))
                {
                    Double vNum = 0;
                    Double.TryParse(valValue, out vNum);
                    ruleValDb = vNum;
                }
                ParameterValueProvider pvp  = new ParameterValueProvider(valRevitParameter.ElementId);
                FilterNumericEquals    fnrv = new FilterNumericEquals();
                var vFilterDoubleRule       = new FilterDoubleRule(pvp, fnrv, ruleValDb, 10e-10);
                var epf = new ElementParameterFilter(vFilterDoubleRule);
                vCollector.WherePasses(epf);
                IList <Element> vElements = vCollector.ToElements();
                if (vElements != null)
                {
                    if (vElements.Count > 0)
                    {
                        vResult = vElements.Concat(vElements).ToList();
                    }
                }
            }
            return(vResult);
        }
Beispiel #7
0
        /// <summary>
        /// Return the first wall found that
        /// uses the given wall type.
        /// </summary>
        static Wall GetFirstWallUsingType(
            Document doc,
            WallType wallType)
        {
            // built-in parameter storing this
            // wall's wall type element id:

            BuiltInParameter bip
                = BuiltInParameter.ELEM_TYPE_PARAM;

            ParameterValueProvider provider
                = new ParameterValueProvider(
                      new ElementId(bip));

            FilterNumericRuleEvaluator evaluator
                = new FilterNumericEquals();

            FilterRule rule = new FilterElementIdRule(
                provider, evaluator, wallType.Id);

            ElementParameterFilter filter
                = new ElementParameterFilter(rule);

            FilteredElementCollector collector
                = new FilteredElementCollector(doc)
                  .OfClass(typeof(Wall))
                  .WherePasses(filter);

            return(collector.FirstElement() as Wall);
        }
Beispiel #8
0
        public static FilteredElementCollector collectorFromTreeView(Document doc, ObservableCollection <Node> nodes)
        {
            IList <ElementFilter> familyAndTypeFilters = new List <ElementFilter>();

            foreach (var category in nodes)
            {
                foreach (var family in category.Children)
                {
                    foreach (var familyType in family.Children)
                    {
                        if (familyType.IsChecked == true)
                        {
                            ParameterValueProvider    fvp     = new ParameterValueProvider(new ElementId(BuiltInParameter.ELEM_FAMILY_AND_TYPE_PARAM));
                            FilterStringRuleEvaluator fsre    = new FilterStringEquals();
                            string                 ruleString = String.Format("{0}: {1}", family.Text, familyType.Text);
                            FilterRule             fRule      = new FilterStringRule(fvp, fsre, ruleString, true);
                            ElementParameterFilter filter     = new ElementParameterFilter(fRule);

                            familyAndTypeFilters.Add(filter);
                        }
                    }
                }
            }

            LogicalOrFilter familyAndTypeFilter = new LogicalOrFilter(familyAndTypeFilters);

            FilteredElementCollector collector = new FilteredElementCollector(doc).WherePasses(familyAndTypeFilter);

            return(collector);
        }
        public static FilteredElementCollector GetElementsByShareParamValue(
            Document doc,
            BuiltInCategory bic,
            string sParaName,
            string sValue)
        {
            SharedParameterElement para =
                (from p in new FilteredElementCollector(doc)
                 .OfClass(typeof(SharedParameterElement))
                 .Cast <SharedParameterElement>()
                 where p.Name.Equals(sParaName)
                 select p).First();

            ParameterValueProvider provider
                = new ParameterValueProvider(para.Id);

            FilterStringRuleEvaluator evaluator
                = new FilterStringEquals();

            string sType = sValue;

            FilterRule rule = new FilterStringRule(
                provider, evaluator, sType, false);

            ElementParameterFilter filter
                = new ElementParameterFilter(rule);

            FilteredElementCollector collector
                = new FilteredElementCollector(doc)
                  .OfCategory(bic)
                  .WherePasses(filter);

            return(collector);
        }
        public static FilteredElementCollector GetElementsByShareParamValue(Document doc, BuiltInCategory bic, string sParaName, double dValue)
        {
            SharedParameterElement para =
                (from p in new FilteredElementCollector(doc)
                 .OfClass(typeof(SharedParameterElement))
                 .Cast <SharedParameterElement>()
                 where p.Name.Equals(sParaName)
                 select p).First();

            ParameterValueProvider provider
                = new ParameterValueProvider(para.Id);

            FilterNumericRuleEvaluator evaluator
                = new FilterNumericEquals();

            double sLength_feet = UnitUtils.Convert(
                dValue,
                DisplayUnitType.DUT_METERS,
                DisplayUnitType.DUT_DECIMAL_FEET);
            double epsilon = 0.0001;

            FilterRule rule = new FilterDoubleRule(
                provider, evaluator, sLength_feet, epsilon);

            ElementParameterFilter filter
                = new ElementParameterFilter(rule);

            FilteredElementCollector collector
                = new FilteredElementCollector(doc)
                  .OfCategory(bic)
                  .WherePasses(filter);

            return(collector);
        }
Beispiel #11
0
        //Check to see if a Sheet Number already exists in the project and create it if not
        private ViewSheet CheckSheet(string _sheetNumber, ElementId _vpTypeId)
        {
            try
            {
                ViewSheet sheet = null;
                ParameterValueProvider    pvp = new ParameterValueProvider(new ElementId(BuiltInParameter.SHEET_NUMBER));
                FilterStringRuleEvaluator fsr = new FilterStringEquals();
                FilterRule             fRule  = new FilterStringRule(pvp, fsr, _sheetNumber, true);
                ElementParameterFilter filter = new ElementParameterFilter(fRule);

                if (new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Sheets).WherePasses(filter).FirstOrDefault() is ViewSheet vs)
                {
                    sheet = vs;
                }
                else
                {
                    sheet             = ViewSheet.Create(doc, _vpTypeId);
                    sheet.Name        = "DO NOT PRINT";
                    sheet.SheetNumber = _sheetNumber;

                    //Set additional View Parameters based on Firm standards and Project Broswer Sorting templates
                    //sheet.LookupParameter("Sheet Sort").Set("PLANS");

                    //Set the Appears In Sheet List to False so duplicate sheets do not appear in Sheet Index Schedule
                    sheet.get_Parameter(BuiltInParameter.SHEET_SCHEDULED).Set(0);
                }
                return(sheet);
            }
            catch
            {
                return(null);
            }
        }
Beispiel #12
0
        /// <summary>
        /// Optional - example of parameter filter.
        /// Find walls whose length is longer than a certain length. e.g., 60 feet
        ///     wall.parameter(length) > 60 feet
        /// This could get more complex than looping through in terms of writing a code.
        /// See page 87 of Developer guide.
        /// </summary>
        public IList <Element> FindLongWalls()
        {
            // Constant for this function.
            const double kWallLength = 60.0; // 60 feet. hard coding for simplicity.

            // First, narrow down to the elements of the given type and category
            var collector = new FilteredElementCollector(_doc).OfClass(typeof(Wall));

            // Define a filter by parameter
            // 1st arg - value provider
            BuiltInParameter lengthParam = BuiltInParameter.CURVE_ELEM_LENGTH;
            int iLengthParam             = (int)lengthParam;
            var paramValueProvider       = new ParameterValueProvider(new ElementId(iLengthParam));

            // 2nd - evaluator
            FilterNumericGreater evaluator = new FilterNumericGreater();

            // 3rd - rule value
            double ruleVal = kWallLength;

            // 4th - epsilon
            const double eps = 1E-06;

            // Define a rule
            var filterRule = new FilterDoubleRule(paramValueProvider, evaluator, ruleVal, eps);

            // Create a new filter
            var paramFilter = new ElementParameterFilter(filterRule);

            // Go through the filter
            IList <Element> elems = collector.WherePasses(paramFilter).ToElements();

            return(elems);
        }
        public ViewSheet ReferenceSheet(Document doc, View view)
        {
            ViewSheet viewhseetrf            = null;
            DateTime  start                  = DateTime.Now;
            FilterableValueProvider provider = new ParameterValueProvider(new ElementId(BuiltInParameter.VIEW_SHEET_VIEWPORT_INFO));
            FilterRule               rule    = new FilterStringRule(provider, new FilterStringGreater(), string.Empty, false);
            ElementParameterFilter   epf     = new ElementParameterFilter(rule, false);
            FilteredElementCollector viewCol = new FilteredElementCollector(doc).WherePasses(epf);

            viewCol.OfClass(typeof(ViewSheet));
            StringBuilder sb = new StringBuilder();

            foreach (ViewSheet v in viewCol)
            {
                try
                {
                    ISet <ElementId> col = v.GetAllPlacedViews();
                    foreach (var fg in col)
                    {
                        if (fg == view.Id)
                        {
                            sb.AppendLine("View: " + v.Name);
                            viewhseetrf = v;
                        }
                    }
                }
                catch { }
            }
            return(viewhseetrf);
        }
Beispiel #14
0
        /// <summary>
        /// Возвращает список всех чистых помещений
        /// </summary>
        public static List <Room> GetAllCleanRooms(Document doc)
        {
            FilteredElementCollector collector = new FilteredElementCollector(doc);
            RoomFilter roomFilter = new RoomFilter();

            collector.WherePasses(roomFilter);

            // Настройка фильтра для комнат заданным параметром "BL_Класс чистоты",
            // равным "A", "B", "C" или "D"
            Guid spGuid = new Guid("02f7e9d4-f055-479e-a36f-5b8e098d40f5");
            Room fRoom  = collector.FirstElement() as Room;

            Parameter testSharedParam           = fRoom.get_Parameter(spGuid);
            ElementId sharedParamId             = testSharedParam.Id;
            ParameterValueProvider    provider  = new ParameterValueProvider(sharedParamId);
            FilterStringRuleEvaluator fsreEqual = new FilterStringEquals();

            string     testStrCNC     = "CNC";
            string     testVoidStrCNC = "";
            FilterRule fCNCRule       = new FilterStringRule(provider, fsreEqual, testStrCNC, false);
            FilterRule fVoidStrRule   = new FilterStringRule(provider, fsreEqual, testVoidStrCNC, false);

            ElementParameterFilter paramNoCNCFilter  = new ElementParameterFilter(fCNCRule, true);
            ElementParameterFilter paramNoVoidFilter = new ElementParameterFilter(fVoidStrRule, true);

            collector.WherePasses(paramNoVoidFilter).WherePasses(paramNoCNCFilter);

            List <Room> cleanRooms = (from e in collector.ToElements()
                                      where e is Room
                                      select e as Room).ToList <Room>();

            return(cleanRooms);
        }
Beispiel #15
0
        public static ICollection <ElementId> GetTypeBICInPhase(Document doc, Type thisType, BuiltInCategory bic, Phase phase)
        {
            // http://spiderinnet.typepad.com/blog/2011/07/
            // elementparameterfilter-using-filterelementidrule-to-filter-element-parameters-in-c.html
            //
            // • An ElementParameterFilter needs a filter rule, the FilterElementIdRule in this case.
            // • The FilterElementIdRule needs a parameter value provider (ParameterValueProvider) and
            // a filter rule evaluator (FilterStringRuleEvaluator), specifically the FilterNumericEquals here.
            // • Do not feel surprised that the FilterNumericEquals evaluator also works with the FilterElementIdRule
            // as the ElementId is effectively nothing more than an integer value.
            // • The ParameterValueProvider needs an argument of parameter, as the phase created parameter
            // BuiltInParameter.PHASE_CREATED in this case.
            // • The parameter is represented by an ElementId, which is the numeric value of the specified BuiltInParameter.
            // • A fast filter, ElementClassFilter, represented by its shortcut method (OfClass), is also used to
            // narrow down the FilteredElementCollector first. It not only speeds up the search but also makes sure only walls are returned.

            ParameterValueProvider provider = new ParameterValueProvider(new ElementId((int)BuiltInParameter.PHASE_CREATED));
            FilterElementIdRule    rule1    = new FilterElementIdRule(provider, new FilterNumericEquals(), phase.Id);
            ElementParameterFilter filter1  = new ElementParameterFilter(rule1);

            FilteredElementCollector collector = new FilteredElementCollector(doc);

            collector.OfClass(thisType);
            collector.OfCategory(bic);
            collector.WherePasses(filter1);
            return(collector.ToElementIds());
        }
Beispiel #16
0
        /// <summary>
        /// Return the first wall type with the given name.
        /// </summary>
        static WallType GetFirstWallTypeNamed(
            Document doc,
            string name)
        {
            // built-in parameter storing this
            // wall type's name:

            BuiltInParameter bip
                = BuiltInParameter.SYMBOL_NAME_PARAM;

            ParameterValueProvider provider
                = new ParameterValueProvider(
                      new ElementId(bip));

            FilterStringRuleEvaluator evaluator
                = new FilterStringEquals();

            FilterRule rule = new FilterStringRule(
                provider, evaluator, name, false);

            ElementParameterFilter filter
                = new ElementParameterFilter(rule);

            FilteredElementCollector collector
                = new FilteredElementCollector(doc)
                  .OfClass(typeof(WallType))
                  .WherePasses(filter);

            return(collector.FirstElement() as WallType);
        }
Beispiel #17
0
        /// <summary>
        /// Return the viewport on the given
        /// sheet displaying the given view.
        /// </summary>
        Element GetViewport(ViewSheet sheet, View view)
        {
            Document doc = sheet.Document;

            // filter for view name:

            BuiltInParameter bip
                = BuiltInParameter.VIEW_NAME;

            ParameterValueProvider provider
                = new ParameterValueProvider(
                      new ElementId(bip));

            FilterStringRuleEvaluator evaluator
                = new FilterStringEquals();

            //FilterRule rule = new FilterStringRule( // 2021
            //  provider, evaluator, view.Name, true );

            FilterRule rule = new FilterStringRule( // 2022
                provider, evaluator, view.Name);

            ElementParameterFilter name_filter
                = new ElementParameterFilter(rule);

            BuiltInCategory bic
                = BuiltInCategory.OST_Viewports;

            // retrieve the specific named viewport:

            //Element viewport
            //  = new FilteredElementCollector( doc )
            //    .OfCategory( bic )
            //    .WherePasses( name_filter )
            //    .FirstElement();
            //return viewport;

            // unfortunately, there are not just one,
            // but two candidate elements. apparently,
            // we can distibuish them using the
            // owner view id property:

            List <Element> viewports
                = new List <Element>(
                      new FilteredElementCollector(doc)
                      .OfCategory(bic)
                      .WherePasses(name_filter)
                      .ToElements());

            Debug.Assert(viewports[0].OwnerViewId.Equals(ElementId.InvalidElementId),
                         "expected the first viewport to have an invalid owner view id");

            Debug.Assert(!viewports[1].OwnerViewId.Equals(ElementId.InvalidElementId),
                         "expected the second viewport to have a valid owner view id");

            int i = 1;

            return(viewports[i]);
        }
Beispiel #18
0
        private void DocumentOpenedAction(object sender, DocumentOpenedEventArgs even)
        {
            settings              = ExtensibleStorage.GetTooltipInfo(even.Document.ProjectInformation);
            this.mysql            = new MysqlUtil(settings);
            this.sqlite           = new SQLiteHelper(settings);
            m_previousDocPathName = even.Document.PathName;
            current_doc           = even.Document;

            //过滤测点待使用
            //打开文档就过滤一次
            keyNameToElementMap = new Dictionary <string, Element>();
            BuiltInParameter       testParam   = BuiltInParameter.ALL_MODEL_TYPE_NAME;
            ParameterValueProvider pvp         = new ParameterValueProvider(new ElementId(testParam));
            FilterStringEquals     eq          = new FilterStringEquals();
            FilterRule             rule        = new FilterStringRule(pvp, eq, Res.String_ParameterSurveyType, false);
            ElementParameterFilter paramFilter = new ElementParameterFilter(rule);
            Document document = current_doc;
            FilteredElementCollector elementCollector = new FilteredElementCollector(document).OfClass(typeof(FamilyInstance));
            IList <Element>          elems            = elementCollector.WherePasses(paramFilter).ToElements();

            foreach (var elem in elems)
            {
                string    param_value = string.Empty;
                Parameter param       = elem.get_Parameter(Res.String_ParameterName);
                if (null != param && param.StorageType == StorageType.String)
                {
                    param_value = param.AsString();
                    if (!string.IsNullOrWhiteSpace(param_value))
                    {
                        keyNameToElementMap.Add(param_value, elem);
                    }
                }
            }


            //准备Material
            IEnumerable <Material> allMaterial = new FilteredElementCollector(even.Document).OfClass(typeof(Material)).Cast <Material>();

            foreach (Material elem in allMaterial)
            {
                if (elem.Name.Equals(Res.String_Color_Redline))
                {
                    color_red = elem;
                }
                if (elem.Name.Equals(Res.String_Color_Gray))
                {
                    color_gray = elem;
                }
                if (elem.Name.Equals(Res.String_Color_Blue))
                {
                    color_blue = elem;
                }
                if (color_gray != null && color_red != null && color_blue != null)
                {
                    this.ColorMaterialIsReady = true;
                    break;
                }
            }
        }
 public static FilteredElementCollector WhereTypeIdEqualsTo(this FilteredElementCollector collector, ElementId value)
 {
     using (var provider = new ParameterValueProvider(new ElementId(BuiltInParameter.ELEM_TYPE_PARAM)))
         using (var evaluator = new FilterNumericEquals())
             using (var rule = new FilterElementIdRule(provider, evaluator, value))
                 using (var filter = new ElementParameterFilter(rule))
                     return(collector.WherePasses(filter));
 }
 public static FilteredElementCollector WhereParameterEqualsTo(this FilteredElementCollector collector, BuiltInParameter paramId, string value, bool caseSensitive = true)
 {
     using (var provider = new ParameterValueProvider(new ElementId(paramId)))
         using (var evaluator = new FilterStringEquals())
             using (var rule = new FilterStringRule(provider, evaluator, value, caseSensitive))
                 using (var filter = new ElementParameterFilter(rule))
                     return(collector.WherePasses(filter));
 }
Beispiel #21
0
        public static ElementParameterFilter ParameterValueFilter(string valueQualifier, BuiltInParameter parameterName)
        {
            BuiltInParameter          testParam = parameterName;
            ParameterValueProvider    pvp       = new ParameterValueProvider(new ElementId((int)testParam));
            FilterStringRuleEvaluator str       = new FilterStringEquals();
            FilterStringRule          paramFr   = new FilterStringRule(pvp, str, valueQualifier, false);
            ElementParameterFilter    epf       = new ElementParameterFilter(paramFr);

            return(epf);
        }
Beispiel #22
0
    public Result Execute(
      ExternalCommandData commandData,
      ref string message,
      ElementSet elements)
    {
        // Get application and document objects
        UIApplication uiApp = commandData.Application;
        Document doc = uiApp.ActiveUIDocument.Document;
        UIDocument uidoc = uiApp.ActiveUIDocument;

        try
        {
            using (Transaction trans = new Transaction(doc, "UpperCase Views on Sheets."))
            {
                // Delete all unnamed Reference Planes in the project
                // Create Filter to check for Name
                BuiltInParameter bip = BuiltInParameter.DATUM_TEXT;
                ParameterValueProvider provider = new ParameterValueProvider(new ElementId(bip));
                FilterStringEquals evaluator = new FilterStringEquals();
                FilterStringRule rule = new FilterStringRule(provider, evaluator, "", false);
                ElementParameterFilter filter = new ElementParameterFilter(rule);

                ICollection<ElementId> refPlanes = new FilteredElementCollector(doc)
                    .OfClass(typeof(ReferencePlane))
                    .WherePasses(filter)
                    .ToElementIds();

                int count = refPlanes.Count;
                try
                {
                    trans.Start();
                    doc.Delete(refPlanes);
                    trans.Commit();
                }
                catch (Exception x)
                {
                    message = x.Message;
                    return Result.Failed;
                }

                TaskDialog.Show("Delete Reference Planes", "You have successfully delete " + count.ToString() + " unnamed reference planes!");
                return Result.Succeeded;
            }
        }
        // Catch any Exceptions and display them.
        catch (Autodesk.Revit.Exceptions.OperationCanceledException)
        {
            return Result.Cancelled;
        }
        catch (Exception x)
        {
            message = x.Message;
            return Result.Failed;
        }
    }
        public Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            // Get application and document objects
            UIApplication uiApp = commandData.Application;
            Document      doc   = uiApp.ActiveUIDocument.Document;
            UIDocument    uidoc = uiApp.ActiveUIDocument;

            try
            {
                using (Transaction trans = new Transaction(doc, "UpperCase Views on Sheets."))
                {
                    // Delete all unnamed Reference Planes in the project
                    // Create Filter to check for Name
                    BuiltInParameter       bip       = BuiltInParameter.DATUM_TEXT;
                    ParameterValueProvider provider  = new ParameterValueProvider(new ElementId(bip));
                    FilterStringEquals     evaluator = new FilterStringEquals();
                    FilterStringRule       rule      = new FilterStringRule(provider, evaluator, "", false);
                    ElementParameterFilter filter    = new ElementParameterFilter(rule);

                    ICollection <ElementId> refPlanes = new FilteredElementCollector(doc)
                                                        .OfClass(typeof(ReferencePlane))
                                                        .WherePasses(filter)
                                                        .ToElementIds();

                    int count = refPlanes.Count;
                    try
                    {
                        trans.Start();
                        doc.Delete(refPlanes);
                        trans.Commit();
                    }
                    catch (Exception x)
                    {
                        message = x.Message;
                        return(Result.Failed);
                    }

                    TaskDialog.Show("Delete Reference Planes", "You have successfully delete " + count.ToString() + " unnamed reference planes!");
                    return(Result.Succeeded);
                }
            }
            // Catch any Exceptions and display them.
            catch (Autodesk.Revit.Exceptions.OperationCanceledException)
            {
                return(Result.Cancelled);
            }
            catch (Exception x)
            {
                message = x.Message;
                return(Result.Failed);
            }
        }
Beispiel #24
0
        /// <summary>
        /// Retrieve all circuit elements in current active document,
        /// which we identify as all family instance or electrical system
        /// elements with a non-empty RBS_ELEC_CIRCUIT_NUMBER or "Circuit Number"
        /// parameter.
        /// </summary>
        public static IList <Element> GetCircuitElements(Document doc)
        {
            //
            // prepend as many 'fast' filters as possible, because parameter access is 'slow':
            //
            ElementClassFilter       f1        = new ElementClassFilter(typeof(FamilyInstance));
            ElementClassFilter       f2        = new ElementClassFilter(typeof(ElectricalSystem));
            LogicalOrFilter          f3        = new LogicalOrFilter(f1, f2);
            FilteredElementCollector collector = new FilteredElementCollector(doc).WherePasses(f3);

            BuiltInParameter bip = BuiltInParameter.RBS_ELEC_CIRCUIT_NUMBER;

#if DEBUG
            int n1 = collector.ToElements().Count;

            List <Element> a = new List <Element>();
            foreach (Element e in collector)
            {
                Parameter p = e.get_Parameter(BuiltInParameter.RBS_ELEC_CIRCUIT_NUMBER);
                if (null != p && 0 < p.AsString().Length)
                {
                    a.Add(e);
                }
            }
            int n2 = a.Count;
            Debug.Assert(n1 > n2, "expected filter to eliminate something");

            List <Element> b = (
                from e in collector.ToElements()
                where (null != e.get_Parameter(bip)) && (0 < e.get_Parameter(bip).AsString().Length)
                select e).ToList <Element>();

            int n3 = b.Count;
            Debug.Assert(n2 == n3, "expected to reproduce same result");
#endif // DEBUG

            //
            // this is unclear ... negating the rule that says the parameter
            // exists and is empty could mean that elements pass if the parameter
            // is non-empty, but also if the parameter does not exist ...
            // so maybe returning the collection b instead of c would be a safer bet?
            //
            ParameterValueProvider    provider  = new ParameterValueProvider(new ElementId(bip));
            FilterStringRuleEvaluator evaluator = new FilterStringEquals();
            FilterRule             rule         = new FilterStringRule(provider, evaluator, string.Empty, false);
            ElementParameterFilter filter       = new ElementParameterFilter(rule, true);

            collector.WherePasses(filter);
            IList <Element> c  = collector.ToElements();
            int             n4 = c.Count;
            Debug.Assert(n2 == n4, "expected to reproduce same result");

            return(c);
        }
Beispiel #25
0
        public Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            UIDocument uidoc = commandData.Application.ActiveUIDocument;

            try
            {
                int roomNum = 1;
                while (true)
                {
                    Reference selRef = uidoc.Selection.PickObject(ObjectType.Element,
                                                                  new MySelectionFilter(),
                                                                  "Pick a room 2");

                    Room room = (Room)uidoc.Document.GetElement(selRef.ElementId);

                    FilteredElementCollector collector = new FilteredElementCollector(uidoc.Document);

                    collector.WherePasses(new RoomFilter());

                    ParameterValueProvider provider = new ParameterValueProvider(new ElementId(BuiltInParameter.ROOM_NUMBER));

                    FilterStringEquals evaluator = new FilterStringEquals();

                    FilterStringRule rule = new FilterStringRule(provider, evaluator, roomNum.ToString(), false);


                    ElementParameterFilter filter = new ElementParameterFilter(rule);

                    collector.WherePasses(filter);

                    IList <Element> rooms = collector.ToElements();

                    if (rooms.Count > 0)
                    {
                        ((Room)(rooms[0])).Number = room.Number;
                    }

                    room.Number = roomNum.ToString();

                    uidoc.Document.Regenerate();

                    roomNum++;
                }
            }
            catch (Autodesk.Revit.Exceptions.OperationCanceledException)
            {
            }


            return(Result.Succeeded);
        }
Beispiel #26
0
 /// <summary>
 /// Returns the priority which is defined in the given process definition.
 /// The priority value is identified with the given propertyKey.
 /// Returns null if the process definition is null or no priority was defined.
 /// </summary>
 /// <param name="processDefinition"> the process definition that should contains the priority </param>
 /// <param name="propertyKey"> the key which identifies the property </param>
 /// <param name="execution"> the current execution </param>
 /// <param name="errorMsgHead"> the error message header which is used if the evaluation fails </param>
 /// <returns> the priority defined in the given process </returns>
 protected internal virtual long?getProcessDefinedPriority(ProcessDefinitionImpl processDefinition, string propertyKey, ExecutionEntity execution, string errorMsgHead)
 {
     if (processDefinition != null)
     {
         ParameterValueProvider priorityProvider = (ParameterValueProvider)processDefinition.getProperty(propertyKey);
         if (priorityProvider != null)
         {
             return(evaluateValueProvider(priorityProvider, execution, errorMsgHead));
         }
     }
     return(null);
 }
Beispiel #27
0
        /** param name="level" the level for which the stairs should be retrieved for.
         *  The list always consists of two elements.
         *  The first list contains the list of stairs, that start on this level.
         *  The second list contains the list of stairs, that end on this level.
         *
         *  returns a List of all stairs that start or end at the current level.
         */
        public List <KeyValuePair <string, List <Stairs> > > GetAllStairsFromLevel(UIDocument currentDocument, List <Stairs> allStairs, Level currentLevel)
        {
            var filteredStairs    = new List <KeyValuePair <string, List <Stairs> > >();
            var baseStairsOnLevel = new List <Stairs>();
            var topStairsOnLevel  = new List <Stairs>();
            FilterNumericRuleEvaluator evaluator = new FilterNumericEquals();

            BuiltInParameter       baseLevelParameter = BuiltInParameter.STAIRS_BASE_LEVEL_PARAM;
            ParameterValueProvider baseLevelProvider  = new ParameterValueProvider(new ElementId(baseLevelParameter));
            FilterRule             baseLevelRule      = new FilterElementIdRule(baseLevelProvider, evaluator, currentLevel.Id);
            ElementParameterFilter baseLevelFilter    = new ElementParameterFilter(baseLevelRule);

            FilteredElementCollector baseStairsCollector = new FilteredElementCollector(currentDocument.Document).WhereElementIsNotElementType().OfCategory(BuiltInCategory.OST_Stairs);
            ICollection <ElementId>  baseStairIds        = baseStairsCollector.WherePasses(baseLevelFilter).ToElementIds();

            foreach (ElementId currentBaseStairsId in baseStairIds)
            {
                if (Stairs.IsByComponent(currentDocument.Document, currentBaseStairsId))
                {
                    Stairs currentBaseStairs = currentDocument.Document.GetElement(currentBaseStairsId) as Stairs;

                    if (!StairsListContainsElement(baseStairsOnLevel, currentBaseStairs) && !StairsListContainsElement(topStairsOnLevel, currentBaseStairs))
                    {
                        baseStairsOnLevel.Add(currentBaseStairs);
                    }
                }
            }

            BuiltInParameter       topLevelParameter = BuiltInParameter.STAIRS_TOP_LEVEL_PARAM;
            ParameterValueProvider topLevelProvider  = new ParameterValueProvider(new ElementId(topLevelParameter));
            FilterRule             topLevelRule      = new FilterElementIdRule(topLevelProvider, evaluator, currentLevel.Id);
            ElementParameterFilter topLevelFilter    = new ElementParameterFilter(topLevelRule);

            FilteredElementCollector topStairsCollector = new FilteredElementCollector(currentDocument.Document).WhereElementIsNotElementType().OfCategory(BuiltInCategory.OST_Stairs);
            ICollection <ElementId>  topStairsIds       = topStairsCollector.WherePasses(topLevelFilter).ToElementIds();

            foreach (ElementId currentTopStairsId in topStairsIds)
            {
                if (Stairs.IsByComponent(currentDocument.Document, currentTopStairsId))
                {
                    Stairs currentTopStairs = currentDocument.Document.GetElement(currentTopStairsId) as Stairs;

                    if (!StairsListContainsElement(baseStairsOnLevel, currentTopStairs) && !StairsListContainsElement(topStairsOnLevel, currentTopStairs))
                    {
                        topStairsOnLevel.Add(currentTopStairs);
                    }
                }
            }

            filteredStairs.Add(new KeyValuePair <string, List <Stairs> >(BASE_LEVEL_KEY, baseStairsOnLevel));
            filteredStairs.Add(new KeyValuePair <string, List <Stairs> >(TOP_LEVEL_KEY, topStairsOnLevel));
            return(filteredStairs);
        }
        //returns a list of elements that have the same value for a specific parameter
        public static List <Element> GetElementsWithTheSameParameterValue(BuiltInParameter parameter, string value)
        {
            List <Element>         elements = new List <Element>();
            ParameterValueProvider provider = new ParameterValueProvider(new ElementId((int)parameter));
            FilterStringRule       rule1    = new FilterStringRule(provider, new FilterStringEquals(), value, false);
            ElementParameterFilter filter1  = new ElementParameterFilter(rule1, false);

            return
                ((new FilteredElementCollector(doc))
                 .WherePasses(filter1)
                 .ToElements() as List <Element>);
        }
Beispiel #29
0
        /// <summary>
        /// Parses a output parameter and adds it to the <seealso cref="IoMapping"/>.
        /// </summary>
        /// <param name="outputParameterElement"> the output parameter element </param>
        /// <param name="ioMapping"> the mapping to add the element </param>
        /// <exception cref="BpmnParseException"> if the output parameter element is malformed </exception>
        public static void parseOutputParameterElement(Element outputParameterElement, IoMapping ioMapping)
        {
            string nameAttribute = outputParameterElement.attribute("name");

            if (string.ReferenceEquals(nameAttribute, null) || nameAttribute.Length == 0)
            {
                throw new BpmnParseException("Missing attribute 'name' for outputParameter", outputParameterElement);
            }

            ParameterValueProvider valueProvider = parseNestedParamValueProvider(outputParameterElement);

            // add parameter
            ioMapping.addOutputParameter(new OutputParameter(nameAttribute, valueProvider));
        }
Beispiel #30
0
        protected internal virtual void initializeInputParameter(CmmnElement element, CmmnActivity activity, CmmnHandlerContext context, CallableElement callableElement)
        {
            ExpressionManager expressionManager = context.ExpressionManager;

            IList <CamundaIn> inputs = getInputs(element);

            foreach (CamundaIn input in inputs)
            {
                // businessKey
                string businessKey = input.CamundaBusinessKey;
                if (!string.ReferenceEquals(businessKey, null) && businessKey.Length > 0)
                {
                    ParameterValueProvider businessKeyValueProvider = createParameterValueProvider(businessKey, expressionManager);
                    callableElement.BusinessKeyValueProvider = businessKeyValueProvider;
                }
                else
                {
                    // create new parameter
                    CallableElementParameter parameter = new CallableElementParameter();
                    callableElement.addInput(parameter);

                    if (input.CamundaLocal)
                    {
                        parameter.ReadLocal = true;
                    }

                    // all variables
                    string variables = input.CamundaVariables;
                    if ("all".Equals(variables))
                    {
                        parameter.AllVariables = true;
                        continue;
                    }

                    // source/sourceExpression
                    string source = input.CamundaSource;
                    if (string.ReferenceEquals(source, null) || source.Length == 0)
                    {
                        source = input.CamundaSourceExpression;
                    }

                    ParameterValueProvider sourceValueProvider = createParameterValueProvider(source, expressionManager);
                    parameter.SourceValueProvider = sourceValueProvider;

                    // target
                    string target = input.CamundaTarget;
                    parameter.Target = target;
                }
            }
        }
Beispiel #31
0
        /// <summary>
        /// Generic Parameter value filter. An attempt to write a generic method,
        /// that returns an element filter consumed by FilteredElementCollector.
        /// </summary>
        /// <typeparam name="T1">Type of the parameter VALUE to filter by.</typeparam>
        /// <typeparam name="T2">Type of the PARAMETER to filter.</typeparam>
        /// <param name="value">Currently: string, bool.</param>
        /// <param name="parameterId">Currently: Guid, BuiltInCategory.</param>
        /// <returns>ElementParameterFilter consumed by FilteredElementCollector.</returns>
        public static ElementParameterFilter ParameterValueGenericFilter <T1, T2>(Document doc, T1 value, T2 parameterId)
        {
            //Initialize ParameterValueProvider
            ParameterValueProvider pvp = null;

            switch (parameterId)
            {
            case BuiltInParameter bip:
                pvp = new ParameterValueProvider(new ElementId((int)bip));
                break;

            case Guid guid:
                SharedParameterElement spe = SharedParameterElement.Lookup(doc, guid);
                pvp = new ParameterValueProvider(spe.Id);
                break;

            default:
                throw new NotImplementedException("ParameterValueGenericFilter: T2 (parameter) type not implemented!");
            }

            //Branch off to value types
            switch (value)
            {
            case string str:
                FilterStringRuleEvaluator fsrE = new FilterStringEquals();
                FilterStringRule          fsr  = new FilterStringRule(pvp, fsrE, str, false);
                return(new ElementParameterFilter(fsr));

            case bool bol:
                int _value;

                if (bol == true)
                {
                    _value = 1;
                }
                else
                {
                    _value = 0;
                }

                FilterNumericRuleEvaluator fnrE = new FilterNumericEquals();
                FilterIntegerRule          fir  = new FilterIntegerRule(pvp, fnrE, _value);
                return(new ElementParameterFilter(fir));

            default:
                throw new NotImplementedException("ParameterValueGenericFilter: T1 (value) type not implemented!");
            }
        }
        public Result Execute(ExternalCommandData commandData,
                              ref string message,
                              ElementSet elements)
        {
            try
            {
                uiApp = commandData.Application;
                uiDoc = uiApp.ActiveUIDocument;
                app = uiApp.Application;
                doc = uiDoc.Document;

                FilteredElementCollector refPlaneCollector = new FilteredElementCollector(doc);
                IList<Element> refPlanes = refPlaneCollector.OfClass(typeof(ReferencePlane)).ToElements();

                ElementId nameParamterId = new ElementId(BuiltInParameter.DATUM_TEXT);
                ParameterValueProvider pvp = new ParameterValueProvider(nameParamterId);
                FilterStringRuleEvaluator evaluator = new FilterStringEquals();
                FilterRule rule = new FilterStringRule(pvp, evaluator, "", false);
                ElementFilter filter = new ElementParameterFilter(rule);

                FilteredElementCollector unnamedRefPlaneCollector = new FilteredElementCollector(doc);
                unnamedRefPlaneCollector.OfClass(typeof(ReferencePlane));
                unnamedRefPlaneCollector.WherePasses(filter);
                IList<Element> unnamedRefPlanes = unnamedRefPlaneCollector.ToElements();

                Transaction transaction = new Transaction(doc);
                transaction.Start("Purging unnamed reference planes");

                foreach (Element refPlane in unnamedRefPlanes)
                     doc.Delete(refPlane.Id);

                transaction.Commit();

                TaskDialog.Show("Purge Unnamed Ref Planes",
                                String.Format("{0} reference planes found.\n{1} unnamed reference planes deleted.",
                                               refPlanes.Count.ToString(), unnamedRefPlanes.Count.ToString()));

                return Result.Succeeded;
            }
            catch (Exception e)
            {
                TaskDialog.Show("Revit Quick Tools", e.Message);
                return Result.Failed;
            }
        }
        void f3( Document doc )
        {
            FilteredElementCollector collector
            = new FilteredElementCollector( doc );

              collector.OfClass( typeof( Level ) );
              ElementId id = new ElementId(
            BuiltInParameter.DATUM_TEXT );

              ParameterValueProvider provider
            = new ParameterValueProvider( id );

              FilterStringRuleEvaluator evaluator
            = new FilterStringContains();

              FilterRule rule = new FilterStringRule(
            provider, evaluator, "Level", false );

              ElementParameterFilter filter
            = new ElementParameterFilter( rule );
        }
    /// <summary>
    /// Find a specific family type for a wall, which is a system family. 
    /// Most efficient way to find a named family symbol: use a parameter filter.
    /// </summary>
    public Element FindFamilyType_Wall_v3(
      string wallFamilyName,
      string wallTypeName)
    {
      ParameterValueProvider provider
        = new ParameterValueProvider(
          new ElementId(BuiltInParameter.DATUM_TEXT));

      FilterStringRuleEvaluator evaluator
        = new FilterStringEquals();

      FilterRule rule = new FilterStringRule(
        provider, evaluator, wallTypeName, true);

      ElementParameterFilter filter
        = new ElementParameterFilter(rule);

      return new FilteredElementCollector(_doc)
        .OfClass(typeof(WallType))
        .WherePasses(filter)
        .FirstElement();
    }
        /// <summary>
        /// Return a list of all elements with the 
        /// specified value in their shared parameter with 
        /// the given name oand group. They are retrieved
        /// using a parameter filter, and the required 
        /// parameter id is found by temporarily adding 
        /// the shared parameter to the project info.
        /// </summary>
        static IList<Element> GetElementsMatchingParameter(
            Document doc,
            string paramName,
            string paramGroup,
            string paramValue)
        {
            IList<Element> elems = new List<Element>();

              // Determine if definition for parameter binding exists

              Definition definition = null;
              BindingMap bm = doc.ParameterBindings;
              DefinitionBindingMapIterator it = bm.ForwardIterator();
              while( it.MoveNext() )
              {
            Definition def = it.Key;
            if( def.Name.Equals( paramName ) )
            {
              definition = def;
              break;
            }
              }
              if( definition == null )
              {
            return elems; // parameter binding not defined
              }

              using( Transaction tx = new Transaction( doc ) )
              {
            tx.Start( "Set temporary parameter" );

            // Temporarily set project information element
            // parameter in order to determine param.Id

            FilteredElementCollector collectorPI
              = new FilteredElementCollector( doc );

            collectorPI.OfCategory(
              BuiltInCategory.OST_ProjectInformation );

            Element projInfoElem
              = collectorPI.FirstElement();

            // using http://thebuildingcoder.typepad.com/blog/2012/04/adding-a-category-to-a-shared-parameter-binding.html

            Parameter param = null;

            //param = HelperParams.GetOrCreateElemSharedParam(
            //     projInfoElem, paramName, paramGroup,
            //     ParameterType.Text, false, true );

            if( param != null )
            {
              ElementId paraId = param.Id;

              tx.RollBack(); // discard project element change

              ParameterValueProvider provider
            = new ParameterValueProvider( paraId );

              FilterRule rule = new FilterStringRule(
            provider, new FilterStringEquals(),
            paramValue, true );

              ElementParameterFilter filter
            = new ElementParameterFilter( rule );

              FilteredElementCollector collector
            = new FilteredElementCollector(
              doc, doc.ActiveView.Id );

              elems = collector.WherePasses( filter )
            .ToElements();
            }
              }
              return elems;
        }
        void f2( Document doc, Level level )
        {
            FilteredElementCollector collector
            = new FilteredElementCollector( doc );

              collector.OfCategory(
            BuiltInCategory.OST_StructuralFraming );

              collector.OfClass( typeof( FamilyInstance ) );

              BuiltInParameter bip = BuiltInParameter
            .INSTANCE_REFERENCE_LEVEL_PARAM;

              ParameterValueProvider provider
            = new ParameterValueProvider(
              new ElementId( bip ) );

              FilterNumericRuleEvaluator evaluator
            = new FilterNumericGreater();

              ElementId idRuleValue = level.Id;

              FilterElementIdRule rule
            = new FilterElementIdRule(
              provider, evaluator, idRuleValue );

              ElementParameterFilter filter
            = new ElementParameterFilter( rule );

              collector.WherePasses( filter );
        }
        /// <summary>
        /// Return the first wall type with the given name.
        /// </summary>
        static WallType GetFirstWallTypeNamed(
            Document doc,
            string name)
        {
            // built-in parameter storing this
              // wall type's name:

              BuiltInParameter bip
            = BuiltInParameter.SYMBOL_NAME_PARAM;

              ParameterValueProvider provider
            = new ParameterValueProvider(
              new ElementId( bip ) );

              FilterStringRuleEvaluator evaluator
            = new FilterStringEquals();

              FilterRule rule = new FilterStringRule(
            provider, evaluator, name, false );

              ElementParameterFilter filter
            = new ElementParameterFilter( rule );

              FilteredElementCollector collector
            = new FilteredElementCollector( doc )
              .OfClass( typeof( WallType ) )
              .WherePasses( filter );

              return collector.FirstElement() as WallType;
        }
        /// <summary>
        /// Return the all elements that
        /// use the given ElementType.
        /// </summary>
        static FilteredElementCollector GetAllElementsUsingType(
            Document doc,
            ElementType et)
        {
            // built-in parameter storing the type element id:

              BuiltInParameter bip
            = BuiltInParameter.ELEM_TYPE_PARAM;

              ParameterValueProvider provider
            = new ParameterValueProvider(
              new ElementId( bip ) );

              FilterNumericRuleEvaluator evaluator
            = new FilterNumericEquals();

              FilterRule rule = new FilterElementIdRule(
            provider, evaluator, et.Id );

              ElementParameterFilter filter
            = new ElementParameterFilter( rule );

              FilteredElementCollector collector
            = new FilteredElementCollector( doc )
              .WhereElementIsNotElementType()
              .WherePasses( filter );

              return collector;
        }
        /// <summary>
        /// Retrieve all stairs on a given level.
        /// </summary>
        FilteredElementCollector GetStairsOnLevel(
            Document doc,
            Level level)
        {
            ElementId id = level.Id;

              BuiltInCategory bic
            = BuiltInCategory.OST_Stairs;

              FilteredElementCollector collector
            = new FilteredElementCollector( doc );

              collector.OfCategory( bic );

              // explicit iteration and manual
              // checking of a property:

              List<Element> stairs = new List<Element>();

              foreach( Element e in collector )
              {
            if( e.LevelId.Equals( id ) )
            {
              stairs.Add( e );
            }
              }

              // using LINQ:

              IEnumerable<Element> stairsOnLevelLinq =
            from e in collector
            where e.LevelId.Equals( id )
            select e;

              // using an anonymous method:

              IEnumerable<Element> stairsOnLevelAnon =
            collector.Where<Element>( e
              => e.LevelId.Equals( id ) );

              // using a parameter filter:

              BuiltInParameter bip
            = BuiltInParameter.STAIRS_BASE_LEVEL_PARAM;

              ParameterValueProvider provider
            = new ParameterValueProvider(
              new ElementId( bip ) );

              FilterNumericRuleEvaluator evaluator
            = new FilterNumericEquals();

              FilterRule rule = new FilterElementIdRule(
            provider, evaluator, id );

              ElementParameterFilter filter
            = new ElementParameterFilter( rule );

              return collector.WherePasses( filter );
        }
        /// <summary>
        /// Return the viewport on the given
        /// sheet displaying the given view.
        /// </summary>
        Element GetViewport( ViewSheet sheet, View view )
        {
            Document doc = sheet.Document;

              // filter for view name:

              BuiltInParameter bip
            = BuiltInParameter.VIEW_NAME;

              ParameterValueProvider provider
            = new ParameterValueProvider(
              new ElementId( bip ) );

              FilterStringRuleEvaluator evaluator
            = new FilterStringEquals();

              FilterRule rule = new FilterStringRule(
            provider, evaluator, view.Name, true );

              ElementParameterFilter name_filter
            = new ElementParameterFilter( rule );

              BuiltInCategory bic
            = BuiltInCategory.OST_Viewports;

              // retrieve the specific named viewport:

              //Element viewport
              //  = new FilteredElementCollector( doc )
              //    .OfCategory( bic )
              //    .WherePasses( name_filter )
              //    .FirstElement();
              //return viewport;

              // unfortunately, there are not just one,
              // but two candidate elements. apparently,
              // we can distibuish them using the
              // owner view id property:

              List<Element> viewports
            = new List<Element>(
              new FilteredElementCollector( doc )
            .OfCategory( bic )
            .WherePasses( name_filter )
            .ToElements() );

              Debug.Assert( viewports[0].OwnerViewId.Equals( ElementId.InvalidElementId ),
            "expected the first viewport to have an invalid owner view id" );

              Debug.Assert( !viewports[1].OwnerViewId.Equals( ElementId.InvalidElementId ),
            "expected the second viewport to have a valid owner view id" );

              int i = 1;

              return viewports[i];
        }
        /// <summary>
        /// Return all elements from the given collector
        /// whose element id is greater than 'lastId'.
        /// </summary>
        FilteredElementCollector GetElementsAfter(
            FilteredElementCollector input,
            ElementId lastId)
        {
            BuiltInParameter bip = BuiltInParameter.ID_PARAM;

              ParameterValueProvider provider
            = new ParameterValueProvider(
              new ElementId( bip ) );

              FilterNumericRuleEvaluator evaluator
            = new FilterNumericGreater();

              FilterRule rule = new FilterElementIdRule(
            provider, evaluator, lastId );

              ElementParameterFilter filter
            = new ElementParameterFilter( rule );

              return input.WherePasses( filter );
        }
        public Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            UIApplication uiapp = commandData.Application;
              UIDocument uidoc = uiapp.ActiveUIDocument;
              Application app = uiapp.Application;
              Document doc = uidoc.Document;

              Reference r = uidoc.Selection.PickObject(
            ObjectType.Element );

              // 'Autodesk.Revit.DB.Reference.Element' is
              // obsolete: Property will be removed. Use
              // Document.GetElement(Reference) instead.
              //Wall wall = r.Element as Wall; // 2011

              Wall wall = doc.GetElement( r ) as Wall; // 2012

              //Parameter parameter = wall.get_Parameter( "Unconnected Height" ); // 2014, causes warning CS0618: 'Autodesk.Revit.DB.Element.get_Parameter(string)' is obsolete: 'This property is obsolete in Revit 2015, as more than one parameter can have the same name on a given element. Use Element.Parameters to obtain a complete list of parameters on this Element, or Element.GetParameters(String) to get a list of all parameters by name, or Element.LookupParameter(String) to return the first available parameter with the given name.'
              Parameter parameter = wall.get_Parameter( BuiltInParameter.WALL_USER_HEIGHT_PARAM ); // 2015, avoids warning, in language indepependent and more effective to look up

              ParameterValueProvider pvp
            = new ParameterValueProvider( parameter.Id );

              FilterNumericRuleEvaluator fnrv
            = new FilterNumericGreater();

              FilterRule fRule
            = new FilterDoubleRule( pvp, fnrv, 20, 1E-6 );

              ElementParameterFilter filter
            = new ElementParameterFilter( fRule );

              FilteredElementCollector collector
            = new FilteredElementCollector( doc );

              // Find walls with unconnected height
              // less than or equal to 20:

              ElementParameterFilter lessOrEqualFilter
            = new ElementParameterFilter( fRule, true );

              IList<Element> lessOrEqualFounds
            = collector.WherePasses( lessOrEqualFilter )
              .OfCategory( BuiltInCategory.OST_Walls )
              .OfClass( typeof( Wall ) )
              .ToElements();

              TaskDialog.Show( "Revit", "Walls found: "
            + lessOrEqualFounds.Count );

              return Result.Succeeded;
        }
        void f4( Document doc )
        {
            // Use numeric evaluator and integer rule to test ElementId parameter
              // Filter levels whose id is greater than specified id value

              BuiltInParameter testParam
            = BuiltInParameter.ID_PARAM;

              ParameterValueProvider pvp
            = new ParameterValueProvider(
              new ElementId( (int) testParam ) );

              FilterNumericRuleEvaluator fnrv
            = new FilterNumericGreater();

              // filter elements whose Id is greater than 99

              ElementId ruleValId = new ElementId( 99 );

              FilterRule paramFr = new FilterElementIdRule(
            pvp, fnrv, ruleValId );

              ElementParameterFilter epf
            = new ElementParameterFilter( paramFr );

              FilteredElementCollector collector
            = new FilteredElementCollector( doc );

              collector.OfClass( typeof( ViewPlan ) )
            .WherePasses( epf ); // only deal with ViewPlan

              // Use numeric evaluator and integer rule to test bool parameter
              // Filter levels whose crop view is false

              int ruleValInt = 0;

              testParam = BuiltInParameter.VIEWER_CROP_REGION;

              pvp = new ParameterValueProvider(
            new ElementId( (int) testParam ) );

              fnrv = new FilterNumericEquals();

              paramFr = new FilterIntegerRule(
            pvp, fnrv, ruleValInt );

              epf = new ElementParameterFilter( paramFr );

              collector = new FilteredElementCollector( doc );

              collector.OfClass( typeof( ViewPlan ) )
            .WherePasses( epf ); // only deal with ViewPlan

              // Use numeric evaluator and double rule to test double parameter
              // Filter levels whose top offset is greater than specified value

              double ruleValDb = 10;

              testParam =
            BuiltInParameter.VIEWER_BOUND_OFFSET_TOP;

              pvp = new ParameterValueProvider(
            new ElementId( (int) testParam ) );

              fnrv = new FilterNumericGreater();

              paramFr = new FilterDoubleRule(
            pvp, fnrv, ruleValDb, double.Epsilon );

              collector = new FilteredElementCollector( doc );

              collector.OfClass( typeof( ViewPlan ) )
            .WherePasses( epf ); // only deal with ViewPlan

              // Use string evaluator and string rule to test string parameter
              // Filter all elements whose view name contains level

              String ruleValStr = "Level";

              testParam = BuiltInParameter.VIEW_NAME;

              pvp = new ParameterValueProvider(
            new ElementId( (int) testParam ) );

              FilterStringRuleEvaluator fnrvStr
            = new FilterStringContains();

              paramFr = new FilterStringRule(
            pvp, fnrvStr, ruleValStr, false );

              collector = new FilteredElementCollector( doc );

              collector.OfClass( typeof( ViewPlan ) )
            .WherePasses( epf ); // only deal with ViewPlan
        }
        public Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            UIApplication uiapp = commandData.Application;
              UIDocument uidoc = uiapp.ActiveUIDocument;
              Application app = uiapp.Application;
              Document doc = uidoc.Document;

              // Construct a parameter filter to get only
              // unnamed reference planes, i.e. reference
              // planes whose name equals the empty string:

              BuiltInParameter bip
            = BuiltInParameter.DATUM_TEXT;

              ParameterValueProvider provider
            = new ParameterValueProvider(
              new ElementId( bip ) );

              FilterStringRuleEvaluator evaluator
            = new FilterStringEquals();

              FilterStringRule rule = new FilterStringRule(
            provider, evaluator, "", false );

              ElementParameterFilter filter
            = new ElementParameterFilter( rule );

              FilteredElementCollector col
            = new FilteredElementCollector( doc )
              .OfClass( typeof( ReferencePlane ) )
              .WherePasses( filter );

              int n = 0;
              int nDeleted = 0;

              // No need to cast ... this is pretty nifty,
              // I find ... grab the elements as ReferencePlane
              // instances, since the filter guarantees that
              // only ReferencePlane instances are selected.
              // In Revit 2014, this attempt to delete the
              // reference planes while iterating over the
              // filtered element collector throws an exception:
              // Autodesk.Revit.Exceptions.InvalidOperationException:
              // HResult=-2146233088
              // Message=The iterator cannot proceed due to
              // changes made to the Element table in Revit's
              // database (typically, This can be the result
              // of an Element deletion).
              //
              //foreach( ReferencePlane rp in col )
              //{
              //  ++n;
              //  nDeleted += DeleteIfNotHosting( rp ) ? 1 : 0;
              //}

              ICollection<ElementId> ids = col.ToElementIds();

              n = ids.Count();

              if( 0 < n )
              {
            using( Transaction tx = new Transaction( doc ) )
            {
              tx.Start( string.Format(
            "Delete {0} ReferencePlane{1}",
            n, Util.PluralSuffix( n ) ) );

              // This also causes the exception "One or more of
              // the elementIds cannot be deleted. Parameter
              // name: elementIds
              //
              //ICollection<ElementId> ids2 = doc.Delete(
              //  ids );
              //nDeleted = ids2.Count();

              List<ElementId> ids2 = new List<ElementId>(
            ids );

              foreach( ElementId id in ids2 )
              {
            try
            {
              ICollection<ElementId> ids3 = doc.Delete(
                id );

              nDeleted += ids3.Count;
            }
            catch( Autodesk.Revit.Exceptions.ArgumentException )
            {
            }
              }

              tx.Commit();
            }
              }

              Util.InfoMsg( string.Format(
            "{0} unnamed reference plane{1} examined, "
            + "{2} element{3} in total were deleted.",
            n, Util.PluralSuffix( n ),
            nDeleted, Util.PluralSuffix( nDeleted ) ) );

              return Result.Succeeded;
        }
        /// <summary>
        /// Return the first wall found that
        /// uses the given wall type.
        /// </summary>
        static Wall GetFirstWallUsingType(
            Document doc,
            WallType wallType)
        {
            // built-in parameter storing this
              // wall's wall type element id:

              BuiltInParameter bip
            = BuiltInParameter.ELEM_TYPE_PARAM;

              ParameterValueProvider provider
            = new ParameterValueProvider(
              new ElementId( bip ) );

              FilterNumericRuleEvaluator evaluator
            = new FilterNumericEquals();

              FilterRule rule = new FilterElementIdRule(
            provider, evaluator, wallType.Id );

              ElementParameterFilter filter
            = new ElementParameterFilter( rule );

              FilteredElementCollector collector
            = new FilteredElementCollector( doc )
              .OfClass( typeof( Wall ) )
              .WherePasses( filter );

              return collector.FirstElement() as Wall;
        }
    /// <summary>
    /// Optional - example of parameter filter. 
    /// Find walls whose length is longer than a certain length. e.g., 60 feet 
    ///     wall.parameter(length) > 60 feet 
    /// This could get more complex than looping through in terms of writing a code. 
    /// See page 87 of Developer guide. 
    /// </summary> 
    public IList<Element> FindLongWalls()
    {
      // Constant for this function. 
      const double kWallLength = 60.0;  // 60 feet. hard coding for simplicity. 

      // First, narrow down to the elements of the given type and category 
      var collector = new FilteredElementCollector(_doc).OfClass(typeof(Wall));

      // Define a filter by parameter 
      // 1st arg - value provider 
      BuiltInParameter lengthParam = BuiltInParameter.CURVE_ELEM_LENGTH;
      int iLengthParam = (int)lengthParam;
      var paramValueProvider = new ParameterValueProvider(new ElementId(iLengthParam));

      // 2nd - evaluator 
      FilterNumericGreater evaluator = new FilterNumericGreater();

      // 3rd - rule value 
      double ruleVal = kWallLength;

      // 4th - epsilon 
      const double eps = 1E-06;

      // Define a rule 
      var filterRule = new FilterDoubleRule(paramValueProvider, evaluator, ruleVal, eps);

      // Create a new filter 
      var paramFilter = new ElementParameterFilter(filterRule);

      // Go through the filter 
      IList<Element> elems = collector.WherePasses(paramFilter).ToElements();

      return elems;
    }
            public Result Execute(
                ExternalCommandData commandData,
                ref string messages,
                ElementSet elements)
            {
                UIApplication app = commandData.Application;
                Document doc = app.ActiveUIDocument.Document;

                ElementId id = new ElementId(
                  BuiltInParameter.ELEM_ROOM_NUMBER );

                ParameterValueProvider provider
                  = new ParameterValueProvider( id );

                FilterStringRuleEvaluator evaluator
                  = new FilterStringEquals();

                string sRoomNumber = "1";

                FilterRule rule = new FilterStringRule(
                  provider, evaluator, sRoomNumber, false );

                ElementParameterFilter filter
                  = new ElementParameterFilter( rule );

                FilteredElementCollector collector
                  = new FilteredElementCollector( doc );

                string s = string.Empty;

                foreach( Element e in collector )
                {
                  s += e.Name + e.Category.Name.ToString() + "\n";

                }
                System.Windows.Forms.MessageBox.Show( s );

                return Result.Succeeded;
            }
    private static void HostedFamilyInstanceOpenings(Wall wall,
        double minOpeningValue)
    {
      double wallOpeningArea = 0.0;
      double wallTotalOpeningArea = 0.0;

      // Filter all Family Instances where the HOST_ID_PARAM 
      // equals the wall ID
      // 
      // More information at
      // http://thebuildingcoder.typepad.com/
      //                 blog/2010/06/parameter-filter.html#4
      BuiltInParameter testParam =
          BuiltInParameter.HOST_ID_PARAM;
      ParameterValueProvider pvp =
          new ParameterValueProvider(
              new ElementId((int)testParam));

      FilterNumericRuleEvaluator fnrv = new FilterNumericEquals();
      ElementId ruleValId = wall.Id;

      FilterRule paramFr = new FilterElementIdRule
        (pvp, fnrv, ruleValId);
      ElementParameterFilter epf = 
        new ElementParameterFilter(paramFr);
      FilteredElementCollector collector =
          new FilteredElementCollector(wall.Document);

      collector.OfClass(typeof(FamilyInstance)).WherePasses(epf);
      IList<Element> hostedFamilyInstances = collector.ToElements();

      // Now iterate through the collected family instances
      Document doc = wall.Document;
      double previousArea = wall.get_Parameter(
          BuiltInParameter.HOST_AREA_COMPUTED).AsDouble();

      foreach (FamilyInstance instance in hostedFamilyInstances)
      {
        // Delete the hosted family instace and regenerate
        doc.Delete(instance);
        doc.Regenerate();

        // Get the new area to compare
        double newArea = wall.get_Parameter(
            BuiltInParameter.HOST_AREA_COMPUTED).AsDouble();

        // So the instance opening equals:
        double instanceAreaOnTheWall = 
          Math.Abs(newArea - previousArea);

        // The element area (on wall) is smaller than 
        // the minOpeningValue?
        if (instanceAreaOnTheWall <= minOpeningValue)
          wallOpeningArea += instanceAreaOnTheWall;
        else
          wallTotalOpeningArea += instanceAreaOnTheWall;

        if (System.Diagnostics.Debugger.IsAttached)
          TaskDialog.Show(
              "Wall opening (by inst) found (in sq feet)",
              string.Format("Area: {0}", instanceAreaOnTheWall));

        previousArea = newArea;
      }

      AddWallArea(wall.Id, wallOpeningArea, wallTotalOpeningArea);
    }
        public Result Execute(
            ExternalCommandData commandData,
            ref string messages,
            ElementSet elements)
        {
            UIApplication app = commandData.Application;
              Document doc = app.ActiveUIDocument.Document;

              Transaction tx = new Transaction( doc, "Test" );
              tx.Start();

              // use the view filter

              FilteredElementCollector collector
            = new FilteredElementCollector(
              doc, doc.ActiveView.Id );

              // use the parameter filter.
              // get the phase id "New construction"

              ElementId idPhase = GetPhaseId(
            "New Construction", doc );

              ParameterValueProvider provider
            = new ParameterValueProvider(
              new ElementId( (int)
            BuiltInParameter.PHASE_CREATED ) );

              FilterNumericRuleEvaluator evaluator
            = new FilterNumericEquals();

              FilterElementIdRule rule
            = new FilterElementIdRule(
              provider, evaluator, idPhase );

              ElementParameterFilter parafilter
            = new ElementParameterFilter( rule );

              collector.WherePasses( parafilter );

              TaskDialog.Show( "Element Count",
            "There are " + collector.Count().ToString()
            + " elements in the current view created"
            + " with phase New Construction" );

              tx.Commit();

              return Result.Succeeded;
        }
        /// <summary>
        /// Use a parameter filter to return the first element
        /// of the given type and with the specified string-valued
        /// built-in parameter matching the given name.
        /// </summary>
        Element GetFirstElementOfTypeWithBipString(
            Type type,
            BuiltInParameter bip,
            string name)
        {
            FilteredElementCollector a
            = GetElementsOfType( type );

              ParameterValueProvider provider
            = new ParameterValueProvider(
              new ElementId( bip ) );

              FilterStringRuleEvaluator evaluator
            = new FilterStringEquals();

              FilterRule rule = new FilterStringRule(
            provider, evaluator, name, true );

              ElementParameterFilter filter
            = new ElementParameterFilter( rule );

              return a.WherePasses( filter ).FirstElement();
        }
        public Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            UIApplication uiapp = commandData.Application;
              UIDocument uidoc = uiapp.ActiveUIDocument;
              Application app = uiapp.Application;
              Document doc = uidoc.Document;

              Reference r = uidoc.Selection.PickObject(
            ObjectType.Element );

              // 'Autodesk.Revit.DB.Reference.Element' is
              // obsolete: Property will be removed. Use
              // Document.GetElement(Reference) instead.
              //Wall wall = r.Element as Wall; // 2011

              Wall wall = doc.GetElement( r ) as Wall; // 2012

              Parameter parameter = wall.get_Parameter(
            "Unconnected Height" );

              ParameterValueProvider pvp
            = new ParameterValueProvider( parameter.Id );

              FilterNumericRuleEvaluator fnrv
            = new FilterNumericGreater();

              FilterRule fRule
            = new FilterDoubleRule( pvp, fnrv, 20, 1E-6 );

              ElementParameterFilter filter
            = new ElementParameterFilter( fRule );

              FilteredElementCollector collector
            = new FilteredElementCollector( doc );

              // Find walls with unconnected height
              // less than or equal to 20:

              ElementParameterFilter lessOrEqualFilter
            = new ElementParameterFilter( fRule, true );

              IList<Element> lessOrEqualFounds
            = collector.WherePasses( lessOrEqualFilter )
              .OfCategory( BuiltInCategory.OST_Walls )
              .OfClass( typeof( Wall ) )
              .ToElements();

              TaskDialog.Show( "Revit", "Walls found: "
            + lessOrEqualFounds.Count );

              return Result.Succeeded;
        }