/// <summary> /// Finds all the views in the active document. /// </summary> /// <param name="doc">the active document</param> public static ViewSet GetAllViews (Document doc) { ViewSet allViews = new ViewSet(); FilteredElementCollector fec = new FilteredElementCollector(doc); ElementClassFilter elementsAreWanted = new ElementClassFilter(typeof(FloorType)); fec.WherePasses(elementsAreWanted); List<Element> elements = fec.ToElements() as List<Element>; foreach (Element element in elements) { Autodesk.Revit.DB.View view = element as Autodesk.Revit.DB.View; if (null == view) { continue; } else { ElementType objType = doc.GetElement(view.GetTypeId()) as ElementType; if (null == objType || objType.Name.Equals("Drawing Sheet")) { continue; } else { allViews.Insert(view); } } } return allViews; }
public void Level() { var model = dynSettings.Controller.DynamoModel; string samplePath = Path.Combine(_testPath, @".\Level\Level.dyn"); string testPath = Path.GetFullPath(samplePath); model.Open(testPath); Assert.DoesNotThrow(() => dynSettings.Controller.RunExpression(true)); //ensure that the level count is the same var levelColl = new FilteredElementCollector(dynRevitSettings.Doc.Document); levelColl.OfClass(typeof(Autodesk.Revit.DB.Level)); Assert.AreEqual(levelColl.ToElements().Count(), 6); //change the number and run again var numNode = (DoubleInput)dynRevitSettings.Controller.DynamoModel.Nodes.First(x => x is DoubleInput); numNode.Value = "0..20..2"; Assert.DoesNotThrow(() => dynSettings.Controller.RunExpression(true)); //ensure that the level count is the same levelColl = new FilteredElementCollector(dynRevitSettings.Doc.Document); levelColl.OfClass(typeof(Autodesk.Revit.DB.Level)); Assert.AreEqual(levelColl.ToElements().Count(), 11); }
public Result Execute( ExternalCommandData commandData, ref string message, ElementSet elements) { UIApplication app = commandData.Application; m_doc = app.ActiveUIDocument.Document; // filter for family instance and (door or window): ElementClassFilter fFamInstClass = new ElementClassFilter( typeof( FamilyInstance ) ); ElementCategoryFilter fDoorCat = new ElementCategoryFilter( BuiltInCategory.OST_Doors ); ElementCategoryFilter fWindowCat = new ElementCategoryFilter( BuiltInCategory.OST_Windows ); LogicalOrFilter fCat = new LogicalOrFilter( fDoorCat, fWindowCat ); LogicalAndFilter f = new LogicalAndFilter( fCat, fFamInstClass ); FilteredElementCollector openings = new FilteredElementCollector( m_doc ); openings.WherePasses( f ); // map with key = host element id and // value = list of hosted element ids: Dictionary<ElementId, List<ElementId>> ids = GetElementIds( openings ); DumpHostedElements( ids ); m_doc = null; return Result.Succeeded; }
private ProjectSettingsManager(Document document) { var col = new FilteredElementCollector(document).OfClass(typeof(ProjectInfo)); _element = col.ToElements().First(); _schema = Schema.Lookup(_schemaGuid) ?? GetStorageSchema(); //get entity from element if it exists in there already or create new otherwise _entity = _element.GetEntity(_schema); if (_entity == null || _entity.Schema == null) _entity = new Entity(_schema); LoadData(document); //static cache management Cache.Add(document, this); document.DocumentClosing += new EventHandler<DocumentClosingEventArgs>(OnDocumentClosing); document.Application.DocumentSynchronizedWithCentral += new EventHandler<DocumentSynchronizedWithCentralEventArgs>(OnDocumentSynchronized); document.Application.DocumentChanged += new EventHandler<DocumentChangedEventArgs>((sender, args) => { if (args.Operation == UndoOperation.TransactionUndone || args.Operation == UndoOperation.TransactionRedone) { } }); }
public void ReferenceCurve() { var model = dynSettings.Controller.DynamoModel; string samplePath = Path.Combine(_testPath, @".\ReferenceCurve\ReferenceCurve.dyn"); string testPath = Path.GetFullPath(samplePath); model.Open(testPath); dynSettings.Controller.RunExpression(true); FilteredElementCollector fec = new FilteredElementCollector(dynRevitSettings.Doc.Document); fec.OfClass(typeof(CurveElement)); //verify five model curves created int count = fec.ToElements().Count; Assert.IsInstanceOf(typeof(ModelCurve), fec.ToElements().First()); Assert.IsTrue(((ModelCurve)fec.ToElements().First()).IsReferenceLine); Assert.AreEqual(5, count); ElementId id = fec.ToElements().First().Id; //update any number node and verify //that the element gets updated not recreated var doubleNodes = dynSettings.Controller.DynamoModel.Nodes.Where(x => x is DoubleInput); var node = doubleNodes.First() as DoubleInput; Assert.IsNotNull(node); node.Value = node.Value + .1; dynSettings.Controller.RunExpression(true); Assert.AreEqual(5, fec.ToElements().Count); }
public void application_DocumentOpened(object sender, DocumentOpenedEventArgs args) { Document doc = args.Document; //add new parameter when a document opens Transaction transaction = new Transaction(doc, "Add PhaseGraphics"); if (transaction.Start() == TransactionStatus.Started) { var fileName = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), @"Autodesk\Revit\Addins\2012\PhaseSyncSharedParams.txt"); SetNewParameterToInstances(doc, fileName.ToString()); transaction.Commit(); } //sync phasegraphics param with Phases of all empty PhaseGraphics objects Transaction transaction2 = new Transaction(doc, "Sync PhaseGraphics"); ICollection<Element> types = null; if (transaction2.Start() == TransactionStatus.Started) { // Apply the filter to the elements in the active document FilteredElementCollector collector = new FilteredElementCollector(doc); types = collector.WherePasses(PhaseGraphicsTypeFilter()).ToElements(); foreach (Element elem in types) { //get the phasegraphics parameter from its guid if (elem.get_Parameter(new Guid(PhaseGraphicsGUID)).HasValue == false) { SyncPhaseGraphics(doc, elem); } } transaction2.Commit(); } }
/// <summary> /// Adds 1 to the mark of every column in the document /// </summary> /// <param name="commandData">the revit command data</param> /// <param name="message">a message to return</param> /// <param name="elements">Elements to display in a failed message dialog</param> /// <returns>Suceeded, Failed or Cancelled</returns> public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements) { //we want the 'database' document, which represents the Revit Model itself. Document dbDoc = commandData.Application.ActiveUIDocument.Document; //Use a FilteredElementCollector to get all the columns in the model. FilteredElementCollector collector = new FilteredElementCollector(dbDoc); //for this, we use a Category Filter which finds all elements in the Column category ElementCategoryFilter columnFilter = new ElementCategoryFilter(BuiltInCategory.OST_Columns); //structural columns have a different category ElementCategoryFilter structuralColumnFilter =new ElementCategoryFilter(BuiltInCategory.OST_StructuralColumns); //to get elements that match either of these categories, we us a logical 'Or' filter. LogicalOrFilter orFilter = new LogicalOrFilter(columnFilter, structuralColumnFilter); //you can then get these elements as a list. //we also specify WhereElementIsNotElementType() so that we don't get FamilySymbols IList<Element> allColumns = collector.WherePasses(orFilter).WhereElementIsNotElementType().ToElements(); string results = "Updated Marks For : " + Environment.NewLine; //loop through this list and update the mark foreach (Element element in allColumns) { UpdateMark(element); results += element.Id + Environment.NewLine; } TaskDialog.Show("Updated Elements", results); return Result.Succeeded; }
/// <summary> /// Default constructor /// </summary> /// <param name="doc"></param> /// <param name="spaceReference"></param> public RoomSpace(Document doc, Reference spaceReference) { m_doc = doc; LightFixtures = new List<LightFixture>(); Space refSpace = m_doc.GetElement(spaceReference) as Space; // Set properties of newly create RoomSpace object from Space AverageEstimatedIllumination = refSpace.AverageEstimatedIllumination; Area = refSpace.Area; CeilingReflectance = refSpace.CeilingReflectance; FloorReflectance = refSpace.FloorReflectance; WallReflectance = refSpace.WallReflectance; CalcWorkPlane = refSpace.LightingCalculationWorkplane; ParentSpaceObject = refSpace; // Populate light fixtures list for RoomSpace FilteredElementCollector fec = new FilteredElementCollector(m_doc) .OfCategory(BuiltInCategory.OST_LightingFixtures) .OfClass(typeof(FamilyInstance)); foreach (FamilyInstance fi in fec) { if (fi.Space.Id == refSpace.Id) { ElementId eID = fi.GetTypeId(); Element e = m_doc.GetElement(eID); //TaskDialog.Show("C","LF: SPACEID " + fi.Space.Id.ToString() + "\nSPACE ID: " + refSpace.Id.ToString()); LightFixtures.Add(new LightFixture(e,fi)); } } }
public static IEnumerable<ViewSchedule> GetSchedules(this ViewSheet viewSheet) { var doc = viewSheet.Document; FilteredElementCollector collector = new FilteredElementCollector(doc, viewSheet.Id); var scheduleSheetInstances = collector .OfClass(typeof(ScheduleSheetInstance)) .ToElements() .OfType<ScheduleSheetInstance>(); foreach (var scheduleSheetInstance in scheduleSheetInstances) { var scheduleId = scheduleSheetInstance .ScheduleId; if (scheduleId == ElementId.InvalidElementId) continue; var viewSchedule = doc.GetElement(scheduleId) as ViewSchedule; if (viewSchedule != null) yield return viewSchedule; } }
//third exervise put into a user interface public static void updateDoor(Document doc, UIDocument uidoc) { //creates a Collection of the doors as FamilyInstances var doorColl = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Doors) .OfClass(typeof(FamilyInstance)); //Uses linq queries to select the door that have a ToRoom Value IEnumerable<FamilyInstance> doors = from FamilyInstance f in doorColl where f.ToRoom != null select f; //Start the transaction CRITICAL without transactions Revit cannot update using (Transaction t = new Transaction(doc, "Door Data Update")) { //Starts the transction t.Start(); //goes through each door based on the filter above foreach (FamilyInstance e in doors) { //gets the ToRoom number as a string string doorToRoom = e.ToRoom.Number.ToString(); //updates the comments parameter to the ToRoom value e.get_Parameter(BuiltInParameter.ALL_MODEL_INSTANCE_COMMENTS).Set(doorToRoom); } //Commits the changes to the Revit File t.Commit(); } }
GetAllSheets (Document doc) { ElementSet allSheets = new ElementSet(); FilteredElementCollector fec = new FilteredElementCollector(doc); ElementClassFilter elementsAreWanted = new ElementClassFilter(typeof(ViewSheet)); fec.WherePasses(elementsAreWanted); List<Element> elements = fec.ToElements() as List<Element>; foreach (Element element in elements) { ViewSheet viewSheet = element as ViewSheet; if (null == viewSheet) { continue; } else { ElementId objId = viewSheet.GetTypeId(); if (ElementId.InvalidElementId == objId) { continue; } else { allSheets.Insert(viewSheet); } } } return allSheets; }
public Result Execute( ExternalCommandData commandData, ref string message, ElementSet elements) { var doc = commandData.Application .ActiveUIDocument.Document; var fillPatternElements = new FilteredElementCollector( doc ) .OfClass( typeof( FillPatternElement ) ) .OfType<FillPatternElement>() .OrderBy( fp => fp.Name ) .ToList(); var fillPatterns = fillPatternElements.Select( fpe => fpe.GetFillPattern() ); FillPatternsViewModel fillPatternsViewModel = new FillPatternsViewModel( fillPatterns .Select( x => new FillPatternViewModel( x ) ) ); FillPatternsView fillPatternsView = new FillPatternsView() { DataContext = fillPatternsViewModel }; fillPatternsView.ShowDialog(); return Result.Succeeded; }
Execute () { //Get every level by iterating through all elements systemLevelsData = new List<LevelsDataSource>(); FilteredElementCollector fec = new FilteredElementCollector(m_app.ActiveUIDocument.Document); ElementClassFilter elementsAreWanted = new ElementClassFilter(typeof(Level)); fec.WherePasses(elementsAreWanted); List<Element> elements = fec.ToElements() as List<Element>; foreach (Element element in elements) { Level systemLevel = element as Level; if (systemLevel != null) { LevelsDataSource levelsDataSourceRow = new LevelsDataSource(); levelsDataSourceRow.LevelIDValue = systemLevel.Id.IntegerValue; levelsDataSourceRow.Name = systemLevel.Name; levelsDataSourceRow.Elevation = systemLevel.Elevation; systemLevelsData.Add(levelsDataSourceRow); } } LevelsForm displayForm = new LevelsForm(this); displayForm.ShowDialog(); return true; }
public void changeFamiliesNames(Document doc) { //Gets the families Family familyNames = null; FilteredElementCollector collector = new FilteredElementCollector(doc); ICollection<Element> collection = collector.OfClass(typeof(Family)).ToElements(); ValueDictionary dictionaryList = new ValueDictionary(); var dictionary = dictionaryList.GetRenameFamilies(); using (Transaction t = new Transaction(doc)) { t.Start("new name"); foreach (Element e in collection) { familyNames = e as Family; string familyName = familyNames.Name; //Checks the dictionary and if found renames the family if (dictionary.ContainsKey(familyName)) { string value = dictionary[familyName]; familyNames.Name = value; count++; } } t.Commit(); string message = "Number of Families Renamed: "; MessageBox.Show(message + count.ToString()); } }
/// <summary> /// populate with element types from active doc /// </summary> private void InitializeTreeView() { FilteredElementCollector coll = new FilteredElementCollector(m_app.ActiveUIDocument.Document); coll.WherePasses(new LogicalOrFilter(new ElementIsElementTypeFilter(false), new ElementIsElementTypeFilter(true))); FilteredElementIterator elemIter = coll.GetElementIterator(); //ElementIterator elemIter = m_app.ActiveUIDocument.Document.Elements; ArrayList elemTypes = new ArrayList(); /// collect all unique elem types while (elemIter.MoveNext()) { /// if this elem type is already accounted for, ignore it if (elemTypes.Contains(elemIter.Current.GetType())) continue; else { elemTypes.Add(elemIter.Current.GetType()); } } /// populate tree with elem types foreach (Type type in elemTypes) { TreeNode treeNode = new TreeNode(type.Name); treeNode.Tag = type; m_treeView.Nodes.Add(treeNode); } /// sort the tree m_treeView.TreeViewNodeSorter = new TreeSorter(); m_treeView.Sort(); }
public void deleteLinePatterns(Document doc) { var collector = new FilteredElementCollector(doc) .OfClass(typeof(LinePatternElement)).Where(i => i.Name.StartsWith("IMPORT")).ToList(); List<ElementId> ids = new List<ElementId>(); for (int i = 0; i < collector.Count(); i++) { ids.Add(collector[i].Id); } using (Transaction t = new Transaction(doc, "Remove Pattern")) { t.Start(); try { doc.Delete(ids); } catch (Exception) { t.RollBack(); return; } t.Commit(); } }
private void Form1_Load(object sender, EventArgs e) { //read from exportOptions for project if (Helpers.GetExportOptionsInfo(m_doc, m_neo)) { // lblFolderPath.Text = Options._folderExport; FilteredElementCollector fec = new FilteredElementCollector(m_doc).OfClass(typeof(View3D)); foreach (Element elem in fec) { View3D v = elem as View3D; cbViewList.Items.Add(v); } cbViewList.DisplayMember = "ViewName"; //Set selection to property //cbViewList.SelectedItem = selectedView; cbViewList.Text = Options._exportView.Name; } else this.DialogResult = System.Windows.Forms.DialogResult.Cancel; }
/// <summary> /// Set a Revit Curtain Panel /// </summary> /// <param name="setCurtainPanel"></param> /// <returns></returns> public static Element Create(this Grevit.Types.SetCurtainPanel setCurtainPanel) { // If there arent any valid properties return null if (setCurtainPanel.panelID == 0 || setCurtainPanel.panelType == "") return null; // Get the panel to change Panel panel = (Panel)GrevitCommand.document.GetElement(new ElementId(setCurtainPanel.panelID)); // get its host wall Element wallElement = panel.Host; if (wallElement.GetType() == typeof(Autodesk.Revit.DB.Wall)) { // Cast the Wall Autodesk.Revit.DB.Wall wall = (Autodesk.Revit.DB.Wall)wallElement; // Try to get the curtain panel type FilteredElementCollector collector = new FilteredElementCollector(GrevitCommand.document).OfClass(typeof(PanelType)); Element paneltype = collector.FirstElement(); foreach (Element em in collector.ToElements()) if (em.Name == setCurtainPanel.panelType) paneltype = em; // Cast the Element type ElementType type = (ElementType)paneltype; // Change the panel type wall.CurtainGrid.ChangePanelType(panel, type); } return panel; }
public void CanChangeLacingAndHaveElementsUpdate() { string samplePath = Path.Combine(_testPath, @".\Core\LacingTest.dyn"); string testPath = Path.GetFullPath(samplePath); Controller.DynamoViewModel.OpenCommand.Execute(testPath); var xyzNode = dynSettings.Controller.DynamoModel.Nodes.First(x => x.NickName == "Point.ByCoordinates"); Assert.IsNotNull(xyzNode); //test the shortest lacing xyzNode.ArgumentLacing = LacingStrategy.Shortest; dynSettings.Controller.RunExpression(true); var fec = new FilteredElementCollector((Autodesk.Revit.DB.Document)DocumentManager.Instance.CurrentDBDocument); fec.OfClass(typeof(ReferencePoint)); Assert.AreEqual(4, fec.ToElements().Count()); //test the longest lacing xyzNode.ArgumentLacing = LacingStrategy.Longest; dynSettings.Controller.RunExpression(true); fec = null; fec = new FilteredElementCollector((Autodesk.Revit.DB.Document)DocumentManager.Instance.CurrentDBDocument); fec.OfClass(typeof(ReferencePoint)); Assert.AreEqual(5, fec.ToElements().Count()); //test the cross product lacing xyzNode.ArgumentLacing = LacingStrategy.CrossProduct; dynSettings.Controller.RunExpression(true); fec = null; fec = new FilteredElementCollector((Autodesk.Revit.DB.Document)DocumentManager.Instance.CurrentDBDocument); fec.OfClass(typeof(ReferencePoint)); Assert.AreEqual(20, fec.ToElements().Count()); }
public void LinePatternViewer() { LPMainWindow main_win = null; try { Document theDoc = this.ActiveUIDocument.Document; System.Collections.ObjectModel.ObservableCollection<LinePattern> data = new System.Collections.ObjectModel.ObservableCollection<LinePattern>(); //Collect all line pattern elements FilteredElementCollector collector = new FilteredElementCollector(theDoc); IList<Element> linepatternelements = collector.WherePasses(new ElementClassFilter(typeof(LinePatternElement))).ToElements(); foreach (LinePatternElement lpe in linepatternelements) { data.Add(lpe.GetLinePattern()); } //start main window main_win = new LinePatternMacro.LPMainWindow(data); System.Windows.Interop.WindowInteropHelper x = new System.Windows.Interop.WindowInteropHelper(main_win); x.Owner = Process.GetCurrentProcess().MainWindowHandle; main_win.ShowDialog(); } catch (Exception err) { Debug.WriteLine(new string('*', 100)); Debug.WriteLine(err.ToString()); Debug.WriteLine(new string('*', 100)); if (main_win != null && main_win.IsActive) main_win.Close(); } }
public static Tuple<Face, Reference> GetClosestFace(Document document, XYZ p) { Face resultFace = null; Reference resultReference = null; double min_distance = double.MaxValue; FilteredElementCollector collector = new FilteredElementCollector(document); var walls = collector.OfClass(typeof (Wall)); foreach (Wall wall in walls) { IList<Reference> sideFaces = HostObjectUtils.GetSideFaces(wall, ShellLayerType.Interior); // access the side face Face face = document.GetElement(sideFaces[0]).GetGeometryObjectFromReference(sideFaces[0]) as Face; var intersection = face.Project(p); if (intersection != null) { if (intersection.Distance < min_distance) { resultFace = face; resultReference = sideFaces[0]; min_distance = intersection.Distance; } } } //resultFace. return new Tuple<Face,Reference>( resultFace, resultReference); }
public void Execute(UIDocument uiDocument, object data) { var filter = data as string; if (null == filter) return; var family = "TestAnno"; var parameters = new[] {"Series", "Number", "Text"}; var document = uiDocument.Document; var schedule = new FilteredElementCollector(document).OfClass(typeof (ViewSchedule)) .FirstOrDefault(s => s.Name.Contains(filter)); Element schedElem = null; using (var t = new Transaction(document)) { t.Start("Place schedule"); if (null == schedule) schedule = Schedule.Factory(uiDocument.Document, family, parameters, filter); schedElem = ScheduleSheetInstance.Create(uiDocument.Document, uiDocument.ActiveView.Id, schedule.Id, new XYZ()); t.Commit(); } uiDocument.Selection.SetElementIds(new List<ElementId>() { schedElem.Id }); //var uiapp = new UIApplication(document.Application); //uiapp.PostCommand(RevitCommandId.LookupCommandId("ID_EDIT_MOVE")); //uiDocument.PromptToPlaceViewOnSheet(schedule, false); }
public void DividedSurface() { var model = ViewModel.Model; string samplePath = Path.Combine(workingDirectory, @".\DividedSurface\DividedSurface.dyn"); string testPath = Path.GetFullPath(samplePath); ViewModel.OpenCommand.Execute(testPath); ViewModel.Model.RunExpression(); FilteredElementCollector fec = new FilteredElementCollector(DocumentManager.Instance.CurrentUIDocument.Document); fec.OfClass(typeof(DividedSurface)); //did it create a divided surface? Assert.AreEqual(1, fec.ToElements().Count()); var ds = (DividedSurface)fec.ToElements()[0]; Assert.AreEqual(5, ds.USpacingRule.Number); Assert.AreEqual(5, ds.VSpacingRule.Number); //can we change the number of divisions var numNode = ViewModel.Model.Nodes.OfType<DoubleInput>().First(); numNode.Value = "10"; ViewModel.Model.RunExpression(); //did it create a divided surface? Assert.AreEqual(10, ds.USpacingRule.Number); Assert.AreEqual(10, ds.VSpacingRule.Number); //ensure there is a warning when we try to set a negative number of divisions numNode.Value = "-5"; ViewModel.Model.RunExpression(); Assert.Greater(ViewModel.Model.EngineController.LiveRunnerCore.RuntimeStatus.WarningCount, 0); }
public void TestOne() { using (var t = new Transaction(DocumentManager.Instance.CurrentDBDocument)) { if (t.Start("Test one.") == TransactionStatus.Started) { //create a reference point var pt = DocumentManager.Instance.CurrentDBDocument.FamilyCreate.NewReferencePoint(new XYZ(5, 5, 5)); if (t.Commit() != TransactionStatus.Committed) { t.RollBack(); } } else { throw new Exception("Transaction could not be started."); } } //verify that the point was created var collector = new FilteredElementCollector(DocumentManager.Instance.CurrentDBDocument); collector.OfClass(typeof (ReferencePoint)); Assert.AreEqual(1, collector.ToElements().Count); }
private static IEnumerable<Parameter> GetInstanceParams(Document document, string familyName, IEnumerable<string> paramNames) { var collector = new FilteredElementCollector(document); var instances = collector.OfCategory(BuiltInCategory.OST_GenericAnnotation) .WhereElementIsNotElementType() .ToElements() .ToList(); var sheetNoteInst = instances.FirstOrDefault(i => i.Name == familyName); if (null == sheetNoteInst) return null; var familyParams = sheetNoteInst.Parameters; var scheduleParams = familyParams .OfType<Parameter>() .Where(p => paramNames.Any(n => n == p.Definition.Name)); return scheduleParams; }
public Result Execute( ExternalCommandData commandData, ref string message, ElementSet elements) { Document doc = commandData.Application .ActiveUIDocument.Document; FilteredElementCollector collector = new FilteredElementCollector( doc ); collector.OfClass( typeof( Level ) ); Level level = collector.FirstElement() as Level; Transaction t = new Transaction( doc ); t.Start( "Create unbounded room" ); FailureHandlingOptions failOpt = t.GetFailureHandlingOptions(); failOpt.SetFailuresPreprocessor( new RoomWarningSwallower() ); t.SetFailureHandlingOptions( failOpt ); doc.Create.NewRoom( level, new UV( 0, 0 ) ); t.Commit(); return Result.Succeeded; }
/// <summary> /// Bind to combobox's DropDownOpened Event, add new levels that created by user. /// </summary> /// <param name="evnetArgs">Autodesk.Revit.UI.Events.ComboBoxDropDownOpenedEventArgs</param> public void AddNewLevels(object sender, ComboBoxDropDownOpenedEventArgs args) { Autodesk.Revit.UI.ComboBox comboboxLevel = sender as Autodesk.Revit.UI.ComboBox; if (null == comboboxLevel) { return; } FilteredElementCollector collector = new FilteredElementCollector(uiApplication.ActiveUIDocument.Document); ICollection<Element> founds = collector.OfClass(typeof(Level)).ToElements(); foreach (Element elem in founds) { Level level = elem as Level; bool alreadyContained = false; foreach (ComboBoxMember comboboxMember in comboboxLevel.GetItems()) { if (comboboxMember.Name == level.Name) { alreadyContained = true; } } if (!alreadyContained) { ComboBoxMemberData comboBoxMemberData = new ComboBoxMemberData(level.Name, level.Name); ComboBoxMember comboboxMember = comboboxLevel.AddItem(comboBoxMemberData); comboboxMember.Image = new BitmapImage(new Uri(Path.Combine(ButtonIconsFolder, "LevelsSelector.png"), UriKind.Absolute)); } } }
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 { if (!doc.IsWorkshared) { TaskDialog.Show("Workset 3D View", "Project doesn't have any Worksets."); } else { ViewFamilyType vft = new FilteredElementCollector(doc) .OfClass(typeof(ViewFamilyType)) .Cast<ViewFamilyType>() .FirstOrDefault(q => q.ViewFamily == ViewFamily.ThreeDimensional); using (Transaction t = new Transaction(doc, "Workset View Creation")) { t.Start(); int i = 0; // Loop through all User Worksets only foreach (Workset wst in new FilteredWorksetCollector(doc) .WherePasses(new WorksetKindFilter(WorksetKind.UserWorkset))) { // Create a 3D View View3D view = View3D.CreateIsometric(doc, vft.Id); // Set the name of the view to match workset view.Name = "WORKSET - " + wst.Name; // Isolate elements in the view using a filter to find elements only in this workset view.IsolateElementsTemporary(new FilteredElementCollector(doc) .WherePasses(new ElementWorksetFilter(wst.Id)) .Select(q => q.Id) .ToList()); i++; } t.Commit(); TaskDialog.Show("Workset 3D View", i.ToString() + " Views Created Successfully!"); } } return Result.Succeeded; } catch (Autodesk.Revit.Exceptions.OperationCanceledException) { return Result.Cancelled; } catch (Exception ex) { message = ex.Message; return Result.Failed; } }
/// <summary> /// Get saved addresses in Storage. Currently only one address is supported /// </summary> /// <param name="document">The document storing the saved address.</param> /// <param name="schema">The schema for address.</param> /// <returns>List of stored addresses</returns> private IList<DataStorage> GetAddressInStorage(Document document, Schema schema) { FilteredElementCollector collector = new FilteredElementCollector(document); collector.OfClass(typeof(DataStorage)); Func<DataStorage, bool> hasTargetData = ds => (ds.GetEntity(schema) != null && ds.GetEntity(schema).IsValid()); return collector.Cast<DataStorage>().Where<DataStorage>(hasTargetData).ToList<DataStorage>(); }
/// <summary> /// Looks at a way to get to the more specific family types with a given name. /// </summary> public void FindFamilyType() { // In this exercise, we will look for the following family types for wall and door // Hard coding for similicity. modify here if you want to try out with other family types. // Constant to this function. // This is for wall. e.g., "Basic Wall: Generic - 200mm" const string wallFamilyName = Util.Constant.WallFamilyName; const string wallTypeName = Util.Constant.WallTypeName; const string wallFamilyAndTypeName = wallFamilyName + ": " + wallTypeName; // This is for door. e.g., "M_Single-Flush: 0915 x 2134mm const string doorFamilyName = Util.Constant.DoorFamilyName; const string doorTypeName = Util.Constant.DoorTypeName; const string doorFamilyAndTypeName = doorFamilyName + ": " + doorTypeName; // Keep messages to the user in this function. string msg = "Find Family Type - All:\r\n\r\n"; // (1) Get a specific system family type. e.g., wall type. // There are a few different ways to do this. // (1.1) First version uses LINQ query. ElementType wallType1 = (ElementType)FindFamilyType_Wall_v1(wallFamilyName, wallTypeName); // Show the result. msg += ShowFamilyTypeAndId("Find wall family type (using LINQ): ", wallFamilyAndTypeName, wallType1) + "\r\n"; // (1.2) Another way is to use iterator. (cf. look for example, Developer guide 87) ElementType wallType2 = (ElementType)FindFamilyType_Wall_v2(wallFamilyName, wallTypeName); msg += ShowFamilyTypeAndId("Find wall family type (using iterator): ", wallFamilyAndTypeName, wallType2) + "\r\n"; // (1.3) The most efficient method is to use a parameter filter, since // this avoids mashalling and transporting all the data for the rejected // results from the internal Revit memory to the external .NET space: ElementType wallType3 = FindFamilyType_Wall_v3( wallFamilyName, wallTypeName) as ElementType; msg += ShowFamilyTypeAndId("Find wall family type (using parameter filter): ", wallFamilyAndTypeName, wallType2) + "\r\n"; // (2) Get a specific component family type. e.g., door type. // // (2.1) Similar approach as (1.1) using LINQ. ElementType doorType1 = (ElementType)FindFamilyType_Door_v1(doorFamilyName, doorTypeName); msg += ShowFamilyTypeAndId("Find door type (using LINQ): ", doorFamilyAndTypeName, doorType1) + "\r\n"; // (2.2) Get a specific door type. The second approach. // Another approach will be to look up from Family, then from Family.Symbols property. // This gets more complicated although it is logical approach. ElementType doorType2 = (ElementType)FindFamilyType_Door_v2(doorFamilyName, doorTypeName); msg += ShowFamilyTypeAndId("Find door type (using Family): ", doorFamilyAndTypeName, doorType2) + "\r\n"; // (3) Here is more generic form. defining a more generalized function below. // // (3.1) For the wall type ElementType wallType4 = (ElementType)FindFamilyType(_doc, typeof(WallType), wallFamilyName, wallTypeName, null); msg += ShowFamilyTypeAndId("Find wall type (using generic function): ", wallFamilyAndTypeName, wallType4) + "\r\n"; // (3.2) For the door type. ElementType doorType3 = (ElementType)FindFamilyType(_doc, typeof(FamilySymbol), doorFamilyName, doorTypeName, BuiltInCategory.OST_Doors); msg += ShowFamilyTypeAndId("Find door type (using generic function): ", doorFamilyAndTypeName, doorType3) + "\r\n"; // (3.3) Simply return the first wall and door type encountered, so we do // not have to worry about setting up its family and symbol name // correctly: ElementType wallType5 = new FilteredElementCollector(_doc) .WhereElementIsElementType() // superfluous, because WallType is derived from ElementType .OfClass(typeof(WallType)) .OfCategory(BuiltInCategory.OST_Walls) // superfluous, because al WallType instances have this category .FirstElement() as ElementType; msg += ShowFamilyTypeAndId("Find first wall type (using generic function): ", wallType5.Name, wallType5) + "\r\n"; ElementType doorType4 = GetFirstFamilySymbol(_doc, BuiltInCategory.OST_Doors) as ElementType; msg += ShowFamilyTypeAndId("Find first door type (using generic function): ", doorType4.Name, doorType4) + "\r\n"; // Finally, show the result all together TaskDialog.Show("Find family types", msg); }
public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements) { //Pegar uidoc e doc UIDocument uidoc = commandData.Application.ActiveUIDocument; Document doc = uidoc.Document; try { //Filtro para pegar apenas vergalhões ISelectionFilter selectionFilter = new vergalhaoSelectionFilter(); //Pegar elemento Reference pickedObj = uidoc.Selection.PickObject(ObjectType.Element, selectionFilter, "Selecione uma vergalhão"); ElementId eleId = pickedObj.ElementId; Element ele = doc.GetElement(eleId); Rebar rebar = ele as Rebar; //Pega o elemento selecionado como um vergalhão //Pegar o o ospedeiro do elemento ElementId hostId = rebar.GetHostId(); Element hostEle = doc.GetElement(hostId); //Pegar a vista ativa e criar um plano com base em sua origem e direção View view = doc.ActiveView; ViewType viewType = view.ViewType; XYZ origem = view.Origin; XYZ direcao = view.ViewDirection; Plane plano = Plane.CreateByNormalAndOrigin(direcao, origem); //Forma do vergalhão ElementId shapeId = rebar.GetShapeId(); ElementType shape = doc.GetElement(shapeId) as ElementType; //Cria o nome da família do item de detalhe, "Detalhe vergalhão 01", "Detalhe vergalhão 22", etc String shapeName = "Detalhe vergalhão " + shape.Name; //Dimensões do vergalhão, adicionar outras conforme for evoluindo, servirão para alterar a família de item de detalhe Double dA = ele.LookupParameter("A").AsDouble(); Double dB = ele.LookupParameter("B").AsDouble(); using (Transaction trans = new Transaction(doc, "Criar elemento")) { trans.Start(); //Variável para guardar o sketchplane SketchPlane sketchPlane; //Pegar o SketchPlane de acordo com o tipo de vista, se for elevação ou corte o SketchPlane será a partir do plano criado anteriormente if (viewType == ViewType.Elevation || viewType == ViewType.Section) { sketchPlane = SketchPlane.Create(doc, plano); } else { sketchPlane = view.SketchPlane; } //Define o SketchPlane da vista view.SketchPlane = sketchPlane; //Procura a família de item de detalhe com base no nome e ativa o mesmo FilteredElementCollector collector = new FilteredElementCollector(doc); IList <Element> symbols = collector.OfClass(typeof(FamilySymbol)).WhereElementIsElementType().ToElements(); FamilySymbol symbol = null; foreach (Element elem in symbols) { if (elem.Name == shapeName) { symbol = elem as FamilySymbol; break; } } if (!symbol.IsActive) { symbol.Activate(); } //Pega o ponto selecionado XYZ pickedPoint = uidoc.Selection.PickPoint(); //Cria o item de detalhe no ponto e define seus parâmetros FamilyInstance familyInstance = doc.Create.NewFamilyInstance(pickedPoint, symbol, view); familyInstance.LookupParameter("A").Set(dA); familyInstance.LookupParameter("B").Set(dB); trans.Commit(); } return(Result.Succeeded); } catch (Exception e) { message = e.Message; return(Result.Failed); } }
/// <summary> /// Find a specific family type for a door. /// another approach will be to look up from Family, then from Family.Symbols property. /// This gets more complicated although it is logical approach. /// </summary> public Element FindFamilyType_Door_v2(string doorFamilyName, string doorTypeName) { // (1) find the family with the given name. var familyCollector = new FilteredElementCollector(_doc); familyCollector.OfClass(typeof(Family)); // Use the iterator Family doorFamily = null; FilteredElementIterator familyItr = familyCollector.GetElementIterator(); //familyItr.Reset(); while ((familyItr.MoveNext())) { Family fam = (Family)familyItr.Current; // Check name and categoty if ((fam.Name == doorFamilyName) & (fam.FamilyCategory.Id.IntegerValue == (int)BuiltInCategory.OST_Doors)) { // We found the family. doorFamily = fam; break; } } // (2) Find the type with the given name. Element doorType2 = null; // Id of door type we are looking for. if (doorFamily != null) { // If we have a family, then proceed with finding a type under Symbols property. //FamilySymbolSet doorFamilySymbolSet = doorFamily.Symbols; // 'Autodesk.Revit.DB.Family.Symbols' is obsolete: // 'This property is obsolete in Revit 2015. Use Family.GetFamilySymbolIds() instead.' // Iterate through the set of family symbols. //FamilySymbolSetIterator doorTypeItr = doorFamilySymbolSet.ForwardIterator(); //while (doorTypeItr.MoveNext()) //{ // FamilySymbol dType = (FamilySymbol)doorTypeItr.Current; // if ((dType.Name == doorTypeName)) // { // doorType2 = dType; // Found it. // break; // } //} /// Following part is modified code for Revit 2015 ISet <ElementId> familySymbolIds = doorFamily.GetFamilySymbolIds(); if (familySymbolIds.Count > 0) { // Get family symbols which is contained in this family foreach (ElementId id in familySymbolIds) { FamilySymbol dType = doorFamily.Document.GetElement(id) as FamilySymbol; if ((dType.Name == doorTypeName)) { doorType2 = dType; // Found it. break; } } } /// End of modified code for Revit 2015 } return(doorType2); }
/// <summary> /// Toggle back and forth between two different documents /// </summary> void ToggleViews( View view1, string filepath2) { Document doc = view1.Document; UIDocument uidoc = new UIDocument(doc); Application app = doc.Application; UIApplication uiapp = new UIApplication(app); // Select some elements in the first document ICollection <ElementId> idsView1 = new FilteredElementCollector(doc, view1.Id) .WhereElementIsNotElementType() .ToElementIds(); // Open the second file UIDocument uidoc2 = uiapp .OpenAndActivateDocument(filepath2); Document doc2 = uidoc2.Document; // Do something in second file using (Transaction tx = new Transaction(doc2)) { tx.Start("Change Scale"); doc2.ActiveView.get_Parameter( BuiltInParameter.VIEW_SCALE_PULLDOWN_METRIC) .Set(20); tx.Commit(); } // Save modified second file SaveAsOptions opt = new SaveAsOptions { OverwriteExistingFile = true }; doc2.SaveAs(filepath2, opt); // Switch back to original file; // in a new file, doc.PathName is empty if (!string.IsNullOrEmpty(doc.PathName)) { uiapp.OpenAndActivateDocument( doc.PathName); doc2.Close(false); // no problem here, says Remy } else { // Avoid using OpenAndActivateDocument uidoc.ShowElements(idsView1); uidoc.RefreshActiveView(); //doc2.Close( false ); // Remy says: Revit throws the exception and doesn't close the file } }
public static void PipeElementMYSQLPara(Document doc, FilteredElementCollector ductCollector, System.Data.DataTable dt) { foreach (Element ele in ductCollector) { Pipe pipe = ele as Pipe; Level level = level = doc.GetElement(pipe.LevelId) as Level; if (pipe != null) { string Olev = null; string shuidui = null; string chuizhidui = null; double offset = 0.0; string slope = null; string type = null; string guanduan = null; string r = null; foreach (Parameter param in pipe.Parameters) { InternalDefinition definition = null; definition = param.Definition as InternalDefinition; if (null == definition) { continue; } if (BuiltInParameter.RBS_START_LEVEL_PARAM == definition.BuiltInParameter) { Olev = param.AsValueString(); } if (BuiltInParameter.RBS_CURVE_HOR_OFFSET_PARAM == definition.BuiltInParameter) { shuidui = param.AsValueString(); } if (BuiltInParameter.RBS_CURVE_VERT_OFFSET_PARAM == definition.BuiltInParameter) { chuizhidui = param.AsValueString(); } if (BuiltInParameter.RBS_OFFSET_PARAM == definition.BuiltInParameter) { offset = param.AsDouble(); } if (BuiltInParameter.RBS_PIPE_SLOPE == definition.BuiltInParameter) { slope = param.AsValueString(); } if (BuiltInParameter.RBS_PIPING_SYSTEM_TYPE_PARAM == definition.BuiltInParameter) { type = param.AsValueString(); } if (BuiltInParameter.RBS_PIPE_SEGMENT_PARAM == definition.BuiltInParameter) { guanduan = param.AsValueString(); } if (BuiltInParameter.RBS_PIPE_DIAMETER_PARAM == definition.BuiltInParameter) { r = param.AsValueString(); } } CreatePipeMySQLRow(dt, pipe.PipeType.Name, Olev, shuidui, chuizhidui, FeetTomm(offset), slope, type, guanduan, r ); } } }
/// <summary> /// Obtain all elements of a given type from the current document /// </summary> /// <typeparam name="T"></typeparam> /// <returns></returns> public IEnumerable <T> ElementsOfType <T>() where T : Element { var fec = new FilteredElementCollector(CurrentDBDocument); return(fec.OfClass(typeof(T)).Cast <T>()); }
private void BtnCreateSpaces_Click(object sender, RoutedEventArgs e) { //Use a Try block to keep any errors from crashing Revit try { //Integer variable to count the number of Spaces Created int count = 0; //Create a new Dictionary to hold Levels and Level Names, then populate with Element Collector Dictionary <string, Level> levels = new Dictionary <string, Level>(); using (FilteredElementCollector fecLevels = new FilteredElementCollector(doc).OfClass(typeof(Level))) { foreach (Level level in fecLevels.ToElements()) { levels.Add(level.Name, level); } } //Use a bool switch if there are levels not found bool missingLevels = false; int missingCount = 0; //Get the Link Document by casting the Selected Value of the Combo Box to a Document RevitLinkInstance rvtLinkInstance = (RevitLinkInstance)ComboBoxLinks.SelectedValue; //Get the Transform for the Link Instance to position the spaces relative to any Transformation of the link instance Transform LinkTransform = rvtLinkInstance.GetTotalTransform(); //Use a Transaction for the Document you are creating spaces in using (Transaction trans = new Transaction(doc)) { //Start the transaction and give it a name for the Undo / Redo list trans.Start("Create Spaces from Rooms"); //Loop through each of the Checked Items (rooms) in the List view to copy foreach (ElementIdName Room in LinkedRooms) { if (Room.Check) { //Cast the Room from the ListView and Linked Document Room LinkedRoom = (Room)linkDoc.GetElement(Room.ElemId); //Get the location of the Linked Room to place the Space LocationPoint roomLocationPoint = LinkedRoom.Location as LocationPoint; //Try and get the level from the current document with the same name as the Linked Document if (levels.TryGetValue(LinkedRoom.Level.Name, out Level level)) { //If a level with the same name is found, create the new Space from that level and transformed room location Space space = doc.Create.NewSpace(level, new UV(LinkTransform.OfPoint(roomLocationPoint.Point).X, LinkTransform.OfPoint(roomLocationPoint.Point).Y)); //Set the Name and Number of the space to match the room it cam from. space.Name = LinkedRoom.get_Parameter(BuiltInParameter.ROOM_NAME).AsString(); space.Number = LinkedRoom.Number; count++; } else { //If the level can't be found, change the bool switch missingLevels = true; missingCount++; } } } //Commit the transaction to save the changed to the document trans.Commit(); } //Tell the user how many spaces were created or missed if (!missingLevels) { TaskDialog.Show("Create Spaces", "Created " + count + " Spaces"); } else { TaskDialog.Show("Create Spaces", "Created " + count + " Spaces\n\nCorresponding Level not found for " + missingCount + " Spaces"); } //Set the Dialog Result so that the calling Method resturns the correct result and the changes stick DialogResult = true; //Close the form Close(); } //Display a message that an error occured when trying to create Spaces, set the Dialog Result, and close the form. catch (Exception ex) { TaskDialog.Show("Create Spaces Error", ex.ToString()); DialogResult = false; Close(); } }
public WalkerHandler(UIApplication uiapp) { try { m_app = uiapp; m_doc = uiapp.ActiveUIDocument.Document; View3D view3d = m_doc.ActiveView as View3D; if (null != view3d) { activeView = view3d; } else { FilteredElementCollector collector = new FilteredElementCollector(m_doc); List <View3D> view3ds = collector.OfClass(typeof(View3D)).ToElements().Cast <View3D>().ToList(); var viewfound = from view in view3ds where view.IsTemplate == false && view.IsPerspective == false && view.ViewName == "{3D}" select view; if (viewfound.Count() > 0) { activeView = viewfound.First(); using (Transaction trans = new Transaction(m_doc, "Open 3D View")) { try { trans.Start(); uiapp.ActiveUIDocument.ActiveView = activeView; trans.Commit(); } catch { trans.RollBack(); } } } } bcfProjectId = ParameterUtil.GetBCFProjectId(m_app); if (!string.IsNullOrEmpty(bcfProjectId)) { googleFolders = FileManager.FindGoogleFolders(bcfProjectId); if (null != googleFolders.ColorSheet) { bcfColorSchemeId = googleFolders.ColorSheet.Id; } if (null != googleFolders.CategorySheet) { categorySheetId = googleFolders.CategorySheet.Id; } if (!string.IsNullOrEmpty(bcfColorSchemeId) && !string.IsNullOrEmpty(categorySheetId)) { schemeInfo = FileManager.ReadColorSchemes(bcfColorSchemeId, categorySheetId, false); } bcfFileDictionary = DataStorageUtil.ReadLinkedBCFFileInfo(m_doc, bcfProjectId); bcfDictionary = GetBCFDictionary(m_doc); List <BuiltInCategory> bltCategories = catDictionary.Values.ToList(); bool parameterCreated = ParameterUtil.CreateBCFParameters(m_app, bltCategories); foreach (string catName in categoryNames) { CategoryInfo catInfo = new CategoryInfo(catName, true); categoryInfoList.Add(catInfo); } } else { MessageBox.Show("Please enter a BCF Project Id in Project Information.", "Empty BCF Project Id", MessageBoxButton.OK, MessageBoxImage.Information); } } catch (Exception ex) { MessageBox.Show("Failed to initialize External Event handler.\n" + ex.Message, "External Event Handler", MessageBoxButton.OK, MessageBoxImage.Warning); } }
static void CreateFaceWalls( Document doc) { Application app = doc.Application; Document massDoc = app.NewFamilyDocument( _conceptual_mass_template_path); CreateMassExtrusion(massDoc); //if( File.Exists( _family_path ) ) // File.Delete( _family_path ); SaveAsOptions opt = new SaveAsOptions(); opt.OverwriteExistingFile = true; massDoc.SaveAs(_family_path, opt); using (Transaction tx = new Transaction(doc)) { tx.Start("Create FaceWall"); if (!doc.LoadFamily(_family_path)) { throw new Exception("DID NOT LOAD FAMILY"); } Family family = new FilteredElementCollector(doc) .OfClass(typeof(Family)) .Where <Element>(x => x.Name.Equals(_family_name)) .Cast <Family>() .FirstOrDefault(); FamilySymbol fs = doc.GetElement( family.GetFamilySymbolIds().First <ElementId>()) as FamilySymbol; // Create a family instance Level level = doc.ActiveView.GenLevel; FamilyInstance fi = doc.Create.NewFamilyInstance( XYZ.Zero, fs, level, StructuralType.NonStructural); doc.Regenerate(); // required to generate the geometry! // Determine wall type. WallType wallType = new FilteredElementCollector(doc) .OfClass(typeof(WallType)) .Cast <WallType>() .Where <WallType>(x => FaceWall.IsWallTypeValidForFaceWall(doc, x.Id)) .FirstOrDefault(); // Retrieve mass element geometry. Options options = app.Create.NewGeometryOptions(); options.ComputeReferences = true; //options.View = doc.ActiveView; // conceptual mass is not visible in default view GeometryElement geo = fi.get_Geometry(options); // Create a sloped wall from the geometry. foreach (GeometryObject obj in geo) { Solid solid = obj as Solid; if (null != solid) { foreach (Face f in solid.Faces) { Debug.Assert(null != f.Reference, "we asked for references, didn't we?"); PlanarFace pf = f as PlanarFace; if (null != pf) { XYZ v = pf.Normal; // Errors: // // Could not create a face wall. // // Caused by using ActiveView.Level // instead of ActiveView.GenLevel. // // This reference cannot be applied to a face wall. // // Caused by using this on a horizontal face. if (!Util.IsVertical(v)) { FaceWall.Create( doc, wallType.Id, WallLocationLine.CoreCenterline, f.Reference); } } } } } tx.Commit(); } }
/// <summary> /// List all elements in Revit database. /// </summary> void ListAllElements() { // Create an output file: string filename = Path.Combine( Path.GetTempPath(), "RevitElements.txt"); StreamWriter sw = new StreamWriter(filename); // The Revit API does not expect an application // ever to need to iterate over all elements. // To do so, we need to use a trick: ask for all // elements fulfilling a specific criteria and // unite them with all elements NOT fulfilling // the same criteria; an arbitrary criterion // could be chosen: FilteredElementCollector collector = new FilteredElementCollector(_doc) .WhereElementIsElementType(); FilteredElementCollector collector2 = new FilteredElementCollector(_doc) .WhereElementIsNotElementType(); collector.UnionWith(collector2); // Loop over the elements and list their data: string s, line; foreach (Element e in collector) { line = "Id=" + e.Id.IntegerValue.ToString(); // element id line += "; Class=" + e.GetType().Name; // element class, i.e. System.Type // The element category is not implemented for all classes, // and may return null; for family elements, one can sometimes // use the FamilyCategory property instead. s = string.Empty; if (null != e.Category) { s = e.Category.Name; } if (0 == s.Length && e is Family && null != ((Family)e).FamilyCategory) { s = ((Family)e).FamilyCategory.Name; } if (0 == s.Length) { s = "?"; } line += "; Category=" + s; // The element Name property has a different meaning for different classes, // but is mostly implemented 'logically'. More precise info on elements // can be obtained in class-specific ways. line += "; Name=" + e.Name; //line += "; UniqueId=" + e.UniqueId; //line += "; Guid=" + GetGuid( e.UniqueId ); sw.WriteLine(line); } sw.Close(); TaskDialog.Show("List all elements", string.Format("Element list has been written to '{0}'.", filename)); }
/// <summary> /// Non-recursively list all import instances /// in all families used in the current project document. /// </summary> public Result ExecuteWithoutRecursion( ExternalCommandData commandData, ref string message, ElementSet elements) { UIApplication app = commandData.Application; Document doc = app.ActiveUIDocument.Document; FilteredElementCollector instances = new FilteredElementCollector(doc); instances.OfClass(typeof(FamilyInstance)); Dictionary <string, Family> families = new Dictionary <string, Family>(); foreach (FamilyInstance i in instances) { Family family = i.Symbol.Family; if (!families.ContainsKey(family.Name)) { families[family.Name] = family; } } List <string> keys = new List <string>( families.Keys); keys.Sort(); foreach (string key in keys) { Family family = families[key]; if (family.IsInPlace) { Debug.Print("Family '{0}' is in-place.", key); } else { Document fdoc = doc.EditFamily(family); FilteredElementCollector c = new FilteredElementCollector(doc); c.OfClass(typeof(ImportInstance)); IList <Element> imports = c.ToElements(); int n = imports.Count; Debug.Print( "Family '{0}' contains {1} import instance{2}{3}", key, n, Util.PluralSuffix(n), Util.DotOrColon(n)); if (0 < n) { foreach (ImportInstance i in imports) { //string name = i.ObjectType.Name; // 2011 string name = doc.GetElement(i.GetTypeId()).Name; // 2012 Debug.Print(" '{0}'", name); } } } } return(Result.Failed); }
public void Duct_from_AutoCad() { UIDocument uidoc = this.ActiveUIDocument; Document doc = uidoc.Document; Autodesk.Revit.DB.View currentview = doc.ActiveView; if (currentview.ViewType != ViewType.FloorPlan) { return; } //Only works in floorplans try { puntoref_revit = uidoc.Selection.PickPoint("Pick origin point in REVIT"); } catch { return; } OpenFileDialog archivofile = new OpenFileDialog(); archivofile.Title = "Open CAD data file"; archivofile.CheckFileExists = true; archivofile.CheckPathExists = true; archivofile.Filter = "Txt|*.txt"; if (archivofile.ShowDialog() != DialogResult.OK) { return; } string nombrefile = archivofile.FileName; string[] lineasarchivo = File.ReadAllLines(nombrefile); string lineadata = String.Empty; //get Rectangular Duct Type FilteredElementCollector collectorductos = new FilteredElementCollector(doc); collectorductos.OfClass(typeof(Autodesk.Revit.DB.Mechanical.DuctType)).ToElements(); Autodesk.Revit.DB.Mechanical.DuctType ducttypefinal = null; foreach (Element elemw in collectorductos) { Autodesk.Revit.DB.Mechanical.DuctType duct_type = elemw as Autodesk.Revit.DB.Mechanical.DuctType; System.Diagnostics.Debug.Print(duct_type.Name); Parameter ovaltoround = duct_type.get_Parameter(BuiltInParameter.RBS_CURVETYPE_MULTISHAPE_TRANSITION_OVALROUND_PARAM); Parameter recttooval = duct_type.get_Parameter(BuiltInParameter.RBS_CURVETYPE_MULTISHAPE_TRANSITION_RECTOVAL_PARAM); Parameter recttoround = duct_type.get_Parameter(BuiltInParameter.RBS_CURVETYPE_MULTISHAPE_TRANSITION_PARAM); int val_ovaltoround = ovaltoround.AsElementId().IntegerValue; int val_recttooval = recttooval.AsElementId().IntegerValue; int val_recttoround = recttoround.AsElementId().IntegerValue; System.Diagnostics.Debug.Print("Oval to round:" + val_ovaltoround.ToString()); System.Diagnostics.Debug.Print("Rect to oval:" + val_recttooval.ToString()); System.Diagnostics.Debug.Print("Rect to round:" + val_recttoround.ToString()); //if val_recttoround is -1 the ducttype is OVAL //if val_ovaltoround is -1 the ducttype is RECTANGULAR // if val_recttooval is -1 the ducttyoe is ROUND if (val_ovaltoround == -1) { ducttypefinal = duct_type; break; } } // lineadata = lineasarchivo[0]; string[] datos = lineadata.Split(';'); double x1 = Math.Round(Convert.ToDouble(datos[0]), 6) / 0.3048; double y1 = Math.Round(Convert.ToDouble(datos[1]), 6) / 0.3048; double z1 = Math.Round(Convert.ToDouble(datos[2]), 6) / 0.3048; puntoref_cad = new XYZ(x1, y1, z1); vector_correccion = puntoref_revit - puntoref_cad; XYZ puntoCR = new XYZ(); int Countducts = 0; using (Transaction tr = new Transaction(doc, "DuctFromCAD")) { tr.Start(); for (int ii = 1; ii < lineasarchivo.Length; ii++) { lineadata = lineasarchivo[ii]; datos = lineadata.Split(';'); x1 = Math.Round(Convert.ToDouble(datos[0]), 6) / 0.3048; y1 = Math.Round(Convert.ToDouble(datos[1]), 6) / 0.3048; z1 = Math.Round(Convert.ToDouble(datos[2]), 6) / 0.3048; double x2 = Math.Round(Convert.ToDouble(datos[3]), 6) / 0.3048; double y2 = Math.Round(Convert.ToDouble(datos[4]), 6) / 0.3048; double z2 = Math.Round(Convert.ToDouble(datos[5]), 6) / 0.3048; double ancho = Math.Round(Convert.ToDouble(datos[6]), 3); string dim_ducto = datos[7]; if (dim_ducto != null && dim_ducto != "") { string[] blanksplit = dim_ducto.Split(' '); string[] sizeplit = blanksplit[0].Split('x'); double widthduct = Convert.ToDouble(sizeplit[0]) / 12; //from inches to feet double heightduct = Convert.ToDouble(sizeplit[1]) / 12; //from inches to feet System.Diagnostics.Debug.Print(widthduct.ToString() + "x" + heightduct.ToString()); XYZ p1 = new XYZ(x1, y1, z1) + vector_correccion; XYZ p2 = new XYZ(x2, y2, z2) + vector_correccion; if (p1.DistanceTo(p2) < 1) { continue; } //Not less than a feet try { Autodesk.Revit.DB.Mechanical.Duct new_duct = doc.Create.NewDuct(p1, p2, ducttypefinal); new_duct.get_Parameter(BuiltInParameter.RBS_CURVE_WIDTH_PARAM).Set(widthduct); new_duct.get_Parameter(BuiltInParameter.RBS_CURVE_HEIGHT_PARAM).Set(heightduct); doc.Create.NewTag(currentview, new_duct, false, TagMode.TM_ADDBY_CATEGORY, TagOrientation.TAG_HORIZONTAL, p1.Add(p2).Divide(2)); //doc.Create.NewTextNote(currentview, p1.Add(p2).Divide(2.001), XYZ.BasisX, XYZ.BasisZ, 1, TextAlignFlags.TEF_ALIGN_CENTER, sizeplit[0] + "x" + sizeplit[1]); Countducts++; } catch { } } } tr.Commit(); } MessageBox.Show("Imported " + Countducts.ToString() + " Ducts"); }
public SheetsCSLRequest(UIApplication uiApp, String text) { MainUI uiForm = BARevitTools.Application.thisApp.newMainUi; //Reset the progress bar uiForm.sheetsCSLProgressBar.Value = 0; uiForm.sheetsCSLProgressBar.Minimum = 0; uiForm.sheetsCSLProgressBar.Step = 1; uiForm.sheetsCSLProgressBar.Visible = true; UIDocument uidoc = uiApp.ActiveUIDocument; var sheetsCollector = new FilteredElementCollector(uidoc.Document).OfClass(typeof(ViewSheet)).ToElements(); //Create some objects for storage string selectedSheetNumber = uiForm.sheetsCSLComboBox.Text; List <string> selectedSheets = new List <string>(); List <ElementId> viewsToCopy = new List <ElementId>(); List <ElementId> viewportTypeIds = new List <ElementId>(); List <XYZ> viewportLocations = new List <XYZ>(); //Count the number of sheets with checkboxes in the DataGridView. Use that to set the number of steps for the progress bar int countOfSheets = 0; foreach (DataGridViewRow row in uiForm.sheetsCSLDataGridView.Rows) { if (row.Cells["Select"].Value != null) { if (row.Cells["Select"].Value.ToString() == "True") { selectedSheets.Add(row.Cells["Sheet Number"].Value.ToString()); countOfSheets++; } else { continue; } } else { continue; } } uiForm.sheetsCSLProgressBar.Maximum = countOfSheets; //Get the sheet to copy legends from if (uiForm.sheetsCSLComboBox.Text != "<Originating Sheet>") { //Cycle through the collection of sheets foreach (ViewSheet sheet in sheetsCollector) { //If the current sheet number matches the sheet number of the sheet to copy from, continue if (sheet.SheetNumber.ToString() == selectedSheetNumber) { //Collect the viewports from the sheet ICollection <ElementId> viewportIds = sheet.GetAllViewports(); foreach (ElementId viewportId in viewportIds) { //For each viewport, get the ViewId, TypeId, and location Viewport viewportElement = uidoc.Document.GetElement(viewportId) as Viewport; ElementId viewportViewId = viewportElement.ViewId; ElementId viewportViewTypeId = viewportElement.GetTypeId(); XYZ viewportLocation = viewportElement.GetBoxCenter(); Autodesk.Revit.DB.View viewportView = uidoc.Document.GetElement(viewportViewId) as Autodesk.Revit.DB.View; //If the viewport is a legend, continue if (viewportView.ViewType.ToString() == "Legend") { //Add the three sets of data to the lists viewsToCopy.Add(viewportViewId); viewportTypeIds.Add(viewportViewTypeId); viewportLocations.Add(viewportLocation); } else { continue; } } break; } else { continue; } } } //Start a new transaction Transaction t1 = new Transaction(uidoc.Document, "CopyLegendsFromSheetToSheets"); t1.Start(); //For each sheet in the collector... foreach (ViewSheet sheet in sheetsCollector) { //If the selected sheets contains the sheet number, continue if (selectedSheets.Contains(sheet.SheetNumber.ToString())) { //Step forward the progress bar uiForm.sheetsCSLProgressBar.PerformStep(); int x = viewsToCopy.Count(); int i = 0; //For each sheet in viewsToCopy while (i < x) { try { //Create a new viewport and place it on the sheet in the same location Viewport newViewport = Viewport.Create(uidoc.Document, sheet.Id, viewsToCopy[i], viewportLocations[i]); newViewport.ChangeTypeId(viewportTypeIds[i]); i++; } catch { i++; } } } else { continue; } } t1.Commit(); t1.Dispose(); //Reset the filter text box if it was set uiForm.sheetsCSLFilterTextBox.Text = ""; //Reset the backcolor of each row in the DataGridView foreach (DataGridViewRow row in uiForm.sheetsCSLDataGridView.Rows) { row.Cells["Select"].Value = false; row.Cells["Select"].Style.BackColor = uiForm.sheetsCSLDataGridView.DefaultCellStyle.BackColor; } }
/// <summary> /// delete elements depends on the input params.json file /// </summary> /// <param name="data"></param> public static void DeleteAllElements(DesignAutomationData data) { if (data == null) { throw new ArgumentNullException(nameof(data)); } Application rvtApp = data.RevitApp; if (rvtApp == null) { throw new InvalidDataException(nameof(rvtApp)); } string modelPath = data.FilePath; if (String.IsNullOrWhiteSpace(modelPath)) { throw new InvalidDataException(nameof(modelPath)); } // If the input revit model passed is a workshared revit file then by default the Design Automation // bridge will open the model detached from central, opting DetachAndPreserveWorsets option. // Non-worshared revit file will be load as is. Document doc = data.RevitDoc; if (doc == null) { throw new InvalidOperationException("Could not open document."); } // For CountIt workItem: If RvtParameters is null, count all types DeleteElementsParams deleteElementsParams = DeleteElementsParams.Parse("params.json"); using (Transaction transaction = new Transaction(doc)) { transaction.Start("Delete Elements"); if (deleteElementsParams.walls) { FilteredElementCollector col = new FilteredElementCollector(doc).OfClass(typeof(Wall)); doc.Delete(col.ToElementIds()); } if (deleteElementsParams.floors) { FilteredElementCollector col = new FilteredElementCollector(doc).OfClass(typeof(Floor)); doc.Delete(col.ToElementIds()); } if (deleteElementsParams.doors) { FilteredElementCollector collector = new FilteredElementCollector(doc); ICollection <ElementId> collection = collector.OfClass(typeof(FamilyInstance)) .OfCategory(BuiltInCategory.OST_Doors) .ToElementIds(); doc.Delete(collection); } if (deleteElementsParams.windows) { FilteredElementCollector collector = new FilteredElementCollector(doc); ICollection <ElementId> collection = collector.OfClass(typeof(FamilyInstance)) .OfCategory(BuiltInCategory.OST_Windows) .ToElementIds(); doc.Delete(collection); } transaction.Commit(); } ModelPath path = ModelPathUtils.ConvertUserVisiblePathToModelPath("result.rvt"); // If a worshared file is opened as a part of this addin then the new file will be // saved as central. SaveAsOptions opts = new SaveAsOptions(); if (doc.IsWorkshared) { opts.SetWorksharingOptions(new WorksharingSaveAsOptions { SaveAsCentral = true }); WorksharingUtils.RelinquishOwnership(doc, new RelinquishOptions(true), new TransactWithCentralOptions()); } doc.SaveAs(path, new SaveAsOptions()); }
/// <summary> /// List the family types /// </summary> public void ListFamilyTypes() { // (1) Get a list of family types available in the current rvt project. // // For system family types, there is a designated // properties that allows us to directly access to the types. // e.g., _doc.WallTypes //WallTypeSet wallTypes = _doc.WallTypes; // 2013 FilteredElementCollector wallTypes = new FilteredElementCollector(_doc) // 2014 .OfClass(typeof(WallType)); int n = wallTypes.Count(); string s = string.Empty; //int n = 0; foreach (WallType wType in wallTypes) { s += "\r\n" + wType.Kind.ToString() + " : " + wType.Name; //++n; } TaskDialog.Show(n.ToString() + " Wall Types:", s); // (1.1) Same idea applies to other system family, such as Floors, Roofs. //FloorTypeSet floorTypes = _doc.FloorTypes; FilteredElementCollector floorTypes = new FilteredElementCollector(_doc) // 2014 .OfClass(typeof(FloorType)); s = string.Empty; foreach (FloorType fType in floorTypes) { // Family name is not in the property for // floor, so use BuiltInParameter here. Parameter param = fType.get_Parameter( BuiltInParameter.SYMBOL_FAMILY_NAME_PARAM); if (param != null) { s += param.AsString(); } s += " : " + fType.Name + "\r\n"; } TaskDialog.Show( floorTypes.Count().ToString() + " floor types (by rvtDoc.FloorTypes): ", s); // (1.2a) Another approach is to use a filter. here is an example with wall type. var wallTypeCollector1 = new FilteredElementCollector(_doc); wallTypeCollector1.WherePasses(new ElementClassFilter(typeof(WallType))); IList <Element> wallTypes1 = wallTypeCollector1.ToElements(); // Using a helper function to display the result here. See code below. ShowElementList(wallTypes1, "Wall Types (by Filter): "); // (1.2b) The following are the same as two lines above. // These alternative forms are provided for convenience. // Using OfClass() // //FilteredElementCollector wallTypeCollector2 = new FilteredElementCollector(_doc); //wallTypeCollector2.OfClass(typeof(WallType)); // (1.2c) The following are the same as above for convenience. // Using short cut this time. // //FilteredElementCollector wallTypeCollector3 = new FilteredElementCollector(_doc).OfClass(typeof(WallType)); // // (2) Listing for component family types. // // For component family, it is slightly different. // There is no designate property in the document class. // You always need to use a filtering. e.g., for doors and windows. // Remember for component family, you will need to check element type and category. var doorTypeCollector = new FilteredElementCollector(_doc); doorTypeCollector.OfClass(typeof(FamilySymbol)); doorTypeCollector.OfCategory(BuiltInCategory.OST_Doors); IList <Element> doorTypes = doorTypeCollector.ToElements(); ShowElementList(doorTypes, "Door Types (by Filter): "); }
public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements) { #region Recorder验证 ////Recorder验证 发现使用了doc的全文件路径则功能失效 //var recorder = new FaceRecorderForRevit( "Xia", ApplicationPath.GetCurrentPath(doc)); //var value = recorder.GetValue("Xia1", "", 10); //recorder.WriteValue("Xia1","111"); #endregion var uiApp = commandData.Application; var app = commandData.Application.Application; var uiDoc = commandData.Application.ActiveUIDocument; var doc = commandData.Application.ActiveUIDocument.Document; var view = doc.ActiveView; if (view.ViewType != ViewType.FloorPlan && view.ViewType != ViewType.Elevation && view.ViewType != ViewType.DrawingSheet && view.ViewType != ViewType.CeilingPlan && view.ViewType != ViewType.Section && view.ViewType != ViewType.Detail && view.ViewType != ViewType.DraftingView && view.ViewType != ViewType.EngineeringPlan) { PmSoft.Common.Controls.PMMessageBox.Show("需选择二维视图或者图纸"); return(Result.Cancelled); } if (false) { var selectedId = uiDoc.Selection.PickObject(ObjectType.Element, new PipeFilter()).ElementId; FamilySymbol tagSymbol = null; VLTransactionHelper.DelegateTransaction(doc, "加载族", () => { //查找族类型 string tagName = "管道尺寸标记"; var symbols = new FilteredElementCollector(doc) .WherePasses(new ElementCategoryFilter(BuiltInCategory.OST_PipeTags)) .WherePasses(new ElementClassFilter(typeof(FamilySymbol))); var targetSymbol = symbols.FirstOrDefault(c => (c as FamilySymbol).FamilyName == tagName); if (targetSymbol != null) { tagSymbol = targetSymbol as FamilySymbol; } //空时加载族类型 if (tagSymbol == null) { var symbolFile = @"E:\WorkingSpace\Tasks\0609管道标注\管道尺寸标记.rfa"; Family family; if (doc.LoadFamily(symbolFile, out family)) { //获取族类型集合Id var familySymbolIds = family.GetFamilySymbolIds(); foreach (var familySymbolId in familySymbolIds) { var element = doc.GetElement(familySymbolId) as FamilySymbol; if (element != null && element.FamilyName == tagName) { tagSymbol = element; break; } } } else { TaskDialogShow("加载族文件失败"); } } return(true); }); if (tagSymbol == null) { return(Result.Failed); } VLTransactionHelper.DelegateTransaction(doc, "选择使用的标注", () => { //TODO return(true); }); VLTransactionHelper.DelegateTransaction(doc, "文字位于管道", () => { var pipe = doc.GetElement(selectedId); var locationCurve = (pipe.Location as LocationCurve).Curve; var midPoint = (locationCurve.GetEndPoint(0) + locationCurve.GetEndPoint(1)) / 2; var tag = doc.Create.NewTag(view, pipe, false, TagMode.TM_ADDBY_CATEGORY, TagOrientation.Horizontal, midPoint); return(true); }); VLTransactionHelper.DelegateTransaction(doc, "文字位于管道上方", () => { double length = 8; var pipe = doc.GetElement(selectedId); var locationCurve = (pipe.Location as LocationCurve).Curve; var midPoint = (locationCurve.GetEndPoint(0) + locationCurve.GetEndPoint(1)) / 2; var parallelVector = (locationCurve as Line).Direction; var verticalVector = new XYZ(parallelVector.Y, -parallelVector.X, 0); if (verticalVector.Y < 0 || (verticalVector.Y == 0 && verticalVector.X == -1))//控制到一二象限 { verticalVector = new XYZ(-verticalVector.X, -verticalVector.Y, verticalVector.Z); } var tag = doc.Create.NewTag(view, pipe, false, TagMode.TM_ADDBY_CATEGORY, TagOrientation.Horizontal, midPoint + length * verticalVector); return(true); }); VLTransactionHelper.DelegateTransaction(doc, "引线", () => { double length = 5; bool needLeader = true; var pipe = doc.GetElement(selectedId); var locationCurve = (pipe.Location as LocationCurve).Curve; var midPoint = (locationCurve.GetEndPoint(0) + locationCurve.GetEndPoint(1)) / 2; var parallelVector = (locationCurve as Line).Direction; var verticalVector = new XYZ(parallelVector.Y, -parallelVector.X, 0); if (verticalVector.Y < 0 || (verticalVector.Y == 0 && verticalVector.X == -1)) { verticalVector = new XYZ(-verticalVector.X, -verticalVector.Y, verticalVector.Z); } var tag = doc.Create.NewTag(view, pipe, needLeader, TagMode.TM_ADDBY_CATEGORY, TagOrientation.Horizontal, midPoint + length * verticalVector); return(true); }); VLTransactionHelper.DelegateTransaction(doc, "标记距离管道边缘5mm", () => { double length = 5; bool needLeader = false; var pipe = doc.GetElement(selectedId); var locationCurve = (pipe.Location as LocationCurve).Curve; var midPoint = (locationCurve.GetEndPoint(0) + locationCurve.GetEndPoint(1)) / 2; var parallelVector = (locationCurve as Line).Direction; var verticalVector = new XYZ(parallelVector.Y, -parallelVector.X, 0); if (verticalVector.Y < 0 || (verticalVector.Y == 0 && verticalVector.X == -1)) { verticalVector = new XYZ(-verticalVector.X, -verticalVector.Y, verticalVector.Z); } var tag = doc.Create.NewTag(view, pipe, needLeader, TagMode.TM_ADDBY_CATEGORY, TagOrientation.Horizontal, midPoint + length * verticalVector); return(true); }); } if (false) { VLTransactionHelper.DelegateTransaction(doc, "一键标注", () => { //可以通过Tag的TaggedLocalElelemtId获取其对应的对象 //Tag是属于某View的 var pipesWithTag = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_PipeTags); pipesWithTag = pipesWithTag.WhereElementIsNotElementType(); var tagIds = pipesWithTag.Where(c => c.OwnerViewId == view.Id) .Select(c => (c as IndependentTag).TaggedLocalElementId).ToList().Distinct(); var pipes = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_PipeCurves); pipes = pipes.WhereElementIsNotElementType(); foreach (var pipe in pipes) { if (!tagIds.Contains(pipe.Id)) { var locationCurve = (pipe.Location as LocationCurve).Curve; var midPoint = (locationCurve.GetEndPoint(0) + locationCurve.GetEndPoint(1)) / 2; var tag = doc.Create.NewTag(view, pipe, false, TagMode.TM_ADDBY_CATEGORY, TagOrientation.Horizontal, midPoint); } } return(true); }); } generateOnLineEdge = !generateOnLineEdge; var selectedIds = uiDoc.Selection.PickObjects(ObjectType.Element, new PipeFilter()); AnnotationCreater builder = new AnnotationCreater(); var result = builder.LoadFamilySymbols(doc, true); if (result) { result = VLTransactionHelper.DelegateTransaction(doc, "多管标注生成", () => { switch (builder.GenerateMultipleTagSymbol(doc, selectedIds.Select(c => c.ElementId), generateOnLineEdge ? MultiPipeTagLocation.OnLine : MultiPipeTagLocation.OnLineEdge)) { case AnnotationBuildResult.Success: return(true); case AnnotationBuildResult.NotParallel: case AnnotationBuildResult.NoLocationType: default: return(false); } }); } //if (!generateOnLineEdge) //{ // generateOnLineEdge = true; // var selectedIds = uiDoc.Selection.PickObjects(ObjectType.Element, new PipeFilter()); // AnnotationCreater creator = new AnnotationCreater(); // if (creator.LoadFamilySymbols(doc)) // { // switch (creator.GenerateMultipleTagSymbol(doc, selectedIds, MultiPipeTagLocation.OnLine)) // { // case AnnotationBuildResult.Success: // return Result.Succeeded; // case AnnotationBuildResult.NotParallel: // case AnnotationBuildResult.NoLocationType: // default: // return Result.Failed; // } // } //} VLTransactionHelper.DelegateTransaction(doc, "多管-一键标注", () => { return(true); }); VLTransactionHelper.DelegateTransaction(doc, "多管-包括链接进来的管道", () => { return(true); }); VLTransactionHelper.DelegateTransaction(doc, "多管-标注自动避让", () => { return(true); }); VLTransactionHelper.DelegateTransaction(doc, "修改标高的基面", () => { return(true); }); return(Result.Succeeded); }
public IEnumerable <Element> ElementsOfCategory(BuiltInCategory category) { var fec = new FilteredElementCollector(CurrentDBDocument); return(fec.OfCategory(category)); }
/// <summary> /// Implementation of the command binding event for the IFC export command. /// </summary> /// <param name="sender">The event sender (Revit UIApplication).</param> /// <param name="args">The arguments (command binding).</param> public void OnIFCExport(object sender, CommandEventArgs args) { try { // Prepare basic objects UIApplication uiApp = sender as UIApplication; UIDocument uiDoc = uiApp.ActiveUIDocument; Document activeDoc = uiDoc.Document; TheDocument = activeDoc; // Note that when exporting multiple documents, we are still going to use the configurations from the // active document. IFCExportConfigurationsMap configurationsMap = new IFCExportConfigurationsMap(); configurationsMap.Add(IFCExportConfiguration.GetInSession()); configurationsMap.AddBuiltInConfigurations(); configurationsMap.AddSavedConfigurations(); String mruSelection = null; if (m_mruConfiguration != null && configurationsMap.HasName(m_mruConfiguration)) { mruSelection = m_mruConfiguration; } PotentiallyUpdatedConfigurations = false; IFCExport mainWindow = new IFCExport(uiApp, configurationsMap, mruSelection); mainWindow.ShowDialog(); // If user chose to continue if (mainWindow.Result == IFCExportResult.ExportAndSaveSettings) { int docsToExport = mainWindow.DocumentsToExport.Count; // This shouldn't happen, but just to be safe. if (docsToExport == 0) { return; } bool multipleFiles = docsToExport > 1; // prompt for the file name SaveFileDialog fileDialog = new SaveFileDialog(); fileDialog.AddExtension = true; String defaultDirectory = m_mruExportPath != null ? m_mruExportPath : null; if (defaultDirectory == null) { String revitFilePath = TheDocument.PathName; if (!String.IsNullOrEmpty(revitFilePath)) { defaultDirectory = Path.GetDirectoryName(revitFilePath); } } if (defaultDirectory == null) { defaultDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); } string defaultExt = mainWindow.GetFileExtension(); fileDialog.FileName = multipleFiles ? Properties.Resources.MultipleFiles : GenerateFileNameFromDocument(mainWindow.DocumentsToExport[0], null); fileDialog.DefaultExt = defaultExt; fileDialog.Filter = mainWindow.GetFileFilter(); fileDialog.InitialDirectory = defaultDirectory; bool?fileDialogResult = fileDialog.ShowDialog(); // If user chooses to continue if (fileDialogResult.HasValue && fileDialogResult.Value) { // change options IFCExportConfiguration selectedConfig = mainWindow.GetSelectedConfiguration(); // Prompt the user for the file location and path String fullName = fileDialog.FileName; String path = Path.GetDirectoryName(fullName); String fileName = multipleFiles ? string.Empty : Path.GetFileName(fullName); // This option should be rarely used, and is only for consistency with old files. As such, it is set by environment variable only. String use2009GUID = Environment.GetEnvironmentVariable("Assign2009GUIDToBuildingStoriesOnIFCExport"); bool use2009BuildingStoreyGUIDs = (use2009GUID != null && use2009GUID == "1"); string unsuccesfulExports = string.Empty; // In rare occasions, there may be two projects loaded into Revit with the same name. This isn't supposed to be allowed, but can happen if, // e.g., a user creates a new project, exports it to IFC, and then calls Open IFC. In this case, if we export both projects, we will overwrite // one of the exports. Prevent that by keeping track of the exported file names. ISet <string> exportedFileNames = new HashSet <string>(); foreach (Document document in mainWindow.DocumentsToExport) { TheDocument = document; // Call this before the Export IFC transaction starts, as it has its own transaction. IFCClassificationMgr.DeleteObsoleteSchemas(document); Transaction transaction = new Transaction(document, "Export IFC"); transaction.Start(); FailureHandlingOptions failureOptions = transaction.GetFailureHandlingOptions(); failureOptions.SetClearAfterRollback(false); transaction.SetFailureHandlingOptions(failureOptions); // Normally the transaction will be rolled back, but there are cases where we do update the document. // There is no UI option for this, but these two options can be useful for debugging/investigating // issues in specific file export. The first one supports export of only one element //exportOptions.AddOption("SingleElement", "174245"); // The second one supports export only of a list of elements //exportOptions.AddOption("ElementsForExport", "174245;205427"); if (multipleFiles) { fileName = GenerateFileNameFromDocument(document, exportedFileNames) + "." + defaultExt; fullName = path + "\\" + fileName; } // Prepare the export options IFCExportOptions exportOptions = new IFCExportOptions(); ElementId activeViewId = GenerateActiveViewIdFromDocument(document); selectedConfig.ActiveViewId = selectedConfig.UseActiveViewGeometry ? activeViewId.IntegerValue : -1; selectedConfig.UpdateOptions(exportOptions, activeViewId); bool result = document.Export(path, fileName, exportOptions); Dictionary <ElementId, string> linksGUIDsCache = new Dictionary <ElementId, string>(); if (result) { // Cache for links guids if (selectedConfig.ExportLinkedFiles == true) { Autodesk.Revit.DB.FilteredElementCollector collector = new FilteredElementCollector(document); collector.WhereElementIsNotElementType().OfCategory(BuiltInCategory.OST_RvtLinks); System.Collections.Generic.ICollection <ElementId> rvtLinkInstanceIds = collector.ToElementIds(); foreach (ElementId linkId in rvtLinkInstanceIds) { Element linkInstance = document.GetElement(linkId); if (linkInstance == null) { continue; } Parameter parameter = linkInstance.get_Parameter(BuiltInParameter.IFC_GUID); if (parameter != null && parameter.HasValue && parameter.StorageType == StorageType.String) { String sGUID = parameter.AsString(), sGUIDlower = sGUID.ToLower(); foreach (KeyValuePair <ElementId, string> value in linksGUIDsCache) { if (value.Value.ToLower().IndexOf(sGUIDlower) == 0) { sGUID += "-"; } } linksGUIDsCache.Add(linkInstance.Id, sGUID); } } } } else { unsuccesfulExports += fullName + "\n"; } // Roll back the transaction started earlier, unless certain options are set. if (result && (use2009BuildingStoreyGUIDs || selectedConfig.StoreIFCGUID)) { transaction.Commit(); } else { transaction.RollBack(); } // Export links if (selectedConfig.ExportLinkedFiles == true) { exportOptions.AddOption("ExportingLinks", true.ToString()); ExportLinkedDocuments(document, fullName, linksGUIDsCache, exportOptions); exportOptions.AddOption("ExportingLinks", false.ToString()); } } if (!string.IsNullOrWhiteSpace(unsuccesfulExports)) { using (TaskDialog taskDialog = new TaskDialog(Properties.Resources.IFCExport)) { taskDialog.MainInstruction = string.Format(Properties.Resources.IFCExportProcessError, unsuccesfulExports); taskDialog.MainIcon = TaskDialogIcon.TaskDialogIconWarning; TaskDialogResult taskDialogResult = taskDialog.Show(); } } // Remember last successful export location m_mruExportPath = path; } } // The cancel button should cancel the export, not any "OK"ed setup changes. if (mainWindow.Result == IFCExportResult.ExportAndSaveSettings || mainWindow.Result == IFCExportResult.Cancel) { if (PotentiallyUpdatedConfigurations) { configurationsMap = mainWindow.GetModifiedConfigurations(); configurationsMap.UpdateSavedConfigurations(); } // Remember last selected configuration m_mruConfiguration = mainWindow.GetSelectedConfiguration().Name; } } catch (Exception e) { using (TaskDialog taskDialog = new TaskDialog(Properties.Resources.IFCExport)) { taskDialog.MainInstruction = Properties.Resources.IFCExportProcessGenericError; taskDialog.MainIcon = TaskDialogIcon.TaskDialogIconWarning; taskDialog.ExpandedContent = e.ToString(); TaskDialogResult result = taskDialog.Show(); } } }
private void DesignAutomationBridge_DesignAutomationReadyEvent(object sender, DesignAutomationReadyEventArgs e) { LogTrace("Design Automation Ready event triggered..."); e.Succeeded = true; DesignAutomationData data = e.DesignAutomationData; if (data == null) { throw new ArgumentNullException(nameof(data)); } Application rvtApp = data.RevitApp; if (rvtApp == null) { throw new InvalidDataException(nameof(rvtApp)); } string modelPath = data.FilePath; if (String.IsNullOrWhiteSpace(modelPath)) { throw new InvalidDataException(nameof(modelPath)); } Document doc = data.RevitDoc; if (doc == null) { throw new InvalidOperationException("Could not open document."); } using (Autodesk.Revit.DB.Transaction trans = new Transaction(doc, "ExportToDwgs")) { try { trans.Start(); List <View> views = new FilteredElementCollector(doc) .OfClass(typeof(View)) .Cast <View>() .Where(vw => vw.ViewType == ViewType.DrawingSheet && !vw.IsTemplate ).ToList(); List <ElementId> viewIds = new List <ElementId>(); foreach (View view in views) { ViewSheet viewSheet = view as ViewSheet; viewIds.Add(viewSheet.Id); } DWGExportOptions dwgOptions = new DWGExportOptions(); dwgOptions.MergedViews = true; Directory.CreateDirectory(Directory.GetCurrentDirectory() + "\\exportedDwgs"); if (Directory.Exists(Directory.GetCurrentDirectory() + "\\exportedDwgs")) { LogTrace("ExportedDwgs directory exists"); } doc.Export(Directory.GetCurrentDirectory() + "\\exportedDwgs", "result.dwg", viewIds, dwgOptions); LogTrace("Export Process Completedd"); trans.Commit(); } catch (Exception ee) { System.Diagnostics.Debug.WriteLine(ee.Message); System.Diagnostics.Debug.WriteLine(ee.StackTrace); return; } finally { if (trans.HasStarted()) { trans.RollBack(); } } } }
public void ExportLinkedDocuments(Autodesk.Revit.DB.Document document, string fileName, Dictionary <ElementId, string> linksGUIDsCache, IFCExportOptions exportOptions) { // get the extension int index = fileName.LastIndexOf('.'); if (index <= 0) { return; } string sExtension = fileName.Substring(index); fileName = fileName.Substring(0, index); // get all the revit link instances FilteredElementCollector collector = new FilteredElementCollector(document); ElementFilter elementFilter = new ElementClassFilter(typeof(RevitLinkInstance)); List <RevitLinkInstance> rvtLinkInstances = collector.WherePasses(elementFilter).Cast <RevitLinkInstance>().ToList(); IDictionary <String, int> rvtLinkNamesDict = new Dictionary <String, int>(); IDictionary <String, List <RevitLinkInstance> > rvtLinkNamesToInstancesDict = new Dictionary <String, List <RevitLinkInstance> >(); try { // get the link types foreach (RevitLinkInstance rvtLinkInstance in rvtLinkInstances) { // get the instance if (rvtLinkInstance == null) { continue; } // check the cache if (linksGUIDsCache.Keys.Contains(rvtLinkInstance.Id) == false) { continue; } // get the link document Document linkDocument = rvtLinkInstance.GetLinkDocument(); if (linkDocument == null) { continue; } // get the link file path and name String linkPathName = ""; Parameter originalFileNameParam = linkDocument.ProjectInformation.LookupParameter("Original IFC File Name"); if (originalFileNameParam != null && originalFileNameParam.StorageType == StorageType.String) { linkPathName = originalFileNameParam.AsString(); } else { linkPathName = linkDocument.PathName; } // get the link file name String linkFileName = ""; index = linkPathName.LastIndexOf("\\"); if (index > 0) { linkFileName = linkPathName.Substring(index + 1); } else { linkFileName = linkDocument.Title; } // remove the extension index = linkFileName.LastIndexOf('.'); if (index > 0) { linkFileName = linkFileName.Substring(0, index); } // add to names count dictionary if (!rvtLinkNamesDict.Keys.Contains(linkFileName)) { rvtLinkNamesDict.Add(linkFileName, 0); } rvtLinkNamesDict[linkFileName]++; // add to names instances dictionary if (!rvtLinkNamesToInstancesDict.Keys.Contains(linkPathName)) { rvtLinkNamesToInstancesDict.Add(linkPathName, new List <RevitLinkInstance>()); } rvtLinkNamesToInstancesDict[linkPathName].Add(rvtLinkInstance); } } catch { } // get the link instances // We will keep track of the instances we can't export. // Reasons we can't export: // 1. The path for the linked instance doesn't exist. // 2. Couldn't create a temporary document for exporting the linked instance. // 3. The document for the linked instance can't be found. // 4. The linked instance is mirrored, non-conformal, or scaled. IList <string> pathDoesntExist = new List <string>(); IList <string> noTempDoc = new List <string>(); IList <ElementId> cantFindDoc = new List <ElementId>(); IList <ElementId> nonConformalInst = new List <ElementId>(); IList <ElementId> scaledInst = new List <ElementId>(); IList <ElementId> instHasReflection = new List <ElementId>(); foreach (String linkPathName in rvtLinkNamesToInstancesDict.Keys) { // get the name of the copy String linkPathNameCopy = System.IO.Path.GetTempPath(); index = linkPathName.LastIndexOf("\\"); if (index > 0) { linkPathNameCopy += linkPathName.Substring(index + 1); } else { linkPathNameCopy += linkPathName; } index = linkPathNameCopy.LastIndexOf('.'); if (index <= 0) { index = linkPathNameCopy.Length; } linkPathNameCopy = linkPathNameCopy.Insert(index, " - Copy"); int i = 1; while (File.Exists(linkPathNameCopy)) { linkPathNameCopy = linkPathNameCopy.Insert(index, "(" + (++i).ToString() + ")"); } // copy the file File.Copy(linkPathName, linkPathNameCopy); if (!File.Exists(linkPathNameCopy)) { pathDoesntExist.Add(linkPathName); continue; } // open the document Document documentCopy = null; try { if ((linkPathName.Length >= 4 && linkPathName.Substring(linkPathName.Length - 4).ToLower() == ".ifc") || (linkPathName.Length >= 7 && linkPathName.Substring(linkPathName.Length - 7).ToLower() == ".ifcxml") || (linkPathName.Length >= 7 && linkPathName.Substring(linkPathName.Length - 7).ToLower() == ".ifczip")) { documentCopy = document.Application.OpenIFCDocument(linkPathNameCopy); } else { documentCopy = document.Application.OpenDocumentFile(linkPathNameCopy); } } catch { documentCopy = null; } if (documentCopy == null) { noTempDoc.Add(linkPathName); continue; } // get the link document unit scale DisplayUnitType dutLink = documentCopy.GetUnits().GetFormatOptions(UnitType.UT_Length).DisplayUnits; double lengthScaleFactorLink = UnitUtils.ConvertFromInternalUnits(1.0, dutLink); // get the link instances List <RevitLinkInstance> currRvtLinkInstances = rvtLinkNamesToInstancesDict[linkPathName]; IList <string> serTransforms = new List <string>(); IList <string> linkFileNames = new List <string>(); foreach (RevitLinkInstance currRvtLinkInstance in currRvtLinkInstances) { // Nothing to report if the element itself is null. if (currRvtLinkInstance == null) { continue; } // get the link document Document linkDocument = currRvtLinkInstance.GetLinkDocument(); if (linkDocument == null) { cantFindDoc.Add(currRvtLinkInstance.Id); continue; } // get the link transform Transform tr = currRvtLinkInstance.GetTransform(); // We can't handle non-conformal, scaled, or mirrored transforms. if (!tr.IsConformal) { nonConformalInst.Add(currRvtLinkInstance.Id); continue; } if (tr.HasReflection) { instHasReflection.Add(currRvtLinkInstance.Id); continue; } if (!MathUtil.IsAlmostEqual(tr.Determinant, 1.0)) { scaledInst.Add(currRvtLinkInstance.Id); continue; } // get the link file path and name String linkFileName = ""; index = linkPathName.LastIndexOf("\\"); if (index > 0) { linkFileName = linkPathName.Substring(index + 1); } else { linkFileName = linkDocument.Title; } // remove the extension index = linkFileName.LastIndexOf('.'); if (index > 0) { linkFileName = linkFileName.Substring(0, index); } //if link was an IFC file then make a different formating to the file name if ((linkPathName.Length >= 4 && linkPathName.Substring(linkPathName.Length - 4).ToLower() == ".ifc") || (linkPathName.Length >= 7 && linkPathName.Substring(linkPathName.Length - 7).ToLower() == ".ifcxml") || (linkPathName.Length >= 7 && linkPathName.Substring(linkPathName.Length - 7).ToLower() == ".ifczip")) { String fName = fileName; //get output path and add to the new file name index = fName.LastIndexOf("\\"); if (index > 0) { fName = fName.Substring(0, index + 1); } else { fName = ""; } //construct IFC file name linkFileName = fName + linkFileName + "-"; //add guid linkFileName += linksGUIDsCache[currRvtLinkInstance.Id]; } else { // check if there are multiple instances with the same name bool bMultiple = (rvtLinkNamesDict[linkFileName] > 1); // add the path linkFileName = fileName + "-" + linkFileName; // add the guid if (bMultiple) { linkFileName += "-"; linkFileName += linksGUIDsCache[currRvtLinkInstance.Id]; } } // add the extension linkFileName += sExtension; linkFileNames.Add(linkFileName); // scale the transform origin tr.Origin *= lengthScaleFactorLink; // serialize transform serTransforms.Add(SerializeTransform(tr)); } // IFC export requires an open transaction, although no changes should be made Transaction transaction = new Transaction(documentCopy, "Export IFC Link"); transaction.Start(); FailureHandlingOptions failureOptions = transaction.GetFailureHandlingOptions(); failureOptions.SetClearAfterRollback(false); transaction.SetFailureHandlingOptions(failureOptions); // export try { int numLinkInstancesToExport = linkFileNames.Count; exportOptions.AddOption("NumberOfExportedLinkInstances", numLinkInstancesToExport.ToString()); for (int ii = 0; ii < numLinkInstancesToExport; ii++) { string optionName = (ii == 0) ? "ExportLinkInstanceTransform" : "ExportLinkInstanceTransform" + (ii + 1).ToString(); exportOptions.AddOption(optionName, serTransforms[ii]); // Don't pass in file name for the first link instance. if (ii == 0) { continue; } optionName = "ExportLinkInstanceFileName" + (ii + 1).ToString(); exportOptions.AddOption(optionName, linkFileNames[ii]); } // Pass in the first value; the rest will be in the options. String path_ = Path.GetDirectoryName(linkFileNames[0]); String fileName_ = Path.GetFileName(linkFileNames[0]); bool result = documentCopy.Export(path_, fileName_, exportOptions); // pass in the options here } catch { } // rollback the transaction transaction.RollBack(); // close the document documentCopy.Close(false); // delete the copy try { File.Delete(linkPathNameCopy); } catch { } // Show user errors, if any. int numBadInstances = pathDoesntExist.Count + noTempDoc.Count + cantFindDoc.Count + nonConformalInst.Count + scaledInst.Count + instHasReflection.Count; if (numBadInstances > 0) { using (TaskDialog taskDialog = new TaskDialog(Properties.Resources.IFCExport)) { taskDialog.MainInstruction = string.Format(Properties.Resources.LinkInstanceExportErrorMain, numBadInstances); taskDialog.MainIcon = TaskDialogIcon.TaskDialogIconWarning; taskDialog.TitleAutoPrefix = false; string expandedContent = ""; AddExpandedStringContent(ref expandedContent, Properties.Resources.LinkInstanceExportErrorPath, pathDoesntExist); AddExpandedStringContent(ref expandedContent, Properties.Resources.LinkInstanceExportCantCreateDoc, noTempDoc); AddExpandedElementIdContent(ref expandedContent, Properties.Resources.LinkInstanceExportCantFindDoc, cantFindDoc); AddExpandedElementIdContent(ref expandedContent, Properties.Resources.LinkInstanceExportNonConformal, nonConformalInst); AddExpandedElementIdContent(ref expandedContent, Properties.Resources.LinkInstanceExportScaled, scaledInst); AddExpandedElementIdContent(ref expandedContent, Properties.Resources.LinkInstanceExportHasReflection, instHasReflection); taskDialog.ExpandedContent = expandedContent; TaskDialogResult result = taskDialog.Show(); } } } }
static string ExportToImage(Document doc) { var tempFileName = Path.ChangeExtension( Path.GetRandomFileName(), "png"); string tempImageFile; try { tempImageFile = Path.Combine( Path.GetTempPath(), tempFileName); } catch (IOException) { return(null); } IList <ElementId> views = new List <ElementId>(); try { #if !VERSION2014 var direction = new XYZ(-1, 1, -1); var view3D = doc.IsFamilyDocument ? doc.FamilyCreate.NewView3D(direction) : doc.Create.NewView3D(direction); #else var collector = new FilteredElementCollector( doc); var viewFamilyType = collector .OfClass(typeof(ViewFamilyType)) .OfType <ViewFamilyType>() .FirstOrDefault(x => x.ViewFamily == ViewFamily.ThreeDimensional); var view3D = (viewFamilyType != null) ? View3D.CreateIsometric(doc, viewFamilyType.Id) : null; #endif // VERSION2014 if (view3D != null) { // Ensure white background. Color white = new Color(255, 255, 255); view3D.SetBackground( ViewDisplayBackground.CreateGradient( white, white, white)); views.Add(view3D.Id); var graphicDisplayOptions = view3D.get_Parameter( BuiltInParameter.MODEL_GRAPHICS_STYLE); // Settings for best quality graphicDisplayOptions.Set(6); } } catch (Autodesk.Revit.Exceptions .InvalidOperationException) { } var ieo = new ImageExportOptions { FilePath = tempImageFile, FitDirection = FitDirectionType.Horizontal, HLRandWFViewsFileType = ImageFileType.PNG, ImageResolution = ImageResolution.DPI_150, ShouldCreateWebSite = false }; if (views.Count > 0) { ieo.SetViewsAndSheets(views); ieo.ExportRange = ExportRange.SetOfViews; } else { ieo.ExportRange = ExportRange .VisibleRegionOfCurrentView; } ieo.ZoomType = ZoomFitType.FitToPage; ieo.ViewName = "tmp"; if (ImageExportOptions.IsValidFileName( tempImageFile)) { // If ExportRange = ExportRange.SetOfViews // and document is not active, then image // exports successfully, but throws // Autodesk.Revit.Exceptions.InternalException try { doc.ExportImage(ieo); } catch { return(string.Empty); } } else { return(string.Empty); } // File name has format like // "tempFileName - view type - view name", e.g. // "luccwjkz - 3D View - {3D}.png". // Get the first image (we only listed one view // in views). var files = Directory.GetFiles( Path.GetTempPath(), string.Format("{0}*.*", Path .GetFileNameWithoutExtension( tempFileName))); return(files.Length > 0 ? files[0] : string.Empty); }
public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements) { Document doc = commandData.Application.ActiveUIDocument.Document; //因為樓層數會影響一些標準的高度,所以先把樓層高度找出來 FilteredElementCollector levelCollector = new FilteredElementCollector(doc); ElementCategoryFilter levelFilter = new ElementCategoryFilter(BuiltInCategory.OST_Levels); List <Element> levels = levelCollector.WherePasses(levelFilter).ToElements().ToList(); int floor_count = 0; foreach (Element elem in levels) { if (elem.get_Parameter(BuiltInParameter.ELEM_FAMILY_PARAM).AsValueString() == "樓層") { //在地表的樓層才算,Elevation>=0,屋突好像也不算,名字P開頭的不行 Level level = elem as Level; if (level.Name.ToList()[0] != 'P' & level.Name.ToList()[0] != 'G') { if (level.Elevation >= 0) { floor_count += 1; } } } } if (floor_count >= 10) { regulation_railing_height = 120; } else { regulation_railing_height = 110; } string newFileName = @"C:\Users\8014\Desktop\BIM模型檢核.csv"; StringBuilder sb = new StringBuilder(); sb.AppendLine("5.樓梯垂直淨空高度檢核"); sb.AppendLine("規範:樓梯之垂直淨空距離不得小於 190 公分"); sb.AppendLine("樓梯名稱\t樓梯高度(cm)\t規範高度(cm)\t是否符合規範"); form_list5.Add(new string[] { "5.樓梯垂直淨空高度檢核" }); form_list5.Add(new string[] { "規範:樓梯之垂直淨空距離不得小於 190 公分" }); //先把全部的樓梯抓出來,有分室外梯以及室內梯,不過好像不用特別分室外跟室內耶 FilteredElementCollector stairsCollector = new FilteredElementCollector(doc); ElementCategoryFilter stairsFilter = new ElementCategoryFilter(BuiltInCategory.OST_Stairs); List <Element> all_stairs = stairsCollector.WherePasses(stairsFilter).WhereElementIsNotElementType().ToElements().ToList(); //List<Element> indoor_stairs = new List<Element>(); //foreach(Element elem in all_stairs) //{ // if (elem.get_Parameter(BuiltInParameter.ELEM_TYPE_PARAM).AsValueString().Contains("室內RC")) // indoor_stairs.Add(elem); //} foreach (Element elem in all_stairs) { Stairs stairs = elem as Stairs; double stairs_height = Convert.ToDouble(stairs.get_Parameter(BuiltInParameter.STAIRS_STAIRS_HEIGHT).AsValueString()); string s = stairs.get_Parameter(BuiltInParameter.ELEM_FAMILY_AND_TYPE_PARAM).AsValueString() + "\t" + stairs_height.ToString() + "\t" + regulation_stairs_height.ToString() + "\t" + (stairs_height >= regulation_stairs_height).ToString(); sb.AppendLine(s); string[] row = new string[] { stairs.Id.ToString(), stairs.get_Parameter(BuiltInParameter.ELEM_FAMILY_AND_TYPE_PARAM).AsValueString(), stairs_height.ToString(), regulation_stairs_height.ToString(), "無", (stairs_height >= regulation_stairs_height).ToString() }; form_list5.Add(row); } sb.AppendLine(); sb.AppendLine(); File.AppendAllText(newFileName, sb.ToString(), Encoding.Unicode); form_list5.Add(new string[] { }); form_list5.Add(new string[] { }); StringBuilder sb2 = new StringBuilder(); sb2.AppendLine("6.欄杆扶手高度檢核:"); sb2.AppendLine("規範:設置於露臺、陽臺、室外走廊、室外樓梯、平屋頂及室內天井部 分等之欄桿扶手高度欄桿扶手高度,不得小於1.1公尺,十層以上者,不得小於1.2公尺"); sb2.AppendLine("欄杆名稱\t欄杆高度(cm)\t規範高度(cm)\t是否符合規範"); form_list6.Add(new string[] { "6.欄杆扶手高度檢核:" }); form_list6.Add(new string[] { "規範:設置於露臺、陽臺、室外走廊、室外樓梯、平屋頂及室內天井部 分等之欄桿扶手高度欄桿扶手高度,不得小於1.1公尺,十層以上者,不得小於1.2公尺" }); //接下來要取欄杆高度 //樓梯用的扶手、欄杆是900mm的,跟女兒牆的布一樣 //要扣除掉女兒牆的欄杆的 FilteredElementCollector railingCollector = new FilteredElementCollector(doc); ElementCategoryFilter railingFilter = new ElementCategoryFilter(BuiltInCategory.OST_StairsRailing); List <Element> railings = railingCollector.WherePasses(railingFilter).WhereElementIsNotElementType().ToElements().ToList(); foreach (Element elem in railings) { if (!(elem.Name.Contains("900mm"))) { continue; } Railing railing = elem as Railing; ElementType elementType = doc.GetElement(railing.GetTypeId()) as ElementType; double railing_height = Convert.ToDouble(elementType.get_Parameter(BuiltInParameter.STAIRS_RAILING_HEIGHT).AsValueString()); string s = railing.Name + "\t" + railing_height.ToString() + "\t" + regulation_railing_height.ToString() + "\t" + (railing_height >= regulation_railing_height).ToString(); sb2.AppendLine(s); string[] row = new string[] { railing.Id.ToString(), railing.Name, railing_height.ToString(), regulation_railing_height.ToString(), "無", (railing_height >= regulation_railing_height).ToString() }; form_list6.Add(row); } sb2.AppendLine(); sb2.AppendLine(); File.AppendAllText(newFileName, sb2.ToString(), Encoding.Unicode); form_list6.Add(new string[] { }); form_list6.Add(new string[] { }); return(Result.Succeeded); }
/// <summary> /// Retrieve an existing named Guid /// in the specified Revit document or /// optionally create and return a new /// one if it does not yet exist. /// </summary> public static bool Get( Document doc, string name, out Guid guid, bool create = true) { bool rc = false; guid = Guid.Empty; // Retrieve a DataStorage element with our // extensible storage entity attached to it // and the specified element name. Only zero // or one should exist. ExtensibleStorageFilter f = new ExtensibleStorageFilter( JtNamedGuidStorageSchema.SchemaGuid); DataStorage dataStorage = new FilteredElementCollector(doc) .OfClass(typeof(DataStorage)) .WherePasses(f) .Where <Element>(e => name.Equals(e.Name)) .FirstOrDefault <Element>() as DataStorage; if (dataStorage == null) { if (create) { using (Transaction t = new Transaction( doc, "Create named Guid storage")) { t.Start(); // Create named data storage element dataStorage = DataStorage.Create(doc); dataStorage.Name = name; // Create entity to store the Guid data Entity entity = new Entity( JtNamedGuidStorageSchema.GetSchema()); entity.Set("Guid", guid = Guid.NewGuid()); // Set entity to the data storage element dataStorage.SetEntity(entity); t.Commit(); rc = true; } } } else { // Retrieve entity from the data storage element. Entity entity = dataStorage.GetEntity( JtNamedGuidStorageSchema.GetSchema(false)); Debug.Assert(entity.IsValid(), "expected a valid extensible storage entity"); if (entity.IsValid()) { guid = entity.Get <Guid>("Guid"); rc = true; } } return(rc); }
/// <summary> /// List all import instances in all the given families. /// Retrieve nested families and recursively search in these as well. /// </summary> void ListImportsAndSearchForMore( int recursionLevel, Document doc, Dictionary <string, Family> families) { string indent = new string( ' ', 2 * recursionLevel ); List <string> keys = new List <string>( families.Keys); keys.Sort(); foreach (string key in keys) { Family family = families[key]; if (family.IsInPlace) { Debug.Print(indent + "Family '{0}' is in-place.", key); } else { Document fdoc = doc.EditFamily(family); FilteredElementCollector c = new FilteredElementCollector(doc); c.OfClass(typeof(ImportInstance)); IList <Element> imports = c.ToElements(); int n = imports.Count; Debug.Print(indent + "Family '{0}' contains {1} import instance{2}{3}", key, n, Util.PluralSuffix(n), Util.DotOrColon(n)); if (0 < n) { foreach (ImportInstance i in imports) { string s = i.Pinned ? "" : "not "; //string name = i.ObjectType.Name; // 2011 string name = doc.GetElement(i.GetTypeId()).Name; // 2012 Debug.Print(indent + " '{0}' {1}pinned", name, s); i.Pinned = !i.Pinned; } } Dictionary <string, Family> nestedFamilies = GetFamilies(fdoc); ListImportsAndSearchForMore( recursionLevel + 1, fdoc, nestedFamilies); } } }
public Result Execute( ExternalCommandData commandData, ref String message, ElementSet elements) { UIApplication app = commandData.Application; Document doc = app.ActiveUIDocument.Document; FilteredElementCollector a; Parameter p; int n; #region Using the obsolete TitleBlocks property #if BEFORE_REVIT_2015 // The TitleBlocks property was declared deprecated // in the Revit 2014 API, and removed in Revit 2015. // Using the obsolete deprecated TitleBlocks property FamilySymbolSet titleBlocks = doc.TitleBlocks; n = titleBlocks.Size; Debug.Print( "{0} title block element type{1} listed " + "in doc.TitleBlocks collection{2}", n, (1 == n ? "" : "s"), (0 == n ? "." : ":")); string s; foreach (FamilySymbol tb in titleBlocks) { // these are the family symbols, // i.e. the title block element types, // i.e. not instances, i.e. not sheets, // and they obviously do not have any sheet // number, width or height, so 's' ends up empty: s = GetParameterValueString(tb, BuiltInParameter.SHEET_NUMBER) + GetParameterValueString(tb, BuiltInParameter.SHEET_WIDTH) + GetParameterValueString(tb, BuiltInParameter.SHEET_HEIGHT); Debug.Print( "Title block element type {0} {1}" + s, tb.Name, tb.Id.IntegerValue); } #endif // BEFORE_REVIT_2015 #endregion // Using the obsolete TitleBlocks property // Using this filter returns the same elements // as the doc.TitleBlocks collection: a = new FilteredElementCollector(doc) .OfCategory(BuiltInCategory.OST_TitleBlocks) .OfClass(typeof(FamilySymbol)); n = a.ToElementIds().Count; Debug.Print("{0} title block element type{1} " + "retrieved by filtered element collector{2}", n, (1 == n ? "" : "s"), (0 == n ? "." : ":")); foreach (FamilySymbol symbol in a) { Debug.Print( "Title block element type {0} {1}", symbol.Name, symbol.Id.IntegerValue); } // Retrieve the title block instances: a = new FilteredElementCollector(doc) .OfCategory(BuiltInCategory.OST_TitleBlocks) .OfClass(typeof(FamilyInstance)); Debug.Print("Title block instances:"); foreach (FamilyInstance e in a) { p = e.get_Parameter( BuiltInParameter.SHEET_NUMBER); Debug.Assert(null != p, "expected valid sheet number"); string sheet_number = p.AsString(); p = e.get_Parameter( BuiltInParameter.SHEET_WIDTH); Debug.Assert(null != p, "expected valid sheet width"); string swidth = p.AsValueString(); double width = p.AsDouble(); p = e.get_Parameter( BuiltInParameter.SHEET_HEIGHT); Debug.Assert(null != p, "expected valid sheet height"); string sheight = p.AsValueString(); double height = p.AsDouble(); ElementId typeId = e.GetTypeId(); Element type = doc.GetElement(typeId); Debug.Print( "Sheet number {0} size is {1} x {2} " + "({3} x {4}), id {5}, type {6} {7}", sheet_number, swidth, sheight, Util.RealString(width), Util.RealString(height), e.Id.IntegerValue, type.Name, typeId.IntegerValue); } // Retrieve the view sheet instances: a = new FilteredElementCollector(doc) .OfClass(typeof(ViewSheet)); Debug.Print("View sheet instances:"); foreach (ViewSheet vs in a) { string number = vs.SheetNumber; Debug.Print( "View sheet name {0} number {1} id {2}", vs.Name, vs.SheetNumber, vs.Id.IntegerValue); } return(Result.Succeeded); }
/// <summary> /// Renames all sheets that contain exactly one floor plan to match the name of that view /// Copy the whole method into the macro file on your machine, /// or download this file and add it to the solution in the macro editor /// </summary> public void RenameSheetsToMatchViewNames() { UIDocument uidoc = this.ActiveUIDocument; Document doc = uidoc.Document; // Retrieve all sheets, cast them to type ViewSheet and save them in a list // It is important to use ToList or ToElements when modifying elements // from a FilteredElementCollector var sheets = new FilteredElementCollector(doc) .OfClass(typeof(ViewSheet)) .Cast <ViewSheet>().ToList(); // Initialize a counter that will identify how many sheets have been modified int renamedSheetsCount = 0; // Open a transaction that allows changes to be made to the model using (Transaction trans = new Transaction(doc, "Rename sheets")) { // Start the transaction trans.Start(); // Loop through each sheet retrieved above foreach (var sheet in sheets) { // Get all the views placed on the sheet var viewsOnSheet = sheet.GetAllPlacedViews(); // If there is not exactly 1 view on the sheet, // Skip this sheet and continue to the next one if (viewsOnSheet.Count != 1) { continue; } // Get the id of the view // The single call is used because we know there is only 1 // based on the check above var viewId = viewsOnSheet.Single(); // Get the view from the id, and cast it to type View var view = (View)doc.GetElement(viewId); // If the view is not a floor plan, // skip the sheet and continue to the next one if (view.ViewType != ViewType.FloorPlan) { continue; } // Open a sub-transaction for the upcoming modification to the sheet using (SubTransaction subTrans = new SubTransaction(doc)) { // Start the sub-transaction subTrans.Start(); // Set the sheet name to the view name sheet.Name = view.Name; // Commit the change made subTrans.Commit(); // Increment the sheet counter by 1 renamedSheetsCount++; } // End of foreach loop } // Commit the transaction trans.Commit(); } // Show a message indicating how many sheets were modified TaskDialog.Show("Done", "Renamed " + renamedSheetsCount + " sheets"); }
Result IExternalCommand.Execute(ExternalCommandData commandData, ref string message, ElementSet elements) { try { m_document = commandData.Application.ActiveUIDocument.Document; m_documentUI = commandData.Application.ActiveUIDocument; m_thisAppId = commandData.Application.ActiveAddInId; // creating and registering the updater for the document. if (m_sectionUpdater == null) { using (Transaction tran = new Transaction(m_document, "Register Section Updater")) { tran.Start(); m_sectionUpdater = new SectionUpdater(m_thisAppId); m_sectionUpdater.Register(m_document); tran.Commit(); } } TaskDialog.Show("Message", "Please select a section view, then select a window."); ElementId modelId = null; Element sectionElement = null; ElementId sectionId = null; try { Reference referSection = m_documentUI.Selection.PickObject(ObjectType.Element, "Please select a section view."); if (referSection != null) { Element sectionElem = m_document.GetElement(referSection); if (sectionElem != null) { sectionElement = sectionElem; } } Reference referModel = m_documentUI.Selection.PickObject(ObjectType.Element, "Please select a window to associated with the section view."); if (referModel != null) { Element model = m_document.GetElement(referModel); if (model != null) { if (model is FamilyInstance) { modelId = model.Id; } } } } catch (OperationCanceledException) { TaskDialog.Show("Message", "The selection has been canceled."); return(Result.Cancelled); } if (modelId == null) { TaskDialog.Show("Error", "The model is supposed to be a window.\n The operation will be canceled."); return(Result.Cancelled); } // Find the real ViewSection for the selected section element. string name = sectionElement.Name; FilteredElementCollector collector = new FilteredElementCollector(m_document); collector.WherePasses(new ElementCategoryFilter(BuiltInCategory.OST_Views)); var viewElements = from element in collector where element.Name == name select element; List <Autodesk.Revit.DB.Element> sectionViews = viewElements.ToList <Autodesk.Revit.DB.Element>(); if (sectionViews.Count == 0) { TaskDialog.Show("Message", "Cannot find the view name " + name + "\n The operation will be canceled."); return(Result.Failed); } sectionId = sectionViews[0].Id; // Associated the section view to the window, and add a trigger for it. if (!idsToWatch.Contains(modelId) || m_oldSectionId != sectionId) { idsToWatch.Clear(); idsToWatch.Add(modelId); m_oldSectionId = sectionId; UpdaterRegistry.RemoveAllTriggers(m_sectionUpdater.GetUpdaterId()); m_sectionUpdater.AddTriggerForUpdater(m_document, idsToWatch, sectionId, sectionElement); TaskDialog.Show("Message", "The ViewSection id: " + sectionId + " has been associated to the window id: " + modelId + "\n You can try to move or modify the window to see how the updater works."); } else { TaskDialog.Show("Message", "The model has been already associated to the ViewSection."); } m_document.DocumentClosing += UnregisterSectionUpdaterOnClose; return(Result.Succeeded); } catch (System.Exception ex) { message = ex.ToString(); return(Result.Failed); } }
protected IFCImportCache(Document doc, string fileName) { // Get all categories of current document Settings documentSettings = doc.Settings; DocumentCategories = documentSettings.Categories; GenericModelsCategory = DocumentCategories.get_Item(BuiltInCategory.OST_GenericModel); // Cache the original shared parameters file, and create and read in a new one. OriginalSharedParametersFile = doc.Application.SharedParametersFilename; doc.Application.SharedParametersFilename = fileName + ".sharedparameters.txt"; DefinitionFile definitionFile = doc.Application.OpenSharedParameterFile(); if (definitionFile == null) { StreamWriter definitionFileStream = new StreamWriter(doc.Application.SharedParametersFilename, false); definitionFileStream.Close(); definitionFile = doc.Application.OpenSharedParameterFile(); } if (definitionFile == null) { throw new InvalidOperationException("Can't create definition file for shared parameters, aborting import."); } DefinitionInstanceGroup = definitionFile.Groups.get_Item("IFC Parameters"); if (DefinitionInstanceGroup == null) { DefinitionInstanceGroup = definitionFile.Groups.Create("IFC Parameters"); } DefinitionTypeGroup = definitionFile.Groups.get_Item("IFC Type Parameters"); if (DefinitionTypeGroup == null) { DefinitionTypeGroup = definitionFile.Groups.Create("IFC Type Parameters"); } // Cache list of schedules. FilteredElementCollector viewScheduleCollector = new FilteredElementCollector(doc); ICollection <Element> viewSchedules = viewScheduleCollector.OfClass(typeof(ViewSchedule)).ToElements(); foreach (Element viewSchedule in viewSchedules) { ScheduleDefinition definition = (viewSchedule as ViewSchedule).Definition; if (definition == null) { continue; } ElementId categoryId = definition.CategoryId; if (categoryId == ElementId.InvalidElementId) { continue; } ViewSchedules[new KeyValuePair <ElementId, string>(categoryId, viewSchedule.Name)] = viewSchedule.Id; ViewScheduleNames.Add(viewSchedule.Name); } // Find the status bar, so we can add messages. StatusBar = RevitStatusBar.Create(); }
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; bool permission = false; List <ViewSheet> sheets = new FilteredElementCollector(doc) .OfClass(typeof(ViewSheet)) .WhereElementIsNotElementType() .Cast <ViewSheet>() .ToList(); List <ElementId> usedViews = new List <ElementId>(); foreach (var sheet in sheets) { usedViews.AddRange(sheet.GetAllPlacedViews().ToList()); } usedViews = usedViews.Distinct().ToList(); if (usedViews.Count == 0) { TaskDialog.Show("Error", "Cannot let that happen - at least one view needs to remain in the project. (No views are placed on sheets.)"); return(Result.Failed); } List <ElementId> delete = new FilteredElementCollector(doc) .OfCategory(BuiltInCategory.OST_Views) .OfClass(typeof(Autodesk.Revit.DB.View)) .WhereElementIsNotElementType() .Cast <Autodesk.Revit.DB.View>() .Where(x => !x.IsTemplate) .Where(sc => (sc as ViewSchedule) == null) .Select(x => x.Id) .ToList(); TaskDialog.Show("Warning", "Be careful with that though .. "); string msg = "You want to delete all those hard drawn views. You certain?"; System.Windows.Forms.DialogResult dialogResult = System.Windows.Forms.MessageBox.Show(msg, "Are you really sure?", System.Windows.Forms.MessageBoxButtons.YesNo); if (dialogResult == System.Windows.Forms.DialogResult.Yes) { permission = true; } else if (dialogResult == System.Windows.Forms.DialogResult.No) { permission = false; } if (!permission) { return(Result.Cancelled); } using (Transaction t = new Transaction(doc, "Delete Views not on Sheets")) { t.Start(); doc.Delete(delete.Except(usedViews).ToArray()); t.Commit(); } return(Result.Succeeded); }
/// <summary> /// Get all the views to be displayed /// </summary> private void GetViews() { FilteredElementCollector collector = new FilteredElementCollector(m_activeDoc); FilteredElementIterator itor = collector.OfClass(typeof(View)).GetElementIterator(); itor.Reset(); ViewSet views = new ViewSet(); ViewSet floorPlans = new ViewSet(); ViewSet ceilingPlans = new ViewSet(); ViewSet engineeringPlans = new ViewSet(); while (itor.MoveNext()) { View view = itor.Current as View; // skip view templates because they're invalid for import/export if (view == null || view.IsTemplate) { continue; } else if (view.ViewType == Autodesk.Revit.DB.ViewType.FloorPlan) { floorPlans.Insert(view); } else if (view.ViewType == Autodesk.Revit.DB.ViewType.CeilingPlan) { ceilingPlans.Insert(view); } else if (view.ViewType == Autodesk.Revit.DB.ViewType.EngineeringPlan) { engineeringPlans.Insert(view); } } foreach (View floorPlan in floorPlans) { foreach (View ceilingPlan in ceilingPlans) { if (floorPlan.ViewName == ceilingPlan.ViewName) { views.Insert(floorPlan); } } } foreach (View engineeringPlan in engineeringPlans) { if (engineeringPlan.ViewName == engineeringPlan.GenLevel.Name) { views.Insert(engineeringPlan); } } View activeView = m_activeDoc.ActiveView; Autodesk.Revit.DB.ViewType viewType = activeView.ViewType; if (viewType == Autodesk.Revit.DB.ViewType.FloorPlan || viewType == Autodesk.Revit.DB.ViewType.CeilingPlan) { m_views.Insert(activeView); foreach (View view in views) { if (view.GenLevel.Elevation < activeView.GenLevel.Elevation) { m_views.Insert(view); } } } else if (viewType == Autodesk.Revit.DB.ViewType.EngineeringPlan) { if (views.Contains(activeView)) { m_views.Insert(activeView); } foreach (View view in views) { if (view.GenLevel.Elevation < activeView.GenLevel.Elevation) { m_views.Insert(view); } } } else//Get view of the lowest elevation { int i = 0; double elevation = 0; View viewLowestElevation = null; foreach (View view in views) { if (i == 0) { elevation = view.GenLevel.Elevation; viewLowestElevation = view; } else { if (view.GenLevel.Elevation <= elevation) { elevation = view.GenLevel.Elevation; viewLowestElevation = view; } } i++; } m_views.Insert(viewLowestElevation); } }
public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements) { Tracelog("Addin Start"); //Get application and document objects UIApplication UIApp = commandData.Application; UIDocument UIDoc = UIApp.ActiveUIDocument; Application app = UIApp.Application; Document doc = UIDoc.Document; // Get all doors. FilteredElementCollector collectorForDoors = new FilteredElementCollector(doc); collectorForDoors.OfCategory(BuiltInCategory.OST_Doors).OfClass(typeof(FamilyInstance)); // Iterate the collector and show the information if ( collectorForDoors.Count<Element>() > 0 ) { // I have a valid collection to iterate foreach(Element ele in collectorForDoors) { TaskDialog.Show(ele.Category.Name, ele.Name); } } else { // No collection found. Tracelog("No collection found"); } return (Result.Succeeded); }