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
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report
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;
}
}
}