public static IList <Element> GetWallsIntersectBoundingBox(Document doc, Element elem) { ExclusionFilter exclusionFilter = new ExclusionFilter(new List <ElementId> { elem.Id }); ElementParameterFilter elementParameterFilter = new ElementParameterFilter(ParameterFilterRuleFactory .CreateEqualsRule(new ElementId(BuiltInParameter.WALL_BASE_CONSTRAINT), elem.LevelId), true); BoundingBoxXYZ bndBx = elem.get_Geometry (new Options { IncludeNonVisibleObjects = true }).GetBoundingBox(); BoundingBoxIntersectsFilter bndBxFlt = new BoundingBoxIntersectsFilter(new Outline(bndBx.Min, bndBx.Max), 0.1); IList <Element> elements = new FilteredElementCollector(doc) .WherePasses(exclusionFilter) .OfClass(typeof(Wall)) .WherePasses(bndBxFlt) .WherePasses(elementParameterFilter) .ToElements() .ToList(); return(elements); }
private static FilterRule CreateRule(ElementId ParameterId, string Function, ElementId ValueId) { switch (Function) { case "Равно": return(ParameterFilterRuleFactory.CreateEqualsRule(ParameterId, ValueId)); case "Не равно": return(ParameterFilterRuleFactory.CreateNotEqualsRule(ParameterId, ValueId)); case "Больше": return(ParameterFilterRuleFactory.CreateGreaterRule(ParameterId, ValueId)); case "Больше или равно": return(ParameterFilterRuleFactory.CreateLessOrEqualRule(ParameterId, ValueId)); case "Меньше": return(ParameterFilterRuleFactory.CreateLessRule(ParameterId, ValueId)); case "Меньше или равно": return(ParameterFilterRuleFactory.CreateLessOrEqualRule(ParameterId, ValueId)); default: return(null); } }
private void BtnChange_Click(object sender, RoutedEventArgs e) { //Use a try so an exception doesn't crash revit try { //Case the Old and New views from the Combobox Selected Values View OldView = (View)ComboBoxOldReference.SelectedValue; View NewView = (View)ComboBoxNewReference.SelectedValue; //Use a Filter Rule to Collect ONLY views that have the View Name of the OldView FilterRule rule = ParameterFilterRuleFactory.CreateEqualsRule(new ElementId(BuiltInParameter.VIEW_NAME), OldView.Name, true); //Create a Filter from the Filter Rule ElementParameterFilter filter = new ElementParameterFilter(rule); //Use a Collecter with the Filter to get Viewers that are not ElementTypes if (OldView.ViewType == NewView.ViewType) { using (FilteredElementCollector fec = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Viewers).WherePasses(filter).WhereElementIsNotElementType()) { //Create a new Transaction to make make changes to the Document using (Transaction Trans = new Transaction(doc)) { //Start the Transaction and Name it for the Undo/rdo Menu Trans.Start("Change View Reference"); //Iterate each Viewer returned by the Collector foreach (Element viewer in fec.ToElements()) { //The Viewers do not contain the same parameters as the actual views, so we check for one of them if (viewer.GetParameters("Discipline").Count == 0) { ReferenceableViewUtils.ChangeReferencedView(doc, viewer.Id, NewView.Id); } } //Commit the Transaction to save the changes Trans.Commit(); } } //Set the Dialog result to true so the Command will keep the changes DialogResult = true; //Close the Form Close(); } else { TaskDialog.Show("View Type Mismatch", "Current View and New View are not of the Same View Type\n\nCurrent View Type: " + OldView.ViewType.ToString() + "\nNew View Type: " + NewView.ViewType.ToString()); } } //Catch and Display any Exeptions that are thrown catch (Exception ex) { TaskDialog.Show("Error", ex.ToString()); //Set the Dialog result to False so the Command will not keep any changes DialogResult = false; //Close the Form Close(); } }
public bool IsElementVisibleInView( View view, Element el) { if (view == null) { throw new ArgumentNullException(nameof(view)); } if (el == null) { throw new ArgumentNullException(nameof(el)); } // Obtain the element's document. Document doc = el.Document; ElementId elId = el.Id; // Create a FilterRule that searches // for an element matching the given Id. FilterRule idRule = ParameterFilterRuleFactory .CreateEqualsRule( new ElementId(BuiltInParameter.ID_PARAM), elId); var idFilter = new ElementParameterFilter(idRule); // Use an ElementCategoryFilter to speed up the // search, as ElementParameterFilter is a slow filter. Category cat = el.Category; var catFilter = new ElementCategoryFilter(cat.Id); // Use the constructor of FilteredElementCollector // that accepts a view id as a parameter to only // search that view. // Also use the WhereElementIsNotElementType filter // to eliminate element types. FilteredElementCollector collector = new FilteredElementCollector(doc, view.Id) .WhereElementIsNotElementType() .WherePasses(catFilter) .WherePasses(idFilter); // If the collector contains any items, then // we know that the element is visible in the // given view. return(collector.Any()); }
internal static IList <ElementType> ViewportTypes(Document doc) { FilterRule rule = ParameterFilterRuleFactory.CreateEqualsRule(new ElementId((int)BuiltInParameter.SYMBOL_FAMILY_NAME_PARAM), "Viewport", false); ElementParameterFilter filter = new ElementParameterFilter(rule); IList <ElementType> viewportTypes; using (FilteredElementCollector fec = new FilteredElementCollector(doc).OfClass(typeof(ElementType)).WherePasses(filter)) { viewportTypes = fec.Cast <ElementType>().ToList(); } return(viewportTypes); }
static IEnumerable <Element> Factory( Document doc, BuiltInCategory BultCat, string familyTypeName) { return(new FilteredElementCollector(doc) .OfCategory(BultCat) .OfClass(typeof(FamilyInstance)) .WherePasses( new ElementParameterFilter( ParameterFilterRuleFactory.CreateEqualsRule( new ElementId(BuiltInParameter.ELEM_FAMILY_PARAM), familyTypeName, true)))); }
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)); }
public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements) { Tracer.Listeners.Add(new System.Diagnostics.EventLogTraceListener("Application")); UIDocument uidoc = commandData.Application.ActiveUIDocument; Document doc = uidoc.Document; try { IList <FamilyInstance> openings = new FilteredElementCollector(doc, doc.ActiveView.Id) .OfCategory(BuiltInCategory.OST_Windows) .WherePasses(new ElementParameterFilter (ParameterFilterRuleFactory.CreateEqualsRule (new ElementId(BuiltInParameter.ALL_MODEL_FAMILY_NAME), SO_FAMILY_NAME, false))) .WhereElementIsNotElementType() .Cast <FamilyInstance>() .ToList(); if (openings.Count == 0) { throw new Exception("No opening has been unearthed. Toodle-pip."); } using (Transaction t = new Transaction(doc, "Mark Openings")) { t.Start(); foreach (FamilyInstance fi in openings) { if (fi.LookupParameter(SO_BTM_ELEV) == null) { throw new Exception(string.Format("{0} is null", nameof(SO_BTM_ELEV))); } double elev = ((Level)doc.GetElement(fi.LevelId)).Elevation + fi.get_Parameter (BuiltInParameter.INSTANCE_SILL_HEIGHT_PARAM).AsDouble(); fi.LookupParameter(SO_BTM_ELEV) .Set(elev); } t.Commit(); } return(Result.Succeeded); } catch (Autodesk.Revit.Exceptions.OperationCanceledException) { return(Result.Cancelled); } catch (Exception ex) { Tracer.Write(string.Format("{0}\n{1}", ex.Message, ex.StackTrace)); return(Result.Failed); } }
/// <summary> /// Получение элементов ключевой спецификации по её имени /// </summary> public static Element ViewKeyElement(string nameTabl) { FilterRule rule = ParameterFilterRuleFactory.CreateEqualsRule(new ElementId(BuiltInParameter.VIEW_NAME), nameTabl, false); var filter = new ElementParameterFilter(rule); FilteredElementCollector keysp = new FilteredElementCollector(_doc); keysp.OfClass(typeof(ViewSchedule)).WherePasses(filter); if (keysp.Count() != 1) { return(null); } //var sd = filter.PassesFilter(keysp.FirstElement()); return(keysp.FirstElement()); }
// Создание фильтров IdentityDataAnalysis_Visibility и IdentityDataAnalysis_AnVisibility, // назначение им правил private void CreateFilters(UIDocument uiDoc, Parameter parameter, List <Element> elements) { IList <FilterRule> visibilityFilterRules = new List <FilterRule>(); visibilityFilterRules.Add(ParameterFilterRuleFactory.CreateEqualsRule(parameter.Id, "", true)); ElementParameterFilter visibilityFilter = new ElementParameterFilter(visibilityFilterRules); IList <FilterRule> anVisibilityFilterRules = new List <FilterRule>(); anVisibilityFilterRules.Add(ParameterFilterRuleFactory.CreateNotEqualsRule(parameter.Id, "", true)); ElementParameterFilter anVisibilityFilter = new ElementParameterFilter(anVisibilityFilterRules); List <ElementId> categorysIds = GetUniquCategorysIds(elements); ParameterFilterElement filterForVisibility = CreateFilterElement(uiDoc.Document, "IdentityDataAnalysis_Visibility", categorysIds, visibilityFilter); ParameterFilterElement filterForAnVisibility = CreateFilterElement(uiDoc.Document, "IdentityDataAnalysis_AnVisibility", categorysIds, anVisibilityFilter); }
private static FilterRule CreateRule(ElementId ParameterId, string Function, string Value) { switch (Function) { case "Равно": return(ParameterFilterRuleFactory.CreateEqualsRule(ParameterId, Value, true)); case "Не равно": return(ParameterFilterRuleFactory.CreateNotEqualsRule(ParameterId, Value, true)); case "Больше": return(ParameterFilterRuleFactory.CreateGreaterRule(ParameterId, Value, true)); case "Больше или равно": return(ParameterFilterRuleFactory.CreateLessOrEqualRule(ParameterId, Value, true)); case "Меньше": return(ParameterFilterRuleFactory.CreateLessRule(ParameterId, Value, true)); case "Меньше или равно": return(ParameterFilterRuleFactory.CreateLessOrEqualRule(ParameterId, Value, true)); case "Содержит": return(ParameterFilterRuleFactory.CreateContainsRule(ParameterId, Value, true)); case "Не содержит": return(ParameterFilterRuleFactory.CreateNotContainsRule(ParameterId, Value, true)); case "Начинается с": return(ParameterFilterRuleFactory.CreateBeginsWithRule(ParameterId, Value, true)); case "Не начинается с": return(ParameterFilterRuleFactory.CreateNotBeginsWithRule(ParameterId, Value, true)); case "Заканчивается на": return(ParameterFilterRuleFactory.CreateEndsWithRule(ParameterId, Value, true)); case "Не заканчивается на": return(ParameterFilterRuleFactory.CreateNotEndsWithRule(ParameterId, Value, true)); case "Поддерживает": return(ParameterFilterRuleFactory.CreateSharedParameterApplicableRule(Value)); default: return(null); } }
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 { } }
/// <summary> /// Find all instances matching category and "Reference Level", and add to the collection of groups of sorted ids. /// </summary> /// <param name="idGroupsInOrder">The collection of groups of ids, sorted.</param> /// <param name="level">The level to match.</param> /// <param name="category">The category to match.</param> private static void AddInstancesOnReferenceLevelToIdGroupList(List <ICollection <ElementId> > idGroupsInOrder, Level level, BuiltInCategory category) { FilteredElementCollector collector = new FilteredElementCollector(level.Document); collector.OfCategory(category); collector.WhereElementIsNotElementType(); // Use a parameter filter to match the Reference Level parameter FilterRule rule = ParameterFilterRuleFactory.CreateEqualsRule(new ElementId(BuiltInParameter.INSTANCE_REFERENCE_LEVEL_PARAM), level.Id); collector.WherePasses(new ElementParameterFilter(rule)); ICollection <ElementId> idGroup = collector.ToElementIds(); // Only add non-empty groups if (idGroup.Count > 0) { idGroupsInOrder.Add(idGroup); } }
public static Autodesk.Revit.DB.FilterRule GetElementIdRule(ElementId paramId, CriteriaName selectedCriteria, ElementId ruleValue) { Autodesk.Revit.DB.FilterRule rule = null; try { switch (selectedCriteria) { case CriteriaName.equals: rule = ParameterFilterRuleFactory.CreateEqualsRule(paramId, ruleValue); break; case CriteriaName.isgreaterthan: rule = ParameterFilterRuleFactory.CreateGreaterRule(paramId, ruleValue); break; case CriteriaName.isgreaterthanorequalto: rule = ParameterFilterRuleFactory.CreateGreaterOrEqualRule(paramId, ruleValue); break; case CriteriaName.islessthan: rule = ParameterFilterRuleFactory.CreateLessRule(paramId, ruleValue); break; case CriteriaName.islessthanorequalto: rule = ParameterFilterRuleFactory.CreateLessOrEqualRule(paramId, ruleValue); break; case CriteriaName.doesnotequal: rule = ParameterFilterRuleFactory.CreateNotEqualsRule(paramId, ruleValue); break; } } catch (Exception ex) { System.Windows.MessageBox.Show("Failed to get integer filter rule.\n" + ex.Message, "Get Integer Filter Rule", MessageBoxButton.OK, MessageBoxImage.Warning); } return(rule); }
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); }
public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements) { Document doc = commandData.Application.ActiveUIDocument.Document; // Door variables. string doorName = string.Empty; string itemType = string.Empty; string doorType = string.Empty; int height = 0; int width = 0; string props = string.Empty; // Find the right door family. FilteredElementCollector collector = new FilteredElementCollector(doc); FilterRule famNameRule = ParameterFilterRuleFactory .CreateBeginsWithRule( new ElementId((int)BuiltInParameter.ALL_MODEL_FAMILY_NAME), "A-M3-ConceptualDoor", true); FilterRule typeNameRule = ParameterFilterRuleFactory .CreateEqualsRule( new ElementId((int)BuiltInParameter.ALL_MODEL_TYPE_NAME), "Default", true); ElementParameterFilter famNameFlt = new ElementParameterFilter(famNameRule); ElementParameterFilter typeNameFlt = new ElementParameterFilter(typeNameRule); LogicalAndFilter andFilter = new LogicalAndFilter(famNameFlt, typeNameFlt); Func <FamilySymbol, bool> singleLeaf = (fs) => fs.FamilyName == "A-M3-ConceptualDoorSingleLeaf-LOD2"; Func <FamilySymbol, bool> doubleLeaf = (fs) => fs.FamilyName == "A-M3-ConceptualDoorDoubleLeaf-LOD2"; IEnumerable <FamilySymbol> doors = collector .OfCategory(BuiltInCategory.OST_Doors) .WhereElementIsElementType() .WherePasses(andFilter) .Cast <FamilySymbol>(); FamilySymbol singleLeafDoor = doors .Where(singleLeaf) .FirstOrDefault(); FamilySymbol doubleLeafDoor = doors .Where(doubleLeaf) .FirstOrDefault(); if (singleLeafDoor == null) { TaskDialog.Show("No door family", "Please load the family: A-M3-ConceptualDoorSingleLeaf-LOD2"); return(Result.Failed); } // Show the custom window RussianDoorWnd win = new RussianDoorWnd(); win.btnCreate.Click += delegate(object sender, RoutedEventArgs e) { doorName = win.lbg6629.Content.ToString(); itemType = ((ComboBoxItem)win.itemType.SelectedItem).Content.ToString(); doorType = ((ComboBoxItem)win.doorType.SelectedItem).Content.ToString(); height = Int16.Parse((string)((ComboBoxItem)win.height.SelectedItem).Content) * 100; width = Int16.Parse((string)((ComboBoxItem)win.width.SelectedItem).Content) * 100; props = ((ComboBoxItem)win.props.SelectedItem).Content.ToString(); win.Close(); try { using (TransactionGroup tg = new TransactionGroup(doc, "Create new type")) { ElementType newType; tg.Start(); using (Transaction t1 = new Transaction(doc, "Create new type")) { t1.Start(); if (width <= 1200) { newType = singleLeafDoor.Duplicate(doorName); } else { newType = doubleLeafDoor.Duplicate(doorName); } t1.Commit(); } using (Transaction t2 = new Transaction(doc, "Set params")) { t2.Start(); switch (doorType) { case "Г": newType.LookupParameter("Solid Leaf").Set(1); newType.LookupParameter("Glazed Leaf").Set(0); newType.LookupParameter("Leaf with Vent Grille").Set(0); break; case "О": newType.LookupParameter("Solid Leaf").Set(0); newType.LookupParameter("Glazed Leaf").Set(1); newType.LookupParameter("Leaf with Vent Grille").Set(0); break; } newType.LookupParameter("Door Leaf Height") .Set(RvtCnvt.ConvertToInternalUnits((height - 100), DisplayUnitType.DUT_MILLIMETERS)); newType.LookupParameter("Door Leaf Width") .Set(RvtCnvt.ConvertToInternalUnits((width - 100), DisplayUnitType.DUT_MILLIMETERS)); if (props.Contains('Л')) { newType.LookupParameter("RH").Set(0); } else { newType.LookupParameter("RH").Set(1); } if (props.Contains('П')) { newType.LookupParameter("Threshold").Set(1); } else { newType.LookupParameter("Threshold").Set(0); } t2.Commit(); } tg.Assimilate(); } } catch (Autodesk.Revit.Exceptions.ArgumentException ex) { if (ex.ParamName == "name") { TaskDialog.Show("ArgumentError", string.Format("This type already exists.")); } } catch (Exception ex) { TaskDialog.Show("Exception", ex.StackTrace); } }; win.ShowDialog(); return(Result.Succeeded); }
public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements) { UIApplication uiapp = commandData.Application; //Set the Class variable to the Executing Document doc = uiapp.ActiveUIDocument.Document; //Wrap the main functions in a Try block to catch Exceptions and help prevent Revit from crashing try { //initialize a new SortedList to hold all Revit Links SortedList <string, Document> links = new SortedList <string, Document>(); //Filtered Element Collector to get all Revit Link Types in the Document using (FilteredElementCollector rvtLinks = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_RvtLinks).OfClass(typeof(RevitLinkType))) { //Check to make sure there is at least one link if (rvtLinks.ToElements().Count > 0) { //Loop Each Revit Link Type foreach (RevitLinkType rvtLink in rvtLinks.ToElements()) { //Check to see if the Link is currently Loaded if (rvtLink.GetLinkedFileStatus() == LinkedFileStatus.Loaded) { //Create a Filter Rule and Elemenet Parameter Filter for the Revit Link Instance Collector to Match the Type FilterRule rule = ParameterFilterRuleFactory.CreateEqualsRule(new ElementId(BuiltInParameter.SYMBOL_ID_PARAM), rvtLink.get_Parameter(BuiltInParameter.ID_PARAM).AsElementId()); ElementParameterFilter filter = new ElementParameterFilter(rule); //In order to get the Document, we have to get the first or default Revit Link Instance that is of the Revit Link Type RevitLinkInstance link = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_RvtLinks).OfClass(typeof(RevitLinkInstance)).WherePasses(filter).First() as RevitLinkInstance; //Add the Link Name and Link Document to the SortedList links.Add(rvtLink.Name, link.GetLinkDocument()); } } } //Aler the user that the current Document doesn't have any links else { TaskDialog.Show("No Revit Links", "No Links are Loaded in the current Model"); //Stops the Method and returns a Cancelled result return(Result.Cancelled); } } //Create a new Transaction within a using group to make any updates if needed using (Transaction t = new Transaction(doc)) { //Start the Transaction and give it a Name for the Undo / Redo Menu t.Start("Update Linked View"); //Loop through All viewports in the current document foreach (Viewport vp in Helpers.Collectors.ByCategoryNotElementType(doc, BuiltInCategory.OST_Viewports)) { //Get the View from the Viewport using the ViewId property if (doc.GetElement(vp.ViewId) is View view) { //Filter to only Drafting View types which are what the LinkedViews Method creates if (view.ViewType == ViewType.DraftingView) { //Check to see if the Linked View Yes/No Parameter exists get it if (view.LookupParameter("Linked View") is Parameter lView) { //Check to see if the Linked View parameter Yes/No parameter is Checked Yes if (lView.AsInteger() == 1) { //Check if the Linked View GUID and Link Name parameters exists and get them as variables if (view.LookupParameter("Linked View GUID") is Parameter lGUID && view.LookupParameter("Link Name") is Parameter lName) { //Create a Document variable to hold the Link Document from the SortedList Document linkDoc = null; //Check to see if the Link Name exists in the SortedList and get the Document out if so if (links.TryGetValue(lName.AsString(), out linkDoc)) { //Use the Viewport to get the Sheet from the SheetId property ViewSheet vs = (ViewSheet)doc.GetElement(vp.SheetId); //Find the Viewport in the Linked Model using GUID and get the Viewport element if (linkDoc.GetElement(lGUID.AsString()) is Viewport linkVP) { //Get Detail number and Sheet Numbers from the Linked Viewport string linkDetail = linkVP.get_Parameter(BuiltInParameter.VIEWPORT_DETAIL_NUMBER).AsString(); string linkSheet = linkVP.get_Parameter(BuiltInParameter.VIEWPORT_SHEET_NUMBER).AsString(); //Get the Linked View name string linkViewName = linkDoc.GetElement(linkVP.ViewId).Name; //Get the Viewport Number and Viewport Number Paramter from the current Viewport string viewDetail = vp.get_Parameter(BuiltInParameter.VIEWPORT_DETAIL_NUMBER).AsString(); Parameter vpDetail = vp.get_Parameter(BuiltInParameter.VIEWPORT_DETAIL_NUMBER); //Get the Minimum (lower left) point of the Viewport Label (Title) of the Current Viewport XYZ labelMin = linkVP.GetLabelOutline().MinimumPoint; //Check to see if the View Name has changed and update it if needed if (view.Name != linkViewName) { view.Name = linkViewName; } //Check to see if the Viewport is still on the corret Sheet Number if (vs.SheetNumber == linkSheet) { if (vpDetail.AsString() != linkDetail) { vpDetail.Set(linkDetail); } //Get the location of the Viewport and Viewport Label to update Viewort Location if (vp.GetBoxCenter() != linkVP.GetBoxCenter()) { //Move the Viewport to the Label Minimum Point vp.SetBoxCenter(labelMin); //Move the viewport a relative amount from the Viewport Label to the Minimum point of the Viewport ElementTransformUtils.MoveElement(doc, vp.Id, labelMin - vp.GetLabelOutline().MinimumPoint); } } //If the Linked Viewport Sheet Number is different else { try { //Remove the Viewport from the sheet it is on vs.DeleteViewport(vp); //Move the viewport to the new sheet number Viewport newVP = Viewport.Create(doc, CheckSheet(linkSheet, vs).Id, view.Id, labelMin); //Move it to the correct location based on the Linked View location ElementTransformUtils.MoveElement(doc, vp.Id, labelMin - vp.GetLabelOutline().MinimumPoint); //Set the Viewport Detail Number to match the Linked Viewport newVP.get_Parameter(BuiltInParameter.VIEWPORT_DETAIL_NUMBER).Set(linkDetail); } catch { //If there is an exception, just keep moving continue; } } } //If the View cannot be found in the link, the User is asked if they want to delete the view from the project. If they Keep it, the viewport will be removed from the Sheet else { if (TaskDialog.Show("View Not Found", "Linked View '" + view.Name + "' could not be found." + Environment.NewLine + "Would you like to delete the View?", TaskDialogCommonButtons.Yes | TaskDialogCommonButtons.No, TaskDialogResult.Yes) == TaskDialogResult.Yes) { //Delete the View from the project doc.Delete(view.Id); } else { //Remove the Viewport from the Sheet vs.DeleteViewport(vp); } } } //Alert the User that the Link Name doesn't match any current Links in the Proeject else { TaskDialog.Show("Missing Revit Link", "Link '" + lName.AsString() + "' could not be found."); } } } } //ALert the user if the Linked View Yes/No parameter is missing from the project else { TaskDialog.Show("Missing Parameters", "Linked View parameters are missing from this Document."); //Method cannot continue if the parameters are missing so return a Failed result return(Result.Failed); } } } } //Commit the Transaction to Keep any Changes t.Commit(); //Return a Succeeded Result to keep the changes return(Result.Succeeded); } } //Catch any Exceptions encountered and provide the user with the Details catch (Exception ex) { TaskDialog.Show("Error", ex.ToString()); //Method cannot continue so return a Failed result return(Result.Failed); } }
public static FilterRule CreateRule(MyParameter mp, CriteriaType ctype) { Parameter param = mp.RevitParameter; FilterRule rule = null; if (ctype == CriteriaType.Equals) { switch (param.StorageType) { case StorageType.None: break; case StorageType.Integer: rule = ParameterFilterRuleFactory.CreateEqualsRule(param.Id, mp.AsInteger()); break; case StorageType.Double: rule = ParameterFilterRuleFactory.CreateEqualsRule(param.Id, mp.AsDouble(), 0.0001); break; case StorageType.String: string val = mp.AsString(); if (val == null) { break; } rule = ParameterFilterRuleFactory.CreateEqualsRule(param.Id, val, true); break; case StorageType.ElementId: rule = ParameterFilterRuleFactory.CreateEqualsRule(param.Id, mp.AsElementId()); break; default: break; } } if (ctype == CriteriaType.StartsWith) { switch (param.StorageType) { case StorageType.None: break; case StorageType.String: string val = mp.AsString(); if (val == null) { break; } rule = ParameterFilterRuleFactory.CreateBeginsWithRule(param.Id, val, true); break; default: break; } } if (rule == null) { throw new Exception("Не удалось создать правило фильтра"); } return(rule); }
private void Application_DocumentOpened(object sender, Autodesk.Revit.DB.Events.DocumentOpenedEventArgs e) { Application app = sender as Application; UIApplication uiApp = new UIApplication(app); Document doc = uiApp.ActiveUIDocument.Document; Utilits.Doc = doc; //app.DocumentChanged += new EventHandler<DocumentChangedEventArgs>(OnDocumentChanged); //Создание словаря MapConnectorsToCircuits dicConnCirc = new MapConnectorsToCircuits(); //Develop.dicConnectCirc = dicConnCirc; //Перебор всех коннекторов для заполнения коннекторов //ElementId idConnect = ElementId.InvalidElementId; //string idCircuits = ""; List <ElementId> circuitsId = new List <ElementId>(); FilteredElementCollector filtConnectors = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_TelephoneDevices).WhereElementIsNotElementType(); foreach (var el in filtConnectors) { string strIdCirc = el.LookupParameter("ID_Circuits").AsString(); //Проверка если в коннекторе нет цепей if (strIdCirc != null) { string[] spl = strIdCirc.Split('?'); for (int i = 0; i < spl.Length; i++) { string strid = spl[i]; if (Int32.TryParse(strid, out int intId)) { ElementId idCirc = new ElementId(Int32.Parse(strid)); dicConnCirc.Add(el.Id, idCirc); circuitsId.Add(idCirc); } } } } Develop.dicConnectCirc = dicConnCirc; CircUpdater updater = new CircUpdater(uiApp.ActiveAddInId); Develop.updater = updater; //Регистрация апдатера if (!UpdaterRegistry.IsUpdaterRegistered(updater.GetUpdaterId())) { UpdaterRegistry.RegisterUpdater(updater); } if (circuitsId.Count != 0) { //Добавление триггера на электрические цепи Element elem = doc.GetElement(circuitsId.First()); Parameter parNumber = elem.get_Parameter(BuiltInParameter.RBS_ELEC_CIRCUIT_NUMBER); //Parameter parIdConn = elem.GetParameters("IdConnectors").First(); UpdaterRegistry.AddTrigger(updater.GetUpdaterId(), doc, circuitsId, Element.GetChangeTypeParameter(parNumber)); //UpdaterRegistry.AddTrigger(updater.GetUpdaterId(), doc, circuitsId, Element.GetChangeTypeParameter(parIdConn)); UpdaterRegistry.AddTrigger(updater.GetUpdaterId(), doc, circuitsId, Element.GetChangeTypeElementDeletion()); updater.dic = dicConnCirc; } if (filtConnectors.Count() != 0) { //добавление триггера на коннекторы //ElementCategoryFilter filt = new ElementCategoryFilter(BuiltInCategory.OST_TelephoneDevices); IList <FilterRule> ruls = new List <FilterRule>(); FilterRule rule = ParameterFilterRuleFactory.CreateEqualsRule(new ElementId(BuiltInParameter.ELEM_FAMILY_PARAM), "Эмуляция потребителя без нагрузки", false); ruls.Add(rule); rule = ParameterFilterRuleFactory.CreateEqualsRule(new ElementId(BuiltInCategory.OST_TelephoneDevices), (int)BuiltInCategory.OST_TelephoneDevices); ruls.Add(rule); ElementParameterFilter filter = new ElementParameterFilter(ruls); //FilteredElementCollector collector = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_TelephoneDevices).WherePasses(filter); //var fs = new FilteredElementCollector(doc).WhereElementIsNotElementType().Where(x => x.Name == "Bunch"); UpdaterRegistry.AddTrigger(updater.GetUpdaterId(), doc, filter, Element.GetChangeTypeElementDeletion()); } }
public static Autodesk.Revit.DB.FilterRule GetStringRule(ElementId paramId, CriteriaName selectedCriteria, string ruleValue) { Autodesk.Revit.DB.FilterRule rule = null; try { switch (selectedCriteria) { case CriteriaName.beginswith: rule = ParameterFilterRuleFactory.CreateBeginsWithRule(paramId, ruleValue, false); break; case CriteriaName.contains: rule = ParameterFilterRuleFactory.CreateContainsRule(paramId, ruleValue, false); break; case CriteriaName.endswith: rule = ParameterFilterRuleFactory.CreateEndsWithRule(paramId, ruleValue, false); break; case CriteriaName.equals: rule = ParameterFilterRuleFactory.CreateEqualsRule(paramId, ruleValue, false); break; case CriteriaName.isgreaterthan: rule = ParameterFilterRuleFactory.CreateGreaterRule(paramId, ruleValue, false); break; case CriteriaName.isgreaterthanorequalto: rule = ParameterFilterRuleFactory.CreateGreaterOrEqualRule(paramId, ruleValue, false); break; case CriteriaName.islessthan: rule = ParameterFilterRuleFactory.CreateLessRule(paramId, ruleValue, false); break; case CriteriaName.islessthanorequalto: rule = ParameterFilterRuleFactory.CreateLessOrEqualRule(paramId, ruleValue, false); break; case CriteriaName.doesnotbeginwith: rule = ParameterFilterRuleFactory.CreateNotBeginsWithRule(paramId, ruleValue, false); break; case CriteriaName.doesnotcontain: rule = ParameterFilterRuleFactory.CreateNotContainsRule(paramId, ruleValue, false); break; case CriteriaName.doesnotendwith: rule = ParameterFilterRuleFactory.CreateNotEndsWithRule(paramId, ruleValue, false); break; case CriteriaName.doesnotequal: rule = ParameterFilterRuleFactory.CreateNotEqualsRule(paramId, ruleValue, false); break; } } catch (Exception ex) { System.Windows.MessageBox.Show("Failed to get string filter rule.\n" + ex.Message, "Get String Filter Rule", MessageBoxButton.OK, MessageBoxImage.Warning); } return(rule); }
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); }
public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements) { const string TAG_FAMILY_NAME = "Z-M2-MultilayerMaterialTag-LOD1"; const string TAG_TYPE_NAME = "2.5mm"; #region Get access to the current document and aplication. UIApplication uiapp = commandData.Application; UIDocument uidoc = commandData.Application.ActiveUIDocument; Autodesk.Revit.ApplicationServices.Application app = commandData.Application.Application; Autodesk.Revit.DB.Document doc = commandData.Application.ActiveUIDocument.Document; #endregion try { Category walls = doc.Settings.Categories.get_Item(BuiltInCategory.OST_Walls); Category floors = doc.Settings.Categories.get_Item(BuiltInCategory.OST_Floors); Category ceilings = doc.Settings.Categories.get_Item(BuiltInCategory.OST_Ceilings); Category roofs = doc.Settings.Categories.get_Item(BuiltInCategory.OST_Roofs); CategorySet catSet = new CategorySet(); catSet.Insert(walls); catSet.Insert(floors); catSet.Insert(ceilings); catSet.Insert(roofs); using (Transaction t = new Transaction(doc, "Add project parameter")) { t.Start(); CreateProjectParam(app, "LinkedTag", ParameterType.Integer, false, catSet, BuiltInParameterGroup.INVALID, true); if (t.Commit() == TransactionStatus.Committed) { } else { t.RollBack(); } } } catch (Exception ex) { TaskDialog.Show("Error", ex.Message); } if (Schema.Lookup(new Guid("2B195204-1C04-4538-8881-AD22FA697B41")) == null) { BuildNewSchema(doc); } // Retrieving a specific family from the database. try { ElementParameterFilter famNameFlt = new ElementParameterFilter(ParameterFilterRuleFactory .CreateEqualsRule(new ElementId(BuiltInParameter.ALL_MODEL_FAMILY_NAME), TAG_FAMILY_NAME, false)); ElementParameterFilter typeNameFlt = new ElementParameterFilter(ParameterFilterRuleFactory .CreateEqualsRule(new ElementId(BuiltInParameter.ALL_MODEL_TYPE_NAME), TAG_TYPE_NAME, false)); // Collect the familySymbol's id AnnotationSymbolType materialTag = new FilteredElementCollector(doc) .OfCategory(BuiltInCategory.OST_GenericAnnotation) .WherePasses(famNameFlt) .WherePasses(typeNameFlt) .Cast <AnnotationSymbolType>() .FirstOrDefault(); if (materialTag == null) { message = "No FamilyType has been detected."; return(Result.Failed); } if (CreateWorkPlane(doc) != true) { return(Result.Failed); } // Prompt the user to select select the element to be tagged. Reference pickedRef = null; pickedRef = uidoc.Selection.PickObject (ObjectType.Element, new MultilayerStrFilter(), "Please select a multilayer element."); Element selectedElm = doc.GetElement(pickedRef.ElementId); XYZ point = uidoc.Selection.PickPoint("Please pick a point to place the family"); StringBuilder strBld = new StringBuilder(); int rows; int shelfLength; switch (selectedElm.Category.Name) { case "Walls": Wall wl = selectedElm as Wall; WallType wlType = wl.WallType; CompoundStructure cmpStr_wl = wlType.GetCompoundStructure(); strBld = LayersAsString(cmpStr_wl, doc, out shelfLength); rows = wlType.GetCompoundStructure().LayerCount; break; case "Floors": Floor fl = selectedElm as Floor; FloorType flType = fl.FloorType; CompoundStructure cmpStr_fl = flType.GetCompoundStructure(); strBld = LayersAsString(cmpStr_fl, doc, out shelfLength); rows = flType.GetCompoundStructure().LayerCount; break; case "Ceilings": Ceiling cl = selectedElm as Ceiling; CeilingType clType = doc.GetElement(cl.GetTypeId()) as CeilingType; CompoundStructure cmpStr_cl = clType.GetCompoundStructure(); strBld = LayersAsString(cmpStr_cl, doc, out shelfLength); rows = clType.GetCompoundStructure().LayerCount; break; case "Roofs": RoofBase rf = selectedElm as RoofBase; RoofType rfType = rf.RoofType; CompoundStructure cmpStr_rf = rfType.GetCompoundStructure(); strBld = LayersAsString(cmpStr_rf, doc, out shelfLength); rows = rfType.GetCompoundStructure().LayerCount; break; default: TaskDialog.Show("Warning!", "This category is not supported."); return(Result.Failed); } using (Transaction trn_1 = new Transaction(doc, "Materials Mark")) { FamilyInstance createdElm = null; if (trn_1.Start() == TransactionStatus.Started) { createdElm = doc.Create.NewFamilyInstance(point, materialTag, doc.ActiveView); selectedElm.LookupParameter("LinkedTag").Set(createdElm.Id.IntegerValue); if (trn_1.Commit() == TransactionStatus.Committed) { Transaction trn_2 = new Transaction(doc, "Set parameters"); try { trn_2.Start(); createdElm.LookupParameter("multilineText").Set(strBld.ToString()); createdElm.LookupParameter("# of Rows").Set(rows); createdElm.LookupParameter("Shelf Length").Set(ToFt(shelfLength)); XYZ vec; if (selectedElm.Category.Name != "Walls") { vec = new XYZ(0, 0, createdElm.LookupParameter("Arrow Length").AsDouble() * doc.ActiveView.Scale); createdElm.LookupParameter("Down Arrow Direction").Set(1); } else { vec = new XYZ(-createdElm.LookupParameter("Arrow Length").AsDouble() * doc.ActiveView.Scale, 0, 0); createdElm.LookupParameter("Down Arrow Direction").Set(0); } ElementTransformUtils.MoveElement(doc, createdElm.Id, vec); trn_2.Commit(); AddElementToSchema(Schema.Lookup(new Guid("2B195204-1C04-4538-8881-AD22FA697B41")), createdElm, selectedElm.Id); } finally { if (trn_2 != null) { trn_2.Dispose(); } } } else { trn_1.RollBack(); return(Result.Failed); } } else { trn_1.RollBack(); return(Result.Failed); } return(Result.Succeeded); } } catch (Exception ex) { message = ex.Message; return(Result.Failed); } }