internal void PlaceOnSheet(ViewSheet sheet) { if (!m_placeOnSheet) { return; } try { Document doc = sheet.Document; using (Transaction t = new Transaction(doc, "Place on sheet")) { t.Start(); XYZ placementPoint = new XYZ(0, 0, 0); foreach (ElementId scheduleId in m_scheduleIds) { ScheduleSheetInstance scheduleInstance = ScheduleSheetInstance.Create(doc, sheet.Id, scheduleId, placementPoint); placementPoint = new XYZ(0, scheduleInstance.get_BoundingBox(sheet).Min.Y + BORDER_WIDTH, 0); } t.Commit(); } } catch (Exception ex) { throw ex; } }
private static Result createReshoringLayoutSheets(UIDocument uiDoc) { Document _doc = uiDoc.Document; string _titleblockName = "E1 30 x 42 Horizontal: E1 30x42 Horizontal"; XYZ _columnScheduleBottomLeft = new XYZ(2.3354130772204, 2.39482128194158, 0); XYZ _viewCenter = new XYZ(1.45453036348288, 1.18116967618813, 0.871414246948733); XYZ _levelScheduleBottomLeft = new XYZ(0.156336990263879, 2.37688649933288, 0); var _levels = Getters.GetLevels(_doc); Level _levelAbove = null; Level _topLevel = _levels.FirstOrDefault(); Level _bottomLevel = _levels.LastOrDefault(); List <Tuple <ViewSheet, View> > _sheetsWithViews = new List <Tuple <ViewSheet, View> >(); foreach (Level _level in _levels) { if (_levelAbove == null) { _levelAbove = _level; } BoundedViewCreator _boundedViewCreator = new BoundedViewCreator(_level, null, null); SheetCreator _sheetCreator = new SheetCreator(_doc); string _viewName = _boundedViewCreator.GetViewName(string.Empty, "FP"); ViewSheet _viewSheet = _sheetCreator.CreateSheet(_titleblockName, _viewName, _viewName); ViewPlan _viewPlan = _boundedViewCreator.CreateViewPlan(80); _sheetsWithViews.Add(new Tuple <ViewSheet, View>(_viewSheet, _viewPlan)); ViewSchedule _columnSchedule = ScheduleCreator.CreateLayoutColumnSchedule(_doc, _level.Name, " Reshores"); ScheduleSheetInstance _columnScheduleSheetInstance = ScheduleSheetInstance.Create(_doc, _viewSheet.Id, _columnSchedule.Id, _columnScheduleBottomLeft); ViewSchedule _levelSchedule = ScheduleCreator.CreateLayoutLoadSchedule(_doc, _level.Name, " Loads"); ScheduleSheetInstance _levelScheduleSheetInstance = ScheduleSheetInstance.Create(_doc, _viewSheet.Id, _levelSchedule.Id, _levelScheduleBottomLeft); _levelAbove = _level; } _doc.Regenerate(); FamilySymbol _tagSymbol = new FilteredElementCollector(_doc) .OfCategory(BuiltInCategory.OST_MultiCategoryTags) .OfClass(typeof(FamilySymbol)).OfType <FamilySymbol>() .FirstOrDefault(p => p.FamilyName.Contains("Mark")); foreach (var _sheetWithView in _sheetsWithViews) { DimensionCreator.CreateDimensions(_sheetWithView.Item2); TagCreator.CreateTags(_sheetWithView.Item2, _tagSymbol); Viewport.Create(_doc, _sheetWithView.Item1.Id, _sheetWithView.Item2.Id, _viewCenter); } return(Result.Succeeded); }
/// <summary> /// Create a sheet to show the schedule. /// </summary> /// <param name="document">DBDocument of revit file.</param> /// <param name="schedule">View schedule which will be shown on sheet.</param> private void AddScheduleToNewSheet(Document document, ViewSchedule schedule) { //Create a filter to get all the title block types. FilteredElementCollector collector = new FilteredElementCollector(document); collector.OfCategory(BuiltInCategory.OST_TitleBlocks); collector.WhereElementIsElementType(); Transaction t = new Transaction(document, "Create and populate sheet"); t.Start(); //Get ElementId of first title block type. ElementId titleBlockId = collector.FirstElementId(); //Create sheet by gotten title block type. ViewSheet newSheet = ViewSheet.Create(document, titleBlockId); newSheet.Name = "Sheet for " + schedule.Name; document.Regenerate(); //Declare a XYZ to be used as the upperLeft point of schedule sheet instance to be created. XYZ upperLeft = new XYZ(); //If there is an existing title block. if (titleBlockId != ElementId.InvalidElementId) { //Find titleblock of the newly created sheet. collector = new FilteredElementCollector(document); collector.OfCategory(BuiltInCategory.OST_TitleBlocks); collector.OwnedByView(newSheet.Id); Element titleBlock = collector.FirstElement(); //Get bounding box of the title block. BoundingBoxXYZ bbox = titleBlock.get_BoundingBox(newSheet); //Get upperLeft point of the bounding box. upperLeft = new XYZ(bbox.Min.X, bbox.Max.Y, bbox.Min.Z); //Move the point to the postion that is 2 inches right and 2 inches down from the original upperLeft point. upperLeft = upperLeft + new XYZ(2.0 / 12.0, -2.0 / 12.0, 0); } //Create a new schedule sheet instance that makes the sheet to show the data of wall view schedule at upperLeft point. ScheduleSheetInstance placedInstance = ScheduleSheetInstance.Create(document, newSheet.Id, schedule.Id, upperLeft); t.Commit(); }
public void AddViewsToSheet(List <View> views, ElementId viewPortTypeId, bool isDuplicate, ViewDuplicateOption viewDuplicateOption) { foreach (var v in views) { var view = v; if (isDuplicate) { try { if (view.ViewType == ViewType.Schedule) { var viewid = v.Duplicate(ViewDuplicateOption.Duplicate); view = Doc.GetElement(viewid) as View; } else { var viewid = v.Duplicate(viewDuplicateOption); view = Doc.GetElement(viewid) as View; } } catch { var viewid = v.Duplicate(ViewDuplicateOption.Duplicate); view = Doc.GetElement(viewid) as View; } } try { var viewname = view.Name; if (view.ViewType != ViewType.Schedule) { var point = _data.Sel.PickPoint("Pick a Point to Place View:" + viewname); var vp = Viewport.Create(Doc, Doc.ActiveView.Id, view.Id, point); vp.ChangeTypeId(viewPortTypeId); } else { var point = _data.Sel.PickPoint("Pick a Point to Place View:" + viewname); ScheduleSheetInstance.Create(Doc, Doc.ActiveView.Id, view.Id, point); } } catch { TaskDialog.Show("Iven EXT:", v.Name + " only can added in one Sheet."); } } }
internal void PlaceOnSheet(ViewSheet sheet, IMultitableSchedule multiSchedule) { XYZ placementPoint = new XYZ(0, 0, 0); for (int i = 0; i < multiSchedule.Subschedules.Count; ++i) { if (multiSchedule.Subschedules[i].Id == ElementId.InvalidElementId) { continue; } ScheduleSheetInstance scheduleInstance = ScheduleSheetInstance .Create(m_doc, sheet.Id, multiSchedule.Subschedules[i].Id, placementPoint); placementPoint = new XYZ(0, scheduleInstance.get_BoundingBox(sheet).Min.Y + BORDER_WIDTH, 0); } }
public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements) { //Get the current Document from the Command Data Document doc = commandData.Application.ActiveUIDocument.Document; //Check to make sure the user is on a sheet before continuing. if (doc.ActiveView.ViewType == ViewType.DrawingSheet) { //Get a new UIDocument from the current document to use to make a selection UIDocument uidoc = new UIDocument(doc); //Create a new instance of the ViewSelectionFilter to only allow the user to select a ScheduleSheetIntance ISelectionFilter filter = new ViewSelectionFilter(); //A selection of elements from the current Document Selection picked = uidoc.Selection; //Try block to catch if the user cancels the selection process try { //Prompt the user to make a single selection in the Revit interface. Only Shceule Instances will be available based onour SelectionFilter. //The string is what the status bar displays in the Lower Left Reference selection = picked.PickObject(ObjectType.Element, filter, "Select Schedule on Sheet"); //Make sure the user made a selection if (picked != null) { //Set the Class variable to the Viewport the user selected ScheduleInstanceSelected = doc.GetElement(selection) as ScheduleSheetInstance; //Prompt the user with a model dialog to select the sheets to place or update the Schedules on WPF.SheetSelectionWPF frm = new WPF.SheetSelectionWPF(doc); //Make sure the Sheet Selection Form returns the correct DialogResult if (frm.ShowDialog().Value) { //Make sure the user selected at least 1 sheet if (frm.ViewSheetIds.Count > 0) { //Use this try to make sure Revit doesn't crash when trying to place or update the Schedules try { //Create a Transaction within a using block to dispose of everything when complete using (Transaction Trans = new Transaction(doc)) { //Provide a name for the transaction in the Undo / Redo List Trans.Start("Place Multiple Schedules"); foreach (ElementId viewSheetId in frm.ViewSheetIds) { //Get the ViewSheet (Sheet) fro each Element Id in the Document ViewSheet viewSheet = doc.GetElement(viewSheetId) as ViewSheet; //Use a Filtered Element Collector on the Sheet to get all ScheduleSheetInstances which is the reference to the Schedule you see //We do this to check if the Sheet already contains the Schedule we are using ICollection <Element> ScheduleInstances = new FilteredElementCollector(doc, viewSheetId).OfClass(typeof(ScheduleSheetInstance)).ToElements(); //Use this check to see if the Schedule already exists or if it needs to be created bool PlaceSchedule = true; //Loop through each Shcedule Instance on the Sheet foreach (ScheduleSheetInstance ScheduleInstance in ScheduleInstances) { //Check to see if the 'Master' ScheduleId matches the one that was selected by the User if (ScheduleInstance.ScheduleId == ScheduleInstanceSelected.ScheduleId) { //Set the bool to False since the Sheet already contains the schedule, we don't need to create it PlaceSchedule = false; //Move the Schedule on the Sheet to match the same location as the one Selected ScheduleInstance.Point = ScheduleInstanceSelected.Point; } } //If the Schedule was not found on the sheet, the bool stayed True so this will execute if (PlaceSchedule) { //Create a new Sheet Schedule Intance on the Sheet based on the Schedule Selected and at the same location ScheduleSheetInstance.Create(doc, viewSheetId, ScheduleInstanceSelected.ScheduleId, ScheduleInstanceSelected.Point); } } //Commit the Transaction to keep the changes Trans.Commit(); //Return a successful result to Revit so the changes are kept return(Result.Succeeded); } } //Catch an exceptions when adding or updating the Sheet Schedule instances. Tell the user and return a Failed Result so Revit does not keep any changes catch (Exception ex) { TaskDialog.Show("Schedule Placement Error", ex.ToString()); return(Result.Failed); } } //Tell the user that they did not select any sheets and return a Cancelled result so Revit does not keep any changes else { TaskDialog.Show("Sheet Selection", "No Sheets were selected"); return(Result.Cancelled); } } //If the Sheet Selection form was closed or cancelled then return a Cancelled result so Revit does not keep any changes else { return(Result.Cancelled); } } return(Result.Cancelled); } //Catch the Operation canceled Exception which is raised when the user "Escapes" during a Pick Object operation and return a Failed result catch (Autodesk.Revit.Exceptions.OperationCanceledException) { return(Result.Failed); } } //Tell the user that they need to be in a Sheet View to run this Command else { TaskDialog.Show("Sheet Required", "Active view must be a Sheet"); return(Result.Cancelled); } }
public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements) { // Get application and document objects UIApplication ui_app = commandData.Application; UIDocument ui_doc = ui_app?.ActiveUIDocument; Document doc = ui_doc?.Document; ViewSheet vs = doc.ActiveView as ViewSheet; try { using (Transaction t = new Transaction(doc, "Duplicate Sheet")) { t.Start(); FamilyInstance titleblock = new FilteredElementCollector(doc).OfClass(typeof(FamilyInstance)).OfCategory(BuiltInCategory.OST_TitleBlocks).Cast <FamilyInstance>().First(q => q.OwnerViewId == vs.Id); ViewSheet newsheet = ViewSheet.Create(doc, titleblock.GetTypeId()); newsheet.SheetNumber = vs.SheetNumber + "-COPY"; newsheet.Name = vs.Name; // all views but schedules foreach (ElementId eid in vs.GetAllPlacedViews()) { View ev = doc.GetElement(eid) as View; View newview = null; // legends if (ev.ViewType == ViewType.Legend) { newview = ev; } // all non-legend and non-schedule views else { if (ev.CanViewBeDuplicated(ViewDuplicateOption.AsDependent)) { ElementId newviewid = ev.Duplicate(ViewDuplicateOption.AsDependent); newview = doc.GetElement(newviewid) as View; //newview.Name = ev.Name + "-COPY"; } } foreach (Viewport vp in new FilteredElementCollector(doc).OfClass(typeof(Viewport))) { if (vp.SheetId == vs.Id && vp.ViewId == ev.Id) { BoundingBoxXYZ vpbb = vp.get_BoundingBox(vs); XYZ initialCenter = (vpbb.Max + vpbb.Min) / 2; Viewport newvp = Viewport.Create(doc, newsheet.Id, newview.Id, XYZ.Zero); BoundingBoxXYZ newvpbb = newvp.get_BoundingBox(newsheet); XYZ newCenter = (newvpbb.Max + newvpbb.Min) / 2; ElementTransformUtils.MoveElement(doc, newvp.Id, new XYZ( initialCenter.X - newCenter.X, initialCenter.Y - newCenter.Y, 0)); } } // end for each } // end for each // schedules foreach (ScheduleSheetInstance si in (new FilteredElementCollector(doc).OfClass(typeof(ScheduleSheetInstance)))) { if (si.OwnerViewId == vs.Id) { if (!si.IsTitleblockRevisionSchedule) { foreach (ViewSchedule vsc in new FilteredElementCollector(doc).OfClass(typeof(ViewSchedule))) { if (si.ScheduleId == vsc.Id) { BoundingBoxXYZ sibb = si.get_BoundingBox(vs); XYZ initialCenter = (sibb.Max + sibb.Min) / 2; ScheduleSheetInstance newssi = ScheduleSheetInstance.Create(doc, newsheet.Id, vsc.Id, XYZ.Zero); BoundingBoxXYZ newsibb = newssi.get_BoundingBox(newsheet); XYZ newCenter = (newsibb.Max + newsibb.Min) / 2; ElementTransformUtils.MoveElement(doc, newssi.Id, new XYZ( initialCenter.X - newCenter.X, initialCenter.Y - newCenter.Y, 0)); } } } } }// end foreach t.Commit(); }// end using // Implement Selection Filter to select curves // Measure their total length // Return a message window that displays total length to user // Assuming that everything went right return Result.Succeeded return(Result.Succeeded); } // This is where we "catch" potential errors and define how to deal with them catch (Autodesk.Revit.Exceptions.OperationCanceledException) { // If user decided to cancel the operation return Result.Canceled return(Result.Cancelled); } catch (Exception ex) { // If something went wrong return Result.Failed message = ex.Message; return(Result.Failed); } }
/// <summary> /// Duplicates the input sheet a number of times. It allows for ViewDuplicateOption for dependent views. /// </summary> /// <param name="m_doc"></param> /// <param name="sourceSheet"></param> /// <param name="copies"></param> /// <param name="dependentOption"></param> private void DuplicateSheets(Document m_doc, ViewSheet sourceSheet, int copies, ViewDuplicateOption dependentOption) { // get Title Block FamilyInstance titleBlock = new FilteredElementCollector(m_doc) .OfClass(typeof(FamilyInstance)) .OfCategory(BuiltInCategory.OST_TitleBlocks) .Cast <FamilyInstance>() .First(q => q.OwnerViewId == sourceSheet.Id); using (TransactionGroup tg = new TransactionGroup(m_doc, "Duplicate Sheet")) { tg.Start(); for (int i = 0; i < copies; i++) { // create unique sheet number string uniqueSheetNumber = Data.Helpers.CreateUniqueSheetNumber(m_doc, sourceSheet); using (Transaction t = new Transaction(m_doc, "Duplicate Sheet")) { t.Start(); // create new SHEET, new NUMBER and new NAME ViewSheet newSheet = ViewSheet.Create(m_doc, titleBlock.GetTypeId()); newSheet.SheetNumber = uniqueSheetNumber; newSheet.Name = sourceSheet.Name; #region Loop through viewports (except schedules) because GetAllPlacedViews() does not return Schedules foreach (ElementId eid in sourceSheet.GetAllPlacedViews()) { // get view element Autodesk.Revit.DB.View sourceView = m_doc.GetElement(eid) as Autodesk.Revit.DB.View; Autodesk.Revit.DB.View newView = null; // declare newView variable // DUPLICATE views // if view element is legend newView is equal to sourceView if (sourceView.ViewType == ViewType.Legend) { newView = sourceView; } else // for non-legend views { if (sourceView.GetPrimaryViewId() == ElementId.InvalidElementId) // if parent view { ElementId newViewId = sourceView.Duplicate(ViewDuplicateOption.WithDetailing); newView = m_doc.GetElement(newViewId) as Autodesk.Revit.DB.View; newView.Name = Data.Helpers.CreateUniqueViewName(m_doc, sourceView); //newView.ChangeTypeId(sourceTypeId); } else // if dependent view { ElementId newViewId = sourceView.Duplicate(dependentOption); newView = m_doc.GetElement(newViewId) as Autodesk.Revit.DB.View; newView.Name = Data.Helpers.CreateUniqueViewName(m_doc, sourceView); //newView.ChangeTypeId(sourceTypeId); } } // CREATE viewport and MOVE it foreach (Viewport vp in new FilteredElementCollector(m_doc).OfClass(typeof(Viewport))) { if (vp.SheetId == sourceSheet.Id && vp.ViewId == sourceView.Id) { XYZ sourceCenter = vp.GetBoxCenter(); ElementId sourceTypeId = vp.GetTypeId(); Viewport newViewport = Viewport.Create(m_doc, newSheet.Id, newView.Id, XYZ.Zero); newViewport.ChangeTypeId(sourceTypeId); Ana_NoOfViewports += 1; // add 1 to the viewport counter XYZ newCenter = newViewport.GetBoxCenter(); ElementTransformUtils.MoveElement(m_doc, newViewport.Id, new XYZ( sourceCenter.X - newCenter.X, sourceCenter.Y - newCenter.Y, 0)); } } } #endregion #region Loop through schedules foreach (ScheduleSheetInstance si in (new FilteredElementCollector(m_doc).OfClass(typeof(ScheduleSheetInstance)))) { if (si.OwnerViewId == sourceSheet.Id) { if (!si.IsTitleblockRevisionSchedule) { foreach (ViewSchedule viewSchedule in new FilteredElementCollector(m_doc).OfClass(typeof(ViewSchedule))) { if (si.ScheduleId == viewSchedule.Id) { XYZ sourceCenter = si.Point; ScheduleSheetInstance newSSheetInstance = ScheduleSheetInstance.Create(m_doc, newSheet.Id, viewSchedule.Id, XYZ.Zero); XYZ newCenter = newSSheetInstance.Point; ElementTransformUtils.MoveElement(m_doc, newSSheetInstance.Id, new XYZ( sourceCenter.X - newCenter.X, sourceCenter.Y - newCenter.Y, 0)); } } } } } #endregion t.Commit(); } } tg.Assimilate(); } }
private static Result createPourSheets(UIDocument uiDoc) { //ToDo: these might be good as settings in a future UI string _titleblockName = "E1 30 x 42 Horizontal: E1 30x42 Horizontal"; //string _elementName = "C-2"; // "EllisShore_LumberWithClamps"; // //int _3dViewScale = 48; //XYZ _3dViewportCenter = new XYZ(2.21129429621462, 0.656294714474886, 0); // //int _sectionViewScale = 32; //XYZ _sectionViewportCenter = new XYZ(0.7791340191012, 1.72774616204266, 0); int _floorplanViewScale = 24; XYZ _floorplanViewportCenter = new XYZ(1.23473112570493, 1.15208223453682, 0); XYZ _columnScheduleBottomLeft = new XYZ(2.31721454780864, 2.37688649933288, 0); XYZ _levelScheduleBottomLeft = new XYZ(0.156336990263879, 2.37688649933288, 0); Document _doc = uiDoc.Document; //Get a BoundedView3DDefinition for each Level - Scope Box in the project var _levels = Getters.GetLevels(_doc); var _scopeBoxes = Getters.GetScopeBoxes(_doc); var _boundedViewCreators = new List <BoundedViewCreator>(); double _extraExtents = 0.5; foreach (Level _level in _levels) { Level _levelAbove = _levels.FirstOrDefault(p => p.Elevation > _level.Elevation); if (_levelAbove == null) { continue; } foreach (Element _scopeBox in _scopeBoxes) { BoundingBoxXYZ _scopeBoxBounds = _scopeBox.get_BoundingBox(null); BoundingBoxXYZ _viewBounds = new BoundingBoxXYZ { Min = new XYZ( _scopeBoxBounds.Min.X - _extraExtents, _scopeBoxBounds.Min.Y - _extraExtents, _level.Elevation - _extraExtents), Max = new XYZ( _scopeBoxBounds.Max.X + _extraExtents, _scopeBoxBounds.Max.Y + _extraExtents, _levelAbove.Elevation + _extraExtents) }; _boundedViewCreators.Add(new BoundedViewCreator(_level, _scopeBox, _viewBounds)); } } //Generate Views, set their Boundaries & Names, Adjust Visiblity Graphics OverrideGraphicSettings _70Transparent = new OverrideGraphicSettings(); _70Transparent.SetSurfaceTransparency(70); List <Tuple <ElementId, string, List <View> > > _createdSheetIdViewIdSets = new List <Tuple <ElementId, string, List <View> > >(); foreach (var _boundedViewCreator in _boundedViewCreators) { SheetCreator _sheetCreator = new SheetCreator(_doc); //Create Sheet string _pourName = _boundedViewCreator.GetViewName(string.Empty, string.Empty); ViewSheet _viewSheet = _sheetCreator.CreateSheet(_titleblockName, _pourName, _pourName); ////Create 3D View //View3D _3DView = _boundedViewCreator.CreateView3D(_3dViewScale); //_3DView.SetCategoryHidden(new ElementId(BuiltInCategory.OST_VolumeOfInterest), true); //_3DView.SetCategoryOverrides(new ElementId(BuiltInCategory.OST_Floors), _70Transparent); //Create Floorplan View ViewPlan _floorPlanView = _boundedViewCreator.CreateViewPlan(_floorplanViewScale); _floorPlanView.SetCategoryHidden(new ElementId(BuiltInCategory.OST_VolumeOfInterest), true); _floorPlanView.SetCategoryOverrides(new ElementId(BuiltInCategory.OST_Floors), _70Transparent); ////Create Section View //ViewSection _sectionView = _boundedViewCreator.CreateViewSection(_sectionViewScale); //_sectionView.SetCategoryHidden(new ElementId(BuiltInCategory.OST_VolumeOfInterest), true); //_sectionView.SetCategoryOverrides(new ElementId(BuiltInCategory.OST_Floors), _70Transparent); //Create Schedules ViewSchedule _columnSchedule = ScheduleCreator.CreatePourColumnSchedule(_doc, _pourName, " Reshores"); ScheduleSheetInstance _columnScheduleSheetInstance = ScheduleSheetInstance.Create(_doc, _viewSheet.Id, _columnSchedule.Id, _columnScheduleBottomLeft); ViewSchedule _levelSchedule = ScheduleCreator.CreatePourLoadSchedule(_doc, _boundedViewCreator.Level?.Name, " - " + _boundedViewCreator.ScopeBox?.Name + " Loads"); ScheduleSheetInstance _levelScheduleSheetInstance = ScheduleSheetInstance.Create(_doc, _viewSheet.Id, _levelSchedule.Id, _levelScheduleBottomLeft); _createdSheetIdViewIdSets.Add(new Tuple <ElementId, string, List <View> >( _viewSheet.Id, _pourName, new List <View> { /*_3DView,*/ _floorPlanView, /*_sectionView*/ } )); } _doc.Regenerate(); FamilySymbol _tagSymbol = new FilteredElementCollector(_doc) .OfCategory(BuiltInCategory.OST_MultiCategoryTags) .OfClass(typeof(FamilySymbol)).OfType <FamilySymbol>() .FirstOrDefault(p => p.FamilyName.Contains("Mark")); foreach (var _createdSheetIdViewIdSet in _createdSheetIdViewIdSets) { foreach (View _view in _createdSheetIdViewIdSet.Item3) { if (_view == null) { continue; } //if (_view is View3D) Viewport.Create(_doc, _createdSheetIdViewIdSet.Item1, _view.Id, _3dViewportCenter); else if (_view is ViewPlan) { DimensionCreator.CreateDimensions(_view); TagCreator.CreateTags(_view, _tagSymbol); Viewport.Create(_doc, _createdSheetIdViewIdSet.Item1, _view.Id, _floorplanViewportCenter); } //else if (_view is ViewSection) Viewport.Create(_doc, _createdSheetIdViewIdSet.Item1, _view.Id, _sectionViewportCenter); } } return(Result.Succeeded); }
public void ProcessSelection() { using (Transaction trans = new Transaction(activeDoc, "CopyLegends")) { trans.Start(); foreach (SheetWrapper sw in Sheets) { if (sw.SelectSheet) { // extract elements from element references foreach (Reference r in selectedViews) { Element e = activeDoc.GetElement(r.ElementId); // check if element is schedule or legend if (e.Category.Id.IntegerValue.Equals((int)BuiltInCategory.OST_ScheduleGraphics)) { // process as schedule try { ScheduleSheetInstance sch = (ScheduleSheetInstance)e; bool scheduleOnSheet = false; // get viewsheet and check if schedule already on sheet // if schedule on sheet adjust position else create new foreach (ScheduleSheetInstance si in new FilteredElementCollector(activeDoc) .OfClass(typeof(ScheduleSheetInstance))) { if (si.OwnerViewId == sw.ID && si.ScheduleId == sch.ScheduleId) { si.Point = sch.Point; scheduleOnSheet = true; } else { continue; } } if (!scheduleOnSheet) { // create new schedule instance ScheduleSheetInstance.Create(activeDoc, sw.ID, sch.ScheduleId, sch.Point); } } catch (Exception) { } } else { // process as legend try { Viewport vp = (Viewport)e; bool legendOnSheet = false; // get all viewports on this sheet and check if legend already on sheet // if legend on sheet adjust position else add new one ViewSheet vs = activeDoc.GetElement(sw.ID) as ViewSheet; ICollection<ElementId> allViewports = vs.GetAllViewports(); foreach (ElementId id in allViewports) { Viewport currentVp = activeDoc.GetElement(id) as Viewport; if (currentVp.ViewId == vp.ViewId) { currentVp.SetBoxCenter(vp.GetBoxCenter()); legendOnSheet = true; } else { continue; } } if (!legendOnSheet) { // create new legend on sheet Viewport.Create(activeDoc, sw.ID, vp.ViewId, vp.GetBoxCenter()); } } catch (Exception) { } } } } } trans.Commit(); } }
public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements) { Document doc = commandData.Application.ActiveUIDocument.Document; // Retrieve active view View activeView = doc.ActiveView; ViewType activeViewType = activeView.ViewType; if (activeViewType == ViewType.DrawingSheet) { TaskDialog.Show("Error", "Current view is a sheet. Please open a view."); return(Result.Succeeded); } using (ViewSheetsWindow VOSwindow = new ViewSheetsWindow(commandData)) { // Revit application as window's owner System.Windows.Interop.WindowInteropHelper helper = new System.Windows.Interop.WindowInteropHelper(VOSwindow); helper.Owner = System.Diagnostics.Process.GetCurrentProcess().MainWindowHandle; VOSwindow.ShowDialog(); // List with all selected sheets List <int> intIds = VOSwindow.listIds; // Check if view is already on sheets bool isViewOnSheet = Helpers.Helpers.IsViewOnSheet(doc, activeView); bool viewPlaced = false; // List to store views placed on sheet var viewSheetSuccess = new List <string>(); // Transaction Transaction transactionViews = new Transaction(doc, "Place Views on Sheets"); transactionViews.Start(); // Place view on selected sheets foreach (var item in intIds) { ElementId eId = new ElementId(item); ViewSheet sheet = doc.GetElement(eId) as ViewSheet; // Set view placement point XYZ centerTitleBlock; try { // Retrieve title block FamilyInstance tBlock = new FilteredElementCollector(doc, sheet.Id) .OfCategory(BuiltInCategory.OST_TitleBlocks) .FirstElement() as FamilyInstance; // Retrieve title block size double sheetHeight = tBlock.get_Parameter(BuiltInParameter.SHEET_HEIGHT).AsDouble(); double sheetWidth = tBlock.get_Parameter(BuiltInParameter.SHEET_WIDTH).AsDouble(); // Center of title block centerTitleBlock = new XYZ(sheetWidth / 2, sheetHeight / 2, 0); } catch { centerTitleBlock = new XYZ(); // TODO: Error log } // If activeView is a schedule if (activeViewType == ViewType.Schedule || activeViewType == ViewType.ColumnSchedule || activeViewType == ViewType.PanelSchedule) { ScheduleSheetInstance.Create(doc, sheet.Id, activeView.Id, centerTitleBlock); // Mark sheet as successfully placed viewSheetSuccess.Add(sheet.SheetNumber); } // View is a legend else if (activeViewType == ViewType.Legend) { // Place legend if it is not placed on any sheet if (isViewOnSheet == false) { Viewport.Create(doc, sheet.Id, activeView.Id, centerTitleBlock); // Mark sheet as successfully placed viewSheetSuccess.Add(sheet.SheetNumber); } // Check where is the legend placed on else { ISet <ElementId> viewIds = sheet.GetAllPlacedViews(); bool flagLegend = true; // Check if legend is placed on selected sheet foreach (var vId in viewIds) { if (vId == activeView.Id) { flagLegend = false; TaskDialog.Show("Warning", $"Legend already placed on {sheet.Name}."); break; } } // Placed on selected sheet if it is not placed already if (flagLegend) { Viewport.Create(doc, sheet.Id, activeView.Id, centerTitleBlock); // Mark sheet as successfully placed viewSheetSuccess.Add(sheet.SheetNumber); } } } // If activeView is already place on a sheet else if (isViewOnSheet || viewPlaced == true) { // Duplicate view ElementId viewId = activeView.Duplicate(ViewDuplicateOption.WithDetailing); // Place duplicated view on sheet Viewport.Create(doc, sheet.Id, viewId, centerTitleBlock); // Mark sheet as successfully placed viewSheetSuccess.Add(sheet.SheetNumber); } // If activeView is not on sheet else { Viewport.Create(doc, sheet.Id, activeView.Id, centerTitleBlock); viewPlaced = true; // Mark sheet as successfully placed viewSheetSuccess.Add(sheet.SheetNumber); } } // Commit transaction transactionViews.Commit(); // Display result message to user if (viewSheetSuccess.Count > 0) { TaskDialog.Show("Success", activeView.Name + " has been placed on: \n" + string.Join("\n", viewSheetSuccess)); } } return(Result.Succeeded); }
private bool DoWork(ExternalCommandData commandData, ref String message, ElementSet elements) { if (null == commandData) { throw new ArgumentNullException(nameof(commandData)); } if (null == message) { throw new ArgumentNullException(nameof(message)); } if (null == elements) { throw new ArgumentNullException(nameof(elements)); } ResourceManager res_mng = new ResourceManager(GetType()); ResourceManager def_res_mng = new ResourceManager(typeof(Properties.Resources)); UIApplication ui_app = commandData.Application; UIDocument ui_doc = ui_app?.ActiveUIDocument; Application app = ui_app?.Application; Document doc = ui_doc?.Document; Selection selection = ui_doc?.Selection; var tr_name = res_mng.GetString("_transaction_name"); try { using (var tr = new Transaction(doc, tr_name)) { if (TransactionStatus.Started == tr.Start() ) { ProjectSettingsStorage pStore = new ProjectSettingsStorage(); ProjectSettings set = pStore.ReadSettings(doc); ICollection <ElementId> selectedIds = selection.GetElementIds(); ICollection <ElementId> panelIds = new List <ElementId>(); IList <ElementId> elems = new List <ElementId>(); IList <bool> check = new List <bool>(); if (0 == selectedIds.Count) { // If no elements selected. TaskDialog.Show("Revit", "You haven't selected any elements."); } else { int totalCount = 0; int currentCount = 0; int localTotal = 10; int localCurrent = 0; String info = "The following assemblies have successfully been created: "; foreach (ElementId id in selectedIds) { Element elem = ui_doc.Document.GetElement(id); elem.LookupParameter("BIMSF_Container"); //foreach (Parameter pa in elem.Parameters) //{ //if (pa.Definition.Name == "BIMSF_Container" && pa.AsString() != null && elem.get_Parameter(BuiltInParameter.ASSEMBLY_NAME) == null) if (elem.LookupParameter("BIMSF_Container") != null && elem.get_Parameter(BuiltInParameter.ASSEMBLY_NAME) == null) { panelIds.Add(id); totalCount += 1; } //} } ProgressForm pf = new ProgressForm(String.Format("{0} of {1} panels processed", currentCount, totalCount), "Creating wall assembly...", (int)100 / totalCount, (int)100 / localTotal); string localString = "Creating wall assembly..."; string globalString = String.Format("{0} of {1} panels processed", currentCount, totalCount); pf.LabelSet(localString, false, false, globalString, false); pf.Show(); foreach (ElementId id in panelIds) { Element elem = ui_doc.Document.GetElement(id); //foreach (Parameter pa in elem.Parameters) //{ Parameter pa = elem.LookupParameter("BIMSF_Container"); if (pa.Definition.Name == "BIMSF_Container" && pa.AsString() != null && elem.get_Parameter(BuiltInParameter.ASSEMBLY_NAME) == null) { ElementId ida = new ElementId(pa.Id.IntegerValue); elems.Clear(); ParameterValueProvider provider = new ParameterValueProvider(ida); FilterStringRuleEvaluator eval = new FilterStringEquals(); FilterRule rule = new FilterStringRule(provider, eval, elem.get_Parameter(pa.Definition).AsString(), false); ElementParameterFilter filter = new ElementParameterFilter(rule); FilteredElementCollector fec = new FilteredElementCollector(ui_doc.Document).WhereElementIsNotElementType().WherePasses(filter); foreach (Element e in fec) { elems.Add(e.Id); } FilteredElementCollector fecC = new FilteredElementCollector(doc, elems).OfCategory(BuiltInCategory.OST_StructuralColumns); FilteredElementCollector fecF = new FilteredElementCollector(doc, elems).OfCategory(BuiltInCategory.OST_StructuralFraming); ElementId categoryId = doc.GetElement(elems.First()).Category.Id; // use category of one of the assembly elements if (AssemblyInstance.IsValidNamingCategory(doc, categoryId, elems)) { TransactionStatus tStat = tr.HasStarted() ? tr.GetStatus() : tr.Start(); pf.LabelSet(localString, true, false, globalString, false); //IList<Element> el = new List<Element>(); //IList<Element> col = new List<Element>(); ReferenceArray colArray = new ReferenceArray(); ReferenceArray framArray = new ReferenceArray(); colArray.Clear(); framArray.Clear(); AssemblyInstance assemblyInstance = AssemblyInstance.Create(doc, elems, categoryId); XYZ pt1 = assemblyInstance.GetTransform().BasisZ; XYZ pt2 = assemblyInstance.GetCenter(); /*el.Clear(); * col.Clear(); * * foreach (Element co in fecC) * { * col.Add(co); * }*/ foreach (Element fr in fecF) { //el.Add(fr); FamilyInstance fi = fr as FamilyInstance; framArray.Append(fi.GetReferenceByName("HardSide")); } /*foreach (ElementId item in elems) * { * if (doc.GetElement(item).Category.Name == "Structural Framing") * { * el.Add(doc.GetElement(item)); * FamilyInstance fi = doc.GetElement(item) as FamilyInstance; * framArray.Append(fi.GetReferenceByName("HardSide")); * }else if (doc.GetElement(item).Category.Name == "Structural Columns") * { * col.Add(doc.GetElement(item)); * } * }*/ //Element il = el.First(); LocationCurve lc = fecF.FirstElement().Location as LocationCurve; Curve line = lc.Curve; XYZ start = line.GetEndPoint(0); XYZ end = line.GetEndPoint(1); XYZ v = (end - start); double angle = v.AngleTo(XYZ.BasisX); foreach (Element column in fecC) { FamilyInstance fi = column as FamilyInstance; LocationPoint colLc = column.Location as LocationPoint; double colAngle = colLc.Rotation; if (Math.Round(colAngle, 2) == Math.Round(angle, 2) || Math.Round(colAngle, 2) == Math.Round(angle + Math.PI, 2) || Math.Round(colAngle, 2) == Math.Round(angle - Math.PI, 2)) { colArray.Append(fi.GetReferenceByName("HardSide")); //TaskDialog.Show("HardSide", colAngle + "\n" + angle); } else { colArray.Append(fi.GetReferenceByName("LeftSide")); //TaskDialog.Show("Revit",colAngle + "\n" + angle); } } //TaskDialog.Show("Revit", angle.ToString()); Transform trf = Transform.CreateRotationAtPoint(pt1, angle, pt2); assemblyInstance.SetTransform(trf); tr.Commit(); // commit the transaction that creates the assembly instance before modifying the instance's name localCurrent += 1; localString = "Creating 3D view..."; pf.LabelSet(localString, true, false, globalString, false); if (tr.GetStatus() == TransactionStatus.Committed) { tr.Start("Set Assembly Name"); assemblyInstance.AssemblyTypeName = elem.get_Parameter(pa.Definition).AsString(); info += "\n" + assemblyInstance.AssemblyTypeName; tr.Commit(); } if (assemblyInstance.AllowsAssemblyViewCreation()) // create assembly views for this assembly instance { if (tr.GetStatus() == TransactionStatus.Committed) { tr.Start("View Creation"); View3D view3D = AssemblyViewUtils.Create3DOrthographic(doc, assemblyInstance.Id); localCurrent += 1; localString = "Creating elevation view..."; pf.LabelSet(localString, true, false, globalString, false); View elView = AssemblyViewUtils.CreateDetailSection(doc, assemblyInstance.Id, AssemblyDetailViewOrientation.ElevationFront); localCurrent += 1; localString = "Populating elevation view..."; pf.LabelSet(localString, true, false, globalString, false); TagMode tm = TagMode.TM_ADDBY_CATEGORY; bool addLead = false; XYZ center; TagOrientation to; foreach (Element co in fecC) { to = TagOrientation.Vertical; LocationPoint cols = co.Location as LocationPoint; XYZ colPt = cols.Point; double colX = colPt.X; double colY = colPt.Y; ElementId blId = co.get_Parameter(BuiltInParameter.FAMILY_BASE_LEVEL_PARAM).AsElementId(); Level bl = doc.GetElement(blId) as Level; double zb = bl.Elevation; double blo = co.get_Parameter(BuiltInParameter.FAMILY_BASE_LEVEL_OFFSET_PARAM).AsDouble(); double bot = zb + blo; ElementId tlId = co.get_Parameter(BuiltInParameter.FAMILY_TOP_LEVEL_PARAM).AsElementId(); Level tl = doc.GetElement(tlId) as Level; double zt = tl.Elevation; double tlo = co.get_Parameter(BuiltInParameter.FAMILY_TOP_LEVEL_OFFSET_PARAM).AsDouble(); double top = zt + tlo; double zCent = (top + bot) / 2; center = new XYZ(colX, colY, zCent); Reference refer = new Reference(co); IndependentTag.Create(doc, elView.Id, refer, addLead, tm, to, center); } foreach (Element fr in fecF) { to = TagOrientation.Horizontal; LocationCurve loc = fr.Location as LocationCurve; XYZ start2 = loc.Curve.GetEndPoint(0); XYZ end2 = loc.Curve.GetEndPoint(1); center = (start2 + end2) / 2; Reference refer = new Reference(fr); IndependentTag.Create(doc, elView.Id, refer, addLead, tm, to, center); } /*foreach (ElementId eI in elems) * { * Element e = doc.GetElement(eI); * * if ((BuiltInCategory)e.Category.Id.IntegerValue == BuiltInCategory.OST_StructuralColumns || (BuiltInCategory)e.Category.Id.IntegerValue == BuiltInCategory.OST_StructuralFraming) * { * XYZ center; * TagOrientation to; * if ((BuiltInCategory)e.Category.Id.IntegerValue == BuiltInCategory.OST_StructuralColumns) * { * to = TagOrientation.Vertical; * LocationPoint cols = e.Location as LocationPoint; * XYZ colPt = cols.Point; * double colX = colPt.X; * double colY = colPt.Y; * ElementId blId = e.get_Parameter(BuiltInParameter.FAMILY_BASE_LEVEL_PARAM).AsElementId(); * Level bl = doc.GetElement(blId) as Level; * double zb = bl.Elevation; * double blo = e.get_Parameter(BuiltInParameter.FAMILY_BASE_LEVEL_OFFSET_PARAM).AsDouble(); * double bot = zb + blo; * * ElementId tlId = e.get_Parameter(BuiltInParameter.FAMILY_TOP_LEVEL_PARAM).AsElementId(); * Level tl = doc.GetElement(tlId) as Level; * double zt = tl.Elevation; * double tlo = e.get_Parameter(BuiltInParameter.FAMILY_TOP_LEVEL_OFFSET_PARAM).AsDouble(); * double top = zt + tlo; * double zCent = (top + bot) / 2; * * center = new XYZ(colX,colY,zCent); * } * else * { * to = TagOrientation.Horizontal; * LocationCurve loc = e.Location as LocationCurve; * XYZ start2 = loc.Curve.GetEndPoint(0); * XYZ end2 = loc.Curve.GetEndPoint(1); * center = (start2 + end2) / 2; * } * * * Reference refer = new Reference(e); * IndependentTag.Create(doc, elView.Id, refer, addLead, tm, to, center); * * } * * }*/ try { //LocationCurve framC = fecF.FirstElement().Location as LocationCurve; FamilyInstance fi = fecC.FirstElement() as FamilyInstance; //Transform fiP = fi.GetTransform(); LocationPoint col1 = fecC.FirstElement().Location as LocationPoint; //XYZ test = fiP.OfPoint(col1.Point); ElementId col1Bot = fecC.FirstElement().get_Parameter(BuiltInParameter.FAMILY_BASE_LEVEL_PARAM).AsElementId(); Level col1LB = doc.GetElement(col1Bot) as Level; double bottom = col1LB.Elevation; ElementId col1Top = fecC.FirstElement().get_Parameter(BuiltInParameter.FAMILY_TOP_LEVEL_PARAM).AsElementId(); Level col1LT = doc.GetElement(col1Top) as Level; double top = col1LT.Elevation; //Line framT = framC.Curve as Line; //XYZ framP = framT.Origin; Line framL = Line.CreateBound(new XYZ(col1.Point.X, col1.Point.Y, bottom), new XYZ(col1.Point.X, col1.Point.Y, top)); Dimension di = doc.Create.NewDimension(elView, framL, framArray); di.DimensionType = doc.GetElement(set.HorizontalDimFlr) as DimensionType; } catch (Exception e) { TaskDialog.Show("Revit", e.Message + "\n" + e.Source); } try { LocationCurve framC = fecF.FirstElement().Location as LocationCurve; ElementId col1Bot = fecC.FirstElement().get_Parameter(BuiltInParameter.FAMILY_BASE_LEVEL_PARAM).AsElementId(); Level col1LB = doc.GetElement(col1Bot) as Level; double bottom = col1LB.Elevation; Line framT = framC.Curve as Line; XYZ framS = framT.GetEndPoint(0); XYZ framE = framT.GetEndPoint(1); //Line framL = framT.CreateOffset(-1, XYZ.BasisZ) as Line; //XYZ framP = framT.Origin; Line framL = Line.CreateBound(new XYZ(framS.X, framS.Y, bottom - 1.5), new XYZ(framE.X, framE.Y, bottom - 1.5)); Dimension di = doc.Create.NewDimension(elView, framL, colArray); di.DimensionType = doc.GetElement(set.HeightDimWa) as DimensionType; LocationPoint clp = fecC.FirstElement().Location as LocationPoint; } catch (Exception e) { TaskDialog.Show("Revit", e.Message + "\n" + e.Source); } localCurrent += 1; localString = "Creating plan view..."; pf.LabelSet(localString, true, false, globalString, false); View plView = AssemblyViewUtils.CreateDetailSection(doc, assemblyInstance.Id, AssemblyDetailViewOrientation.ElevationTop); localCurrent += 1; localString = "Creating material takeoff schedule..."; pf.LabelSet(localString, true, false, globalString, false); ViewSchedule partList = AssemblyViewUtils.CreatePartList(doc, assemblyInstance.Id); XYZ pt3D = new XYZ(0.1, 0.45, 0); XYZ ptEl = new XYZ(0.5, 0.5, 0); XYZ ptPl = new XYZ(0.5, 0.5, 0); XYZ ptPa = new XYZ(0.03, 0.1, 0); if (set != null) { view3D.ViewTemplateId = set.View3DTemplate; } if (set != null) { elView.ViewTemplateId = set.ViewElTemplate; } if (set != null) { plView.ViewTemplateId = set.ViewPlTemplate; } if (set != null) { partList.ViewTemplateId = set.ViewPaTemplate; } if (set != null) { try { localCurrent += 1; localString = "Creating spool sheet..."; pf.LabelSet(localString, true, false, globalString, false); ElementType noTitle = null; FilteredElementCollector fen = new FilteredElementCollector(doc).OfClass(typeof(ElementType)); foreach (Element item in fen) { if (item.Name == "No Title") { noTitle = item as ElementType; } } ViewSheet sheet = AssemblyViewUtils.CreateSheet(doc, assemblyInstance.Id, set.TemplateTemplate); localCurrent += 1; localString = "Adding views to sheet..."; pf.LabelSet(localString, true, false, globalString, false); Viewport v3D = AddViewToSheet(doc, sheet, noTitle, pt3D, view3D.Id); Viewport vEl = AddViewToSheet(doc, sheet, noTitle, ptEl, elView.Id); BoundingBoxXYZ bbEl = vEl.get_BoundingBox(sheet); Viewport vPl = AddViewToSheet(doc, sheet, noTitle, ptPl, plView.Id); BoundingBoxXYZ bbPl = vPl.get_BoundingBox(sheet); ScheduleSheetInstance vPa = ScheduleSheetInstance.Create(doc, sheet.Id, partList.Id, ptPa); localCurrent += 1; localString = "Cleaning up spool sheet..."; pf.LabelSet(localString, true, false, globalString, false); BoundingBoxXYZ bb = sheet.CropBox; BoundingBoxXYZ bbvPa = vPa.get_BoundingBox(sheet); double minX = bb.Min.X; double maxX = bb.Max.X; double xLen = maxX - minX; //TaskDialog.Show("Revit",minX + ", " + maxX + "\n" +bbvPa.Min.Y + ", " + bbvPa.Max.Y + "\n" + bbPl.Min.X + ", " + bbPl.Min.Y); vPa.Point = new XYZ(vPa.Point.X, vPa.Point.Y - bbvPa.Min.Y, vPa.Point.Z); double schedX = bbvPa.Max.X + 0.03; double centEl = (bbEl.Max.X - bbEl.Min.X) / 2; double centElY = (bbEl.Max.Y - bbEl.Min.Y) / 2; double centPlY = (bbPl.Max.Y - bbPl.Min.Y) / 2; vEl.SetBoxCenter(new XYZ(schedX + centEl, (centPlY + 0.05) * 2 + centElY, vEl.GetBoxCenter().Z)); vPl.SetBoxCenter(new XYZ(schedX + centEl, centPlY + 0.05, vPl.GetBoxCenter().Z)); sheet.SheetNumber = elem.get_Parameter(pa.Definition).AsString(); sheet.Name = "Framing"; } catch (Exception ex) { TaskDialog.Show("Error", ex.Message); break; } } localCurrent += 1; localString = String.Format("Wall assembly {0} completed...", elem.get_Parameter(pa.Definition).AsString()); pf.LabelSet(localString, true, false, globalString, false); tr.Commit(); localCurrent = 0; } } currentCount += 1; globalString = String.Format("{0} of {1} panels processed", currentCount, totalCount); pf.LabelSet(localString, false, true, globalString, true); } //info += "\n\t" + pa.Definition.Name + ": " + pa.AsString(); } //} } pf.Close(); tr.Start(); doc.Regenerate(); tr.Commit(); TaskDialog.Show("Revit", info); } return(true); } } } catch (Exception ex) { message = ex.Message; } finally { res_mng.ReleaseAllResources(); def_res_mng.ReleaseAllResources(); } return(false); }
public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements) { Document doc = commandData.Application.ActiveUIDocument.Document; // Call WPF for user input using (DuplicateSheetsWPF customWindow = new DuplicateSheetsWPF(commandData)) { // Revit application as window's owner System.Windows.Interop.WindowInteropHelper helper = new System.Windows.Interop.WindowInteropHelper(customWindow); helper.Owner = System.Diagnostics.Process.GetCurrentProcess().MainWindowHandle; customWindow.ShowDialog(); // Retrieve all user input List <int> sheetIds = customWindow.sheetIds; var titleBlockComboBox = customWindow.SelectedComboItemTitleBlock; var copyViews = customWindow.copyViews; var optDuplicate = customWindow.optDuplicate; var optDuplicateDetailing = customWindow.optDuplicateDetailing; var optDuplicateDependant = customWindow.optDuplicateDependant; var viewPrefix = customWindow.viewPrefix; var viewSuffix = customWindow.viewSuffix; var sheetPrefix = customWindow.sheetPrefix; var sheetSuffix = customWindow.sheetSuffix; // Establish duplicate options at top to avoid reassignment inside loop var viewDuplicateOption = ViewDuplicateOption.Duplicate; if (optDuplicateDetailing == true) { viewDuplicateOption = ViewDuplicateOption.WithDetailing; } else if (optDuplicateDependant == true) { viewDuplicateOption = ViewDuplicateOption.AsDependent; } // Group transacation TransactionGroup tg = new TransactionGroup(doc, "Duplicate sheets"); tg.Start(); // List to store sheets duplicated var viewSheetSuccess = new List <string>(); // Duplicate all selected sheets foreach (var sId in sheetIds) { // Retrieve sheet and sheet Id ElementId sheetId = new ElementId(sId); ViewSheet vSheet = doc.GetElement(sheetId) as ViewSheet; // Retrieve title block according to user input FamilyInstance titleblock = null; if (titleBlockComboBox.Content as string != "Current Title Block") { titleblock = titleBlockComboBox.Tag as FamilyInstance; } else { // Retrieve titleblock from current sheet titleblock = new FilteredElementCollector(doc).OfClass(typeof(FamilyInstance)) .OfCategory(BuiltInCategory.OST_TitleBlocks).Cast <FamilyInstance>() .First(q => q.OwnerViewId == vSheet.Id); } // Guard against no loaded titleblocks in project or in sheet if (titleblock == null) { titleblock = new FilteredElementCollector(doc).OfClass(typeof(FamilyInstance)) .OfCategory(BuiltInCategory.OST_TitleBlocks).Cast <FamilyInstance>() .First(); } // Retrieve elements on sheet var elementsInViewId = new FilteredElementCollector(doc, sheetId).ToElementIds(); // Retrieve viewports in view FilteredElementCollector viewPorts = new FilteredElementCollector(doc, sheetId).OfClass(typeof(Viewport)); // Retrieve schedules in view FilteredElementCollector schedules = new FilteredElementCollector(doc).OwnedByView(sheetId) .OfClass(typeof(ScheduleSheetInstance)); // Retrieve viewSchedules FilteredElementCollector viewSchedules = new FilteredElementCollector(doc).OfClass(typeof(ViewSchedule)); // Store copied elements and annotation elements var copiedElementIds = new List <ElementId>(); var annotationElementsId = new List <ElementId>(); using (Transaction t = new Transaction(doc, "Duplicate Sheet")) { // Start transaction to duplicate sheet t.Start(); // Duplicate sheet ViewSheet newsheet = ViewSheet.Create(doc, titleblock.GetTypeId()); newsheet.SheetNumber = sheetPrefix + vSheet.SheetNumber + sheetSuffix; newsheet.Name = vSheet.Name; // Get origin of the titleblock XYZ originTitle = titleblock.GetTransform().Origin; // Check titleblock position Element copyTitleBlock = new FilteredElementCollector(doc).OwnedByView(newsheet.Id).OfCategory(BuiltInCategory.OST_TitleBlocks).FirstElement(); LocationPoint titleLoc = copyTitleBlock.Location as LocationPoint; XYZ titleLocPoint = titleLoc.Point; // Check if title block is in the same position as original if (titleLocPoint.DistanceTo(originTitle) != 0) { // Move it in case it is not titleLoc.Move(originTitle); } // Check if user selected copy views if (copyViews) { // Retrieve all views placed on sheet except schedules foreach (ElementId eId in vSheet.GetAllPlacedViews()) { View origView = doc.GetElement(eId) as View; View newView = null; // Legends if (origView.ViewType == ViewType.Legend) { newView = origView; } // Rest of view types else { if (origView.CanViewBeDuplicated(viewDuplicateOption)) { ElementId newViewId = origView.Duplicate(viewDuplicateOption); newView = doc.GetElement(newViewId) as View; newView.Name = viewPrefix + origView.Name + viewSuffix; } } // Loop through viewports foreach (Viewport vp in viewPorts) { if (vp.SheetId == vSheet.Id && vp.ViewId == origView.Id) { // Retrieve centerpoint of original viewport XYZ center = vp.GetBoxCenter(); // Create viewport in the original spot Viewport newVp = Viewport.Create(doc, newsheet.Id, newView.Id, center); } // Add element in copied list copiedElementIds.Add(vp.Id); } // Add element in copied list copiedElementIds.Add(eId); } // Retrieve and copy schedules foreach (ScheduleSheetInstance sch in schedules) { // Check schedule is not a revision inside titleblock if (!sch.IsTitleblockRevisionSchedule) { foreach (ViewSchedule vsc in viewSchedules) { if (sch.ScheduleId == vsc.Id) { // Retrieve center of schedule XYZ schCenter = sch.Point; // Create schedule in the same position ScheduleSheetInstance newSch = ScheduleSheetInstance.Create(doc, newsheet.Id, vsc.Id, schCenter); } copiedElementIds.Add(vsc.Id); } } } // Duplicate annotation elements foreach (ElementId eId in elementsInViewId) { if (!copiedElementIds.Contains(eId)) { annotationElementsId.Add(eId); } } // Copy annotation elements ElementTransformUtils.CopyElements(vSheet, annotationElementsId, newsheet, null, null); } viewSheetSuccess.Add(newsheet.SheetNumber + " - " + newsheet.Name); // Commit transaction t.Commit(); } } // Commit group transaction tg.Assimilate(); // Display result message to user if (viewSheetSuccess.Count > 0) { TaskDialog.Show("Success", "The following sheets have been duplicated: \n" + string.Join("\n", viewSheetSuccess)); } return(Result.Succeeded); } }