Create Plugin

Create Plugin

guilherme.franklin
Participant Participant
1,329 Views
6 Replies
Message 1 of 7

Create Plugin

guilherme.franklin
Participant
Participant

I want to develop a plugin to select a layer and create a table with the objects data, for example, the size of all circles that are in certain selected layer.

I'm new to Autocad API.NET, I'll be grateful for the help.

I'm using Autocad Civil 3D.

0 Likes
Accepted solutions (1)
1,330 Views
6 Replies
Replies (6)
Message 2 of 7

stefan.hofer
Advocate
Advocate
Accepted solution

Here is a example for CIRCLES

In Autocad, you can use the command MYTABLE and select a object and get all circles on this layer in a table.

 

In your main file do something like this:

 

Tools.LayerToTable layerToTable = null;
[CommandMethod("MYTABLE")]
public void MyTable()
{
    if (layerToTable == null) { layerToTable = new Tools.LayerToTable(); }
    try
    {
        layerToTable.GetObjectsOnLayer();
    }
    catch (System.Exception e) { MessageBox.Show("Original error: " + e.Message); }
}

 

 

Then make a new file (LayerToTable.cs) and paste this code:

 

 

using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.EditorInput;
using acApp = Autodesk.AutoCAD.ApplicationServices.Application;
using System.Linq;
using System.Collections.Generic;
using Autodesk.AutoCAD.Interop.Common;
using Autodesk.AutoCAD.Interop;
using Autodesk.AutoCAD.Geometry;
using Autodesk.AutoCAD.Colors;
using System;

namespace Tools
{
    public partial class LayerToTable
    {
        public void GetObjectsOnLayer()
        {
            // Use the active document
            Document doc = acApp.DocumentManager.MdiActiveDocument;
            Database db = doc.Database;
            Editor ed = doc.Editor;

            // Select a object
            PromptSelectionOptions pso = new PromptSelectionOptions();
            pso.SingleOnly = true;
            pso.SinglePickInSpace = true;
            PromptSelectionResult Selection = ed.GetSelection(pso);

            if (Selection.Status == PromptStatus.OK)
            {
                using (Transaction tr = db.TransactionManager.StartTransaction())
                {
                    try
                    {
                        // Get the selected entity
                        Entity SelectedEntity = (Entity)(tr.GetObject(Selection.Value.OfType<SelectedObject>().First().ObjectId, OpenMode.ForRead));

                        try
                        {
                            // Create the selection set
                            PromptSelectionResult acSSPrompt = null;

                            try
                            {
                                try
                                {
                                    TypedValue[] acTypValAr = new TypedValue[4];
                                    acTypValAr.SetValue(new TypedValue(67, 0), 0); // Model space = 0, paper space = 1
                                    acTypValAr.SetValue(new TypedValue((int)DxfCode.Visibility, 0), 1); // Visible = 0, invisible = 1
                                    acTypValAr.SetValue(new TypedValue((int)DxfCode.LayerName, SelectedEntity.Layer), 2); // Layer name
                                    acTypValAr.SetValue(new TypedValue((int)DxfCode.Start, "CIRCLE"), 3); // Circle
                                    SelectionFilter acSelFtr = new SelectionFilter(acTypValAr);

                                    // Select all entities on the selected object layer
                                    acSSPrompt = ed.SelectAll(acSelFtr);
                                }
                                catch (System.Exception ex)
                                {
                                    acApp.ShowAlertDialog("Filter error. Original error: " + ex.Message);
                                }

                                if (acSSPrompt.Value.Count <= 0)
                                {
                                    acApp.ShowAlertDialog("no objects selected.");
                                    return;
                                }

                                // Create a list with all circles in the selection
                                List<Tuple<Circle, Point3d, double>> circles = new List<Tuple<Circle, Point3d, double>>();
                                try
                                {
                                    foreach (SelectedObject obj in acSSPrompt.Value)
                                    {
                                        try
                                        {
                                            using (Circle circle = (Circle)obj.ObjectId.GetObject(OpenMode.ForRead))
                                            {
                                                circles.Add(new Tuple<Circle, Point3d, double>(circle, circle.Center, circle.Radius));
                                            }
                                        }
                                        catch
                                        {
                                            // All objects except circles...
                                            //acApp.ShowAlertDialog("Using circle error (not a circle?)");
                                        }
                                    }
                                }
                                catch
                                {
                                    acApp.ShowAlertDialog("ObjectId error");
                                }

                                // Start creating the table
                                if (circles.Count > 0)
                                {
                                    try
                                    {
                                        bool result = CrateTable(circles);
                                        if (!result) acApp.ShowAlertDialog("Table not created.");
                                    }
                                    catch (System.Exception ex)
                                    {
                                        acApp.ShowAlertDialog("CreateTable() error. Original error: " + ex.Message);
                                    }
                                }
                                else
                                {
                                    acApp.ShowAlertDialog("no circles found on this layer: " + SelectedEntity.Layer);
                                }
                            }
                            catch (System.Exception ex)
                            {
                                acApp.ShowAlertDialog("Select error. Original error: " + ex.Message);
                            }
                            acSSPrompt = null;
                        }
                        catch
                        {
                            acApp.ShowAlertDialog("No objects found...");
                        }
                    }
                    catch
                    {
                        acApp.ShowAlertDialog("No valid object...");
                    }
                    tr.Commit();
                }
            }
        }

        private bool CrateTable(List<Tuple<Circle, Point3d, double>> circles)
        {
            AcadDocument thisDrawing = (AcadDocument)acApp.DocumentManager.MdiActiveDocument.GetAcadDocument();
            Document doc = acApp.DocumentManager.MdiActiveDocument;
            Database db = doc.Database;
            Editor ed = doc.Editor;

            PromptPointResult pr = ed.GetPoint("\nEnter table insertion point: ");
            if (pr.Status == PromptStatus.OK)
            {
                // Create the table
                using (DocumentLock acLckDoc = doc.LockDocument())
                {
                    // Layer for the table (current layer or the layername below)
                    bool useCurrentLayer = true;
                    string tableLayer = "0";

                    // Color for position text in the table
                    string strColor = string.Format("Autocad.AcCmColor.{0}", acApp.Version.Major);
                    Color posColorFromIndex = Color.FromColorIndex(ColorMethod.ByAci, 84); // 84 = dark green (autocad color index)
                    AcadAcCmColor posColor = ((AcadApplication)Autodesk.AutoCAD.ApplicationServices.Application.AcadApplication).GetInterfaceObject(strColor);
                    posColor.SetRGB(posColorFromIndex.ColorValue.R, posColorFromIndex.ColorValue.G, posColorFromIndex.ColorValue.B);

                    // Table layer
                    try
                    {
                        using (Transaction acTrans = db.TransactionManager.StartTransaction())
                        {
                            // Open the layer table for read
                            LayerTable acLyrTbl;
                            acLyrTbl = acTrans.GetObject(db.LayerTableId, OpenMode.ForRead) as LayerTable;
                            LayerTableRecord acLyrTblRec_Clayer = acTrans.GetObject(db.Clayer, OpenMode.ForRead) as LayerTableRecord;

                            // Abort if the layers are locked
                            if (!useCurrentLayer && acLyrTbl.Has(tableLayer) == true)
                            {
                                // Use the custom layer for the table
                                LayerTableRecord acLyrTblRec_TableLayer = acTrans.GetObject(acLyrTbl[tableLayer], OpenMode.ForRead) as LayerTableRecord;
                                if (acLyrTblRec_Clayer.IsLocked || acLyrTblRec_TableLayer.IsLocked)
                                {
                                    acApp.ShowAlertDialog("Current layer and table layer ( " + tableLayer + ") must NOT be locked!");
                                    return false;
                                }
                            }
                            else
                            {
                                // Use the current layer for the table
                                tableLayer = acLyrTblRec_Clayer.Name;
                                if (acLyrTblRec_Clayer.IsLocked)
                                {
                                    acApp.ShowAlertDialog("Current layer must NOT be locked!");
                                    return false;
                                }
                            }
                        }
                    }
                    catch (System.Exception ex)
                    {
                        acApp.ShowAlertDialog("Layer error. Original error: " + ex.Message);
                        return false;
                    }

                    using (Transaction acTrans = db.TransactionManager.StartTransaction())
                    {
                        try
                        {
                            // Rows and columns
                            int rows = circles.Count() + 4; // Title | Header + ...Entities... + Empty line | Total line (means entities + 4 rows)
                            int columns = 3;

                            // Width and height of the cells
                            double defaultRowHeight = 5.7;
                            double defaultColumnWidth = 40;
                            double positionColumnWidth = 10;

                            // Round values to...
                            int decimalPlaces = 2;

                            double[] insertPoint = { pr.Value.X, pr.Value.Y, pr.Value.Z };
                            AcadTable acTable = new AcadTable();
                            acTable = thisDrawing.ModelSpace.AddTable(insertPoint, rows, columns, defaultRowHeight, defaultColumnWidth);

                            try
                            {
                                acTable.SetTextHeight((int)AcRowType.acTitleRow, 3);
                                acTable.SetTextHeight((int)AcRowType.acHeaderRow, 2);
                                acTable.SetTextHeight((int)AcRowType.acDataRow, 2);
                                acTable.SetTextStyle((int)AcRowType.acTitleRow, "Arial");
                                acTable.SetTextStyle((int)AcRowType.acHeaderRow, "Arial");
                                acTable.SetTextStyle((int)AcRowType.acDataRow, "Arial");
                                acTable.RowHeight = defaultRowHeight;
                                acTable.Layer = tableLayer;
                            }
                            catch (System.Exception ex)
                            {
                                acApp.ShowAlertDialog("Error define table. Original error: " + ex.Message);
                                return false;
                            }

                            try
                            {
                                // For each row...
                                for (int i = 0; i < rows; i++)
                                {
                                    if (i == 0)
                                    {
                                        // Title
                                        try
                                        {
                                            acTable.SetRowHeight(i, 0.5);
                                            string title = "Object list: " + circles[0].Item1.GetType().Name;
                                            acTable.SetCellValue(i, 0, title);
                                            acTable.SetCellAlignment(i, 0, AcCellAlignment.acMiddleCenter);
                                        }
                                        catch (System.Exception ex)
                                        {
                                            acApp.ShowAlertDialog("Title error: " + ex.Message);
                                            return false;
                                        }
                                    }
                                    else if (i == 1)
                                    {
                                        // Header
                                        try
                                        {
                                            for (int j = 0; j < columns; j++)
                                            {
                                                if (j == 0)
                                                {
                                                    // Pos.
                                                    SetTableCellValue(acTable, i, j, "Pos.", AcCellAlignment.acMiddleLeft);
                                                    acTable.SetCellContentColor(i, j, posColor);
                                                    acTable.SetColumnWidth(j, positionColumnWidth);
                                                }
                                                else if (j == 1)
                                                {
                                                    // Coordinates
                                                    SetTableCellValue(acTable, i, j, "Coordinates", AcCellAlignment.acMiddleLeft);
                                                    acTable.SetColumnWidth(j, defaultColumnWidth);
                                                }
                                                else if (j == 2)
                                                {
                                                    // Radius
                                                    SetTableCellValue(acTable, i, j, "Radius", AcCellAlignment.acMiddleLeft);
                                                    acTable.SetColumnWidth(j, defaultColumnWidth);
                                                }
                                            }
                                        }
                                        catch (System.Exception ex)
                                        {
                                            acApp.ShowAlertDialog("Header error: " + ex.Message);
                                            return false;
                                        }
                                    }
                                    else if (i == circles.Count() + 2)
                                    {
                                        // Empty line below before the total line
                                        try
                                        {
                                            acTable.VertCellMargin = 0;
                                            acTable.SetRowHeight(i, 0.5);
                                            acTable.MergeCells(i, i, 0, acTable.Columns - 1);
                                            continue;
                                        }
                                        catch (System.Exception ex)
                                        {
                                            acApp.ShowAlertDialog("Emptyline error: " + ex.Message);
                                            return false;
                                        }
                                    }
                                    else if (i == circles.Count() + 3)
                                    {
                                        // Total line below
                                        try
                                        {
                                            acTable.VertCellMargin = 0;
                                            acTable.SetRowHeight(i, defaultRowHeight);
                                            acTable.MergeCells(i, i, 0, acTable.Columns - 1);

                                            SetTableCellValue(acTable, i, 0, "Total: " + circles.Count().ToString(), AcCellAlignment.acMiddleLeft);
                                            continue;
                                        }
                                        catch (System.Exception ex)
                                        {
                                            acApp.ShowAlertDialog("Totelline error: " + ex.Message);
                                            return false;
                                        }
                                    }
                                    else
                                    {
                                        // All entity lines
                                        try
                                        {
                                            for (int j = 0; j < columns; j++)
                                            {
                                                if (j == 0)
                                                {
                                                    // Pos.
                                                    SetTableCellValue(acTable, i, j, (i - 1).ToString(), AcCellAlignment.acMiddleLeft);
                                                    acTable.SetCellContentColor(i, j, posColor);
                                                }
                                                else if (j == 1)
                                                {
                                                    // Coordinates
                                                    Point3d center = circles[i - 2].Item2;
                                                    string xyzText = Math.Round(center.X, decimalPlaces).ToString() + ","
                                                        + Math.Round(center.Y, decimalPlaces).ToString() + ","
                                                        + Math.Round(center.Z, decimalPlaces).ToString();
                                                    SetTableCellValue(acTable, i, j, xyzText, AcCellAlignment.acMiddleRight);
                                                }
                                                else if (j == 2)
                                                {
                                                    // Radius
                                                    string radiusText = Math.Round(circles[i - 2].Item3, decimalPlaces).ToString();
                                                    SetTableCellValue(acTable, i, j, radiusText, AcCellAlignment.acMiddleRight);
                                                }
                                            }
                                        }
                                        catch (System.Exception ex)
                                        {
                                            acApp.ShowAlertDialog("Entity error: " + ex.Message);
                                            return false;
                                        }
                                    }
                                }
                            }
                            catch (System.Exception ex)
                            {
                                acApp.ShowAlertDialog("Fill table cells error: Original error: " + ex.Message);
                                return false;
                            }
                        }
                        catch (System.Exception ex)
                        {
                            acApp.ShowAlertDialog("AcadTable error: " + ex.Message);
                            return false;
                        }
                        acTrans.Commit();
                    }
                }
            }
            return true;
        }

        private void SetTableCellValue(AcadTable table, int r, int c, string value, AcCellAlignment alignment)
        {
            table.SetCellValue(r, c, value);
            table.SetCellAlignment(r, c, alignment);
        }
    }
}

 

Message 3 of 7

guilherme.franklin
Participant
Participant

I did everything as per your instructions, however, I can't find it by running the "MYTABLE" command in Civil3D.Main fileMain fileLayerToTableLayerToTable

0 Likes
Message 4 of 7

stefan.hofer
Advocate
Advocate

Your main file should look something like this one:

using System;
using System.Windows.Forms;
using Autodesk.AutoCAD.Runtime;

[assembly: CommandClass(typeof(Tools.index))]
namespace Tools
{
    public class index : IExtensionApplication
    {
        public void Initialize() { }

        public void Terminate() { throw new NotImplementedException(); }

        Tools.LayerToTable layerToTable = null;
        [CommandMethod("MYTABLE")]
        public void MyTable()
        {
            if (layerToTable == null) { layerToTable = new Tools.LayerToTable(); }
            try
            {
                layerToTable.GetObjectsOnLayer();
            }
            catch (System.Exception e) { MessageBox.Show("Original error: " + e.Message); }
        }
    }
}

 

And you have to load this dll in autocad with the NETLOAD command. (or load it with a lisp file on startup)

0 Likes
Message 5 of 7

guilherme.franklin
Participant
Participant

I managed to execute, however, when inserting the points of the table I could not understand the code execution.select layersselect layersinsert table pointsinsert table pointserror defining tableerror defining table

0 Likes
Message 6 of 7

stefan.hofer
Advocate
Advocate

key not found?

 

i don't use civil. pearhaps in civil some table keys don't exist.

try
{
    acTable.SetTextHeight((int)AcRowType.acTitleRow, 3);
    acTable.SetTextHeight((int)AcRowType.acHeaderRow, 2);
    acTable.SetTextHeight((int)AcRowType.acDataRow, 2);
    acTable.SetTextStyle((int)AcRowType.acTitleRow, "Arial");
    acTable.SetTextStyle((int)AcRowType.acHeaderRow, "Arial");
    acTable.SetTextStyle((int)AcRowType.acDataRow, "Arial");
    acTable.RowHeight = defaultRowHeight;
    acTable.Layer = tableLayer;
}
catch (System.Exception ex)
{
    acApp.ShowAlertDialog("Error define table. Original error: " + ex.Message);
    return false;
}

 

I think (int)acRowType is the key.

you can try to comment out those lines. but i can't say exactly what the problem is.

0 Likes
Message 7 of 7

guilherme.franklin
Participant
Participant

I understand. You helped me a lot, thank you very much.

0 Likes