While running below code im getting thsi error message "Error reading CAD file: Object reference not set to an instance of an object." Please help I'm new to RevitAPI

While running below code im getting thsi error message "Error reading CAD file: Object reference not set to an instance of an object." Please help I'm new to RevitAPI

bim.user23
Observer Observer
263 Views
2 Replies
Message 1 of 3

While running below code im getting thsi error message "Error reading CAD file: Object reference not set to an instance of an object." Please help I'm new to RevitAPI

bim.user23
Observer
Observer

While running below code im getting thsi error message "Error reading CAD file: Object reference not set to an instance of an object." Please help I'm new to RevitAPI .

using System;
using System.Windows.Media;
using System.Text;
using System.Reflection;
using System.Collections.Generic;
using Autodesk.Revit.ApplicationServices;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using Autodesk.Revit.Attributes;
using System.IO;
using System.Windows.Media.Imaging;
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.Runtime;
using Autodesk.AutoCAD.Geometry;

namespace FP
{
public class Class1 : IExternalApplication
{
public Result OnStartup(UIControlledApplication application)
{
application.CreateRibbonTab("Dhana");
RibbonPanel ribbonPanel = application.CreateRibbonPanel("Dhana", "FP");
string AssemblyPath = Assembly.GetExecutingAssembly().Location;
PushButtonData pushButtonData = new PushButtonData("d", "FP", AssemblyPath, "FP.F");
Uri uri = new Uri(@"C:\Users\VENKATA.DANARAO\Downloads\F.png");
BitmapImage bitmapImage = new BitmapImage(uri);
pushButtonData.LargeImage = bitmapImage;
PushButton pushButton = ribbonPanel.AddItem(pushButtonData) as PushButton;
return Result.Succeeded;
}

public Result OnShutdown(UIControlledApplication application)
{
return Result.Succeeded;
}
}

[Transaction(TransactionMode.Manual)]
public class F : IExternalCommand
{
public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
{
var App = commandData.Application;
var UIDoc = App.ActiveUIDocument;
var Doc = UIDoc.Document;

// Ensure UIDoc and Doc are not null
if (UIDoc == null || Doc == null)
{
message = "Active Revit Document or UI Document is null.";
return Result.Failed;
}

Window1 window = new Window1(Doc);
if (window.ShowDialog() == true)
{
CADLinkType link = window.SelectedCadLink;

// Ensure window.SelectedCadLink is not null
if (link == null)
{
message = "No CAD link selected.";
return Result.Failed;
}

String CadLayerName = window.CADLayer;
String FamilyName = window.FamilyName;

// Ensure CAD layer name and family name are not null
if (string.IsNullOrEmpty(CadLayerName))
{
message = "CAD layer name is null or empty.";
return Result.Failed;
}

if (string.IsNullOrEmpty(FamilyName))
{
message = "Family name is null or empty.";
return Result.Failed;
}

ExternalFileReference externalFileReference = link.GetExternalFileReference();

// Check if externalFileReference is null
if (externalFileReference == null)
{
message = "External File reference is null.";
return Result.Failed;
}

var path = ModelPathUtils.ConvertModelPathToUserVisiblePath(externalFileReference.GetAbsolutePath());

// Check if path is valid
if (string.IsNullOrEmpty(path) || !File.Exists(path))
{
message = $"Invalid file path: {path}. File does not exist.";
return Result.Failed;
}

IList<XYZ> RevitPoints = new List<XYZ>();

// Try to read CAD file
try
{
using (Database Acdb = new Database(false, true))
{
Acdb.ReadDwgFile(path, FileOpenMode.OpenForReadAndReadShare, true, null);

using (Autodesk.AutoCAD.DatabaseServices.Transaction ATrans = Acdb.TransactionManager.StartTransaction())
{
BlockTable blockTable = ATrans.GetObject(Acdb.BlockTableId, OpenMode.ForRead) as BlockTable;

// Check if blockTable is null
if (blockTable == null)
{
message = "BlockTable is null. Could not retrieve the block table from the CAD file.";
return Result.Failed;
}

BlockTableRecord modelspace = ATrans.GetObject(blockTable[BlockTableRecord.ModelSpace], OpenMode.ForRead) as BlockTableRecord;

// Check if modelspace is null
if (modelspace == null)
{
message = "ModelSpace BlockTableRecord is null. Could not retrieve model space from the CAD file.";
return Result.Failed;
}

// Iterate through entities in modelspace
foreach (ObjectId objectId in modelspace)
{
Entity entity = ATrans.GetObject(objectId, OpenMode.ForRead) as Entity;

// Debugging: Log entity information
if (entity != null)
{
// Log details for debugging purposes
System.Diagnostics.Debug.WriteLine($"Entity Layer: {entity.Layer}, Entity Type: {entity.GetType().Name}");

// Check if entity matches the CAD layer
if (entity.Layer == CadLayerName && entity is BlockReference dbpoint)
{
Point3d position = dbpoint.Position;
XYZ P = new XYZ(position.X, position.Y, position.Z);
RevitPoints.Add(P);
}
}
else
{
message = $"Entity is null while iterating through modelspace for ObjectId: {objectId}.";
return Result.Failed;
}
}

ATrans.Commit();
}
}
}
catch (System.Exception ex)
{
message = $"Error reading CAD file: {ex.Message}";
return Result.Failed;
}

// Get the FamilySymbol for placing instances
FamilySymbol familySymbol = new FilteredElementCollector(Doc)
.OfClass(typeof(FamilySymbol))
.Cast<FamilySymbol>()
.FirstOrDefault(f => f.Name == FamilyName);

// Check if familySymbol is null
if (familySymbol == null)
{
message = $"Family '{FamilyName}' not found.";
return Result.Failed;
}

// Activate family if not active
if (!familySymbol.IsActive)
{
familySymbol.Activate();
Doc.Regenerate();
}

// Place family instances at the collected points
using (Autodesk.Revit.DB.Transaction Trans = new Autodesk.Revit.DB.Transaction(Doc))
{
Trans.Start();
foreach (XYZ g in RevitPoints)
{
FamilyInstance c = Doc.Create.NewFamilyInstance(g, familySymbol, Autodesk.Revit.DB.Structure.StructuralType.NonStructural);
}
Trans.Commit();
}
}

return Result.Succeeded;
}
}
}

0 Likes
264 Views
2 Replies
Replies (2)
Message 2 of 3

longt61
Advocate
Advocate

That is a really long code file. Maybe you should pinpoint where the exception happens and summarize what you were trying to do and how you did it so that we can get a better understanding and help you.
My fuzzy guess is that you try to read and modify a CAD link instance in your Revit document. Normal, that would not be possible without some tricks or workarounds because you need a AutoCAD API context to directly do it instead of Revit API. That is why one of the AutoCAD object is null and you received such exception.

0 Likes
Message 3 of 3

jeremy_tammik
Alumni
Alumni

Welcome to the Revit API! I suggest that you start with simple things that work, and run through a couple of tutorials like the My First Revit Plug-in or others. Do things that work first and understand the basics, before trying to tackle problematic tasks and error messages. Have you taken a look at the getting sytarted material already?
  

  

That said, the error that you are encountering os a very common .NET error that can be caused by many things:
  

   

To fix it, it helps to understand what is causing it. To do so, run your code in a debugger, step though it line buy line, and observe the values of all the variables. At some point, the null reference will be hit and you will be able to see what is causing it.
   

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