Question

I have created a custom class

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.EditorInput;
using Autodesk.AutoCAD.Geometry;
using Autodesk.AutoCAD.Runtime;
using System.Threading;
using Autodesk.AutoCAD.Customization;

namespace Plugin
{
    public class Bar : BlockTableRecord
    {
        /// <summary>
        /// Bar is a set of lines together with a text represenging a single object
        /// It has default length, width and its described by a label at the top of the Bar.
        /// </summary>

        //Autocad document
        private Document doc;
        private DocumentLock lockedDoc;
        private Editor editor;
        private Database db;

        //id
        private static int count;

        ///getters and setters for Bar properties
        public int Position { set; get; }
        public double Length { set; get; }
        public double Width { set; get; }
        public LineWeight Weight { set; get; }
        public int ColorIndex { set; get; }
        private int Bars { set; get; }
        private double BarLength { set; get; }
        private double Angle { set; get; }

        //drawing objects
        public DBText Title;
        public DBText LengthText;
        public Polyline line;

        //helper variables

        public void Instantiate()
        {
            Interlocked.Increment(ref count);

            //default values
            Weight = LineWeight.LineWeight030;
            Width = 30;
            ColorIndex = 4;
            BarLength = 250;
            Position = count;

            Title = new DBText();
            Title.ColorIndex = 2;
            Title.Height = 16;

            LengthText = new DBText();
            LengthText.Height = 8;

            Name = "Bar" + count;
        }

        public Bar()
        {
            Instantiate();
        }

        public Bar(Document d)
        {
            doc = d;
            editor = doc.Editor;
            db = doc.Database;

            Instantiate();
        }

        ~Bar()
        {
            Interlocked.Decrement(ref count);
        }

        public void drawLineFromUserInput()
        {
            using (lockedDoc = doc.LockDocument())
            {
                PromptPointResult pointResult;
                PromptPointOptions pointOptions = new PromptPointOptions("");

                pointOptions.Message = "\nEnter the start point of the line: ";
                pointResult = editor.GetPoint(pointOptions);
                Point3d startLinePoint = pointResult.Value;

                if (pointResult.Status == PromptStatus.Cancel)
                {
                    Application.ShowAlertDialog("Error getting the point");
                    return;
                }

                pointOptions.Message = "\nEnter the end point of the line: ";
                pointOptions.UseBasePoint = true;
                pointOptions.BasePoint = startLinePoint;
                pointResult = editor.GetPoint(pointOptions);
                Point3d endLinePoint = pointResult.Value;

                if (pointResult.Status == PromptStatus.Cancel)
                {
                    Application.ShowAlertDialog("Error getting the point");
                    return;
                }

                try
                {
                    using (Transaction transaction = db.TransactionManager.StartTransaction())
                    {
                        db.LineWeightDisplay = true;

                        BlockTable blockTable;
                        BlockTableRecord blockTableRecord;

                        blockTable = transaction.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable;

                        blockTableRecord = transaction.GetObject(blockTable[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord;

                        Polyline drawnLine = new Polyline();//startLinePoint, endLinePoint
                        drawnLine.AddVertexAt(0, new Point2d(startLinePoint.X, startLinePoint.Y), 0, 0, 0);
                        drawnLine.AddVertexAt(1, new Point2d(endLinePoint.X, endLinePoint.Y), 0, 0, 0);
                        drawnLine.SetDatabaseDefaults();
                        drawnLine.LineWeight = Weight;
                        drawnLine.ColorIndex = ColorIndex;

                        blockTableRecord.AppendEntity(drawnLine);
                        transaction.AddNewlyCreatedDBObject(drawnLine, true);

                        editor.Regen();

                        line = drawnLine.Clone() as Polyline;

                        PromptSelectionResult selectionResult = editor.SelectLast();

                        if (selectionResult.Status == PromptStatus.OK)
                        {
                            PromptPointResult ppr = editor.Drag(selectionResult.Value, "Select the location of the Bar",
                                delegate(Point3d pt, ref Matrix3d mat)
                                {
                                    if (startLinePoint == pt)
                                    {
                                        return SamplerStatus.NoChange;
                                    }
                                    else
                                    {
                                        mat = Matrix3d.Displacement(startLinePoint.GetVectorTo(pt));
                                    }
                                    return SamplerStatus.OK;
                                });

                            if (ppr.Status == PromptStatus.OK)
                            {
                                Point3d newLocation = ppr.Value;
                                Matrix3d mat = Matrix3d.Displacement(startLinePoint.GetVectorTo(newLocation));

                                line.TransformBy(mat);

                                Length = line.Length;

                                Angle = PointUtil.angleFromXAxis(line.StartPoint, line.EndPoint);

                                Bars = (int)Math.Ceiling(Length / BarLength);

                                Title.TextString = "Pos " + Position + " ϕ " + Width + "mm tot(" + count + ")";

                                LengthText.TextString = Math.Round(Length).ToString();

                                DBText info = new DBText();
                                info.Visible = false;
                                info.TextString = "Position=" + Position;

                                Point3d startPoint = line.StartPoint;

                                line.TransformBy(Matrix3d.Displacement(line.StartPoint.GetVectorTo(Point3d.Origin)));

                                Title.TransformBy(Matrix3d.Rotation(Angle, Vector3d.ZAxis, Point3d.Origin));

                                LengthText.TransformBy(Matrix3d.Rotation(Angle, Vector3d.ZAxis, Point3d.Origin));

                                Title.TransformBy(Matrix3d.Displacement(getMoveTextVector(line.StartPoint, line.EndPoint, Math.PI / 16, 0.1 * Length)));

                                LengthText.TransformBy(Matrix3d.Displacement(getMoveTextVector(line.StartPoint, line.EndPoint, -Math.PI / 48, 0.1 * Length)));

                                Title.TransformBy(Matrix3d.Displacement(Point3d.Origin.GetVectorTo(line.StartPoint)));

                                blockTable.UpgradeOpen();
                                blockTable.Add(this);
                                transaction.AddNewlyCreatedDBObject(this, true);

                                AppendEntity(Title);
                                transaction.AddNewlyCreatedDBObject(Title, true);

                                AppendEntity(LengthText);
                                transaction.AddNewlyCreatedDBObject(LengthText, true);

                                AppendEntity(line);
                                transaction.AddNewlyCreatedDBObject(line, true);

                                AppendEntity(info);
                                transaction.AddNewlyCreatedDBObject(info, true);

                                BlockReference blockReference = new BlockReference(Point3d.Origin, this.ObjectId);
                                blockReference.TransformBy(Matrix3d.Displacement(Point3d.Origin.GetVectorTo(startPoint)));

                                blockTableRecord.AppendEntity(blockReference);
                                transaction.AddNewlyCreatedDBObject(blockReference, true);

                            }
                        }

                        transaction.Commit();
                    }
                }
                catch (System.Exception e)
                {
                    Application.ShowAlertDialog(e.Message);
                }
            }
        }

        public static Vector3d getMoveTextVector(Point3d startPoint, Point3d endPoint, double angle, double width)
        {
            Line l = new Line(startPoint, endPoint);

            Point3d p = l.GetPointAtDist(l.Length / 2 - width);

            Vector3d vector = l.StartPoint.GetVectorTo(p);

            vector = vector.RotateBy(angle, Vector3d.ZAxis);

            return vector;
        }

        public void UpdatePosition(int position)
        {
            using (Transaction transaction = db.TransactionManager.StartTransaction())
            {
                Position = position;
                Title.TextString = "Pos " + Position + " ϕ " + Width + "mm tot(" + count + ")";
                transaction.Commit();
            }
        }


    }
}

I've added the instance of Bar to a BlockTable.When i loop through all the BlockTableRecords:

    [CommandMethod("Edit")]
    public static void EditEntity()
    {
        PromptEntityResult per = editor.GetEntity("Select Entity");

        if (per.Status == PromptStatus.OK)
        {
            using (Transaction transaction = db.TransactionManager.StartTransaction())
            {
                BlockReference blockReference = transaction.GetObject(per.ObjectId, OpenMode.ForRead) as BlockReference;

                if (blockReference != null)
                {
                    BlockTableRecord btr = blockReference.BlockTableRecord.GetObject(OpenMode.ForRead) as BlockTableRecord;

                    new PositionProperties(doc, btr).Show();
                }
            }
        }
    }

I get the instance of BlockTableRecord but i cant get the instance of the Bar class I created.Is there a way to store the information of the class that I created?

Was it helpful?

Solution

Check out my GitHub.

https://github.com/XxZer0xX

here is an quick example.

using System;
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;

namespace stackclass
{
/// <summary>
/// Description of MyClass.
/// </summary>
public class MyClass : BlockTableRecord
{
    public string BlkRecordName {get;set;}

    public MyClass(BlockTableRecord _RecordParam)
    {
        BlkRecordName = _RecordParam.Name;
    }

    public MyClass(){}
}


public static class MyClassInstanciator 
{
    public static void Main(string[] args) 
    {
        var AcDoc = Application.DocumentManager.MdiActiveDocument;
        using (var Trans = Application.DocumentManager.MdiActiveDocument.TransactionManager.StartTransaction()) {

            var BlkTable = Trans.GetObject(AcDoc.Database.BlockTableId,OpenMode.ForRead) as BlockTable;
            foreach (var BlkRcrdId in BlkTable) {
                var _blkRcrd = Trans.GetObject(BlkRcrdId,OpenMode.ForRead) as BlockTableRecord;
                var MyClassRcd = new MyClass(_blkRcrd);
                // or
                var _MyClassRcd = new MyClass();
                _MyClassRcd.BlkRecordName = _blkRcrd.Name;
            }
        }
    }
}

Update:

based on the way you have your class structured you are either going to have to instantiate a new version of your class and then assign the Id = 2; or you are going to have to add the static class modifier and then have a property named Id.

example:

public static class MyClass : BlockTableRecord
{
    public static string Id {get;set;}
}

public static class UsingStaticClass 
{
    public static void setIdWithValue(string[] args) 
    {
             MyClass.Id = 2;
    }

    public static void RetrieveIdValue()
    {
           var someOtherValue = MyClass.Id;
    }
}

Is this what you mean?

Additional Update:

Your code usage here is not right.

foreach (ObjectId obj in bt)
{
    BlockTableRecord btr = obj.GetObject(OpenMode.ForRead) as BlockTableRecord;
}

In a foreach while inside of a AutoCad.Database variable is an objectId as you have obj as in the loop.

in the example above you are trying to grab the Object using a property of the the BlockTableRecord. your Code should be like this and should be inside of a transaction

foreach(ObjectId ObjId in BlkTbl)
{
     var BlkRcd = Transaction.GetObject(ObjId,OpenMode.ForRead) as BlockTableRecord;
}

you need to use the transaction to grab any object from the database.

OTHER TIPS

if I need to store info with an Object, I use Xdata. Almost every Object has its own XDATA-Container. It works almost like a dictionary. You can find enough examples on the net. Alternatively you could check XRecords for larger amount of data or binary data... Custom Objects are not really supported this way. To create your own objecttype, you needed to switch to ObjectARX....

HTH, Daniel

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top