public static IList<ViewBox> GetViewBoxes(ViewSheet vs) { ISet<ElementId> views = vs.GetAllPlacedViews(); List<ViewBox> boxes = new List<ViewBox>(); foreach (ElementId id in views) { View v = vs.Document.GetElement(id) as View; switch (v.ViewType) { case ViewType.AreaPlan: case ViewType.CeilingPlan: case ViewType.Elevation: case ViewType.EngineeringPlan: case ViewType.FloorPlan: case ViewType.Section: case ViewType.ThreeD: ViewBox box = GetViewBox(v); if (box != null) boxes.Add(box); break; default: // skip break; } } return boxes; }
/// <summary> /// List the size and location of the given /// sheet, the views it contains, and the /// transforms from Revit model space to the view /// and from the view to the sheet. /// </summary> static void ListSheetAndViewTransforms( ViewSheet sheet) { Document doc = sheet.Document; // http://thebuildingcoder.typepad.com/blog/2010/09/view-location-on-sheet.html GetViewTransform(sheet); foreach (ElementId id in sheet.GetAllViewports()) { Viewport vp = doc.GetElement(id) as Viewport; XYZ center = vp.GetBoxCenter(); Outline outline = vp.GetBoxOutline(); XYZ diff = outline.MaximumPoint - outline.MinimumPoint; Debug.Print( "viewport {0} for view {1} outline {2} " + "diff {3} label outline {4}", vp.Id, vp.ViewId, Util.OutlineString(outline), Util.PointString(diff), Util.OutlineString(vp.GetLabelOutline())); } foreach (View v in sheet.GetAllPlacedViews() .Select <ElementId, View>(id => doc.GetElement(id) as View)) { GetViewTransform(v); } }
public Result Execute( ExternalCommandData commandData, ref String message, ElementSet elements) { UIApplication app = commandData.Application; Document doc = app.ActiveUIDocument.Document; ViewSheet currentSheet = doc.ActiveView as ViewSheet; //foreach( View v in currentSheet.Views ) // 2014 warning 'Autodesk.Revit.DB.ViewSheet.Views' is obsolete. Use GetAllPlacedViews() instead. foreach (ElementId id in currentSheet.GetAllPlacedViews()) // 2015 { View v = doc.GetElement(id) as View; // the values returned here do not seem to // accurately reflect the positions of the // views on the sheet: BoundingBoxUV loc = v.Outline; Debug.Print( "Coordinates of {0} view '{1}': {2}", v.ViewType, v.Name, Util.PointString(loc.Min)); } return(Result.Failed); }
public static IList <ViewBox> GetViewBoxes(ViewSheet vs) { ISet <ElementId> views = vs.GetAllPlacedViews(); List <ViewBox> boxes = new List <ViewBox>(); foreach (ElementId id in views) { View v = vs.Document.GetElement(id) as View; switch (v.ViewType) { case ViewType.AreaPlan: case ViewType.CeilingPlan: case ViewType.Elevation: case ViewType.EngineeringPlan: case ViewType.FloorPlan: case ViewType.Section: case ViewType.ThreeD: ViewBox box = GetViewBox(v); if (box != null) { boxes.Add(box); } break; default: // skip break; } } return(boxes); }
//Get all view place on sheet public List <View> GetAllViewPlaceOnSheet(Document doc, ViewSheet sheet) { ISet <ElementId> Ids = sheet.GetAllPlacedViews(); List <View> col = (from x in Ids select doc.GetElement(x)).Cast <View>().ToList(); var list = (from x in col where x.ViewType == ViewType.FloorPlan || x.ViewType == ViewType.Section select x).ToList(); return(list); }
public static List <View> Create(UIDocument uiDoc, ViewSheet viewSheet) { var doc = uiDoc.Document; return((from id in viewSheet.GetAllPlacedViews() select doc.GetElement(id) as View into v where ValidViewType(v.ViewType) select CreateView(uiDoc, v)).ToList()); }
private static List <View> Create(ViewSheet vs, Document doc) { List <View> result = new List <View>(); foreach (ElementId id in vs.GetAllPlacedViews()) { var v = (View)doc.GetElement(id); if (ValidViewType(v.ViewType)) { result.Add(CreateView(v, doc)); } } return(result); }
public static bool IsonSheet(this ViewSheet sheet, View view) { var allview = sheet.GetAllPlacedViews(); var gh = allview.Where(x => x == view.Id).Cast <ElementId>().ToList(); if (gh.Count != 0) { return(true); } else { return(false); } }
public void FormatDetailNameOnSheet(Document doc) { ViewSheet viewsheet = doc.ActiveView as ViewSheet; if (viewsheet != null) { var list = viewsheet.GetAllPlacedViews(); Transaction tran = new Transaction(doc, "Format view name"); tran.Start(); foreach (var item in list) { } tran.Commit(); } }
private IEnumerable <ViewDrafting> getViewsOnSheets(Element _sheet, Document _source) { ViewSheet currentSheet = _sheet as ViewSheet; ICollection <ElementId> placedViews = currentSheet.GetAllPlacedViews(); List <ViewDrafting> views = new List <ViewDrafting>(); foreach (ElementId eId in placedViews) { Element temp = _source.GetElement(eId); if (temp.GetType().ToString() == "Autodesk.Revit.DB.ViewDrafting") { views.Add(temp as ViewDrafting); } } return(views); }
private List <View> AllLegendInSheet(ViewSheet viewSheet, Document doc) { List <View> list = new List <View>(); ISet <ElementId> allPlacedViews = viewSheet.GetAllPlacedViews(); foreach (ElementId elementId in allPlacedViews) { View view = doc.GetElement(elementId) as View; bool flag = view == null; if (!flag) { bool flag2 = view.ViewType == ViewType.Legend; if (flag2) { list.Add(view); } } } return(list); }
public IList <LSObject> AddObject(Document doc) { FilteredElementCollector filteredElementCollector = new FilteredElementCollector(doc).WhereElementIsNotElementType().OfCategory(BuiltInCategory.OST_Sheets).OfClass(typeof(ViewSheet)); foreach (Element element in filteredElementCollector) { bool flag = element is ViewSheet; if (flag) { ViewSheet viewSheet = element as ViewSheet; ICollection <ElementId> allPlacedViews = viewSheet.GetAllPlacedViews(); foreach (ElementId elementId in allPlacedViews) { View view = doc.GetElement(elementId) as View; LSObject item = new LSObject(view.Name, viewSheet.Name, viewSheet.SheetNumber, view.Id.IntegerValue, viewSheet.Id.IntegerValue); this.LstObjects.Add(item); } } } return(this.LstObjects); }
public SheetCopierSheet(string number, string title, SheetCopierManager scopy, ViewSheet sourceSheet) { this.scopy = scopy ?? throw new ArgumentNullException(nameof(scopy)); this.number = number; this.title = title; SourceSheet = sourceSheet ?? throw new ArgumentNullException(nameof(sourceSheet)); sheetCategory = GetSheetCategory(SheetCopierConstants.SheetCategory); userCreatedSheetCategory = sheetCategory; DestinationSheet = null; viewsOnSheet = new ObservableCollection <SheetCopierViewOnSheet>(); foreach (var id in sourceSheet.GetAllPlacedViews()) { Element element = sourceSheet.Document.GetElement(id); var v = element as View; if (v == null) { continue; } viewsOnSheet.Add(new SheetCopierViewOnSheet(v.Name, v, scopy)); } SheetCategories = new ObservableCollection <string>(scopy.SheetCategories.ToList()); }
private List <ViewObject> GetData(Document doc) { List <ViewObject> list = new List <ViewObject>(); FilteredElementCollector filteredElementCollector = new FilteredElementCollector(doc).WhereElementIsNotElementType().OfCategory(BuiltInCategory.OST_Sheets).OfClass(typeof(ViewSheet)); foreach (Element element in filteredElementCollector) { bool flag = element is ViewSheet; if (flag) { ViewSheet viewSheet = element as ViewSheet; ICollection <ElementId> allPlacedViews = viewSheet.GetAllPlacedViews(); foreach (ElementId elementId in allPlacedViews) { View view = doc.GetElement(elementId) as View; ViewObject item = new ViewObject(view.Name, viewSheet.Name, viewSheet.SheetNumber, view.Id.IntegerValue, viewSheet.Id.IntegerValue); list.Add(item); } } } return(list); }
public SheetCopierViewHost(string number, string title, SheetCopierManager scopy, ViewSheet sourceSheet) { this.scopy = scopy ?? throw new ArgumentNullException(nameof(scopy)); this.number = number; this.title = title; SourceSheet = sourceSheet ?? throw new ArgumentNullException(nameof(sourceSheet)); sheetCategory = GetSheetCategory(SheetCopierConstants.SheetCategory); PrimaryCustomSheetParameter = GetSheetCategory(Settings.Default.CustomSheetParameterOne); SecondaryCustomSheetParameter = GetSheetCategory(Settings.Default.CustomSheetParameterTwo); TertiaryCustomSheetParameter = GetSheetCategory(Settings.Default.CustomSheetParameterThree); DestinationSheet = null; Type = ViewHostType.Sheet; childViews = new ObservableCollection <SheetCopierView>(); foreach (var id in sourceSheet.GetAllPlacedViews()) { Element element = sourceSheet.Document.GetElement(id); var v = element as View; if (v == null) { continue; } childViews.Add(new SheetCopierView(v.Name, v, scopy)); } }
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) { double i = 0; double max = sheetCollector.Count(); foreach (Element S in sheetCollector) { i += max / 100; Math.Round(i, MidpointRounding.AwayFromZero); if (i <= 100) { backgroundWorker1.ReportProgress((int)i); } else { i = 100; backgroundWorker1.ReportProgress((int)i); } if (backgroundWorker1.CancellationPending) { e.Cancel = true; return; } foreach (Element L in legendCollector) { foreach (Tuple <string, Element> selectedSheet in WFItem.selectedSheetsList) //Finds which Sheets where selected { foreach (string selectedLegend in WFItem.SelectedLegends) //Finds which Legends were selected { if ((S.get_Parameter(BuiltInParameter.SHEET_NUMBER).AsString() == selectedSheet.Item1) && (L.Name == selectedLegend)) { ViewSheet VS = (ViewSheet)S; foreach (ElementId E in VS.GetAllPlacedViews()) { allElementsOnSheet.Add(localDoc.GetElement(E)); } bool legendOnSheet = false; if (allElementsOnSheet.Count == 0) { AddToSheet.Add(new Tuple <Element, Element>(selectedSheet.Item2, L)); e.Result = "Place Legend on Empty Sheet"; allElementsOnSheet.Clear(); break; } foreach (Element thisLegend in allElementsOnSheet) { if (L.Id == thisLegend.Id) { legendOnSheet = true; e.Result = "Legend on sheet not adding"; break; } else { legendOnSheet = false; e.Result = "adding legend"; } } if (!legendOnSheet) { AddToSheet.Add(new Tuple <Element, Element>(S, L)); e.Result = "adding legend"; allElementsOnSheet.Clear(); break; } allElementsOnSheet.Clear(); //End of if } } } } } }
private void backgroundWorker2_DoWork(object sender, DoWorkEventArgs e) { //https://nerdparadise.com/programming/csharpbackgroundworker double i = 0; double max = sheetCollector.Count(); Viewport legendsViewport = null; foreach (Element S in sheetCollector) { i += max / 100; Math.Round(i, MidpointRounding.AwayFromZero); if (i <= 100) { backgroundWorker2.ReportProgress((int)i); } else { i = 100; backgroundWorker2.ReportProgress((int)i); } //if cancellation is pending, cancel work. if (backgroundWorker2.CancellationPending) { e.Cancel = true; return; } foreach (Element L in legendCollector) { foreach (Tuple <string, Element> selectedSheet in WFItem.selectedSheetsList) //Finds which Sheets where selected { foreach (string selectedLegend in WFItem.SelectedLegends) //Finds which Legends were selected { if ((S.get_Parameter(BuiltInParameter.SHEET_NUMBER).AsString() == selectedSheet.Item1) && (L.Name == selectedLegend)) { ViewSheet VS = (ViewSheet)S; foreach (ElementId E in VS.GetAllPlacedViews()) { allElementsOnSheet.Add(localDoc.GetElement(E)); } bool legendOnSheet = false; foreach (Element thisLegend in allElementsOnSheet) { if (L.Id == thisLegend.Id) { legendOnSheet = true; e.Result = "Legend on sheet removing"; break; } else { legendOnSheet = false; e.Result = "no legend found"; } } if (legendOnSheet) { foreach (Viewport vp in viewPortCollector) { if (vp.SheetId == S.Id) { legendsViewport = vp; } } RemoveFromSheet.Add(new Tuple <Element, Viewport>(S, legendsViewport)); allElementsOnSheet.Clear(); break; } allElementsOnSheet.Clear(); //End of if } } } } } }
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); }
/// <summary> /// Determine the visible elements belonging to the /// specified categories in the views displayed by /// the given sheet and return their graphics and /// instance placements. /// Ignore all but the first geometry loop retrieved. /// </summary> /// <param name="modelCollections">Data container</param> /// <param name="sheet">The view sheet</param> /// <param name="categoryFilter">The desired categories</param> static void GetBimGraphics( SheetModelCollections modelCollections, ViewSheet sheet, ElementFilter categoryFilter) { bool list_ignored_elements = false; Document doc = sheet.Document; Autodesk.Revit.Creation.Application creapp = doc.Application.Create; Options opt = new Options(); // There is no need and no possibility to set // the detail level when retrieving view geometry. // An attempt to specify the detail level will // cause writing the opt.View property to throw // "DetailLevel is already set. When DetailLevel // is set view-specific geometry can't be // extracted." // //opt.DetailLevel = ViewDetailLevel.Coarse; Debug.Print(sheet.Name); foreach (ViewPlan v in sheet.GetAllPlacedViews() .Select <ElementId, View>(id => doc.GetElement(id) as View) .OfType <ViewPlan>() .Where <ViewPlan>(v => IsFloorPlan(v))) { Debug.Print(" " + v.Name); modelCollections.BimelsInViews.Add( v.Id, new List <ObjData>()); opt.View = v; JtBoundingBox2dInt bimelBb = new JtBoundingBox2dInt(); FilteredElementCollector els = new FilteredElementCollector(doc, v.Id) .WherePasses(categoryFilter); foreach (Element e in els) { GeometryElement geo = e.get_Geometry(opt); FamilyInstance f = e as FamilyInstance; if (null != f) { LocationPoint lp = e.Location as LocationPoint; // Simply ignore family instances that // have no location point or no location at // all, e.g. panel. // No, we should not ignore them, but // treat tham as non-transformable parts. if (null == lp) { if (list_ignored_elements) { Debug.Print(string.Format( " ... {0} has no location", e.Name)); } f = null; geo = geo.GetTransformed( Transform.Identity); } else { FamilySymbol s = f.Symbol; if (modelCollections.Symbols.ContainsKey(s.Id)) { if (list_ignored_elements) { Debug.Print(" ... symbol already handled " + e.Name + " --> " + s.Name); } // Symbol already defined, just add instance JtPlacement2dInt placement = new JtPlacement2dInt(f); // Expand bounding box around all BIM // elements, ignoring the size of the // actual geometry, assuming is is small // in comparison and the insertion point // lies within it. bimelBb.ExpandToContain( placement.Translation); InstanceData d = new InstanceData(); d.Id = f.Id; d.Symbol = f.Symbol.Id; d.Placement = placement; modelCollections.BimelsInViews[v.Id] .Add(d); continue; } // Retrieve family instance geometry // transformed back to symbol definition // coordinate space by inverting the // family instance placement transformation Transform t = Transform.CreateTranslation( -lp.Point); Transform r = Transform.CreateRotationAtPoint( XYZ.BasisZ, -lp.Rotation, lp.Point); geo = geo.GetTransformed(t * r); } } int nEmptySolids = 0; int nNonEmptySolids = 0; int nCurves = 0; int nOther = 0; foreach (GeometryObject obj in geo) { // This was true before calling GetTransformed. //Debug.Assert( obj is Solid || obj is GeometryInstance, "expected only solids and instances" ); // This was true before calling GetTransformed. //Debug.Assert( ( obj is GeometryInstance ) == ( e is FamilyInstance ), "expected all family instances to have geometry instance" ); Debug.Assert(obj is Solid || obj is Line || obj is Arc, "expected only solids, lines and arcs after calling GetTransformed on instances"); // Todo: handle arcs, e.g. tessellate Debug.Assert(Visibility.Visible == obj.Visibility, "expected only visible geometry objects"); Debug.Assert(obj.IsElementGeometry, "expected only element geometry"); //bool isElementGeometry = obj.IsElementGeometry; Solid solid = obj as Solid; if (null != solid) { if (0 < solid.Edges.Size) { ++nNonEmptySolids; } else { ++nEmptySolids; } } else if (obj is Curve) { ++nCurves; } else { ++nOther; } } Debug.Print(" {0}: {1} non-emtpy solids, " + "{2} empty, {3} curves, {4} other", e.Name, nNonEmptySolids, nEmptySolids, nCurves, nOther); JtLoops loops = null; if (1 == nNonEmptySolids && 0 == nEmptySolids + nCurves + nOther) { int nFailures = 0; loops = CmdUploadRooms .GetPlanViewBoundaryLoopsGeo( creapp, geo, ref nFailures); } else { double z = double.MinValue; bool first = true; foreach (GeometryObject obj in geo) { // Do we need the graphics style? // It might give us horrible things like // colours etc. ElementId id = obj.GraphicsStyleId; //Debug.Print( " " + obj.GetType().Name ); Solid solid = obj as Solid; if (null == solid) { #region Debug code to ensure horizontal co-planar curves #if DEBUG Debug.Assert(obj is Line || obj is Arc, "expected only lines and arcs here"); Curve c = obj as Curve; if (first) { z = c.GetEndPoint(0).Z; Debug.Assert(Util.IsEqual(z, c.GetEndPoint(1).Z), "expected a plan view with all Z values equal"); first = false; } else { Debug.Assert(Util.IsEqual(z, c.GetEndPoint(0).Z), "expected a plan view with all Z values equal"); Debug.Assert(Util.IsEqual(z, c.GetEndPoint(1).Z), "expected a plan view with all Z values equal"); } Debug.Print(" {0} {1}", obj.GetType().Name, Util.CurveEndpointString(c)); #endif // DEBUG #endregion // Debug code to ensure horizontal co-planar curves } else if (1 == solid.Faces.Size) { Debug.Print( " solid with 1 face"); foreach (Face face in solid.Faces) { #region Debug code to print out face edges #if DEBUG foreach (EdgeArray loop in face.EdgeLoops) { foreach (Edge edge in loop) { // This returns the curves already // correctly oriented: Curve c = edge .AsCurveFollowingFace(face); Debug.Print(" {0}: {1} {2}", edge.GetType().Name, c.GetType().Name, Util.CurveEndpointString(c)); } } #endif // DEBUG #endregion // Debug code to print out face edges if (null == loops) { loops = new JtLoops(1); } loops.Add(CmdUploadRooms.GetLoop( creapp, face)); } } else { #region Debug code for exceptional cases #if DEBUG_2 Debug.Assert(1 >= solid.Faces.Size, "expected at most one visible face in plan view for my simple solids"); int n = solid.Edges.Size; if (0 < n) { Debug.Print( " solid with {0} edges", n); Face[] face2 = new Face[] { null, null }; Face face = null; foreach (Edge edge in solid.Edges) { if (null == face2[0]) { face2[0] = edge.GetFace(0); face2[1] = edge.GetFace(1); } else if (null == face) { if (face2.Contains <Face>(edge.GetFace(0))) { face = edge.GetFace(0); } else if (face2.Contains <Face>(edge.GetFace(1))) { face = edge.GetFace(1); } else { Debug.Assert(false, "expected all edges to belong to one face"); } } else { Debug.Assert(face == edge.GetFace(0) || face == edge.GetFace(1), "expected all edges to belong to one face"); } Curve c = edge.AsCurve(); // This returns the curves already // correctly oriented: //Curve curve = e.AsCurveFollowingFace( // face ); Debug.Print(" {0}: {1} {2}", edge.GetType().Name, c.GetType().Name, Util.CurveEndpointString(c)); } } #endif // DEBUG #endregion // Debug code for exceptional cases } } } // Save the part or instance and // the geometry retrieved for it. // This is where we drop all geometry but // the first loop. if (null != loops) { GeomData gd = new GeomData(); gd.Loop = loops[0]; if (null == f) { // Add part with absolute geometry gd.Id = e.Id; modelCollections.BimelsInViews[v.Id].Add( gd); // Expand bounding box around all BIM // elements. bimelBb.ExpandToContain( gd.Loop.BoundingBox); } else { // Define symbol and add instance JtPlacement2dInt placement = new JtPlacement2dInt(f); InstanceData id = new InstanceData(); id.Id = f.Id; id.Symbol = f.Symbol.Id; id.Placement = placement; modelCollections.BimelsInViews[v.Id].Add( id); gd.Id = f.Symbol.Id; modelCollections.Symbols.Add( f.Symbol.Id, gd); // Expand bounding box around all BIM // elements. JtBoundingBox2dInt bb = gd.Loop.BoundingBox; Point2dInt vtrans = placement.Translation; bimelBb.ExpandToContain(bb.Min + vtrans); bimelBb.ExpandToContain(bb.Max + vtrans); } } } // Set up BIM bounding box for this view modelCollections.ViewsInSheet[sheet.Id].Find( v2 => v2.Id.IntegerValue.Equals( v.Id.IntegerValue)).BimBoundingBox = bimelBb; } }
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); } }
private void DeleteViewsAndSheets(Document doc, bool onsheet, bool notonsheets, bool sheets, bool templates) { List <ElementId> delete = new List <ElementId>(); var allsheets = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Sheets).ToElementIds(); var allviews = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Views).ToElements().Cast <View>().Where(x => x.IsTemplate != true && x.CanBePrinted).ToList(); if (onsheet) { if (allsheets.Count > 0) { foreach (ElementId id in allsheets) { ViewSheet sheet = doc.GetElement(id) as ViewSheet; ISet <ElementId> views = sheet.GetAllPlacedViews(); foreach (ElementId view in views) { if (doc.GetElement(view) != null) { doc.Delete(view); } } } allviews = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Views).ToElements().Cast <View>().Where(x => x.IsTemplate != true && x.CanBePrinted).ToList(); } } if (sheets) { foreach (ElementId sheet in allsheets) { if (doc.GetElement(sheet) != null) { doc.Delete(sheet); } } allsheets = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Sheets).ToElementIds(); } if (notonsheets) { List <ElementId> viewsonsheets = new List <ElementId>(); if (allsheets.Count > 0) { foreach (ElementId id in allsheets) { ViewSheet sheet = doc.GetElement(id) as ViewSheet; viewsonsheets.AddRange(sheet.GetAllPlacedViews()); } } if (viewsonsheets.Count > 0) { allviews = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Views).Excluding(viewsonsheets).ToElements().Cast <View>().Where(x => x.IsTemplate != true && x.CanBePrinted).ToList(); } else { allviews = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Views).ToElements().Cast <View>().Where(x => x.IsTemplate != true && x.CanBePrinted).ToList(); } foreach (View view in allviews) { if (view.IsValidObject) { if (doc.GetElement(view.Id) != null) { if (view.GetDependentViewIds().Count == 0) { doc.Delete(view.Id); } } } } if (viewsonsheets.Count > 0) { allviews = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Views).Excluding(viewsonsheets).ToElements().Cast <View>().Where(x => x.IsTemplate != true && x.CanBePrinted).ToList(); } else { allviews = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Views).ToElements().Cast <View>().Where(x => x.IsTemplate != true && x.CanBePrinted).ToList(); } foreach (View view in allviews) { if (view.IsValidObject) { if (doc.GetElement(view.Id) != null) { if (view.GetDependentViewIds().Count == 0) { doc.Delete(view.Id); } } } } } if (templates) { var alltemplates = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Views).ToElements().Cast <View>().Where(x => x.IsTemplate == true); foreach (View template in alltemplates) { if (doc.GetElement(template.Id) != null) { doc.Delete(template.Id); } } } allviews = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Views).ToElements().Cast <View>().Where(x => x.IsTemplate != true && x.CanBePrinted).ToList(); if (allviews.Count() == 0) { var viewFamilyType = new FilteredElementCollector(doc).OfClass(typeof(ViewFamilyType)).Cast <ViewFamilyType>().FirstOrDefault(x => x.ViewFamily == ViewFamily.ThreeDimensional); var view3D = View3D.CreateIsometric(doc, viewFamilyType.Id); } }
public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements) { Tracer.Listeners.Add(new System.Diagnostics.EventLogTraceListener("Application")); UIDocument uidoc = commandData.Application.ActiveUIDocument; Document doc = uidoc.Document; RebarsCollectorWnd wnd = null; System.Text.StringBuilder strBld = new System.Text.StringBuilder(); try { List <ViewType> allowedViews = new List <ViewType> { ViewType.EngineeringPlan, ViewType.FloorPlan, ViewType.Section, ViewType.Elevation, ViewType.Detail, ViewType.DraftingView }; List <ElementId> rebarIds = new List <ElementId>(); // if the active view is a sheet, bag all the view belonging to it if (doc.ActiveView.ViewType == ViewType.DrawingSheet) { ViewSheet vs = doc.ActiveView as ViewSheet; foreach (ElementId viewId in vs.GetAllPlacedViews()) { View view = doc.GetElement(viewId) as View; if (allowedViews.Contains(view.ViewType)) { rebarIds.AddRange( RebarsUtils .GetAllRebarIdsInView(view)); } } } else if (allowedViews.Contains(doc.ActiveView.ViewType)) { rebarIds.AddRange( RebarsUtils .GetAllRebarIdsInView(doc.ActiveView)); } if (rebarIds.Count == 0) { TaskDialog.Show("Warning", "No rebars have been collected."); return(Result.Cancelled); } // Get partitions and host marks from the data storage IDictionary <string, ISet <string> > partsHostMarks = ExtensibleStorageUtils.GetValues( ExtensibleStorageUtils.GetSchema(UpdateRepository.SCHEMA_GUID), ExtensibleStorageUtils.GetDataStorage(doc, UpdateRepository.DATA_STORAGE_NAME), UpdateRepository.FN_PARTS_HOST_MARKS); // Dig out assemblies grouped by partition + host mark names IDictionary <string, ISet <string> > partsMarksAssemblies = ExtensibleStorageUtils.GetValues( ExtensibleStorageUtils.GetSchema(UpdateRepository.SCHEMA_GUID), ExtensibleStorageUtils.GetDataStorage(doc, UpdateRepository.DATA_STORAGE_NAME), UpdateRepository.FN_HOST_MARKS_ASSEMBLIES); wnd = new RebarsCollectorWnd(partsHostMarks, partsMarksAssemblies); wnd.ButtonClicked += (sender, e) => { using (Transaction t = new Transaction(doc, "Set rebars' properties")) { t.Start(); foreach (ElementId rebarId in rebarIds) { strBld.Clear(); strBld.AppendFormat("Id: {0}", rebarId.ToString()); // Get hold of the element represented by its id Element rebar = doc.GetElement(rebarId); // See about the partitions Parameter partition = rebar.LookupParameter(RebarsUtils.PARTITION); if (partition != null && !partition.IsReadOnly && e.Partition != null) { partition.Set(e.Partition); } // Set the value in the host mark parameter Parameter hostMark = rebar.LookupParameter(RebarsUtils.HOST_MARK); if (hostMark != null && !hostMark.IsReadOnly && e.HostMark != null) { hostMark.Set(e.HostMark); } // if checked, set the value in the assembly mark parameter Parameter assemblyMark = rebar.LookupParameter(RebarsUtils.ASSEMBLY_MARK); if (assemblyMark != null && !assemblyMark.IsReadOnly && e.AssemblyMark != null) { assemblyMark.Set(e.AssemblyMark); } // if checked and calculable, then set the value Parameter isCalculable = rebar.LookupParameter(RebarsUtils.IS_CALCULABLE); if (e.IsCalculable != null && isCalculable != null && !isCalculable.IsReadOnly) { isCalculable .Set((e.IsCalculable == true ? 1 : 0)); } // if checked and specifiable, then set the value Parameter isSpecifiable = rebar.LookupParameter(RebarsUtils.IS_SPECIFIABLE); if (e.IsSpecifiable != null && isSpecifiable != null && !isSpecifiable.IsReadOnly) { isSpecifiable .Set((e.IsSpecifiable == true ? 1 : 0)); } // if checked and in an assembly, then set the value Parameter isAssembly = rebar.LookupParameter(RebarsUtils.IS_IN_ASSEMBLY); if (e.IsAssembly != null && isAssembly != null && !isAssembly.IsReadOnly) { isAssembly .Set((bool)e.IsAssembly ? 1 : 0); } } t.Commit(); } }; wnd.ShowDialog(); return(Result.Succeeded); } catch (Autodesk.Revit.Exceptions .OperationCanceledException) { return(Result.Cancelled); } catch (System.Exception ex) { if (wnd != null) { wnd.Close(); } TaskDialog.Show("Exception", string.Format("{0}\n{1}\n{2}", strBld.ToString(), ex.Message, ex.StackTrace)); Tracer.Write(string.Format("{0}\n{1}", ex.Message, ex.StackTrace)); return(Result.Failed); } }
private void DeleteViewsONSheets(Document doc) { var sheets = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Sheets).ToElementIds(); if (sheets.Count == 0) { return; } List <ElementId> viewsONsheets = new List <ElementId>(); foreach (ElementId id in sheets) { ViewSheet sheet = doc.GetElement(id) as ViewSheet; viewsONsheets.AddRange(sheet.GetAllPlacedViews()); } if (viewsONsheets.Count == 0) { return; } foreach (ElementId id in viewsONsheets) { Autodesk.Revit.DB.View view = doc.GetElement(id) as Autodesk.Revit.DB.View; if (!view.IsTemplate) { try { doc.Delete(id); } catch { } } } var views = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Views).ToElementIds(); if (views.Count == 0) { return; } List <ElementId> usedtemplates = new List <ElementId>(); foreach (ElementId id in views) { Autodesk.Revit.DB.View view = doc.GetElement(id) as Autodesk.Revit.DB.View; if (view.ViewTemplateId != ElementId.InvalidElementId) { if (!usedtemplates.Contains(id)) { usedtemplates.Add(view.ViewTemplateId); } } } foreach (ElementId id in views) { Autodesk.Revit.DB.View view = doc.GetElement(id) as Autodesk.Revit.DB.View; if (view.IsTemplate && !usedtemplates.Contains(id)) { try { doc.Delete(id); } catch { } } } }
private void DeleteViewsNotOnSheets(Document doc) { var sheets = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Sheets).ToElementIds(); List <ElementId> viewsONsheets = new List <ElementId>(); //get views on sheets if (sheets.Count != 0) { foreach (ElementId id in sheets) { ViewSheet sheet = doc.GetElement(id) as ViewSheet; viewsONsheets.AddRange(sheet.GetAllPlacedViews()); } } List <ElementId> usedtemplates = new List <ElementId>(); //get used templates foreach (ElementId id in viewsONsheets) { Autodesk.Revit.DB.View view = doc.GetElement(id) as Autodesk.Revit.DB.View; if (view.ViewTemplateId != ElementId.InvalidElementId) { if (!usedtemplates.Contains(id)) { usedtemplates.Add(view.ViewTemplateId); } } } ICollection <ElementId> viewsNOTsheets = null; //if no views on sheets collect differently if (viewsONsheets.Count != 0) { viewsNOTsheets = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Views).Excluding(viewsONsheets).ToElementIds(); } else { viewsNOTsheets = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Views).ToElementIds(); } //if no views not on sheets return if (viewsNOTsheets.Count == 0) { return; } //delete views not on sheets and unused templates skip views with dependancy foreach (ElementId id in viewsNOTsheets) { Autodesk.Revit.DB.View view = doc.GetElement(id) as Autodesk.Revit.DB.View; if (!view.IsTemplate && view.GetDependentViewIds().Count == 0) { try { doc.Delete(id); } catch { } } else if (view.IsTemplate && !usedtemplates.Contains(id)) { try { doc.Delete(id); } catch { } } } //get remaining views ICollection <ElementId> remainingviews; if (viewsONsheets.Count != 0) { remainingviews = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Views).Excluding(viewsONsheets).ToElementIds(); } else { remainingviews = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Views).ToElementIds(); } //delete views without dependent views foreach (ElementId id in remainingviews) { Autodesk.Revit.DB.View view = doc.GetElement(id) as Autodesk.Revit.DB.View; if (!view.IsTemplate && view.GetDependentViewIds().Count == 0) { try { doc.Delete(id); } catch { } } } }
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); } }
/// <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(); } }