Can anyone tell me why view port variable always comes back null? The parameters of Viewport.Create are not null.
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report
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();
}
}