Skip to content

Latest commit

History

6 Commits

Folders and files

NameName
Last commit message
Last commit date

Repository files navigation

TSmithCode AutoCAD .NET API Reference

Durable C# patterns for document access, transactions, entity inspection, block attributes, controlled writes, and error boundaries in AutoCAD.

This repository is a compact reference library. It is not a runnable evaluation kit and does not replace testing inside the licensed AutoCAD version targeted by an engagement.

Artifact class: Reference library.

Evaluator question

Does the proposed AutoCAD automation approach respect the document, database, transaction, object-lifetime, and licensed-runtime boundaries required for safe implementation?

Decision this supports

Use these patterns to shape a technical conversation or implementation spike. Use the CAD Guardian AutoCAD, AutoLISP, and .NET runnable evaluation kit when an evaluator needs public fixtures, commands, generated evidence, and an explicit first-funded-slice decision.

Best for

  • AutoCAD .NET developers reviewing foundational API patterns.
  • Software architects bridging drawing data into APIs, reports, ERP, GIS, or internal systems.
  • CAD managers preparing a bounded automation conversation before private drawings are shared.

Runtime boundary

These snippets require Autodesk AutoCAD assemblies and a licensed AutoCAD runtime. Target the framework, SDK, and deployment model supported by the AutoCAD release in scope.

Production work may also require document locking, command flags, xref and side-database handling, unit and coordinate policy, layer standards, undo behavior, logging, configuration, deployment packaging, and representative drawing tests.

1. Resolve the active document safely

usingAutodesk.AutoCAD.ApplicationServices;usingAutodesk.AutoCAD.DatabaseServices;usingAutodesk.AutoCAD.EditorInput;usingAutodesk.AutoCAD.Runtime;publicsealedclassDocumentCommands{[CommandMethod("TSMITH_ACTIVE_DOCUMENT")]publicstaticvoidShowActiveDocument(){Document?document=Application.DocumentManager.MdiActiveDocument;if(documentisnull){return;}Databasedatabase=document.Database;Editoreditor=document.Editor;editor.WriteMessage($"\nDrawing: {database.Filename}");}}

Why it matters: AutoCAD commands operate inside a document context. Resolve and validate that context before touching the database or editor.

2. Inspect model-space entities with a read transaction

[CommandMethod("TSMITH_ENTITY_INVENTORY")]publicstaticvoidInventoryModelSpace(){Document?document=Application.DocumentManager.MdiActiveDocument;if(documentisnull){return;}Databasedatabase=document.Database;Editoreditor=document.Editor;varcounts=newDictionary<string,int>(StringComparer.OrdinalIgnoreCase);usingTransactiontransaction=database.TransactionManager.StartOpenCloseTransaction();varblockTable=(BlockTable)transaction.GetObject(database.BlockTableId,OpenMode.ForRead);varmodelSpace=(BlockTableRecord)transaction.GetObject(blockTable[BlockTableRecord.ModelSpace],OpenMode.ForRead);foreach(ObjectIdobjectIdinmodelSpace){if(transaction.GetObject(objectId,OpenMode.ForRead)is not Entityentity){continue;}stringtypeName=entity.GetType().Name;counts[typeName]=counts.GetValueOrDefault(typeName)+1;}foreach((stringtypeName,intcount)incounts.OrderBy(pair =>pair.Key)){editor.WriteMessage($"\n{typeName}: {count}");}}

Why it matters: A read-only inventory is often the safest first slice. It exposes drawing composition before mutation is authorized. A read transaction does not need to be committed.

3. Extract block-attribute values

publicsealedrecordBlockAttributeValue(stringBlockName,stringTag,stringValue);publicstaticIReadOnlyList<BlockAttributeValue>ReadBlockAttributes(Databasedatabase){varvalues=newList<BlockAttributeValue>();usingTransactiontransaction=database.TransactionManager.StartOpenCloseTransaction();varblockTable=(BlockTable)transaction.GetObject(database.BlockTableId,OpenMode.ForRead);varmodelSpace=(BlockTableRecord)transaction.GetObject(blockTable[BlockTableRecord.ModelSpace],OpenMode.ForRead);foreach(ObjectIdobjectIdinmodelSpace){if(transaction.GetObject(objectId,OpenMode.ForRead)is not BlockReferenceblockReference){continue;}foreach(ObjectIdattributeIdinblockReference.AttributeCollection){if(transaction.GetObject(attributeId,OpenMode.ForRead)is not AttributeReferenceattribute){continue;}values.Add(newBlockAttributeValue(blockReference.Name,attribute.Tag,attribute.TextString));}}returnvalues;}

Why it matters: Block attributes frequently carry equipment tags, asset IDs, drawing metadata, and title-block values that must be mapped into a controlled schema.

4. Perform a controlled write with document locking

usingAutodesk.AutoCAD.Geometry;[CommandMethod("TSMITH_CREATE_LINE",CommandFlags.Session)]publicstaticvoidCreateLine(){Document?document=Application.DocumentManager.MdiActiveDocument;if(documentisnull){return;}using(document.LockDocument())using(Transactiontransaction=document.Database.TransactionManager.StartTransaction()){varblockTable=(BlockTable)transaction.GetObject(document.Database.BlockTableId,OpenMode.ForRead);varmodelSpace=(BlockTableRecord)transaction.GetObject(blockTable[BlockTableRecord.ModelSpace],OpenMode.ForWrite);usingvarline=newLine(newPoint3d(0,0,0),newPoint3d(10,10,0));modelSpace.AppendEntity(line);transaction.AddNewlyCreatedDBObject(line,true);transaction.Commit();}document.Editor.WriteMessage("\nLine created.");}

Why it matters: Writes require an explicit transaction and, in session or modeless contexts, an explicit document lock. The command context and AutoCAD release determine the exact locking requirement.

5. Keep failures visible and bounded

[CommandMethod("TSMITH_SAFE_AUDIT")]publicstaticvoidRunSafeAudit(){Document?document=Application.DocumentManager.MdiActiveDocument;if(documentisnull){return;}try{IReadOnlyList<BlockAttributeValue>values=ReadBlockAttributes(document.Database);document.Editor.WriteMessage($"\nAttribute values found: {values.Count}");}catch(Autodesk.AutoCAD.Runtime.Exceptionexception){document.Editor.WriteMessage($"\nAutoCAD audit failed: {exception.ErrorStatus}");}catch(System.Exceptionexception){document.Editor.WriteMessage($"\nUnexpected audit failure: {exception.Message}");}}

Why it matters: A production adapter should distinguish AutoCAD runtime failures from general application failures and route full details to an approved structured log rather than exposing sensitive context in the command line.

Production-readiness checklist

Before moving from reference code to a funded implementation, confirm:

  • target AutoCAD version, SDK, framework, and deployment method;
  • command, document-locking, and multi-document behavior;
  • layer, block, attribute, unit, coordinate, xref, font, and plot dependencies;
  • representative public or approved private fixtures;
  • read-only versus mutation scope;
  • logging, correlation, rollback, undo, and support ownership;
  • output schema and downstream integration contract;
  • installer, signing, security, and release requirements.

Proof boundary

These snippets demonstrate API vocabulary and implementation judgment. They are not compiled release artifacts, customer code, performance evidence, a production add-in, or proof that a private drawing set is ready for automation.

No client drawings, credentials, private names, raw opportunity notes, or license-uncertain fixtures belong in this repository.

What to send

For a technical discussion, send this reference and name the exact operation under review.

For an evaluator deciding whether to fund an AutoCAD automation slice, send the CAD Guardian runnable evaluation kit instead.

Related proof system

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages