THIS CODE ALWAYS THROWS 'ATTEMPT TO CHANGE MODEL OUTSIDE OF TRANSACTION' CAN ANYONE TELL ME WHY?

ed_sa
Enthusiast

THIS CODE ALWAYS THROWS 'ATTEMPT TO CHANGE MODEL OUTSIDE OF TRANSACTION' CAN ANYONE TELL ME WHY?

ed_sa
Enthusiast
Enthusiast

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;
}

// Duplicate the drafting view
ElementId blockId = selectedDraftingView.Duplicate(ViewDuplicateOption.Duplicate);
if (blockId == ElementId.InvalidElementId)
{
TaskDialog.Show("Error", "Failed to duplicate the drafting view.");
transaction.RollBack();
return Result.Failed;
}

// Get the duplicated block element
Element block = currentDoc.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}");
transaction.RollBack(); // Rollback transaction in case of exception
return Result.Failed;
}

0 Likes
Reply
756 Views
14 Replies
Replies (14)

jeremy_tammik
Autodesk
Autodesk

All caps is considered yelling, and often classed as impolite: 

  

  

 

 

Jeremy Tammik Developer Advocacy and Support + The Building Coder + Autodesk Developer Network + ADN Open
0 Likes

ed_sa
Enthusiast
Enthusiast

Thank you for your point of view.  Unfortunately, I haven't gotten an answer on my code as of yet. 

0 Likes

ed_sa
Enthusiast
Enthusiast

It is attention getting though. I agree. Sorry to add another useless comment. Thanks again for your point of view. ๐Ÿ™‚

0 Likes

ctm_mka
Advocate
Advocate

ed, where is your "transaction" coming from? usually we see something like "Transaction transaction = new Transaction(doc);" before "transaction.Start()".

0 Likes

ed_sa
Enthusiast
Enthusiast

Right below the try statement.. ๐Ÿ™‚

0 Likes

ed_sa
Enthusiast
Enthusiast

wait, that's in the code but you can't see it. using etc. right. yes it's there.  I get spam notice if I paste the whole code. too long prob

0 Likes

TripleM-Dev.net
Advisor
Advisor

Use the "Insert / Edit code sample" button in the message editor; </> button

 

How does the codeline below play into the routine? (It closes the document without saving after changes are committed?)

externalDoc.Close(false);

 

ed_sa
Enthusiast
Enthusiast

 

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;
}

// Duplicate the drafting view
ElementId blockId = selectedDraftingView.Duplicate(ViewDuplicateOption.Duplicate);
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 = currentDoc.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();
}
}

 

0 Likes

ed_sa
Enthusiast
Enthusiast

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;
}

// Duplicate the drafting view
ElementId blockId = selectedDraftingView.Duplicate(ViewDuplicateOption.Duplicate);
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 = currentDoc.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();
}
}

 

0 Likes

TripleM-Dev.net
Advisor
Advisor

Is this related to this  post?

 

Looks like you have a transaction for Document A, but Duplicate a View of Document B which has no active transaction.

Seems a post that keeps coming back about copying a Drafting view out of Document B to A, and then placing that new drafting view in Document A on a sheet in Document A.

 

First test small parts of the code, first try to copy a draftview with contents from Document B to A, then the rest is fairly easy.

And again CopyElements a View doesn't include it's content, only the view itself.

 

0 Likes

ed_sa
Enthusiast
Enthusiast

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();
}
}

 

 

0 Likes

ed_sa
Enthusiast
Enthusiast

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();
}
}

 

0 Likes

ed_sa
Enthusiast
Enthusiast

Also there are two types of copy elements.one copies the elements from one document to antoher, the other copies the view from one view to another and viewport.create creates a reference to the elements within the imported copied view. However if you use copyelements, you would have to iterate on each element as it won't copy model elements and will throw an error.  so I decided to duplicate the whole draftview which is this code and skip copyelements altogether in hope the elements will come along. 

0 Likes

ed_sa
Enthusiast
Enthusiast

One more thing.  The blockId Duplicate method finally worked based on your suggestion to add another transaction for the externalDoc. However, when inserting blockId, or better yet, the GetElement(blockId), into the Viewport.Create, it returns a null value for the Viewport.Create  result. That's the current problem I'm having from the code above. Sorry for the repeat code, but I wanted to share the whole code with the community, I believe it should be an addition to revit as a more direct method than insert from file. Thank you for your time sorry for any inconvenience.

0 Likes