//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); } }
/// <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> /// Возвращает список всех чистых помещений /// </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); }
/// <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); }
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 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); }
/// <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]); }
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 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)); }
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); }
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); } }
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); }
/// <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); }
/// <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!"); } }
//This method will check to see if there are any Schedules in the specified document with the same name internal static bool CheckSchedule(Document _doc, string _name) { ParameterValueProvider pvp = new ParameterValueProvider(new ElementId(BuiltInParameter.VIEW_NAME)); FilterStringRuleEvaluator fsr = new FilterStringEquals(); FilterRule fRule = new FilterStringRule(pvp, fsr, _name, true); ElementParameterFilter filter = new ElementParameterFilter(fRule); if (new FilteredElementCollector(_doc).OfCategory(BuiltInCategory.OST_Schedules).WherePasses(filter).FirstOrDefault() is ViewSchedule vs) { return(false); } else { return(true); } }
//Checks to see if a viewport with a specific detail number already exists private bool CheckViewport(string _detailNumber, ViewSheet _vs) { ParameterValueProvider pvp = new ParameterValueProvider(new ElementId(BuiltInParameter.VIEWPORT_DETAIL_NUMBER)); FilterStringRuleEvaluator fsr = new FilterStringEquals(); FilterRule fRule = new FilterStringRule(pvp, fsr, _detailNumber, true); ElementParameterFilter filter = new ElementParameterFilter(fRule); if (new FilteredElementCollector(doc, _vs.Id).OfCategory(BuiltInCategory.OST_Viewports).WherePasses(filter).FirstOrDefault() is Viewport vp) { return(false); } else { return(true); } }
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; } }
private IList <Element> GetElementValueIntOrstring(RevitParameter valRevitParameter, List <ElementId> valCategoryElementId, string valValue) { IList <Element> vResult = new List <Element>(); IList <Element> vResultTemp = new List <Element>(); foreach (var vCategoryId in valCategoryElementId) { IList <ElementFilter> vList = new List <ElementFilter>(); BuiltInCategory vBuiltInCategory = (BuiltInCategory)vCategoryId.IntegerValue; ParameterValueProvider vPovider = new ParameterValueProvider(valRevitParameter.ElementId); string vRulestring = valValue; FilterStringRuleEvaluator vEvaluator = new FilterStringEquals(); FilteredElementCollector vCollector = new FilteredElementCollector(_Doc); vCollector.OfCategory(vBuiltInCategory); FilterRule vRuleRulestring = new FilterStringRule(vPovider, vEvaluator, vRulestring, false); ElementParameterFilter vFilterRulestring = new ElementParameterFilter(vRuleRulestring); LibNumeric insLibNumeric = new LibNumeric(); if (insLibNumeric.IsInt(valValue)) { int vNum = 0; int.TryParse(valValue, out vNum); FilterNumericEquals vEvaluatorNumeri = new FilterNumericEquals(); int vRuleIntVal = vNum; var vFilterIntRule = new FilterIntegerRule(vPovider, vEvaluatorNumeri, vRuleIntVal); var vElementParameterFilterIntRule = new ElementParameterFilter(vFilterIntRule); vList.Add(vElementParameterFilterIntRule); } vList.Add(vFilterRulestring); LogicalOrFilter vLogicalOrFilter = new LogicalOrFilter(vList); vCollector.WherePasses(vLogicalOrFilter); IList <Element> vElements = vCollector.ToElements(); if (vElements != null) { if (vElements.Count > 0) { foreach (var vElement in vElements) { vResult.Add(vElement); } } } } return(vResult); }
/// <summary> /// Collects all available Arrowhead Styles in the project. /// </summary> private void CollectArrowheads() { try { var eId = new ElementId(BuiltInParameter.ALL_MODEL_FAMILY_NAME); var provider = new ParameterValueProvider(eId); FilterStringRuleEvaluator evaluator = new FilterStringEquals(); FilterRule rule = new FilterStringRule(provider, evaluator, "Arrowhead", false); var filter = new ElementParameterFilter(rule); var leaders = new FilteredElementCollector(m_doc) .OfClass(typeof(ElementType)) .WherePasses(filter) .ToElements(); foreach (var element in leaders) { if (string.IsNullOrEmpty(element.Name)) { continue; } var arrowhead = new Arrowhead(element); arrowheadList.Add(arrowhead); } var sortedlist = from arrow in arrowheadList orderby arrow.ArrowName select arrow; arrowheadList = sortedlist.ToList(); comboBoxArrow.ItemsSource = arrowheadList; comboBoxArrow.DisplayMemberPath = "ArrowName"; comboBoxArrow.SelectedValuePath = "ArrowElementId"; if (arrowheadList.Count > 0) { comboBoxArrow.SelectedIndex = 0; } } catch (Exception ex) { Log.AppendLog(LogMessageType.EXCEPTION, ex.Message); } }
/// <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()); }
public void RoomRenumbering() { UIDocument uidoc = ActiveUIDocument; Document doc = uidoc.Document; try { int roomNumber = 1; while (true) { Reference selRef = uidoc.Selection.PickObject(ObjectType.Element, new mySelectionFilter(), "Select a room"); Room room = (Room)doc.GetElement(selRef.ElementId); FilteredElementCollector collector = new FilteredElementCollector(doc); collector.OfClass(typeof(SpatialElement)); collector.WherePasses(new RoomFilter()); ParameterValueProvider provider = new ParameterValueProvider(new ElementId(BuiltInParameter.ROOM_NUMBER)); FilterStringEquals evaluator = new FilterStringEquals(); FilterStringRule rule = new FilterStringRule(provider, evaluator, roomNumber.ToString(), false); ElementParameterFilter filter = new ElementParameterFilter(rule); collector.WherePasses(filter); IList <Element> rooms = collector.ToElements(); using (Transaction t = new Transaction(doc, "Modify room number")) { t.Start(); if (rooms.Count > 0) { ((Room)rooms[0]).Number = room.Number; } room.Number = roomNumber.ToString(); doc.Regenerate(); t.Commit(); } roomNumber++; } } catch (Autodesk.Revit.Exceptions.OperationCanceledException) { } }
//Check to see if Sheet exists using the unique Sheet Number private ViewSheet CheckSheet(string _sheetNumber, ViewSheet _vs) { try { //Create an Empty ViewSheet object to return if sheet is found ViewSheet sheet = null; //Use Parameter Value Provider, Filter Rules, and Element Filters to narrow the results of the Element Collector in the most efficient way ParameterValueProvider pvp = new ParameterValueProvider(new ElementId(BuiltInParameter.SHEET_NUMBER)); FilterStringRuleEvaluator fsr = new FilterStringEquals(); //Check that the PVP (Sheet Number) is equal to the Sheet Number passed to the Method FilterRule fRule = new FilterStringRule(pvp, fsr, _sheetNumber, true); //This is the total Filter to use on the Collector ElementParameterFilter filter = new ElementParameterFilter(fRule); //Use an Elemeent Collector to get the sheet with the Sheet Number passed to the Method if (new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Sheets).WherePasses(filter).FirstOrDefault() is ViewSheet vs) { //Return the ViewSheet Obeject if there is one that matches in the current document sheet = vs; } //If there is not a Sheet with the Sheet Number passed, create one else { //Get the Titleblock Type from the sheet it was on and use for the new Sheet FamilyInstance tb = new FilteredElementCollector(doc, _vs.Id).OfClass(typeof(FamilyInstance)).OfCategory(BuiltInCategory.OST_TitleBlocks).FirstOrDefault() as FamilyInstance; //Create a new Sheet with the Titleblock sheet = ViewSheet.Create(doc, tb.Symbol.Id); //Set the Sheet Name, Number, and Appears In Sheet List parameters sheet.Name = "DO NOT PRINT"; sheet.SheetNumber = _sheetNumber; sheet.LookupParameter("Appears In Sheet List").Set(0); } //Return either the existing Sheet or the New Sheet return(sheet); } catch { //Return a null sheet if there is an error return(null); } }
//This Method will return the ViewSheet by Sheet Number if it exists private ViewSheet CheckSheet(string _sheetNumber) { try { //Create the variables needed for an Element Filter to search for ONLY the one sheet 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); //Use a Collector to search for only the One sheet with the supplied sheet number and if a ViewSheet is found, return it if (new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Sheets).WherePasses(filter).FirstOrDefault() is ViewSheet Sheet) { return(Sheet); } //If no sheet is found, return null return(null); } catch { //If an exception is thrown in the Try block, return null return(null); } }
////////////////////////////////////////////////////////////////////////////////////////// /////////////////// Get collection of elements by name /////////////////////////////// public FilteredElementCollector GetElementofNameType(Document doc, string name) { FilteredElementCollector a = new FilteredElementCollector(doc) .OfClass(typeof(FamilyInstance)); BuiltInParameter bip = BuiltInParameter.ALL_MODEL_TYPE_NAME; 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)); }
/// <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(); }
public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements) { UIApplication uiapp = commandData.Application; Document doc = uiapp.ActiveUIDocument.Document; //create filter and cxollect elements ElementFilter catFilter = new ElementCategoryFilter(BuiltInCategory.OST_GenericModel); var elems = new FilteredElementCollector(doc) .WhereElementIsNotElementType() .WhereElementIsViewIndependent() .WherePasses(catFilter) .ToElements(); string textToSearch = "AECTEST"; Parameter parameter = elems[0].get_Parameter(new Guid("8160aed7-fe71-4da4-aea4-ad283b76a76a")); ParameterValueProvider pvp = new ParameterValueProvider(parameter.Id); FilterStringRuleEvaluator fnrvStr = new FilterStringEquals(); FilterRule fRule = new FilterStringRule(pvp, fnrvStr, textToSearch, false); ElementParameterFilter filter = new ElementParameterFilter(fRule); FilteredElementCollector collector = new FilteredElementCollector(doc); ElementParameterFilter equalFilter = new ElementParameterFilter(fRule); IList <Element> filterByParam = collector.WherePasses(equalFilter) .WherePasses(catFilter) .ToElements(); IList <Element> instances = new FilteredElementCollector(doc) .OfClass(typeof(FamilyInstance)) .WherePasses(equalFilter) .WherePasses(catFilter) .ToElements(); //define lists to store parameters and feed them List <int> listaID = new List <int>(); List <string> listaKomentarz = new List <string>(); List <string> listaZnak = new List <string>(); List <string> listaGuid = new List <string>(); foreach (var i in instances) { FamilyInstance fi = i as FamilyInstance; String parKomentarz = fi.ToRoom.Name; if (parKomentarz == null) { listaKomentarz.Add("Brak danych w Revit"); } else { listaKomentarz.Add(parKomentarz); } } foreach (var e in filterByParam) { int parID = e.get_Parameter(BuiltInParameter.ID_PARAM).AsInteger(); listaID.Add(parID); /* * String parKomentarz = e.get_Parameter(BuiltInParameter.ALL_MODEL_INSTANCE_COMMENTS).AsString(); * if (parKomentarz == null) * { * listaKomentarz.Add("Brak danych w Revit"); * } * else * { * listaKomentarz.Add(parKomentarz); * } * //BuiltInParameter.ALL_MODEL_MARK */ String parZnak = e.get_Parameter(BuiltInParameter.ALL_MODEL_MARK).AsString(); if (parZnak == null) { listaZnak.Add("Brak danych w Revit"); } else { listaZnak.Add(parZnak); } String parGuid = e.get_Parameter(new Guid("61063061-01d9-4ecd-9876-f7ad906ef142")).AsString(); if (parGuid == null) { listaGuid.Add("Brak danych w Revit"); } else { listaGuid.Add(parGuid); } } //define the connection string of azure database. var cnString = "Server=tcp:revit-to-sql-svr-name.database.windows.net,1433;" + "Initial Catalog=RevitToSQL_DBName_01;" + "Persist Security Info=False;" + "User ID=kopeclogin;" + "Password=1qazXSW@;" + "MultipleActiveResultSets=False;" + "Encrypt=True;" + "TrustServerCertificate=False;" + "Connection Timeout=30;"; //define the insert sql command, here I insert data into the GenericModel table in azure db. //@@@@@@@@@@@@@@@@@@ // define datatable (dt) it could be helpfull in revittoexcel project var dt = new DataTable(); dt.Columns.Add("ElementsId"); dt.Columns.Add("Komentarz"); dt.Columns.Add("Znak"); dt.Columns.Add("ElementGUID"); int n = 0; for (int i = 0; i < filterByParam.Count; i++) { dt.Rows.Add(n, listaKomentarz[i], listaZnak[i], listaGuid[i]); n++; } /* * using (var sqlBulk = new SqlBulkCopy(cnString)) * { * sqlBulk.DestinationTableName = "GenericModels"; * sqlBulk.WriteToServer(dt); * } */ using (var connection = new SqlConnection(cnString)) { connection.Open(); var transaction = connection.BeginTransaction(); using (var sqlBulk = new SqlBulkCopy(connection, SqlBulkCopyOptions.KeepIdentity, transaction)) { //sqlBulk.BatchSize = 5000; sqlBulk.DestinationTableName = "GenericModels"; sqlBulk.WriteToServer(dt); } transaction.Commit(); } TaskDialog.Show("Element Info", elems.Count.ToString()); 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 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; }
/// <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]; }
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; }
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 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; }
Result IExternalCommand.Execute(ExternalCommandData commandData, ref string message, ElementSet elements) { UIApplication uiapp = commandData.Application; UIDocument uidoc = uiapp.ActiveUIDocument; Application app = uiapp.Application; Document doc = uidoc.Document; PhaseArray xcom = doc.Phases; Phase lastPhase = xcom.get_Item(xcom.Size - 1); FilterableValueProvider providerRoom = new ParameterValueProvider(new ElementId((int)BuiltInParameter.ROOM_PHASE_ID)); FilterableValueProvider provider = new ParameterValueProvider(new ElementId((int)BuiltInParameter.PHASE_CREATED)); FilterNumericRuleEvaluator evaluator = new FilterNumericEquals(); double FT = 0.3048; ElementId idPhase = lastPhase.Id; FilterElementIdRule rRule = new FilterElementIdRule(providerRoom, evaluator, idPhase); FilterElementIdRule fRule = new FilterElementIdRule(provider, evaluator, idPhase); ElementParameterFilter room_filter = new ElementParameterFilter(rRule); ElementParameterFilter door_filter = new ElementParameterFilter(fRule); IList <Element> rooms = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Rooms) .WhereElementIsNotElementType() .WherePasses(room_filter) .ToElements(); IList <FamilyInstance> doors = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Doors) .WhereElementIsNotElementType() .WherePasses(door_filter).Cast <FamilyInstance>().ToList(); IList <FamilyInstance> windows = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Windows) .WhereElementIsNotElementType() .WherePasses(door_filter).Cast <FamilyInstance>().ToList(); FamilySymbol neocube = new FilteredElementCollector(doc).OfClass(typeof(FamilySymbol)).Where(q => q.Name == "cube").First() as FamilySymbol; IList <XYZ> a = new List <XYZ>(); IList <String> b = new List <String>(); //Room two = rooms[0] as Room; int g = 0; FilterStringRuleEvaluator cubeEval = new FilterStringEquals(); FilterableValueProvider cubeProv = new ParameterValueProvider(new ElementId((int)BuiltInParameter.ALL_MODEL_TYPE_NAME)); FilterStringRule cubeRule = new FilterStringRule(cubeProv, cubeEval, "cube", false); ElementParameterFilter cubeFilter = new ElementParameterFilter(cubeRule); List <FamilyInstance> existCubes = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_GenericModel).WhereElementIsNotElementType().WherePasses(cubeFilter).Cast <FamilyInstance>().ToList(); using (Transaction tr = new Transaction(doc, "creating")) { tr.Start(); foreach (FamilyInstance i in existCubes) { doc.Delete(i.Id); } foreach (Element i in rooms) { for (int ind = 0; ind < doors.Count; ind++) { FamilyInstance dr = doors[ind]; try { if (dr.get_FromRoom(lastPhase).Id == i.Id | dr.get_ToRoom(lastPhase).Id == i.Id) { BoundingBoxXYZ bBox = i.get_BoundingBox(null); LocationPoint origin = (LocationPoint)i.Location; XYZ center = origin.Point; if (!neocube.IsActive) { neocube.Activate(); } FamilyInstance cubeIns = doc.Create.NewFamilyInstance(center, neocube, Autodesk.Revit.DB.Structure.StructuralType.NonStructural); cubeIns.LookupParameter("RoomNum").Set(i.get_Parameter(BuiltInParameter.ROOM_NUMBER).AsString()); cubeIns.LookupParameter("MainText").Set(dr.Symbol.LookupParameter("ADSK_Марка").AsString()); cubeIns.setType(); b.Append("ok"); //dr.LookupParameter("ADSK_Марка").AsValueString()); doors.Remove(dr); ind--; } } catch (Exception) { } } /* * foreach (FamilyInstance dr in doors) * { * try * { * if (dr.get_FromRoom(lastPhase).Id == i.Id | dr.get_ToRoom(lastPhase).Id == i.Id) * { * * BoundingBoxXYZ bBox = i.get_BoundingBox(null); * LocationPoint origin = (LocationPoint)i.Location; * * XYZ center = origin.Point; * if (!neocube.IsActive) * neocube.Activate(); * FamilyInstance cubeIns = doc.Create.NewFamilyInstance(center, neocube, Autodesk.Revit.DB.Structure.StructuralType.NonStructural); * cubeIns.LookupParameter("RoomNum").Set(i.get_Parameter(BuiltInParameter.ROOM_NUMBER).AsString()); * cubeIns.LookupParameter("MainText").Set(dr.Symbol.LookupParameter("ADSK_Марка").AsString()); * cubeIns.LookupParameter("isAreo").Set(0); * * b.Append("ok");//dr.LookupParameter("ADSK_Марка").AsValueString()); * * } * } * catch (Exception) * { * * } * } */ foreach (FamilyInstance dr in windows) { try { if (dr.get_FromRoom(lastPhase).Id == i.Id) { LocationPoint origin = (LocationPoint)i.Location; XYZ center = origin.Point; if (!neocube.IsActive) { neocube.Activate(); } FamilyInstance cubeIns = doc.Create.NewFamilyInstance(center, neocube, Autodesk.Revit.DB.Structure.StructuralType.NonStructural); cubeIns.LookupParameter("RoomNum").Set(i.get_Parameter(BuiltInParameter.ROOM_NUMBER).AsString()); cubeIns.LookupParameter("MainText").Set(dr.Symbol.LookupParameter("ADSK_Марка").AsString()); cubeIns.setType(); FamilyInstance winOtkos = doc.Create.NewFamilyInstance(center, neocube, Autodesk.Revit.DB.Structure.StructuralType.NonStructural); winOtkos.LookupParameter("RoomNum").Set(i.get_Parameter(BuiltInParameter.ROOM_NUMBER).AsString()); winOtkos.LookupParameter("MainText").Set("Площадь откосов: "); winOtkos.LookupParameter("Area").Set(dr.LookupParameter("ADSK_Откосы_Глубина").AsDouble() * (dr.LookupParameter("VIDNAL_Высота проема").AsDouble() * 2 + dr.LookupParameter("VIDNAL_Ширина проема").AsDouble())); winOtkos.setType("area"); FamilyInstance winPodok = doc.Create.NewFamilyInstance(center, neocube, Autodesk.Revit.DB.Structure.StructuralType.NonStructural); winPodok.LookupParameter("RoomNum").Set(i.get_Parameter(BuiltInParameter.ROOM_NUMBER).AsString()); String output = String.Format("Подоконник {0:f2}x{1:f2}", dr.LookupParameter("VIDNAL_Ширина проема").AsDouble() * FT, dr.LookupParameter("ADSK_Откосы_Глубина").AsDouble() * FT); winPodok.LookupParameter("MainText").Set(output); winPodok.setType(); FamilyInstance winUgol = doc.Create.NewFamilyInstance(center, neocube, Autodesk.Revit.DB.Structure.StructuralType.NonStructural); winUgol.LookupParameter("RoomNum").Set(i.get_Parameter(BuiltInParameter.ROOM_NUMBER).AsString()); winUgol.LookupParameter("MainText").Set("ПВХ уголок 60х60"); winUgol.LookupParameter("dlina").Set(dr.LookupParameter("VIDNAL_Высота проема").AsDouble() * 2 + dr.LookupParameter("VIDNAL_Ширина проема").AsDouble()); winUgol.setType("len"); } } catch (Exception) { } } } foreach (Element i in rooms) { if (i.LookupParameter("ЗаменаПокрытияПола").AsInteger() == 1) { LocationPoint origin = (LocationPoint)i.Location; XYZ center = origin.Point; if (!neocube.IsActive) { neocube.Activate(); } FamilyInstance cubeIns = doc.Create.NewFamilyInstance(center, neocube, Autodesk.Revit.DB.Structure.StructuralType.NonStructural); cubeIns.LookupParameter("RoomNum").Set(i.get_Parameter(BuiltInParameter.ROOM_NUMBER).AsString()); cubeIns.LookupParameter("MainText").Set(i.LookupParameter("snosF").AsString()); cubeIns.LookupParameter("Area").Set(i.get_Parameter(BuiltInParameter.ROOM_AREA).AsDouble()); cubeIns.setType("area"); if (cubeIns.LookupParameter("MainText").AsString() == "") { doc.Delete(cubeIns.Id); } } if (i.LookupParameter("НоваяОтделка").AsInteger() == 1) { LocationPoint origin = (LocationPoint)i.Location; XYZ center = origin.Point; if (!neocube.IsActive) { neocube.Activate(); } FamilyInstance cubeIns = doc.Create.NewFamilyInstance(center, neocube, Autodesk.Revit.DB.Structure.StructuralType.NonStructural); cubeIns.LookupParameter("RoomNum").Set(i.get_Parameter(BuiltInParameter.ROOM_NUMBER).AsString()); cubeIns.LookupParameter("MainText").Set("Демонтаж штукатурки"); cubeIns.LookupParameter("Area").Set(i.LookupParameter("WallS").AsDouble()); cubeIns.setType("area"); } } tr.Commit(); } //XYZ origin = new XYZ(0,0,0); /* * using (Transaction tr = new Transaction(doc,"creating")) * { * tr.Start(); * * for (int i = 0; i < a.Count; i++) * { * if (!neocube.IsActive) * neocube.Activate(); * FamilyInstance cubeIns = doc.Create.NewFamilyInstance(a[i], neocube, Autodesk.Revit.DB.Structure.StructuralType.NonStructural); * cubeIns.LookupParameter("MainText").Set(b[i]); * } * * * tr.Commit(); * * } */ //FamilySymbol elt = doors[0].Symbol; //FamilySymbol one=elt as FamilySymbol; TaskDialog msg = new TaskDialog("Info"); msg.MainInstruction = g.ToString(); msg.Show(); return(Result.Succeeded); }
public static ElementFilter createParameterFilter(Document doc, ParameterData parameter, string operation, string ruleString) { ElementId parameterId = parameter.Id; ParameterValueProvider fvp = new ParameterValueProvider(parameterId); StorageType storageType = parameter.StorageType; FilterRule fRule = null; FilterInverseRule fInvRule = null; ElementParameterFilter filter = null; switch (storageType) { case StorageType.String: case StorageType.Integer: FilterStringRuleEvaluator fsre = null; switch (operation) { case "равно": fsre = new FilterStringEquals(); fRule = new FilterStringRule(fvp, fsre, ruleString, true); filter = new ElementParameterFilter(fRule); break; case "не равно": fsre = new FilterStringEquals(); fRule = new FilterStringRule(fvp, fsre, ruleString, true); fInvRule = new FilterInverseRule(fRule); filter = new ElementParameterFilter(fInvRule); break; case "содержит": fsre = new FilterStringContains(); fRule = new FilterStringRule(fvp, fsre, ruleString, true); filter = new ElementParameterFilter(fRule); break; case "не содержит": fsre = new FilterStringContains(); fRule = new FilterStringRule(fvp, fsre, ruleString, true); fInvRule = new FilterInverseRule(fRule); filter = new ElementParameterFilter(fInvRule); break; case "начинается с": fsre = new FilterStringBeginsWith(); fRule = new FilterStringRule(fvp, fsre, ruleString, true); filter = new ElementParameterFilter(fRule); break; case "не начинается с": fsre = new FilterStringBeginsWith(); fRule = new FilterStringRule(fvp, fsre, ruleString, true); fInvRule = new FilterInverseRule(fRule); filter = new ElementParameterFilter(fInvRule); break; case "заканчивается на": fsre = new FilterStringEndsWith(); fRule = new FilterStringRule(fvp, fsre, ruleString, true); filter = new ElementParameterFilter(fRule); break; case "не заканчивается на": fsre = new FilterStringEndsWith(); fRule = new FilterStringRule(fvp, fsre, ruleString, true); fInvRule = new FilterInverseRule(fRule); filter = new ElementParameterFilter(fInvRule); break; } break; case StorageType.Double: FilterNumericRuleEvaluator fnre = null; double ruleValue = Convert.ToDouble(ruleString); switch (operation) { case "равно": fnre = new FilterNumericEquals(); fRule = new FilterDoubleRule(fvp, fnre, ruleValue, 0.0); filter = new ElementParameterFilter(fRule); break; case "не равно": fnre = new FilterNumericEquals(); fRule = new FilterDoubleRule(fvp, fnre, ruleValue, 0.0); fInvRule = new FilterInverseRule(fRule); filter = new ElementParameterFilter(fInvRule); break; case "больше": fnre = new FilterNumericGreater(); fRule = new FilterDoubleRule(fvp, fnre, ruleValue, 0.0); filter = new ElementParameterFilter(fRule); break; case "больше или равно": fnre = new FilterNumericGreaterOrEqual(); fRule = new FilterDoubleRule(fvp, fnre, ruleValue, 0.0); filter = new ElementParameterFilter(fRule); break; case "меньше": fnre = new FilterNumericLess(); fRule = new FilterDoubleRule(fvp, fnre, ruleValue, 0.0); filter = new ElementParameterFilter(fRule); break; case "меньше или равно": fnre = new FilterNumericLessOrEqual(); fRule = new FilterDoubleRule(fvp, fnre, ruleValue, 0.0); filter = new ElementParameterFilter(fRule); break; } break; case StorageType.ElementId: var levels = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Levels).ToElements(); var level = levels.Where(i => i.Name == ruleString).FirstOrDefault(); ElementId ruleId = level.Id; fnre = null; switch (operation) { case "равно": fnre = new FilterNumericEquals(); fRule = new FilterElementIdRule(fvp, fnre, ruleId); filter = new ElementParameterFilter(fRule); break; case "не равно": fnre = new FilterNumericEquals(); fRule = new FilterElementIdRule(fvp, fnre, ruleId); fInvRule = new FilterInverseRule(fRule); filter = new ElementParameterFilter(fInvRule); break; case "выше": fnre = new FilterNumericGreater(); fRule = new FilterElementIdRule(fvp, fnre, ruleId); filter = new ElementParameterFilter(fRule); break; case "ровно или выше": fnre = new FilterNumericGreaterOrEqual(); fRule = new FilterElementIdRule(fvp, fnre, ruleId); filter = new ElementParameterFilter(fRule); break; case "ниже": fnre = new FilterNumericLess(); fRule = new FilterElementIdRule(fvp, fnre, ruleId); filter = new ElementParameterFilter(fRule); break; case "ровно или ниже": fnre = new FilterNumericLessOrEqual(); fRule = new FilterElementIdRule(fvp, fnre, ruleId); filter = new ElementParameterFilter(fRule); break; } break; } return(filter); }
Result IExternalCommand.Execute(ExternalCommandData commandData, ref string message, ElementSet elements) { UIApplication uiapp = commandData.Application; UIDocument uidoc = uiapp.ActiveUIDocument; Application app = uiapp.Application; Document doc = uidoc.Document; //GlobalParameter. //GlobalParameter one = ; FinishForm questions = new FinishForm(doc); questions.Show(); questions.Activate(); double FT = 0.3048; PhaseArray xcom = doc.Phases; Phase lastPhase = xcom.get_Item(xcom.Size - 1); ElementId idPhase = lastPhase.Id; FilterNumericRuleEvaluator evaluator = new FilterNumericEquals(); List <SharedParameterElement> shParamElements = new FilteredElementCollector(doc) .OfClass(typeof(SharedParameterElement)) .Cast <SharedParameterElement>() .ToList(); //SharedParameterElement shParam = shParamElements.Where(x => x.Name == "ADSK_Номер здания").First(); //Фильтр: Помещения на последней стадии FilterableValueProvider providerRoom = new ParameterValueProvider(new ElementId((int)BuiltInParameter.ROOM_PHASE_ID)); FilterElementIdRule rRule = new FilterElementIdRule(providerRoom, evaluator, idPhase); ElementParameterFilter room_filter = new ElementParameterFilter(rRule); //FilterableValueProvider provRoomSchool = new ParameterValueProvider(shParam.Id); FilterStringRuleEvaluator StrEvaluator = new FilterStringEquals(); //FilterRule rScRule = new FilterStringRule(provRoomSchool, StrEvaluator, "",false); //ElementParameterFilter roomSc_filter = new ElementParameterFilter(rScRule); IList <Element> rooms = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Rooms) .WhereElementIsNotElementType() .WherePasses(room_filter) //.WherePasses(roomSc_filter) .ToElements(); //Фильтр: Стены созданные на последней стадии FilterableValueProvider provider = new ParameterValueProvider(new ElementId((int)BuiltInParameter.PHASE_CREATED)); FilterElementIdRule fRule = new FilterElementIdRule(provider, evaluator, idPhase); ElementParameterFilter door_filter = new ElementParameterFilter(fRule); IList <Element> allWalls = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Walls) .WhereElementIsNotElementType() .WherePasses(door_filter) .ToElements(); //Фильтр: экземпляры дверей List <FamilyInstance> doors = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Doors) .WhereElementIsNotElementType() .Cast <FamilyInstance>() .ToList(); List <FamilySymbol> ento = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Entourage) .WhereElementIsElementType() .Cast <FamilySymbol>() .ToList(); List <String> entoName = new List <string>(); foreach (FamilySymbol i in ento) { entoName.Add(i.Name); } List <String> entoFamily = new List <string>(); //List<otdelka> otd = new List<otdelka>(); foreach (FamilySymbol f in ento) { //otd.Add(new otdelka(f.FamilyName+':'+f.Name,f.getP("АР_Состав отделки"))); entoFamily.Add(f.FamilyName); } //List<String> one = new List<string>(); //foreach (FamilySymbol f in ento) //{ // one.Add(f.getP("АР_Состав отделки")); //} //string two = doc.GetElement(rooms[0].LookupParameter("ОТД_Пол").AsElementId()).Name; List <Element> walls = new List <Element>(); List <GhostWall> cWalls = new List <GhostWall>(); foreach (Element item in allWalls) { if (item.LookupParameter("Помещение").AsString() != null & item.LookupParameter("Помещение").AsString() != "") { bool isLocal = (item as Wall).WallType.LookupParameter("rykomoika").AsInteger() == 1 ? true : false; walls.Add(item); cWalls.Add(new GhostWall( item.getP("Помещение"), item.LevelId, item.get_Parameter(BuiltInParameter.HOST_AREA_COMPUTED).AsDouble(), isLocal )); } } List <ElementId> Levels = new List <ElementId>(); rooms = rooms.OrderBy(x => x.get_Parameter(BuiltInParameter.ROOM_NUMBER).AsString()).ToList(); List <RoomFinishing> novaRooms = new List <RoomFinishing>(); foreach (Element e in rooms) { novaRooms.Add(new RoomFinishing(e)); } novaRooms = novaRooms.OrderBy(x => x.Num).ToList(); List <ElementId> wallLevels = new List <ElementId>(); foreach (Element i in rooms) { Levels.Add(i.LevelId); } foreach (Element i in walls) { wallLevels.Add(i.LevelId); } IEnumerable <String> LevelsName = new List <String>(); //Levels=Levels.Distinct().ToList(); //Levels = Levels.OrderBy(x=>doc.GetElement(x).Name).ToList(); foreach (ElementId i in Levels.Distinct().OrderBy(x => doc.GetElement(x).Name)) { LevelsName = LevelsName.Append(doc.GetElement(i).Name); } String str = String.Join(",", LevelsName); IEnumerable <bool> isNewC = new List <bool>(); IEnumerable <bool> isNewW = new List <bool>(); IEnumerable <bool> SecFin = new List <bool>(); List <String> CeilText = new List <String>(); List <String> MainText = new List <String>(); List <String> FloorText = new List <String>(); List <string> WallsLocal = new List <string>(); List <List <Element> > roomByLevel = new List <List <Element> >(); List <List <String> > roomNumByLevel = new List <List <String> >(); List <List <String> > CeilTextByLevel = new List <List <string> >(); List <List <String> > MainTextByLevel = new List <List <string> >(); List <List <String> > FloorTextByLevel = new List <List <string> >(); List <List <List <Element> > > FinishTable = new List <List <List <Element> > >(); List <List <List <String> > > FinishTableNum = new List <List <List <String> > >(); List <List <List <double> > > FinishTableW3S = new List <List <List <double> > >(); List <List <Element> > wallByLevel = new List <List <Element> >(); List <List <String> > wallNumByLevel = new List <List <String> >(); List <List <double> > wallAreaByLevel = new List <List <double> >(); List <List <double> > WallS1 = new List <List <double> >(); List <List <double> > WallS2 = new List <List <double> >(); List <List <string> > WallsLocalText = new List <List <string> >(); List <List <List <Element> > > floorTable = new List <List <List <Element> > >(); List <List <List <string> > > floorTableNum = new List <List <List <string> > >(); List <List <List <double> > > plintTable = new List <List <List <double> > >(); List <List <double> > plintByLevel = new List <List <double> >(); List <List <double> > perimByLevel = new List <List <double> >(); foreach (ElementId lev in Levels.Distinct().OrderBy(x => doc.GetElement(x).Name)) { List <Element> s = new List <Element>(); List <String> n = new List <String>(); List <String> ct = new List <String>(); List <String> mt = new List <String>(); List <String> ft = new List <String>(); List <double> ws = new List <double>(); List <double> ws2 = new List <double>(); List <string> wt = new List <string>(); List <double> pl = new List <double>(); List <double> pr = new List <double>(); for (int i = 0; i < Levels.Count(); i++) { if (Levels[i] == lev) { s.Add(rooms.ElementAt(i)); n.Add(rooms.ElementAt(i).get_Parameter(BuiltInParameter.ROOM_NUMBER).AsString()); ct.Add(rooms.ElementAt(i).LookupParameter("ОТД_Потолок").AsValueString()); mt.Add(rooms.ElementAt(i).LookupParameter("ОТД_Стены").AsValueString()); ft.Add(rooms.ElementAt(i).LookupParameter("ОТД_Пол").AsValueString()); pr.Add(rooms.ElementAt(i).get_Parameter(BuiltInParameter.ROOM_PERIMETER).AsDouble()); ws.Add(0); ws2.Add(0); pl.Add(0); wt.Add(""); CeilText.Add(rooms.ElementAt(i).LookupParameter("ОТД_Потолок").AsValueString()); MainText.Add(rooms.ElementAt(i).LookupParameter("ОТД_Стены").AsValueString()); FloorText.Add(rooms.ElementAt(i).LookupParameter("ОТД_Пол").AsValueString()); } } roomByLevel.Add(s); roomNumByLevel.Add(n); CeilTextByLevel.Add(ct); MainTextByLevel.Add(mt); FloorTextByLevel.Add(ft); WallS1.Add(ws); WallS2.Add(ws2); WallsLocalText.Add(wt); plintByLevel.Add(pl); perimByLevel.Add(pr); List <Element> w = new List <Element>(); List <String> wn = new List <String>(); List <double> wa = new List <double>(); //List<Wall> est = walls as List<Wall>; for (int i = 0; i < wallLevels.Count(); i++) { if (wallLevels[i] == lev) { w.Add(walls[i]); wn.Add(walls[i].LookupParameter("Помещение").AsString()); wa.Add(walls[i].get_Parameter(BuiltInParameter.HOST_AREA_COMPUTED).AsDouble()); } } wallAreaByLevel.Add(wa); wallByLevel.Add(w); wallNumByLevel.Add(wn); } //Плинтус foreach (FamilyInstance d in doors) { foreach (RoomFinishing r in novaRooms) { try { if (d.get_FromRoom(lastPhase).Id == r.Id | d.get_ToRoom(lastPhase).Id == r.Id) { r.Perimeter -= d.LookupParameter("сп_Ширина проёма").AsDouble(); } } catch (Exception) { } } } //Задаём площади отделки помещений и указываем неизменные помещения foreach (ElementId lev in novaRooms.Select(x => x.Level).Distinct()) { foreach (RoomFinishing r in novaRooms.Where(x => x.Level == lev)) { //Стены for (int i = 0; i < novaRooms.Select(x => x.Level).Distinct().Count(); i++) { for (int w = 0; w < wallNumByLevel[i].Count(); w++) { if (wallByLevel[i][w].LevelId != lev) { continue; } Wall checkWall = (Wall)wallByLevel[i][w]; if (r.Num == wallNumByLevel[i][w]) { if (checkWall.WallType.LookupParameter("rykomoika").AsInteger() == 1) { r.LocalWallVal += wallAreaByLevel[i][w]; r.LocalWallText = checkWall.WallType.LookupParameter("СоставОтделкиСтен").AsString(); WallsLocal.Add(checkWall.WallType.LookupParameter("СоставОтделкиСтен").AsString()); continue; } r.MainWallVal += wallAreaByLevel[i][w]; WallsLocal.Add(""); } } } } } for (int lev = 0; lev < Levels.Distinct().Count(); lev++) { for (int r = 0; r < roomNumByLevel[lev].Count(); r++) { //Плинтус for (int i = 0; i < doors.Count(); i++) { try { if (doors[i].get_FromRoom(lastPhase).Id == roomByLevel[lev][r].Id | doors[i].get_ToRoom(lastPhase).Id == roomByLevel[lev][r].Id) { plintByLevel[lev][r] += doors[i].LookupParameter("Ширина").AsDouble(); } } catch (Exception) { } } //Стены for (int w = 0; w < wallNumByLevel[lev].Count(); w++) { Wall checkWall = (Wall)wallByLevel[lev][w]; if (roomNumByLevel[lev][r] == wallNumByLevel[lev][w]) { if (checkWall.WallType.LookupParameter("rykomoika").AsInteger() == 1) { WallS2[lev][r] += wallAreaByLevel[lev][w]; WallsLocalText[lev][r] = checkWall.WallType.LookupParameter("СоставОтделкиСтен").AsString(); WallsLocal.Add(checkWall.WallType.LookupParameter("СоставОтделкиСтен").AsString()); continue; } WallS1[lev][r] += wallAreaByLevel[lev][w]; WallsLocal.Add(""); } } } } WallsLocal = WallsLocal.OrderBy(x => x).ToList(); //Сортируем помещения по типу отделки потолка и стен int finishTypes = 0; List <List <RoomFinishing> > novaFinishTable = new List <List <RoomFinishing> >(); if (WallsLocal.Count == 0) { foreach (string c in novaRooms.Select(x => x.CeilType).Distinct()) { foreach (string w in novaRooms.Select(x => x.WallType).Distinct()) { List <RoomFinishing> cw = novaRooms .Where(x => x.CeilType == c) .Where(y => y.WallType == w) .ToList(); novaFinishTable.Add(cw); foreach (RoomFinishing r in cw) { r.SimilarWallVal = cw.Sum(x => x.MainWallVal); } } } } else { foreach (string wt3 in WallsLocal.Distinct()) { foreach (string c in novaRooms.Select(x => x.CeilType).Distinct()) { foreach (string w in novaRooms.Select(x => x.WallType).Distinct()) { List <RoomFinishing> cw = novaRooms .Where(x => x.CeilType == c) .Where(y => y.WallType == w) .ToList(); novaFinishTable.Add(cw); foreach (RoomFinishing r in cw) { r.SimilarWallVal = cw.Sum(x => x.MainWallVal); } } } } } if (WallsLocal.Count == 0) { foreach (String i in CeilText.Distinct()) { foreach (String j in MainText.Distinct()) { FinishTable.Add(new List <List <Element> >()); FinishTableNum.Add(new List <List <string> >()); FinishTableW3S.Add(new List <List <double> >()); for (int lev = 0; lev < Levels.Distinct().Count(); lev++) { List <Element> SimilarFinish = new List <Element>(); List <String> SimilarFinishNum = new List <String>(); List <double> SimW3S = new List <double>(); for (int r = 0; r < roomByLevel[lev].Count(); r++) { if (CeilTextByLevel[lev][r] == i & MainTextByLevel[lev][r] == j) { SimilarFinish.Add(roomByLevel[lev][r]); SimilarFinishNum.Add(roomNumByLevel[lev][r]); SimW3S.Add(WallS2[lev][r]); } } FinishTable[finishTypes].Add(SimilarFinish); FinishTableNum[finishTypes].Add(SimilarFinishNum); FinishTableW3S[finishTypes].Add(SimW3S); } finishTypes++; } } } else { foreach (string wt3 in WallsLocal.Distinct()) { foreach (String i in CeilText.Distinct()) { foreach (String j in MainText.Distinct()) { FinishTable.Add(new List <List <Element> >()); FinishTableNum.Add(new List <List <string> >()); FinishTableW3S.Add(new List <List <double> >()); for (int lev = 0; lev < Levels.Distinct().Count(); lev++) { List <Element> SimilarFinish = new List <Element>(); List <String> SimilarFinishNum = new List <String>(); List <double> SimW3S = new List <double>(); for (int r = 0; r < roomByLevel[lev].Count(); r++) { if (CeilTextByLevel[lev][r] == i & MainTextByLevel[lev][r] == j & WallsLocalText[lev][r] == wt3) { SimilarFinish.Add(roomByLevel[lev][r]); SimilarFinishNum.Add(roomNumByLevel[lev][r]); SimW3S.Add(WallS2[lev][r]); } } FinishTable[finishTypes].Add(SimilarFinish); FinishTableNum[finishTypes].Add(SimilarFinishNum); FinishTableW3S[finishTypes].Add(SimW3S); } finishTypes++; } } } } List <List <RoomFinishing> > novaFloorTable = new List <List <RoomFinishing> >(); foreach (string i in novaRooms.Select(x => x.FloorType).Distinct()) { foreach (string pl in novaRooms.Select(x => x.PlintusType).Distinct()) { List <RoomFinishing> flpl = novaRooms .Where(x => x.FloorType == i) .Where(y => y.PlintusType == pl) .ToList(); novaFloorTable.Add(flpl); foreach (RoomFinishing r in flpl) { r.SimilarPlintusVal = flpl.Sum(x => x.Perimeter); } } } //Сортируем помещения по типу пола int floorTypes = 0; foreach (string i in FloorText.Distinct()) { floorTable.Add(new List <List <Element> >()); floorTableNum.Add(new List <List <string> >()); plintTable.Add(new List <List <double> >()); for (int lev = 0; lev < Levels.Distinct().Count(); lev++) { List <Element> simFloor = new List <Element>(); List <string> simFloorNum = new List <string>(); List <double> simPlint = new List <double>(); for (int r = 0; r < roomByLevel[lev].Count(); r++) { if (FloorTextByLevel[lev][r] == i) { simFloor.Add(roomByLevel[lev][r]); simFloorNum.Add(roomNumByLevel[lev][r]); simPlint.Add(perimByLevel[lev][r] - plintByLevel[lev][r]); } } floorTable[floorTypes].Add(simFloor); floorTableNum[floorTypes].Add(simFloorNum); plintTable[floorTypes].Add(simPlint); } floorTypes++; } using (Transaction tr = new Transaction(doc, "otdelka")) { tr.Start(); GlobalParameter ohohoh = GlobalParametersManager.FindByName(doc, "НесколькоЭтажей") != ElementId.InvalidElementId ? doc.GetElement(GlobalParametersManager.FindByName(doc, "НесколькоЭтажей")) as GlobalParameter : GlobalParameter.Create(doc, "НесколькоЭтажей", ParameterType.YesNo); int MoreThenOneLevel = ((IntegerParameterValue)ohohoh.GetValue()).Value; //Передаем номера помещений с одинаковым типом отделки стен и потолка for (int lev = 0; lev < roomByLevel.Count(); lev++) { for (int r = 0; r < roomByLevel[lev].Count(); r++) { roomByLevel[lev][r].LookupParameter("SanT").Set(WallsLocalText[lev][r]); roomByLevel[lev][r].LookupParameter("ДлинаПроемов").Set(plintByLevel[lev][r]); } } for (int i = 0; i < FinishTable.Count(); i++) { String fillText = ""; //String fillText2 = ""; double sumW3S = 0; for (int lev = 0; lev < FinishTable[i].Count(); lev++) { sumW3S += FinishTableW3S[i][lev].Sum() * (FT * FT); if (FinishTable[i][lev].Count() == 0) { continue; } else { if (MoreThenOneLevel == 1) { fillText += (lev + 1).ToString() + " этаж:\n"; } fillText += Meta.shortLists(FinishTableNum[i][lev]); fillText += "\n"; } } for (int lev = 0; lev < FinishTable[i].Count(); lev++) { for (int r = 0; r < FinishTable[i][lev].Count(); r++) { try { FinishTable[i][lev][r].LookupParameter("ОТД_Состав.Стены").Set(doc.GetElement(FinishTable[i][lev][r].LookupParameter("ОТД_Стены").AsElementId()).LookupParameter("АР_Состав отделки").AsString()); //FinishTable[i][lev][r].LookupParameter("ОТД_Состав.Потолок").Set(doc.GetElement(FinishTable[i][lev][r].LookupParameter("ОТД_Потолок").AsElementId()).LookupParameter("АР_Состав отделки").AsString()); } catch (Exception) { FinishTable[i][lev][r].LookupParameter("ОТД_Состав.Стены").Set("НЕТ ОТДЕЛКИ"); //FinishTable[i][lev][r].LookupParameter("ОТД_Состав.Потолок").Set("НЕТ ОТДЕЛКИ"); } try { //FinishTable[i][lev][r].LookupParameter("ОТД_Состав.Стены").Set(doc.GetElement(FinishTable[i][lev][r].LookupParameter("ОТД_Стены").AsElementId()).LookupParameter("АР_Состав отделки").AsString()); FinishTable[i][lev][r].LookupParameter("ОТД_Состав.Потолок").Set(doc.GetElement(FinishTable[i][lev][r].LookupParameter("ОТД_Потолок").AsElementId()).LookupParameter("АР_Состав отделки").AsString()); } catch (Exception) { //FinishTable[i][lev][r].LookupParameter("ОТД_Состав.Стены").Set("НЕТ ОТДЕЛКИ"); FinishTable[i][lev][r].LookupParameter("ОТД_Состав.Потолок").Set("НЕТ ОТДЕЛКИ"); } FinishTable[i][lev][r].LookupParameter("testW").Set(fillText); //FinishTable[i][lev][r].LookupParameter("unitTest").Set(fillText2); FinishTable[i][lev][r].LookupParameter("SanS").Set(sumW3S > 0 ? sumW3S.ToString("F1") : ""); FinishTable[i][lev][r].LookupParameter("snS").Set(FinishTableW3S[i][lev][r]); } } } for (int lev = 0; lev < Levels.Distinct().Count(); lev++) { for (int r = 0; r < roomByLevel[lev].Count(); r++) { roomByLevel[lev][r].LookupParameter("WallS1n").Set(WallS1[lev][r]); } } int withNames = questions.withnames; //Если нужны имена помещений //Передаем номера помещений с одинаковым типом стен потолка foreach (List <RoomFinishing> item in novaFinishTable) { if (item == null) { continue; } String fillText = ""; foreach (ElementId lev in item.Select(x => x.Level).Distinct()) { if (MoreThenOneLevel == 1) { fillText += doc.GetElement(lev).LookupParameter("Название уровня").AsString() + ":\n"; } if (withNames == 1) { foreach (RoomFinishing gg in item.Where(x => x.Level == lev)) { fillText += gg.Name + "-" + gg.Num + ", "; } fillText = fillText.Remove(fillText.Length - 2, 2) + "\n"; continue; } fillText += Meta.shortLists(item.Where(x => x.Level == lev).Select(y => y.Num).ToList()) + "\n"; } foreach (ElementId lev in item.Select(x => x.Level).Distinct()) { foreach (RoomFinishing r in item.Where(x => x.Level == lev)) { try { r.refElement.LookupParameter("ОТД_Состав.Потолок").Set(doc.GetElement(r.refElement.LookupParameter("ОТД_Потолок").AsElementId()).LookupParameter("АР_Состав отделки").AsString()); } catch (Exception) { r.refElement.LookupParameter("ОТД_Состав.Потолок").Set("НЕТ ОТДЕЛКИ"); } try { r.refElement.LookupParameter("ОТД_Состав.Стены").Set(doc.GetElement(r.refElement.LookupParameter("ОТД_Стены").AsElementId()).LookupParameter("АР_Состав отделки").AsString()); } catch (Exception) { r.refElement.LookupParameter("ОТД_Состав.Стены").Set("НЕТ ОТДЕЛКИ"); } r.refElement.LookupParameter("testW").Set(fillText); //r.refElement.LookupParameter("ОТД_Кол.Стены").Set(0); r.refElement.LookupParameter("ОТД_Кол.Стены").Set(r.SimilarWallVal); //r.refElement.LookupParameter("PlintusTotal").Set(r.Perimeter); //item.Select(x => x.refElement.LookupParameter("testF").Set(fillText)); //item.Select(x => x.refElement.LookupParameter("PlintusTotal").Set(x.SimilarPlintusVal)); } } } //Передаем номера помещений с одинаковым типом отделки пола foreach (List <RoomFinishing> item in novaFloorTable) { if (item == null) { continue; } String fillText = ""; foreach (ElementId lev in item.Select(x => x.Level).Distinct()) { if (MoreThenOneLevel == 1) { fillText += doc.GetElement(lev).LookupParameter("Название уровня").AsString() + ":\n"; } if (withNames == 1) { foreach (RoomFinishing gg in item.Where(x => x.Level == lev)) { fillText += gg.Name + "-" + gg.Num + ", "; } fillText = fillText.Remove(fillText.Length - 2, 2) + "\n"; continue; } fillText += Meta.shortLists(item.Where(x => x.Level == lev).Select(y => y.Num).ToList()) + "\n"; } foreach (ElementId lev in item.Select(x => x.Level).Distinct()) { foreach (RoomFinishing r in item.Where(x => x.Level == lev)) { r.refElement.LookupParameter("ОТД_Состав.Пол").Set(""); try { r.refElement.LookupParameter("ОТД_Состав.Пол").Set(doc.GetElement(r.refElement.LookupParameter("ОТД_Пол").AsElementId()).LookupParameter("АР_Состав отделки").AsString()); } catch (Exception) { r.refElement.LookupParameter("ОТД_Состав.Пол").Set("НЕТ ОТДЕЛКИ"); } try { r.refElement.LookupParameter("ОТД_Состав.Плинтус").Set(doc.GetElement(r.refElement.LookupParameter("ОТД_Плинтус").AsElementId()).LookupParameter("АР_Состав отделки").AsString()); } catch (Exception) { r.refElement.LookupParameter("ОТД_Состав.Плинтус").Set("НЕТ ОТДЕЛКИ"); } r.refElement.LookupParameter("testF").Set(fillText); r.refElement.LookupParameter("ОТД_Кол.Плинтус").Set(""); if (r.PlintusType != "__Отделка : ---") { r.refElement.LookupParameter("ОТД_Кол.Плинтус").Set((r.SimilarPlintusVal * FT).ToString("F1")); } r.refElement.LookupParameter("PlintusTotal").Set(r.Perimeter); //item.Select(x => x.refElement.LookupParameter("testF").Set(fillText)); //item.Select(x => x.refElement.LookupParameter("PlintusTotal").Set(x.SimilarPlintusVal)); } } } // for (int i = 0; i < floorTable.Count(); i++) // { // double sumPlint = 0; // String fillText = ""; // for (int lev = 0; lev < floorTable[i].Count(); lev++) // { // sumPlint += plintTable[i][lev].Sum() * FT; // if (floorTable[i][lev].Count() == 0) // { // continue; // } // else // { // if (MoreThenOneLevel==1) // { // fillText += (lev + 1).ToString() + " этаж:\n"; // } // fillText += Meta.shortLists(floorTableNum[i][lev]); // fillText += "\n"; // } // } // for (int lev = 0; lev < floorTable[i].Count(); lev++) // { //for (int r = 0; r < floorTable[i][lev].Count(); r++) //{ // try // { // floorTable[i][lev][r].LookupParameter("ОТД_Состав.Пол").Set(doc.GetElement(floorTable[i][lev][r].LookupParameter("ОТД_Пол").AsElementId()).LookupParameter("АР_Состав отделки").AsString()); // } // catch (Exception) // { // floorTable[i][lev][r].LookupParameter("ОТД_Состав.Пол").Set("НЕТ ОТДЕЛКИ"); // } // floorTable[i][lev][r].LookupParameter("testF").Set(fillText); // floorTable[i][lev][r].LookupParameter("PlintusTotal").Set(sumPlint); // if (floorTable[i][lev][r].LookupParameter("плинтус").AsInteger() == 1) // { // floorTable[i][lev][r].setP("PlintusTotalT", (sumPlint * FT).ToString("F1")); // } // } // } // } tr.Commit(); } //String output = String.Join(", ", roomNumByLevel[0]); TaskDialog msg = new TaskDialog("Info"); msg.MainInstruction = "Ok"; //output;// FinishTable.Count().ToString(); msg.Show(); return(Result.Succeeded); }
public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements) { #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 to create a project parameter. 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 { // Create a new FilteredElementCollector FilteredElementCollector collector = new FilteredElementCollector(doc); // Define and apply one or more filters to it. ElementCategoryFilter categoryFilter = new ElementCategoryFilter(BuiltInCategory.OST_GenericAnnotation); ParameterValueProvider pvp_1 = new ParameterValueProvider(new ElementId(BuiltInParameter.ALL_MODEL_FAMILY_NAME)); ParameterValueProvider pvp_2 = new ParameterValueProvider(new ElementId(BuiltInParameter.ALL_MODEL_TYPE_NAME)); FilterStringEquals equals = new FilterStringEquals(); string familyName = "Z-M2-MultilayerMaterialTag-LOD1"; string typeName = "2.5mm"; FilterRule fRule_1 = new FilterStringRule(pvp_1, equals, familyName, false); FilterRule fRule_2 = new FilterStringRule(pvp_2, equals, typeName, false); IList <FilterRule> fRules = new List <FilterRule> { fRule_1, fRule_2 }; ElementParameterFilter filters = new ElementParameterFilter(fRules); // Collect the familySymbol's id ICollection <ElementId> id = collector.WherePasses(categoryFilter).WherePasses(filters).ToElementIds(); if (id.Count == 0) { message = "No FamilyType has been detected."; return(Result.Failed); } AnnotationSymbolType materialTag = doc.GetElement(id.First()) as AnnotationSymbolType; 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); } }
protected override void SolveInstance(IGH_DataAccess DA) { var parameterId = ElementId.InvalidElementId; if (!DA.GetData("ParameterKey", ref parameterId)) { return; } DA.DisableGapLogic(); if (!TryGetParameterDefinition(Revit.ActiveDBDocument, parameterId, out var storageType, out var parameterType)) { if (parameterId.TryGetBuiltInParameter(out var builtInParameter)) { AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, $"Failed to found parameter '{LabelUtils.GetLabelFor(builtInParameter)}' in Revit document."); } else { AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, $"Failed to found parameter '{parameterId.IntegerValue}' in Revit document."); } return; } var provider = new ParameterValueProvider(parameterId); Autodesk.Revit.DB.FilterRule rule = null; if (storageType == StorageType.String) { FilterStringRuleEvaluator ruleEvaluator = null; switch (Condition) { case ConditionType.NotEquals: case ConditionType.Equals: ruleEvaluator = new FilterStringEquals(); break; case ConditionType.Greater: ruleEvaluator = new FilterStringGreater(); break; case ConditionType.GreaterOrEqual: ruleEvaluator = new FilterStringGreaterOrEqual(); break; case ConditionType.Less: ruleEvaluator = new FilterStringLess(); break; case ConditionType.LessOrEqual: ruleEvaluator = new FilterStringLessOrEqual(); break; } var goo = default(GH_String); if (DA.GetData("Value", ref goo)) { rule = new FilterStringRule(provider, ruleEvaluator, goo.Value, true); } } else { FilterNumericRuleEvaluator ruleEvaluator = null; switch (Condition) { case ConditionType.NotEquals: case ConditionType.Equals: ruleEvaluator = new FilterNumericEquals(); break; case ConditionType.Greater: ruleEvaluator = new FilterNumericGreater(); break; case ConditionType.GreaterOrEqual: ruleEvaluator = new FilterNumericGreaterOrEqual(); break; case ConditionType.Less: ruleEvaluator = new FilterNumericLess(); break; case ConditionType.LessOrEqual: ruleEvaluator = new FilterNumericLessOrEqual(); break; } switch (storageType) { case StorageType.Integer: { var goo = default(GH_Integer); if (DA.GetData("Value", ref goo)) { rule = new FilterIntegerRule(provider, ruleEvaluator, goo.Value); } } break; case StorageType.Double: { var goo = default(GH_Number); if (DA.GetData("Value", ref goo)) { if (Condition == ConditionType.Equals || Condition == ConditionType.NotEquals) { if (parameterType == ParameterType.Length || parameterType == ParameterType.Area || parameterType == ParameterType.Volume) { rule = new FilterDoubleRule(provider, ruleEvaluator, ToHost(goo.Value, parameterType), ToHost(Revit.VertexTolerance, parameterType)); } else { rule = new FilterDoubleRule(provider, ruleEvaluator, ToHost(goo.Value, parameterType), 1e-6); } } else { rule = new FilterDoubleRule(provider, ruleEvaluator, ToHost(goo.Value, parameterType), 0.0); } } } break; case StorageType.ElementId: { switch (parameterType) { case (ParameterType)int.MaxValue: // Category { var value = default(Types.Category); if (DA.GetData("Value", ref value)) { rule = new FilterElementIdRule(provider, ruleEvaluator, value); } } break; case ParameterType.FamilyType: { var value = default(Types.ElementType); if (DA.GetData("Value", ref value)) { rule = new FilterElementIdRule(provider, ruleEvaluator, value); } } break; default: { var value = default(Types.Element); if (DA.GetData("Value", ref value)) { rule = new FilterElementIdRule(provider, ruleEvaluator, value); } } break; } } break; } } if (rule is object) { if (Condition == ConditionType.NotEquals) { DA.SetData("Rule", new FilterInverseRule(rule)); } else { DA.SetData("Rule", rule); } } }