so the blockId duplicate worked with the externalDoc reference. thanks for that, but it crashes on the Viewport.Create. I use blockId as the ViewId and it says it cant copy the view using that. here is my revised code. thank you very much for your help:
using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.IO;
using System.Linq;
using System.Windows.Controls;
using System.Windows.Forms;
using Transaction = Autodesk.Revit.DB.Transaction;
namespace RevitAPI_JBA_Development_2022
{
[Transaction(TransactionMode.Manual)]
public class ImportDraftingViewsCommandSHORT : IExternalCommand
{
public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
{
UIApplication uiApp = commandData.Application;
UIDocument uiDoc = uiApp.ActiveUIDocument;
Autodesk.Revit.DB.Document currentDoc = uiDoc.Document;
ICollection<ElementId> copiedViewIds;
try
{
// Open a file dialog to select the external document
string externalDocumentPath = BrowseForFile(); // Path to your external document
// Implement your file dialog logic here
if (string.IsNullOrEmpty(externalDocumentPath))
{
TaskDialog.Show("Error", "No external document selected.");
return Result.Cancelled;
}
// Open the external document
Autodesk.Revit.DB.Document externalDoc = uiApp.Application.OpenDocumentFile(externalDocumentPath);
if (externalDoc == null)
{
TaskDialog.Show("Error", "Failed to open the external document.");
return Result.Failed;
}
// Get all drafting views from the external document
//FilteredElementCollector externalViewsCollector = new FilteredElementCollector(externalDoc)
// .OfClass(typeof(ViewDrafting));
List<ViewDrafting> externalViewsCollector = GetDraftingViews(externalDoc);
List<ViewSheet> viewSheets = GetSheets(currentDoc);
EfficientSelectDraftingViewFormFinalMultipleSHORT importedStuff = new EfficientSelectDraftingViewFormFinalMultipleSHORT(externalViewsCollector, viewSheets);
if (importedStuff.ShowDialog() != DialogResult.OK)
{
externalDoc.Close(false);
return Result.Cancelled;
}
ViewSheet selectedSheet = importedStuff.SelectedSheet;
List<ViewDrafting> selectedDraftingViews = importedStuff.SelectedDraftingViews;
ICollection<ElementId> elementIdsCollection = selectedDraftingViews
.Select(view => view.Id)
.Cast<ElementId>()
.ToList();
if (selectedDraftingViews != null)
{
using (Autodesk.Revit.DB.Transaction transaction = new Autodesk.Revit.DB.Transaction(currentDoc, "Transaction for all"))
{
try
{
transaction.Start();
// Iterate through each drafting view in the external document
foreach (ViewDrafting selectedDraftingView in selectedDraftingViews)
{
if (selectedDraftingView != null)
{
// Check if the drafting view is valid
if (!selectedDraftingView.IsValidObject)
{
TaskDialog.Show("Error", "The selected drafting view is invalid.");
transaction.RollBack();
return Result.Failed;
}
ElementId blockId;
// Duplicate the drafting view
using (Transaction externalTransaction = new Transaction(externalDoc, "ExternalDoc"))
{
externalTransaction.Start();
blockId = selectedDraftingView.Duplicate(ViewDuplicateOption.Duplicate);
externalTransaction.Commit();
}
if (blockId == null || blockId == ElementId.InvalidElementId)
{
TaskDialog.Show("Error", "Failed to duplicate the drafting view.");
transaction.RollBack();
return Result.Failed;
}
// Get the duplicated block element
Element block = externalDoc.GetElement(blockId);
if (block == null)
{
TaskDialog.Show("Error", "Failed to retrieve the duplicated drafting view.");
transaction.RollBack();
return Result.Failed;
}
// Create a viewport for the duplicated drafting view
Viewport viewport = Viewport.Create(currentDoc, selectedSheet.Id, blockId, XYZ.Zero);
if (viewport == null)
{
TaskDialog.Show("Error", "Failed to create viewport for the drafting view.");
transaction.RollBack();
return Result.Failed;
}
}
}
transaction.Commit();
externalDoc.Close(false);
return Result.Succeeded;
}
catch(Exception ex)
{
TaskDialog.Show("Error", $"{ex.Message}");
return Result.Failed;
}
}
}
return Result.Failed;
}
catch (Exception ex)
{
TaskDialog.Show("Error", $"{ex.Message}");
return Result.Failed;
}
}
private string BrowseForFile()
{
using (OpenFileDialog openFileDialog = new OpenFileDialog())
{
openFileDialog.Filter = "Revit Files (*.rvt)|*.rvt|All files(*.*)|*.*";
openFileDialog.FilterIndex = 1;
openFileDialog.RestoreDirectory = true;
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
return openFileDialog.FileName;
}
else
{
return null;
}
}
}
private List<ViewDrafting> GetDraftingViews(Autodesk.Revit.DB.Document document)
{
List<ViewDrafting> draftingViews = new FilteredElementCollector(document)
.OfClass(typeof(ViewDrafting))
.Cast<ViewDrafting>()
.Where(v => v.IsTemplate == false)
.ToList();
return draftingViews;
}
public List<ViewSheet> GetSheets(Autodesk.Revit.DB.Document doc)
{
return new FilteredElementCollector(doc)
.OfClass(typeof(ViewSheet))
.Cast<ViewSheet>()
.ToList();
}
}
}
public class EfficientSelectDraftingViewFormFinalMultipleSHORT : System.Windows.Forms.Form
{
public System.Windows.Forms.ListBox draftingViewListBox;
public System.Windows.Forms.ComboBox sheetComboBox;
public System.Windows.Forms.Button okButton;
public System.Windows.Forms.Button cancelButton;
public ViewSheet SelectedSheet { get; private set; }
public List<ViewDrafting> importDraftingViewsFromExternalDoc;
public List<ViewSheet> sheets;
public List<ViewDrafting> SelectedDraftingViews { get; private set; }
private System.Drawing.Point lastLocation;
public EfficientSelectDraftingViewFormFinalMultipleSHORT(List<ViewDrafting> draftingViewsFromExternalDoc, List<ViewSheet> sheets)
{
try
{
this.importDraftingViewsFromExternalDoc = draftingViewsFromExternalDoc;
this.sheets = sheets;
InitializeComponent();
if (importDraftingViewsFromExternalDoc != null)
{
foreach (var draftingView in importDraftingViewsFromExternalDoc)
{
if (draftingView != null)
{
draftingViewListBox.Items.Add(draftingView.Name);
}
}
//Set the combo box style to allow multiple selection
draftingViewListBox.SelectionMode = System.Windows.Forms.SelectionMode.MultiSimple;
}
if (sheets != null)
{
foreach (var sheet in sheets)
{
sheetComboBox.Items.Add(sheet.Name);
}
}
}
catch (Exception ex)
{
TaskDialog.Show("Error", $"(twenty){ex.Message}");
}
}
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
// Draw a circular border
e.Graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
e.Graphics.DrawEllipse(Pens.Black, 0, 0, this.Width - 1, this.Height - 1);
}
private void InitializeComponent()
{
this.draftingViewListBox = new System.Windows.Forms.ListBox();
this.sheetComboBox = new System.Windows.Forms.ComboBox();
this.okButton = new System.Windows.Forms.Button();
this.cancelButton = new System.Windows.Forms.Button();
// Form
//this.FormBorderStyle = FormBorderStyle.SizableToolWindow;
this.ClientSize = new System.Drawing.Size(320, 320); // Set the form size to fit the circle
this.FormBorderStyle = FormBorderStyle.None; // Remove the border
this.StartPosition = FormStartPosition.CenterScreen; // Center the form on the screen
this.Paint += CircularBorderForm_Paint;
this.MouseDown += Form_MouseDown;
this.MouseMove += Form_MouseMove;
this.MouseUp += Form_MouseUp;
// Drafting View ListBox
this.draftingViewListBox.FormattingEnabled = true;
this.draftingViewListBox.Size = new System.Drawing.Size(200, 120); // Set size
this.draftingViewListBox.Location = new System.Drawing.Point(60, 50); // Position
this.draftingViewListBox.Name = "draftingViewListBox";
this.Controls.Add(this.draftingViewListBox);
this.draftingViewListBox.SelectionMode = System.Windows.Forms.SelectionMode.MultiExtended;
this.draftingViewListBox.KeyDown += listBox_KeyDown;
// Sheet ComboBox
this.sheetComboBox.FormattingEnabled = true;
this.sheetComboBox.Size = new System.Drawing.Size(200, 21); // Set size
this.sheetComboBox.Location = new System.Drawing.Point(60, 190); // Position
this.sheetComboBox.Name = "sheetComboBox";
this.Controls.Add(this.sheetComboBox);
// Ok Button
this.okButton.Location = new System.Drawing.Point(60, 230); // Position
this.okButton.Name = "okButton";
this.okButton.Size = new System.Drawing.Size(75, 23); // Set size
this.okButton.TabIndex = 0;
this.okButton.Text = "OK";
this.okButton.UseVisualStyleBackColor = true;
this.okButton.Click += new System.EventHandler(this.OkButton_Click);
this.Controls.Add(this.okButton);
// Cancel Button
this.cancelButton.Location = new System.Drawing.Point(185, 230); // Position
this.cancelButton.Name = "cancelButton";
this.cancelButton.Size = new System.Drawing.Size(75, 23); // Set size
this.cancelButton.TabIndex = 0;
this.cancelButton.Text = "Cancel";
this.cancelButton.UseVisualStyleBackColor = true;
this.cancelButton.Click += new System.EventHandler(this.CancelButton_Click);
this.Controls.Add(this.cancelButton);
}
private void CircularBorderForm_Paint(object sender, PaintEventArgs e)
{
// Create a circular region
GraphicsPath path = new GraphicsPath();
path.AddEllipse(0, 0, this.Width - 1, this.Height - 1);
Region = new Region(path);
// Dispose the GraphicsPath to free resources
path.Dispose();
}
private void Form_MouseDown(object sender, MouseEventArgs e)
{
lastLocation = e.Location;
}
private void Form_MouseMove(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
this.Left += e.X - lastLocation.X;
this.Top += e.Y - lastLocation.Y;
}
}
private void Form_MouseUp(object sender, MouseEventArgs e)
{
lastLocation = System.Drawing.Point.Empty;
}
private void OkButton_Click(object sender, EventArgs e)
{
SelectedDraftingViews = new List<ViewDrafting>(); // Initialize the list
string selectedSheetName = sheetComboBox.SelectedItem as string;
try
{
List<string> selectedDraftingViewNames = new List<string>();
if (!string.IsNullOrEmpty(selectedSheetName) && draftingViewListBox != null)
{
// Get the selected drafting views
foreach (var selectedItem in draftingViewListBox.SelectedItems)
{
if (selectedItem != null && !string.IsNullOrEmpty(selectedItem.ToString()))
{
if (importDraftingViewsFromExternalDoc != null)
{
var draftingView = importDraftingViewsFromExternalDoc.FirstOrDefault(x => x.Name == selectedItem.ToString());
if (draftingView != null)
{
SelectedDraftingViews.Add(importDraftingViewsFromExternalDoc.FirstOrDefault(x => x.Name == selectedItem.ToString()));
}
}
else
{
TaskDialog.Show("Error", "importDraftingViewsFromExternalDoc is null");
}
}
}
SelectedSheet = sheets.FirstOrDefault(sheet =>
sheet.Name?.Trim().Equals(selectedSheetName?.Trim(), StringComparison.OrdinalIgnoreCase) == true);
if (SelectedSheet == null)
{
TaskDialog.Show("Error", $"Selected sheet '{selectedSheetName}' not found.");
return;
}
this.DialogResult = DialogResult.OK;
this.Close();
}
}
catch (NullReferenceException nullEx)
{
TaskDialog.Show("Error", "A null reference exception occurred. Details: " + nullEx.Message);
}
catch (Exception ex)
{
TaskDialog.Show("Error", $"(21){ex.Message}");
}
}
private void listBox_KeyDown(object sender, KeyEventArgs e)
{
// Check if Ctrl+A is pressed
if (e.Control && e.KeyCode == Keys.A)
{
// Select all items
for (int i = 0; i < draftingViewListBox.Items.Count; i++)
{
draftingViewListBox.SetSelected(i, true);
}
}
else if (e.KeyCode == Keys.Escape) // Check if Escape key is pressed
{
// Deselect all items
draftingViewListBox.ClearSelected();
}
}
private void CancelButton_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.Cancel;
Close();
}
}