.NET

Reply
Active Contributor
farrukhw
Posts: 26
Registered: ‎05-07-2009
Message 11 of 19 (344 Views)

Re: Calling -INSERT Command from AutoCAD.net (2012).

07-08-2012 12:08 PM in reply to: matinau

Same case here. I wrote .Net routines to move and rotate the Block, but then I realized that it would be complicated when I will have to deal with the behavior related to Block's attributes. So I decided to use built-in functionality.

BTW, why is it that you do not recommend to use built-in functionality?

Valued Contributor
CommCorp
Posts: 97
Registered: ‎03-19-2007
Message 12 of 19 (334 Views)

Re: Calling -INSERT Command from AutoCAD.net (2012).

07-09-2012 03:42 AM in reply to: farrukhw

First of all I'm a dot net newbie so this is mostly from what I've read on the forums. In my actual experience I had a program that used "SendCommand" and when in debug mode it would not run (VB.Net Express). It would crash on the SendCommands so to debug a program I had to comment those lines out.

The program ran fine with the "SendCommand" lines in Release mode, but just not in Debug.

 

Active Contributor
farrukhw
Posts: 26
Registered: ‎05-07-2009
Message 13 of 19 (322 Views)

Re: Calling -INSERT Command from AutoCAD.net (2012).

07-09-2012 11:58 PM in reply to: CommCorp

I think, you might be referencing ObjectARX apis in your VB Code.

I'm switched to C# just because of better support and management in .Net Apis.

Member
xsfhlzh1
Posts: 5
Registered: ‎07-19-2012
Message 14 of 19 (305 Views)

Re: Calling -INSERT Command from AutoCAD.net (2012).

07-19-2012 01:32 AM in reply to: farrukhw

 

 

 

Try this code

    internal class BlockRefJig : EntityJig
    {

        Point3d m_Position,m_BasePoint;
        double m_Angle;
        int m_PromptCounter;
        Matrix3d m_Ucs;
        Matrix3d m_Mat;

        //键值对集合(属性定义/引用)
        Dictionary<AttributeDefinition, AttributeReference> m_Attribs;

        public BlockRefJig(BlockReference blkref, Dictionary<AttributeDefinition, AttributeReference> attribs)
            : base(blkref)
        {
            m_Position = new Point3d();
            m_Angle = 0;
            m_Ucs = SystemManager.Editor.CurrentUserCoordinateSystem;
            m_Attribs = attribs;
            Update();
        }

        protected override SamplerStatus Sampler(JigPrompts prompts)
        {
            switch (m_PromptCounter)
            {
                case 0:
                    {
                        JigPromptPointOptions jigOpts = new JigPromptPointOptions("\n请输入基点:");
                        jigOpts.UserInputControls =
                            UserInputControls.Accept3dCoordinates |
                            UserInputControls.NoZeroResponseAccepted |
                            UserInputControls.NoNegativeResponseAccepted;
                        PromptPointResult res = prompts.AcquirePoint(jigOpts);

                        Point3d pnt = res.Value;
                        if (pnt != m_Position)
                        {
                            m_Position = pnt;
                            m_BasePoint = m_Position;
                        }
                        else
                            return SamplerStatus.NoChange;

                        if (res.Status == PromptStatus.Cancel)
                            return SamplerStatus.Cancel;
                        else
                            return SamplerStatus.OK;
                    }
                case 1:
                    {
                        JigPromptAngleOptions jigOpts = new JigPromptAngleOptions("\n请输入旋转角度:");
                        jigOpts.UserInputControls =
                            UserInputControls.Accept3dCoordinates |
                            UserInputControls.NoNegativeResponseAccepted |
                            UserInputControls.GovernedByUCSDetect |
                            UserInputControls.UseBasePointElevation;
                        jigOpts.Cursor = CursorType.RubberBand;
                        jigOpts.UseBasePoint = true;
                        jigOpts.BasePoint = m_BasePoint;
                        PromptDoubleResult res = prompts.AcquireAngle(jigOpts);

                        double angleTemp = res.Value;
                        if (angleTemp != m_Angle)
                            m_Angle = angleTemp;
                        else
                            return SamplerStatus.NoChange;

                        if (res.Status == PromptStatus.Cancel)
                            return SamplerStatus.Cancel;
                        else
                            return SamplerStatus.OK;
                    }
                default:
                    return SamplerStatus.NoChange;
            }
        }

        protected override bool Update()
        {
            try
            {
                /*Ucs下Jig的流程:
                 * 1.先将图元在Wcs下摆正,即//xy平面
                 * 2.将获取点坐标转换到Ucs下
                 * 3.将图元在Ucs下摆正
                 * 4.矩阵变换到Wcs
                 */
                BlockReference blkref = (BlockReference)Entity;
                blkref.Normal = Vector3d.ZAxis;

                blkref.Position = m_Position.Wcs2Ucs();
                blkref.Rotation = m_Angle;
                blkref.TransformBy(m_Ucs);

                //将属性引用按块引用的Ocs矩阵变换
                if (m_Attribs != null)
                {
                    m_Mat = blkref.BlockTransform;
                    foreach (KeyValuePair<AttributeDefinition, AttributeReference> att in m_Attribs)
                    {
                        AttributeReference attref = att.Value;
                        string s = attref.TextString;
                        attref.SetAttributeFromBlock(att.Key, m_Mat);
                        attref.TextString = s;
                    }
                }
                
            }
            catch
            {
                return false;
            }

            return true;

        }

        public void SetPromptCounter(int i)
        {
            if (i == 0 || i == 1)
            {
                m_PromptCounter = i;
            }
        }

    }

 

Member
xsfhlzh1
Posts: 5
Registered: ‎07-19-2012
Message 15 of 19 (304 Views)

Re: Calling -INSERT Command from AutoCAD.net (2012).

07-19-2012 01:40 AM in reply to: xsfhlzh1
        /// <summary>
        /// 添加属性到块参照
        /// </summary>
        /// <param name="blkref">块参照</param>
        /// <param name="atts">属性集合</param>
        /// <returns>属性定义和属性参照对照表</returns>
        public Dictionary<AttributeDefinition, AttributeReference> 
            AppendAttribToBlock(BlockReference blkref, List<string> atts)
        {

            var blkdef = GetObject<BlockTableRecord>(blkref.BlockTableRecord);

            int i = 0;
            if (blkdef.HasAttributeDefinitions)
            {
                var attribs =
                    new Dictionary<AttributeDefinition, AttributeReference>();

                var attdefs = 
                    blkdef.GetEntities<AttributeDefinition>(Transaction)
                    .Where(attdef => !(attdef.Constant || attdef.Invisible));

                foreach (var attdef in attdefs)
                {
                    AttributeReference attref = new AttributeReference();
                    attref.SetAttributeFromBlock(attdef, blkref.BlockTransform);
                    if (i < atts.Count)
                        attref.TextString = atts[i];
                    else
                        attref.TextString = attdef.TextString;
                    i++;
                    blkref.AttributeCollection.AppendAttribute(attref);
                    Transaction.AddNewlyCreatedDBObject(attref, true);
                    attribs.Add(attdef, attref);
                }
                return attribs;
            }
            return null;
        }

 

        /// <summary>
        /// 动态添加块参照
        /// </summary>
        /// <param name="blkdefid">块定义Id</param>
        /// <param name="atts">属性集合</param>
        /// <returns>块参照Id</returns>
        public ObjectId InsertBlockRef(ObjectId blkdefid, List<string> atts)
        {
            BlockTableRecord btr = OpenCurrentSpace();
            BlockReference blkref = new BlockReference(Point3d.Origin, blkdefid);
            ObjectId id = AddEntity(btr, blkref);
            BlockRefJig jig = new BlockRefJig(blkref, AppendAttribToBlock(blkref, atts));
            jig.SetPromptCounter(0);
            PromptResult res = Editor.Drag(jig);
            if (res.Status == PromptStatus.OK)
            {
                jig.SetPromptCounter(1);
                res = Editor.Drag(jig);
                if (res.Status == PromptStatus.OK)
                {
                    return id;
                }
            }
            blkref.Erase();
            return ObjectId.Null;
        }

 

Active Contributor
farrukhw
Posts: 26
Registered: ‎05-07-2009
Message 16 of 19 (282 Views)

Re: Calling -INSERT Command from AutoCAD.net (2012).

07-20-2012 11:57 PM in reply to: xsfhlzh1

Thanks for the code xsfhlzh1.

 

Can you please upload your Visual Studio Project ? I have errors as we don't have Namespaces used in this code.

 

Thanks

Member
xsfhlzh1
Posts: 5
Registered: ‎07-19-2012
Message 17 of 19 (276 Views)

Re: Calling -INSERT Command from AutoCAD.net (2012).

07-21-2012 01:32 AM in reply to: farrukhw
using System.Collections.Generic;
using System.Linq;
using Autodesk.AutoCAD.Runtime;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.EditorInput;
using Autodesk.AutoCAD.Geometry;
using Autodesk.AutoCAD.ApplicationServices;

[assembly: CommandClass(typeof(InsertBlock.Commands))]

namespace InsertBlock
{
    public class Commands
    {

        public static Dictionary<AttributeDefinition, AttributeReference>
            AppendAttribToBlock(Transaction tr, BlockReference blkref, List<string> atts)
        {

            var blkdef = (BlockTableRecord)tr.GetObject(blkref.BlockTableRecord, OpenMode.ForRead);

            int i = 0;
            if (blkdef.HasAttributeDefinitions)
            {
                var attribs =
                    new Dictionary<AttributeDefinition, AttributeReference>();

                var attdefs = 
                    blkdef.Cast<ObjectId>()
                    .Select(id => tr.GetObject(id, OpenMode.ForRead))
                    .OfType<AttributeDefinition>()
                    .Where(attdef => !(attdef.Constant || attdef.Invisible));

                foreach (var attdef in attdefs)
                {
                    AttributeReference attref = new AttributeReference();
                    attref.SetAttributeFromBlock(attdef, blkref.BlockTransform);
                    if (i < atts.Count)
                        attref.TextString = atts[i];
                    else
                        attref.TextString = attdef.TextString;
                    i++;
                    blkref.AttributeCollection.AppendAttribute(attref);
                    tr.AddNewlyCreatedDBObject(attref, true);
                    attribs.Add(attdef, attref);
                }
                return attribs;
            }
            return null;
        }

        public static ObjectId InsertBlockRef(Transaction tr, Database db, Editor ed, ObjectId blkdefid, List<string> atts)
        {
            BlockTableRecord btr = (BlockTableRecord)tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite);
            BlockReference blkref = new BlockReference(Point3d.Origin, blkdefid);
            ObjectId id = btr.AppendEntity(blkref);
            tr.AddNewlyCreatedDBObject(blkref, true);
            BlockRefJig jig = new BlockRefJig(blkref, AppendAttribToBlock(tr, blkref, atts));
            jig.SetPromptCounter(0);
            PromptResult res = ed.Drag(jig);
            if (res.Status == PromptStatus.OK)
            {
                jig.SetPromptCounter(1);
                res = ed.Drag(jig);
                if (res.Status == PromptStatus.OK)
                {
                    return id;
                }
            }
            blkref.Erase();
            return ObjectId.Null;
        }

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

            using (Transaction tr = db.TransactionManager.StartTransaction())
            {
                var bt = (BlockTable)tr.GetObject(db.BlockTableId, OpenMode.ForWrite);
                ObjectId id;
                if (bt.Has("Test1"))
                {
                    id = bt["Test1"];
                }
                else
                {

                    BlockTableRecord btr = new BlockTableRecord();
                    btr.Name = "Test1";
                    id = bt.Add(btr);
                    tr.AddNewlyCreatedDBObject(btr, true);

                    AttributeDefinition att = new AttributeDefinition(Point3d.Origin, "1", "Number", "input number:", db.Textstyle);
                    att.Height = 6;
                    Circle c = new Circle(Point3d.Origin, Vector3d.ZAxis, 10);

                    btr.AppendEntity(att);
                    tr.AddNewlyCreatedDBObject(att, true);
                    btr.AppendEntity(c);
                    tr.AddNewlyCreatedDBObject(c, true);
                    
                }

                InsertBlockRef(tr, db, ed, id, new List<string> { "1" });
                tr.Commit();
            }


        }


    }
}

 

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.EditorInput;
using Autodesk.AutoCAD.Geometry;
using Autodesk.AutoCAD.Runtime;


namespace InsertBlock
{

    internal class BlockRefJig : EntityJig
    {

        Point3d m_Position, m_BasePoint;
        double m_Angle;
        int m_PromptCounter;
        Matrix3d m_Ucs;
        Matrix3d m_Mat;

        Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;

        //键值对集合(属性定义/引用)
        Dictionary<AttributeDefinition, AttributeReference> m_Attribs;

        public BlockRefJig(BlockReference blkref, Dictionary<AttributeDefinition, AttributeReference> attribs)
            : base(blkref)
        {
            m_Position = new Point3d();
            m_Angle = 0;
            m_Ucs = ed.CurrentUserCoordinateSystem;
            m_Attribs = attribs;
            Update();
        }

        protected override SamplerStatus Sampler(JigPrompts prompts)
        {
            switch (m_PromptCounter)
            {
                case 0:
                    {
                        JigPromptPointOptions jigOpts = new JigPromptPointOptions("\n请输入基点:");
                        jigOpts.UserInputControls =
                            UserInputControls.Accept3dCoordinates |
                            UserInputControls.NoZeroResponseAccepted |
                            UserInputControls.NoNegativeResponseAccepted;
                        PromptPointResult res = prompts.AcquirePoint(jigOpts);

                        Point3d pnt = res.Value;
                        if (pnt != m_Position)
                        {
                            m_Position = pnt;
                            m_BasePoint = m_Position;
                        }
                        else
                            return SamplerStatus.NoChange;

                        if (res.Status == PromptStatus.Cancel)
                            return SamplerStatus.Cancel;
                        else
                            return SamplerStatus.OK;
                    }
                case 1:
                    {
                        JigPromptAngleOptions jigOpts = new JigPromptAngleOptions("\n请输入旋转角度:");
                        jigOpts.UserInputControls =
                            UserInputControls.Accept3dCoordinates |
                            UserInputControls.NoNegativeResponseAccepted |
                            UserInputControls.GovernedByUCSDetect |
                            UserInputControls.UseBasePointElevation;
                        jigOpts.Cursor = CursorType.RubberBand;
                        jigOpts.UseBasePoint = true;
                        jigOpts.BasePoint = m_BasePoint;
                        PromptDoubleResult res = prompts.AcquireAngle(jigOpts);

                        double angleTemp = res.Value;
                        if (angleTemp != m_Angle)
                            m_Angle = angleTemp;
                        else
                            return SamplerStatus.NoChange;

                        if (res.Status == PromptStatus.Cancel)
                            return SamplerStatus.Cancel;
                        else
                            return SamplerStatus.OK;
                    }
                default:
                    return SamplerStatus.NoChange;
            }
        }

        protected override bool Update()
        {
            try
            {
                /*Ucs下Jig的流程:
                 * 1.先将图元在Wcs下摆正,即//xy平面
                 * 2.将获取点坐标转换到Ucs下
                 * 3.将图元在Ucs下摆正
                 * 4.矩阵变换到Wcs
                 */
                BlockReference blkref = (BlockReference)Entity;
                blkref.Normal = Vector3d.ZAxis;

                blkref.Position = m_Position.TransformBy(ed.CurrentUserCoordinateSystem);
                blkref.Rotation = m_Angle;
                blkref.TransformBy(m_Ucs);

                //将属性引用按块引用的Ocs矩阵变换
                if (m_Attribs != null)
                {
                    m_Mat = blkref.BlockTransform;
                    foreach (KeyValuePair<AttributeDefinition, AttributeReference> att in m_Attribs)
                    {
                        AttributeReference attref = att.Value;
                        string s = attref.TextString;
                        attref.SetAttributeFromBlock(att.Key, m_Mat);
                        attref.TextString = s;
                    }
                }

            }
            catch
            {
                return false;
            }

            return true;

        }

        public void SetPromptCounter(int i)
        {
            if (i == 0 || i == 1)
            {
                m_PromptCounter = i;
            }
        }

    }

}

 

Member
xsfhlzh1
Posts: 5
Registered: ‎07-19-2012
Message 18 of 19 (274 Views)

Re: Calling -INSERT Command from AutoCAD.net (2012).

07-21-2012 01:38 AM in reply to: xsfhlzh1

The above functions are part of the custom class

The following project should you need

Active Contributor
farrukhw
Posts: 26
Registered: ‎05-07-2009
Message 19 of 19 (268 Views)

Re: Calling -INSERT Command from AutoCAD.net (2012).

07-21-2012 02:43 AM in reply to: xsfhlzh1

Thanks a lot.I'll definitly try that...

 

Best regards

Farrukh

You are not logged in.

Log into access your profile, ask and answer questions, share ideas and more. Haven't signed up yet? Register

Announcements
Are you familiar with the Autodesk Expert Elites? The Expert Elite program is made up of customers that help other customers by sharing knowledge and exemplifying an engaging style of collaboration. To learn more, please visit our Expert Elite website.

Need installation help?

Start with some of our most frequented solutions to get help installing your software.

Ask the Community