How to make a blockreference with existing several lines.

How to make a blockreference with existing several lines.

MarkJamesRogolino
Advocate Advocate
368 Views
5 Replies
Message 1 of 6

How to make a blockreference with existing several lines.

MarkJamesRogolino
Advocate
Advocate

Hello, everyone. Hope you are doing well.

I have a small code for making block with existing several lines or polylines. but it does not work well. Could anyone help me?

my code is as followings.

var documentManager = Application.DocumentManager;
var currentDocument = documentManager.MdiActiveDocument;
var database = currentDocument.Database;
var ed = currentDocument.Editor;
using (DocumentLock docLock = currentDocument.LockDocument())
{                
    using (Transaction tr = database.TransactionManager.StartTransaction())
    {
        try
        {
            BlockTable acBlkTbl;
            acBlkTbl = tr.GetObject(database.BlockTableId, OpenMode.ForWrite) as BlockTable;
            BlockTableRecord acBlkTblRec = tr.GetObject(acBlkTbl[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord;
            //BlockTableRecord acBlkTblRec = new BlockTableRecord();
            acBlkTblRec.Name = "Margin_PreVal" + System.DateTime.Now.Hour.ToString() + System.DateTime.Now.Millisecond.ToString() + System.DateTime.Now.Minute.ToString();
            acBlkTbl.UpgradeOpen();
            ObjectId btrId = acBlkTbl.Add(acBlkTblRec);
            tr.AddNewlyCreatedDBObject(acBlkTblRec, true);
            DBObjectCollection ents = new DBObjectCollection();
            foreach (Line pl in Plugin.marginlinelist)
            {
                 ents.Add((pl));
            }
            foreach (Entity ent in ents)
            {
                Entity clone = ent.Clone() as Entity;
                ent.Erase();
                acBlkTblRec.AppendEntity(clone);
                tr.AddNewlyCreatedDBObject(clone, true);                            
            }
            BlockTableRecord ms = (BlockTableRecord)tr.GetObject(acBlkTbl[BlockTableRecord.ModelSpace], OpenMode.ForWrite);
            var br = new BlockReference(Point3d.Origin, btrId);
            ms.AppendEntity(br);
            tr.AddNewlyCreatedDBObject(br, true);
            tr.Commit();
            Plugin.marginlinelist.Clear();
        }
        catch
        {
            throw;
        }
    }
}

In this code Plugin.marginPlinelist is a array of selected lines or already created lines.

MarkJamesRogolino_0-1737978844195.png

 

Thank you. 

 

0 Likes
Accepted solutions (1)
369 Views
5 Replies
Replies (5)
Message 2 of 6

Brock_Olly
Collaborator
Collaborator

I can't help you, but decided to ask chatGPT.
Interested to see if it can actually help with your questions.

https://chatgpt.com/share/6797b333-2340-8002-947e-f04b6769b391

0 Likes
Message 3 of 6

_gile
Consultant
Consultant
Accepted solution

Hi,

 

Here's a simple example which mimics the "_BLOCK" command.

[CommandMethod("TEST")]
public void Test()
{
    var doc = Application.DocumentManager.MdiActiveDocument;
    var db = doc.Database;
    var ed = doc.Editor;

    // Select entities to make a block
    var selection = ed.GetSelection();
    if (selection.Status != PromptStatus.OK)
        return;

    // Get the block base point
    var promptPointResult = ed.GetPoint("\nSpecify the base point: ");
    if (promptPointResult.Status != PromptStatus.OK)
        return;
    var basePoint = promptPointResult.Value.TransformBy(ed.CurrentUserCoordinateSystem);

    using (var tr = db.TransactionManager.StartTransaction())
    {
        // Get the block name
        var blockTable = (BlockTable)tr.GetObject(db.BlockTableId, OpenMode.ForWrite);
        string blockName;
        while (true)
        {
            var promptStringResult = ed.GetString("\nEnter the block name: ");
            if (promptStringResult.Status == PromptStatus.OK)
            {
                blockName = promptStringResult.StringResult;
                if (blockTable.Has(blockName))
                {
                    ed.WriteMessage($"\n'{blockName}' already exists");
                }
                else
                {
                    break;
                }
            }
            else
            {
                return;
            }
        }

        // Create the block definition
        var ids = new ObjectIdCollection(selection.Value.GetObjectIds());
        var btr = new BlockTableRecord();
        btr.Name = blockName;
        var btrId = blockTable.Add(btr);
        tr.AddNewlyCreatedDBObject(btr, true);
        var mapping = new IdMapping();
        db.DeepCloneObjects(ids, btrId, mapping, false);
        var xform = Matrix3d.Displacement(basePoint.GetAsVector().Negate());
        foreach (IdPair pair in mapping)
        {
            if (pair.IsCloned && pair.IsPrimary)
            {
                var entity = (Entity)tr.GetObject(pair.Value, OpenMode.ForWrite);
                entity.TransformBy(xform);
            }
        }

        // Create the block reference
        var currentSpace = (BlockTableRecord)tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite);
        var br = new BlockReference(basePoint, btrId);
        currentSpace.AppendEntity(br);
        tr.AddNewlyCreatedDBObject(br, true);

        // Erase the selected entities.
        foreach (ObjectId id in ids)
        {
            var entity = (Entity)tr.GetObject(id, OpenMode.ForWrite);
            entity.Erase();
        }

        tr.Commit();
    }
}


Gilles Chanteau
Programmation AutoCAD LISP/.NET
GileCAD
GitHub

Message 4 of 6

MarkJamesRogolino
Advocate
Advocate

Thank you for your perfect help. It works well.

0 Likes
Message 5 of 6

kerry_w_brown
Advisor
Advisor

@Brock_Olly wrote:

I can't help you, but decided to ask chatGPT.
Interested to see if it can actually help with your questions.

https://chatgpt.com/share/6797b333-2340-8002-947e-f04b6769b391


Interesting haiku  :=)

Haiku _ 2025-01-29_17-17-42.jpg

Regards,

 


// Called Kerry or kdub in my other life.

Everything will work just as you expect it to, unless your expectations are incorrect. ~ kdub
Sometimes the question is more important than the answer. ~ kdub

NZST UTC+12 : class keyThumper<T> : Lazy<T>;      another  Swamper
Message 6 of 6

Brock_Olly
Collaborator
Collaborator

Weird, seems like the link does work if I open it in incognito mode though.

0 Likes