Can anyone tell me why view port variable always comes back null? The parameters of Viewport.Create are not null.

Can anyone tell me why view port variable always comes back null? The parameters of Viewport.Create are not null.

ed_sa
Enthusiast Enthusiast
2,423 Views
37 Replies
Message 1 of 38

Can anyone tell me why view port variable always comes back null? The parameters of Viewport.Create are not null.

ed_sa
Enthusiast
Enthusiast

using Autodesk.Navisworks.Api;
using Autodesk.Revit.ApplicationServices;
using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using Document = Autodesk.Revit.DB.Document;
using Transaction = Autodesk.Revit.DB.Transaction;
using View = Autodesk.Revit.DB.View;

namespace RevitAPI_JBA_Development_2022
{
[Transaction(TransactionMode.Manual)]
public class GetDraftViewToSheetElementTransformUtils : IExternalCommand
{
public UIApplication uiApp;
public UIDocument uiDoc;
public Document doc;
public Document externalDoc;
public List<ViewDrafting> draftingViewsFromExternalDoc;
public List<Autodesk.Revit.DB.ViewSheet> sheets;
public ICollection<ElementId> copiedViewElementIds;
SelectDraftingViewForm viewForm;


public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
{
UIApplication uiApp = commandData.Application;
UIDocument uiDoc = uiApp.ActiveUIDocument;
Autodesk.Revit.DB.Document doc = uiDoc.Document;

using (Autodesk.Revit.DB.Transaction docTransaction = new Transaction(doc, "Process Drafting Views"))
{
try
{
docTransaction.Start();
string selectedFilePath = BrowseForFile();
if (selectedFilePath == null)
{
TaskDialog.Show("Message", "Error: File not selected");
return Result.Cancelled;
}

externalDoc = uiApp.Application.OpenDocumentFile(selectedFilePath);
//TaskDialog.Show("Print", $"{externalDoc}");
if (externalDoc == null)
{
TaskDialog.Show("Error", $"Failed to open the external document: {selectedFilePath}");
return Result.Failed;
}

draftingViewsFromExternalDoc = GetDraftingViews(externalDoc);
sheets = GetSheets(doc);

if (draftingViewsFromExternalDoc == null || draftingViewsFromExternalDoc.Count == 0)
{
TaskDialog.Show("Message", "No drafting views found in the external document.");
externalDoc.Close(true);
return Result.Cancelled;
}

// Display a form to select the drafting view
viewForm = new SelectDraftingViewForm(draftingViewsFromExternalDoc, sheets);
if (viewForm.ShowDialog() != DialogResult.OK)
{
externalDoc.Close(false);
return Result.Cancelled;
}

ViewDrafting selectedDraftingView = viewForm.SelectedDraftingView;
//TaskDialog.Show("Print", $"{uiApp}-{doc}-{externalDoc}-{draftingViewsFromExternalDoc}-{viewForm}");
//TaskDialog.Show("Print", $"{externalDoc}");
//TaskDialog.Show("Print", $"{draftingViewsFromExternalDoc}");
if (uiApp != null && doc != null && externalDoc != null && draftingViewsFromExternalDoc != null && viewForm != null && selectedDraftingView != null)
{
try
{
if (uiApp != null && doc != null && externalDoc != null && draftingViewsFromExternalDoc != null && viewForm != null)
{
// Place the selected drafting view onto a new sheet in the current document
ViewSheet selectedSheetImport = PlaceDraftingViewOnSheet(doc, selectedDraftingView);
//TaskDialog.Show("Print", $"{newSheet}");
// Close the external document
//externalDoc.Close(false);

// Update existing elements with imported items if they have the same name
//TaskDialog.Show("Print", "Print TaskDialog number one");
UpdateExistingElements(doc, externalDoc);
//TaskDialog.Show("Print", "Print TaskDialog number two");
docTransaction.Commit();
return Result.Succeeded;
}
else
{
TaskDialog.Show("Error", "One ofthe items is null!");
return Result.Failed;
}
}
catch (Exception ex)
{
if (docTransaction.GetStatus() == TransactionStatus.Started)
{
docTransaction.RollBack();
}
TaskDialog.Show("Error", $"An error occurred: {ex.Message}");
return Result.Failed;
}
}
else
{
TaskDialog.Show("Print", "this is for print");
return Result.Failed;
}
}
catch (Exception ex)
{
TaskDialog.Show("Error", $"Failed to place drafting view on sheet: {ex.Message}");
return Result.Failed;
}
}
}
public GetDraftViewToSheetElementTransformUtils()
{
// Initialize uiApp and uiDoc to null
uiApp = null;
uiDoc = null;
// Initialize other variables
doc = this.doc;
externalDoc = null;
draftingViewsFromExternalDoc = new List<ViewDrafting>();
copiedViewElementIds = new List<ElementId>();
SelectDraftingViewForm viewForm;


}

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)
{
return new FilteredElementCollector(document)
.OfClass(typeof(ViewDrafting))
.Cast<ViewDrafting>()
.ToList();
}

public List<ViewSheet> GetSheets(Document doc)
{
return new FilteredElementCollector(doc)
.OfClass(typeof(ViewSheet))
.Cast<ViewSheet>()
.ToList();
}

//Version 1
//private ViewSheet PlaceDraftingViewOnSheet(Document currentDoc, ViewDrafting draftingView)
//{
// if (currentDoc == null || draftingView == null)
// {
// TaskDialog.Show("Error", "Document or DraftingView is null");
// return null;
// }
// try
// {
// // Retrieve the selected sheet from the combo box
// string selectedSheetName = viewForm.sheetComboBox.SelectedItem as string;
// if (string.IsNullOrEmpty(selectedSheetName))
// {
// TaskDialog.Show("Error", "No sheet selected");
// return null;
// }

// // Retrieve the selected sheet from the list of sheets
// ViewSheet selectedSheet = sheets.FirstOrDefault(sheet => sheet.Name == selectedSheetName);
// if (selectedSheet == null)
// {
// TaskDialog.Show("Error", $"Selected sheet '{selectedSheetName}' not found");
// return null;
// }

// // Copy the drafting view to the selected sheet
// ElementId copiedViewElementId = ElementTransformUtils.CopyElements(externalDoc, new List<ElementId> { draftingView.Id }, currentDoc, null, null).First();
// if (copiedViewElementId == null || copiedViewElementId == ElementId.InvalidElementId)
// {
// TaskDialog.Show("Error", "Failed to copy the drafting view to the sheet");
// return null;
// }

// copiedViewElementIds.Add(copiedViewElementId);

// Element copiedElement = currentDoc.GetElement(copiedViewElementId);
// if (copiedElement is ViewDrafting copiedView)
// {
// // Create a new viewport for the drafting view
// Viewport viewport = Viewport.Create(currentDoc, selectedSheet.Id, copiedView.Id, XYZ.Zero);
// if (viewport == null)
// {
// TaskDialog.Show("Error", "Failed to create viewport for the drafting view");
// return null;
// }
// }

// return selectedSheet;
// }
// catch (Exception ex)
// {
// TaskDialog.Show("Error", $"An error occurred: {ex.Message}");
// return null;
// }
//}

//Version 2
//private ViewSheet PlaceDraftingViewOnSheet(Document currentDoc, ViewDrafting draftingView)
//{
// if (currentDoc == null || draftingView == null)
// {
// TaskDialog.Show("Error", "Document or DraftingView is null");
// return null;
// }
// try
// {
// // Create a new sheet
// //ViewSheet newSheet = ViewSheet.Create(currentDoc, ElementId.InvalidElementId);
// // Retrieve the list of sheets from the current document
// List<ViewSheet> sheets = new FilteredElementCollector(currentDoc)
// .OfClass(typeof(ViewSheet))
// .Cast<ViewSheet>()
// .ToList();

// if (sheets == null)
// {
// TaskDialog.Show("Error", "Failed to create a new sheet");
// return null;
// }
// //TaskDialog.Show("Print", $"new Sheet{newSheet}");
// // Copy the drafting view to the new sheet
// ElementId copiedViewElementId = ElementTransformUtils.CopyElements(externalDoc, new List<ElementId> { draftingView.Id }, currentDoc, null, null).First();
// //TaskDialog.Show("Print", $"copied View element Id{copiedViewElementId}");
// if (copiedViewElementId == null || copiedViewElementId == ElementId.InvalidElementId)
// {
// TaskDialog.Show("Error", "Failed to copy the drafting view to the new sheet");
// return null;
// }

// copiedViewElementIds.Add(copiedViewElementId);
// Element copiedElement = currentDoc.GetElement(copiedViewElementId);
// //TaskDialog.Show("Print", $"copied Element{copiedElement}");

// if (copiedElement is ViewDrafting copiedView)
// {
// //TaskDialog.Show("Print", $"{copiedView}-{currentDoc}-{newSheet}much before");

// //TaskDialog.Show("Print", $"{copiedView}-{currentDoc}-{newSheet} Before that");
// try
// {
// //TaskDialog.Show("Print", $"{copiedView}-{currentDoc}-{newSheet} Before it");
// if (copiedView != null && currentDoc != null && newSheet != null)
// {
// Viewport viewport = Viewport.Create(currentDoc, newSheet.Id, copiedView.Id, XYZ.Zero);
// if (viewport == null)
// {
// TaskDialog.Show("Error", "Failed to create viewport for the drafting view");
// return null;
// }
// //TaskDialog.Show("Print", $"{copiedView}-{currentDoc}-{newSheet} Afterwards");
// }
// else
// {
// TaskDialog.Show("Error", "One of the items is null");
// }
// }
// catch (Exception ex)
// {
// TaskDialog.Show("Error", $"{ex.Message}");
// }
// }
// return sheets;

// }
// catch (Exception ex)
// {
// TaskDialog.Show("Error", $"An error occurred: {ex.Message}");
// return null;
// }

//}

//Version 3
private ViewSheet PlaceDraftingViewOnSheet(Document currentDoc, ViewDrafting draftingView)
{
if (currentDoc == null || draftingView == null)
{
TaskDialog.Show("Error", "Document or DraftingView is null");
return null;
}

try
{
// Retrieve the selected sheet from the combo box
string selectedSheetName = viewForm.sheetComboBox.SelectedItem as string;
if (string.IsNullOrEmpty(selectedSheetName))
{
TaskDialog.Show("Error", "No sheet selected");
return null;
}

// Retrieve the selected sheet from the list of sheets
ViewSheet selectedSheet = sheets.FirstOrDefault(sheet => sheet.Name == selectedSheetName);
if (selectedSheet == null)
{
TaskDialog.Show("Error", $"Selected sheet '{selectedSheetName}' not found");
return null;
}

// Copy the drafting view to the selected sheet
ElementId copiedViewElementId = ElementTransformUtils.CopyElements(externalDoc, new List<ElementId> { draftingView.Id }, currentDoc, null, null).FirstOrDefault();
if (copiedViewElementId == null || copiedViewElementId == ElementId.InvalidElementId)
{
TaskDialog.Show("Error", "Failed to copy the drafting view to the sheet");
return null;
}

copiedViewElementIds.Add(copiedViewElementId);

// Get the copied drafting view element
Element copiedElement = currentDoc.GetElement(copiedViewElementId);
if (copiedElement is ViewDrafting copiedView)
{
// Create a new viewport for the drafting view
Viewport viewport = Viewport.Create(currentDoc, selectedSheet.Id, copiedView.Id, XYZ.Zero);
if (viewport == null)
{
TaskDialog.Show("Error", "Failed to create viewport for the drafting view");
return null;
}

return selectedSheet;
}
else
{
TaskDialog.Show("Error", "Copied element is not a drafting view");
return null;
}
}
catch (Exception ex)
{
TaskDialog.Show("Error", $"An error occurred: {ex.Message}");
return null;
}
}

 

private void UpdateExistingElements(Document currentDoc, Document externalDoc)
{
// List to store names of imported elements from the external document
List<string> importedElementNames = new List<string>();

// Retrieve names of imported elements from external document
foreach (var elementId in copiedViewElementIds)
{
Element importedElement = externalDoc.GetElement(elementId);
if (importedElement != null)
{
string elementName = importedElement.Name;
if (!string.IsNullOrEmpty(elementName))
{
importedElementNames.Add(elementName);
}
}
}

try
{
// Iterate over copied view element IDs
foreach (var importedElementId in copiedViewElementIds)
{
// Retrieve imported element from current document
Element importedElement = currentDoc.GetElement(importedElementId);
if (importedElement != null)
{
string importedElementName = importedElement.Name;
if (!string.IsNullOrEmpty(importedElementName))
{
// Check if imported element name exists in the current document
if (importedElementNames.Contains(importedElementName))
{
// Find existing element with the same name
var existingElement = new FilteredElementCollector(currentDoc)
.WhereElementIsNotElementType()
.FirstOrDefault(e => e.Name == importedElementName);

if (existingElement != null)
{
// Delete existing element
currentDoc.Delete(existingElement.Id);
// Copy imported element to replace existing element
ElementTransformUtils.CopyElement(currentDoc, importedElementId, null);
}
}
else
{
// Check if imported element is a FamilySymbol
FamilySymbol familySymbol = importedElement as FamilySymbol;
if (familySymbol != null)
{
// Duplicate and activate the FamilySymbol
FamilySymbol newSymbol = familySymbol.Duplicate(importedElementName) as FamilySymbol;
newSymbol.Activate();
}
else
{
// Check if imported element is an ElementType
ElementType elementType = importedElement as ElementType;
if (elementType != null)
{
// Duplicate the ElementType
ElementType newType = elementType.Duplicate(importedElementName) as ElementType;
}
}
}
}
}
}
}
catch (Exception ex)
{
// Handle any exceptions that occur during the process
TaskDialog.Show("Error", $"{ex.Message}");
}
}
}
}


//public class SelectDraftingViewForm : System.Windows.Forms.Form
//{
// private System.Windows.Forms.ComboBox comboBox1;
// private Button okButton;
// private Button cancelButton;
// public ViewDrafting SelectedDraftingView { get; private set; }
// public List<ViewDrafting> draftingViewsFromExternalDoc;
// public SelectDraftingViewForm(List<ViewDrafting> draftingViewsFromExternalDoc)
// {
// try
// {
// InitializeComponent();
// this.draftingViewsFromExternalDoc = draftingViewsFromExternalDoc;
// foreach (var draftingView in draftingViewsFromExternalDoc)
// {
// comboBox1.Items.Add(draftingView.Name);
// }
// }
// catch (Exception ex)
// {
// TaskDialog.Show("Error", $"{ex.Message}");
// }

// }

// private void InitializeComponent()
// {
// this.comboBox1 = new System.Windows.Forms.ComboBox();
// this.okButton = new System.Windows.Forms.Button();
// this.cancelButton = new System.Windows.Forms.Button();

// // ComboBox
// this.comboBox1.FormattingEnabled = true;
// this.comboBox1.Location = new System.Drawing.Point(12, 12);
// this.comboBox1.Name = "comboBox1";
// this.comboBox1.Size = new System.Drawing.Size(200, 21);
// this.comboBox1.TabIndex = 0;

// // Ok Button
// this.okButton.Location = new System.Drawing.Point(12, 50);
// this.okButton.Name = "okButton";
// this.okButton.Size = new System.Drawing.Size(75, 23);
// this.okButton.TabIndex = 1;
// this.okButton.Text = "OK";
// this.okButton.UseVisualStyleBackColor = true;
// this.okButton.Click += new System.EventHandler(this.OkButton_Click);

// // Cancel Button
// this.cancelButton.Location = new System.Drawing.Point(137, 50);
// this.cancelButton.Name = "cancelButton";
// this.cancelButton.Size = new System.Drawing.Size(75, 23);
// this.cancelButton.TabIndex = 2;
// this.cancelButton.Text = "Cancel";
// this.cancelButton.UseVisualStyleBackColor = true;
// this.cancelButton.Click += new System.EventHandler(this.CancelButton_Click);

// // Form
// this.ClientSize = new System.Drawing.Size(224, 85);
// this.Controls.Add(this.cancelButton);
// this.Controls.Add(this.okButton);
// this.Controls.Add(this.comboBox1);
// this.Name = "SelectDraftingViewForm";
// this.Text = "Select Drafting View";
// }

 

// private void OkButton_Click(object sender, EventArgs e)
// {
// try
// {
// string selectedDraftingViewName = comboBox1.SelectedItem as string;
// if (!string.IsNullOrEmpty(selectedDraftingViewName) && draftingViewsFromExternalDoc != null)
// {
// SelectedDraftingView = draftingViewsFromExternalDoc
// .FirstOrDefault(view => view.Name == selectedDraftingViewName);
// }
// DialogResult = DialogResult.OK;
// Close();
// }
// catch (Exception ex)
// {
// TaskDialog.Show("Error", $"{ex.Message}");
// }
// }

// private void CancelButton_Click(object sender, EventArgs e)
// {
// DialogResult = DialogResult.Cancel;
// Close();
// }
//}
public class SelectDraftingViewForm : System.Windows.Forms.Form
{
public System.Windows.Forms.ComboBox draftingViewComboBox;
public System.Windows.Forms.ComboBox sheetComboBox;
public Button okButton;
public Button cancelButton;
public ViewDrafting SelectedDraftingView { get; private set; }
public ViewSheet SelectedSheet { get; private set; }
public List<ViewDrafting> importDraftingViewsFromExternalDoc;
public List<ViewSheet> sheets;


public SelectDraftingViewForm(List<ViewDrafting> draftingViewsFromExternalDoc, List<ViewSheet> sheets)
{
try
{
this.importDraftingViewsFromExternalDoc = draftingViewsFromExternalDoc;
this.sheets = sheets;
InitializeComponent();

if (importDraftingViewsFromExternalDoc != null)
{
foreach (var draftingView in importDraftingViewsFromExternalDoc)
{
draftingViewComboBox.Items.Add(draftingView.Name);
}
}

if(sheets!= null)
{
foreach (var sheet in sheets)
{
sheetComboBox.Items.Add(sheet.Name);
}
}
}
catch (Exception ex)
{
TaskDialog.Show("Error", $"{ex.Message}");
}

}

private void InitializeComponent()
{
this.draftingViewComboBox = new System.Windows.Forms.ComboBox();
this.sheetComboBox = new System.Windows.Forms.ComboBox();
this.okButton = new System.Windows.Forms.Button();
this.cancelButton = new System.Windows.Forms.Button();

// Drafting View ComboBox
this.draftingViewComboBox.FormattingEnabled = true;
this.draftingViewComboBox.Location = new System.Drawing.Point(12, 12);
this.draftingViewComboBox.Name = "draftingViewComboBox";
this.draftingViewComboBox.Size = new System.Drawing.Size(200, 21);
this.draftingViewComboBox.TabIndex = 0;

// Sheet ComboBox
this.sheetComboBox.FormattingEnabled = true;
this.sheetComboBox.Location = new System.Drawing.Point(12, 40);
this.sheetComboBox.Name = "sheetComboBox";
this.sheetComboBox.Size = new System.Drawing.Size(200, 21);
this.sheetComboBox.TabIndex = 1;

// Ok Button
this.okButton.Location = new System.Drawing.Point(12, 80);
this.okButton.Name = "okButton";
this.okButton.Size = new System.Drawing.Size(75, 23);
this.okButton.TabIndex = 2;
this.okButton.Text = "OK";
this.okButton.UseVisualStyleBackColor = true;
this.okButton.Click += new System.EventHandler(this.OkButton_Click);

// Cancel Button
this.cancelButton.Location = new System.Drawing.Point(137, 80);
this.cancelButton.Name = "cancelButton";
this.cancelButton.Size = new System.Drawing.Size(75, 23);
this.cancelButton.TabIndex = 3;
this.cancelButton.Text = "Cancel";
this.cancelButton.UseVisualStyleBackColor = true;
this.cancelButton.Click += new System.EventHandler(this.CancelButton_Click);

// Form
this.ClientSize = new System.Drawing.Size(224, 120);
this.Controls.Add(this.cancelButton);
this.Controls.Add(this.okButton);
this.Controls.Add(this.sheetComboBox);
this.Controls.Add(this.draftingViewComboBox);
this.Name = "SelectDraftingViewForm";
this.Text = "Select Drafting View";
}

private void OkButton_Click(object sender, EventArgs e)
{
try
{
string selectedDraftingViewName = draftingViewComboBox.SelectedItem as string;
string selectedSheetName = sheetComboBox.SelectedItem as string;

if (!string.IsNullOrEmpty(selectedDraftingViewName) && !string.IsNullOrEmpty(selectedSheetName))
{
SelectedDraftingView = importDraftingViewsFromExternalDoc
.FirstOrDefault(view => view.Name == selectedDraftingViewName);

SelectedSheet = sheets.FirstOrDefault(sheet => sheet.Name == selectedSheetName);
}

DialogResult = DialogResult.OK;
Close();
}
catch (Exception ex)
{
TaskDialog.Show("Error", $"{ex.Message}");
}
}

private void CancelButton_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.Cancel;
Close();
}
}

 

 

0 Likes
2,424 Views
37 Replies
Replies (37)
Message 21 of 38

TripleM-Dev.net
Advisor
Advisor

I've added the following code after the draftview is copied

 

FilteredElementCollector vft = new FilteredElementCollector(externalDoc, draftingView.Id);
                    View copyview = (View)currentDoc.GetElement(copiedViewElementId);
                    ElementTransformUtils.CopyElements(draftingView, vft.ToElementIds(), copyview, Transform.Identity, null);

 

I can see the content on sheet, but I get a error about constraints regarding the content.

Try it with some simple Draftview content....

0 Likes
Message 22 of 38

ed_sa
Enthusiast
Enthusiast

are you talking about here: 

// Validate the sheet and drafting view dimensions
if (!ValidateSheetAndDraftingView(selectedSheet, draftingView))
{
return null; // Validation failed
}

// Copy the drafting view to the current document
ElementId copiedViewElementId = ElementTransformUtils.CopyElements(externalDoc, new List<ElementId> { draftingView.Id }, currentDoc, null, null).FirstOrDefault();

(HEREHEREHERE?)
if (copiedViewElementId == null || copiedViewElementId == ElementId.InvalidElementId)
{
TaskDialog.Show("Error", "Failed to copy the drafting view to the sheet");
return null;
}

0 Likes
Message 23 of 38

ed_sa
Enthusiast
Enthusiast

FOR WHAT PURPOSE? IT SEEMS THE DRAFTINGVIEW CAPTURE HAPPENED WITH THIS METHOD:  private List<ViewDrafting> GetDraftingViews(Autodesk.Revit.DB.Document document)
{
return new FilteredElementCollector(document)
.OfClass(typeof(ViewDrafting))
.Cast<ViewDrafting>()
.ToList();
} that seems to be for the elements, not draftview itself.  

0 Likes
Message 24 of 38

ed_sa
Enthusiast
Enthusiast

why would ElementTransformUtils.CopyElements(externalDoc, new List<ElementId> { draftingView.Id }, currentDoc, null, null).FirstOrDefault(); not work you think?  one's copyelement, the other is copyelements.

0 Likes
Message 25 of 38

ed_sa
Enthusiast
Enthusiast

sorry for plethora of replies.  it works to load the content from the draftview onto a seperate draftview on separate draftview tab, but it doesnt place it on the designated sheet, I think we got over the toughest challenge however thanks to you. Much appreciated!!

0 Likes
Message 26 of 38

ed_sa
Enthusiast
Enthusiast

what message with constraints do you get specifically?

0 Likes
Message 27 of 38

TripleM-Dev.net
Advisor
Advisor

Never mind the error about constraints that's content on draftview related.

 

It needs a lot of editing to make it work, the code below works, but I had to split the transaction.

So remove the first transaction in you're code (or replace by transaction group) use code below and place the viewport creation also in it's own transaction.

 

ElementId copiedViewElementId = ElementId.InvalidElementId;

using (Autodesk.Revit.DB.Transaction docTransaction = new Transaction(currentDoc, "Copy Draftview"))
 {
  docTransaction.Start();

  ICollection<ElementId> CopiedElements = ElementTransformUtils.CopyElements(externalDoc, new List<ElementId> { draftingView.Id }, currentDoc, null, null);
  copiedViewElementId = CopiedElements.FirstOrDefault();
                 
  // Copy the drafting view to the current document
  // ElementId copiedViewElementId = ElementTransformUtils.CopyElements(externalDoc, new List<ElementId> { draftingView.Id }, currentDoc, null, null).FirstOrDefault();
  if (copiedViewElementId == null || copiedViewElementId == ElementId.InvalidElementId)
  {
      TaskDialog.Show("Error", "Failed to copy the drafting view to the sheet");
      return null;
  }
  {                         
      View copyview = (View)currentDoc.GetElement(copiedViewElementId); 
      FilteredElementCollector vft = new FilteredElementCollector(externalDoc, draftingView.Id).OfCategory(BuiltInCategory.OST_Lines); ;
      ElementTransformUtils.CopyElements(draftingView, vft.ToElementIds(), copyview, Transform.Identity, null);
   }

   docTransaction.Commit();
}
// Store the copied view element ID for later use
copiedViewElementIds.Add(copiedViewElementId);

 

So Turns out (probably due to OpenDocumentFile usage) that the content of the view needs to be copied.

CopyElements with View to View argument, but remove the external view itself from the copyelements collection.

I've limited the collection for quick testing to lines. (.OfCategory(BuiltInCategory.OST_Lines) line)

 

Advise:

Split the code more with seperate functions for Copy Draftview and for Placing view on sheet.

For Copying the Draftview just create a new draftview in the model and then copy the content of the external draftview onto it. (the first CopyElements call in the code above is not really needed....maybe if the view itself has certain settings attached...)

 

Anyway, good luck. It's quite a interesting case but a complex one.

- Michel

0 Likes
Message 28 of 38

ed_sa
Enthusiast
Enthusiast

must it be OST_Lines.  I need the full draft view, or does OST_Lines mean that? I have exactly the same. We're ont eh same page. 

0 Likes
Message 29 of 38

ed_sa
Enthusiast
Enthusiast

lso, I have 6 different transactions. I did that for every doc.Regenerate. prob not necessary. Do you know why it does that?

0 Likes
Message 30 of 38

ed_sa
Enthusiast
Enthusiast

Much appreciated by the way. 

0 Likes
Message 31 of 38

ed_sa
Enthusiast
Enthusiast

also, it doesn't automatically add the draftview family types to the family tab in project browser. It should I think.

0 Likes
Message 32 of 38

ed_sa
Enthusiast
Enthusiast

you can add morecategories than OST_Lines, still looking for the way to doit.  apparently you can iterate through , if you use LogicalOrfilter which takes two arguments at a time as in:

//// Create a FilteredElementCollector for the elements within the drafting view
//FilteredElementCollector collector = new FilteredElementCollector(currentDoc, copyView.Id);

//// Filter for elements based on criteria other than category
//ICollection<ElementId> elementIds = collector
// .WhereElementIsNotElementType() // Exclude element types
// .WherePasses(new LogicalOrFilter(
// new ElementCategoryFilter(BuiltInCategory.OST_Lines), // Include OST_Lines category
// new ElementCategoryFilter(BuiltInCategory.OST_TextNotes) // Include Text Notes category
// //new ElementCategoryFilter(BuiltInCategory.OST_Dimensions) // Include Dimensions category
// // Add more filters as needed to include other categories or criteria
// ))
// .ToElementIds(); and add those elements individually I suppose not sure yet how.

0 Likes
Message 33 of 38

TripleM-Dev.net
Advisor
Advisor

the OST_Lines limit was just a quick way of testing, not much can go wrong with only line

 

Well I gave it a go,

1. use ElementCategoryFilter as inverted filter with WherePasses, and exclude Views -> Failed error on something in draftview

2. So use ElementMulticategoryFilter with Views and ImportSymbol, well ImportSymbol doesn't have a builtincategory so a no-go

3. Use a Where filter for Annotation category, now only text comes in (lines, incl. detail lines are model categories!)

4. As last I just tested against Categories id < 0 (maybe only the imported symbol has issues?)

 

The final replacement for the CopyElements of the Draftview.

View copyview = (View)currentDoc.GetElement(copiedViewElementId);
IEnumerable<ElementId> vft = new FilteredElementCollector(externalDoc, draftingView.Id).Where(e => e.Category != null && e.Category.Id.IntegerValue < 0).Select(e => e.Id);   
ElementTransformUtils.CopyElements(draftingView, vft.ToList(), copyview, Transform.Identity, null);

 

Depending on the content of drafting views it will need a lot of testing....in my sample model (with a import symbol) it gave a error and possible reason for creating the additional draftview....?

 

Well I am done with it.

Good luck with it.

0 Likes
Message 34 of 38

ed_sa
Enthusiast
Enthusiast

I came across this: 

using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using System.Collections.Generic;
using System.Linq;

public void CopyElementsFromDraftingViewToSheet(Document doc, ElementId draftingViewId, ViewSheet sheet)
{
    // 1. Convert drafting view element to View type
    View draftingView = doc.GetElement(draftingViewId) as View;
    if (draftingView == null)
    {
        TaskDialog.Show("Error", "The specified view is not a drafting view.");
        return;
    }

    // 2. Retrieve all element IDs within the drafting view
    FilteredElementCollector collector = new FilteredElementCollector(doc, draftingViewId);
    ICollection<ElementId> draftingElementIds = collector.ToElementIds();

    // 3. Copy elements onto the sheet
    using (Transaction transaction = new Transaction(doc, "Copy Elements to Sheet"))
    {
        transaction.Start();

        foreach (ElementId elementId in draftingElementIds)
        {
            Element element = doc.GetElement(elementId);
            if (element != null && !element.IsElementType)
            {
                // Place the element on the sheet
                Viewport viewport = Viewport.Create(doc, sheet.Id, elementId, XYZ.Zero);
            }
        }

        transaction.Commit();
    }
}  it iterate through element types instead of IntegerValue >0 . I haven't tested yet, I will test yours first.

0 Likes
Message 35 of 38

ed_sa
Enthusiast
Enthusiast

 I SEE YOU'VE ADDED THE IENUMERABLE INTERFACE, WHICH IN MY CASE I HADN'T AND IT CAUSED IT TO PRINT TWO DRAFT VIEWS SHEET, ONE BLANK, ONE WITH CONTENT.  DO YOU KNOW WHY IT WOULD DO THAT USING THE FILTEREDELEMENTCOLLECTOR TYPE VS USING THE IENUMERABLE INTERFACE? 

0 Likes
Message 36 of 38

ed_sa
Enthusiast
Enthusiast

I figured the IEnumerable addition vs not.  with IEnumerable you eliminate the blank id reference and keep everything else within the view, meaning the elements. only difference. 

0 Likes
Message 37 of 38

ed_sa
Enthusiast
Enthusiast

yes that solved one of my problems for sure.  apparently I need to create a new sheet within the chosen tab/sheet as well

0 Likes
Message 38 of 38

ed_sa
Enthusiast
Enthusiast

I did get the answer actually.  so, draftviewElements are not just a view, they're a composition of elements plus the reference id. When you use FilteredElementCollector you have the first element as reference Id. if you make it an Enumerable<ElementId> type for instance, you get rid of that first element id.  Furthermore, before using Viewport.Create, you have to iterate on those IEnumerable items. I believe it might be because of actions such as .CopyElements, which copy the elements and somehow(item which Im to figure out why), it inserts null values, or skips bits and bytes, and so that list becomes one with null values in between. (this is just a hard guess).when you insert copyView, the copiedView of the draftView, if even one of the elements show as null, it will throw an error.  So, I came up with these checks below: 

if (currentDoc == null || selectedDraftingView == null || viewForm == null || selectedSheet == null)
{
TaskDialog.Show("Error", "One or more required parameters is null(twelve)");
return null;
}
if (!(selectedDraftingView is ViewDrafting))
{
TaskDialog.Show("Error", "The selected view is not a drafting view");
return null;
}
// Check if selectedDraftingView contains any elements
FilteredElementCollector collector = new FilteredElementCollector(selectedDraftingView.Document, selectedDraftingView.Id);
ICollection<Element> draftingViewElements = collector
.WhereElementIsNotElementType()
.ToElements();

if (draftingViewElements.Count == 0 )
{
TaskDialog.Show("Info", "The selected drafting view does not contain any elements.");
return null;
}.

AS WELL AS :


foreach (Element element in draftingViewElements)
{
if (element != null)
{
if (selectedSheet == null || selectedDraftingView == null)
{
TaskDialog.Show("Error", $"Selected sheet '{selectedSheet.Name}' not found(thirteen)");
return null;
}  ESPECIALLY THIS LAST PART WAS ESSENTIAL FOR VIEWPORT.CREATE(selectedSheet==null || selectedDraftinView ==null) that iterates each element in the drafting view before the elements get copied into : ElementId copiedViewElementId = ElementTransformUtils.CopyElements(externalDoc, new List<ElementId> { selectedDraftingView.Id }, currentDoc, null, null).FirstOrDefault();  It works beautiful! try it. 

0 Likes