Viewport.Create returns null every time despite parameters not being null.

Viewport.Create returns null every time despite parameters not being null.

ed_sa
Enthusiast Enthusiast
255 Views
2 Replies
Message 1 of 3

Viewport.Create returns null every time despite parameters not being null.

ed_sa
Enthusiast
Enthusiast

from code excerpt below: 

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);
if (newSheet == 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)
{
// Get the view range parameters
Parameter cutPlaneElevationParam = copiedView.get_Parameter(BuiltInParameter.PLAN_VIEW_CUT_PLANE_HEIGHT);
Parameter viewDepthParam = copiedView.get_Parameter(BuiltInParameter.VIEWER_BOUND_OFFSET_FAR);

// Check if either parameter is null
if (cutPlaneElevationParam == null || viewDepthParam == null)
{
// Display a warning message about null parameters
TaskDialog.Show("Warning", "One or both view range parameters are null. Proceeding with default values for view range.");

// If cutPlaneElevationParam is null, set a default value (e.g., 1000mm)
if (cutPlaneElevationParam == null)
{
// Set a default cut plane elevation value (adjust as needed)
const double defaultCutPlaneElevation = 1000.0; // Default value in millimeters
cutPlaneElevationParam = copiedView.get_Parameter(BuiltInParameter.PLAN_VIEW_CUT_PLANE_HEIGHT);
if (cutPlaneElevationParam != null)
{
cutPlaneElevationParam.Set(defaultCutPlaneElevation);
}
}
// You can handle the viewDepthParam similarly if needed
}
//TaskDialog.Show("Print", $"{copiedView}-{currentDoc}-{newSheet}");
// Create a new viewport for the drafting view
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 newSheet;

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

}

 

whole code:

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;

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 ICollection<ElementId> copiedViewElementIds;

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);
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
SelectDraftingViewForm viewForm = new SelectDraftingViewForm(draftingViewsFromExternalDoc);
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 newSheetImport = 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, newSheetImport);
//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>();

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

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);
if (newSheet == 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)
{
// Get the view range parameters
Parameter cutPlaneElevationParam = copiedView.get_Parameter(BuiltInParameter.PLAN_VIEW_CUT_PLANE_HEIGHT);
Parameter viewDepthParam = copiedView.get_Parameter(BuiltInParameter.VIEWER_BOUND_OFFSET_FAR);

// Check if either parameter is null
if (cutPlaneElevationParam == null || viewDepthParam == null)
{
// Display a warning message about null parameters
TaskDialog.Show("Warning", "One or both view range parameters are null. Proceeding with default values for view range.");

// If cutPlaneElevationParam is null, set a default value (e.g., 1000mm)
if (cutPlaneElevationParam == null)
{
// Set a default cut plane elevation value (adjust as needed)
const double defaultCutPlaneElevation = 1000.0; // Default value in millimeters
cutPlaneElevationParam = copiedView.get_Parameter(BuiltInParameter.PLAN_VIEW_CUT_PLANE_HEIGHT);
if (cutPlaneElevationParam != null)
{
cutPlaneElevationParam.Set(defaultCutPlaneElevation);
}
}
// You can handle the viewDepthParam similarly if needed
}
//TaskDialog.Show("Print", $"{copiedView}-{currentDoc}-{newSheet}");
// Create a new viewport for the drafting view
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 newSheet;

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

}


private void UpdateExistingElements(Document currentDoc, ViewSheet newSheet)
{
// Get the names of the imported elements from the external document
List<string> importedElementNames = new List<string>();
//TaskDialog.Show("Print", $"Message one{importedElementNames}");
foreach (var elementId in copiedViewElementIds)
{
//TaskDialog.Show("Print", $"Message two{elementId}");
Element importedElement = externalDoc.GetElement(elementId); // Retrieve from the external document
//TaskDialog.Show("Print", $"Message three{importedElement}");
if (importedElement != null)
{
string elementName = importedElement.Name;
//TaskDialog.Show("Print", $"Message four{elementName}");
if (!string.IsNullOrEmpty(elementName))
{
importedElementNames.Add(elementName);
//TaskDialog.Show("Print", $"Message five{importedElementNames}");
}
}
}

try
{
foreach (var importedElementId in copiedViewElementIds)
{
Element importedElement = currentDoc.GetElement(importedElementId);
//TaskDialog.Show("Print", $"Message six {importedElement}");
if (importedElement != null)
{
//TaskDialog.Show("Print", $"Message seven {importedElement}");
string importedElementName = importedElement.Name;
if (!string.IsNullOrEmpty(importedElementName))
{
//TaskDialog.Show("Print", $"Message eight {importedElementName}");
// Check if the imported element name exists in the current document
if (importedElementNames.Contains(importedElementName))
{
// Find the existing element with the same name
var existingElement = new FilteredElementCollector(currentDoc)
.WhereElementIsNotElementType()
.FirstOrDefault(e => e.Name == importedElementName);
//TaskDialog.Show("Print", $"Message Nine {existingElement}");
if (existingElement != null)
{
// Replace the existing element with the imported element
currentDoc.Delete(existingElement.Id);
//TaskDialog.Show("Print", $"message ten {currentDoc}");
ElementTransformUtils.CopyElement(currentDoc, importedElementId, null);
}
}
else
{
// Add the imported element to the family types of the document
FamilySymbol familySymbol = importedElement as FamilySymbol;
//TaskDialog.Show("Print", $"familySymbol message eleven{familySymbol}");
if (familySymbol != null)
{
TaskDialog.Show("Print", $"message twelve {familySymbol}");
// Create a new instance of the same FamilySymbol in the document
FamilySymbol newSymbol = familySymbol.Duplicate(importedElementName) as FamilySymbol;
//TaskDialog.Show("Print", $"Message thirteen {importedElementNames}");
newSymbol.Activate();
}
else
{
// Check if the imported element is an ElementType
ElementType elementType = importedElement as ElementType;
//TaskDialog.Show("Print", $"element type message fourteen {importedElementNames}");
if (elementType != null)
{
// Create a new instance of the same ElementType in the document
ElementType newType = elementType.Duplicate(importedElementName) as ElementType;
TaskDialog.Show("Print", $"new type message fifteen{importedElementNames}");
}
}
}
}
}
}
}
catch (Exception ex)
{
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();
}
}
}
}

 

 

0 Likes
Accepted solutions (1)
256 Views
2 Replies
Replies (2)
Message 2 of 3

jeremy_tammik
Alumni
Alumni
Accepted solution

I would not consider the large listing that you share a "snippet". Please invest some effort in your question yourself first, to make it easier for the rest of the universe to answer. Thank you!

    

Also, please refer to the answer to your second very similar query:

  

https://forums.autodesk.com/t5/revit-api-forum/can-anyone-tell-me-why-view-port-variable-always-come...

  

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

ed_sa
Enthusiast
Enthusiast

Thank you for your criticism. However, in this case I think it was necessary because I didn't know at that point where the error was coming from, plus, I don't think anyone minds getting sample code like that, it's probably enriching the forum if anything. The other thread was incomplete code, which is why I added this one, but apparently you can't delete comments, ergo two comments. Im so sorry for the inconvenience man. By the way, the other thread had some content and a possible path to a solution. It turns out drafting views can be placed by viewport, but some type of geometry has to  be defined. Im have  'location' which is XYZ.Zero, but chatgpt apparently recommends a recalculation, Im yet to find out what that means. In any case, check the other thread, that's going somewhere with the code I believe. Thank you for reply.

0 Likes