Show Posts

This section allows you to view all posts made by this member. Note that you can only see posts made in areas you currently have access to.


Topics - fixo

Pages: 1 ... 4 5 [6] 7
76
Tables / Apply a minimum column width setting
« on: June 25, 2012, 06:21:56 AM »
 
Code: [Select]
       // Apply a minimum column width setting
        [CommandMethod("ChangeTableColumnsWidths", "CtCw", CommandFlags.UsePickSet)]

        public static void ChangeTableColumnsWidths()
        {

            Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;

            Editor ed = doc.Editor;

            try
            {
                PromptEntityOptions peo = new PromptEntityOptions("\nSelect table to fix columns");

                peo.SetRejectMessage("\nYou have to select table...");

                peo.AddAllowedClass(typeof(Table), false);

                peo.AllowNone = false;

                PromptEntityResult per = ed.GetEntity(peo);

                if (per.Status != PromptStatus.OK)

                    return;

                ObjectId id = per.ObjectId;

                Transaction tr = doc.TransactionManager.StartTransaction();

                using (tr)
                {

                    // Open the table for read content
                    Table tb = tr.GetObject(id, OpenMode.ForRead) as Table;
                    List<List<double>> tbcontent = new List<List<double>>();
                    // to simplify code look up to the first cell of header rows, ignore title row
                    Cell cl = tb.Cells[1, 0];
                    // get text height
                    double th = (double)cl.TextHeight;//cl.Contents[0].TextHeight;

                    double ratio = 1.25;// ratio between height and width of characters, approx., calc by yourself for your font
                    double lwd = th * ratio;
                    for (int i = 1; i < tb.Rows.Count; i++)
                    {
                        List<double> tmpline = new List<double>();

                        for (int j = 0; j < tb.Columns.Count; j++)
                        {

                            tmpline.Add(tb.Cells[i, j].Value == null ? 0.0 : tb.Cells[i, j].TextString.Length); //if empty cell then add  zero
                        }
                        tbcontent.Add(tmpline);

                    }

                    List<double> raws = new List<double>();

                    for (int j = 0; j < tb.Columns.Count; j++)
                    {
                        List<double> tmp = new List<double>();
                        for (int i = 0; i < tbcontent.Count; i++)
                        {
                            List<double> tmpline = tbcontent[i];
                            double twid = tmpline[j] * lwd;
                            tmp.Add(twid);
                        }
                        raws.Add(tmp.Max());

                    }
                    //open for write
                    tb.UpgradeOpen();
                    //aplly new column width
                    for (int i = 0; i < raws.Count; i++)
                    {
                        tb.Columns[i].Width = raws[i];
                    }

                    tb.Width = raws.Sum();//optional, set table common with

                    tb.UpgradeOpen();

                    tr.Commit();
                }
            }
            catch (System.Exception ex)
            {
                Autodesk.AutoCAD.ApplicationServices.Application.ShowAlertDialog("\n" + ex.Message + "\n" + ex.StackTrace);
            }
            finally
            {

            }
        }

      VB.NET
Code: [Select]

      ' Apply a minimum column width setting   
        <CommandMethod("ChangeTableColumnsWidths", "CtCw", CommandFlags.UsePickSet)> _
        Public Shared Sub ChangeTableColumnsWidths()
            Dim doc As Document = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument
            Dim ed As Editor = doc.Editor
            Try
                Dim peo As New PromptEntityOptions(vbLf & "Select table to fix columns")
                peo.SetRejectMessage(vbLf & "You have to select table...")
                peo.AddAllowedClass(GetType(Table), False)
                peo.AllowNone = False
                Dim per As PromptEntityResult = ed.GetEntity(peo)
                If per.Status <> PromptStatus.OK Then
                    Return
                End If
                Dim id As ObjectId = per.ObjectId
                Dim tr As Transaction = doc.TransactionManager.StartTransaction()
                Using tr
                    ' Open the table for read content   
                    Dim tb As Table = TryCast(tr.GetObject(id, OpenMode.ForRead), Table)
                    Dim tbcontent As New List(Of List(Of Double))()
                    ' to simplify code look up to the first cell of header rows, ignore title row   
                    Dim cl As Cell = tb.Cells(1, 0)
                    ' get text height         
                    Dim th As Double = CDbl(cl.TextHeight)
                    'cl.Contents[0].TextHeight;   
                    Dim ratio As Double = 1.25
                    ' ratio between height and width of characters, approx., calc by yourself for your font 
                    Dim lwd As Double = th * ratio
                    For i As Integer = 1 To tb.Rows.Count - 1
                        Dim tmpline As New List(Of Double)()
                        For j As Integer = 0 To tb.Columns.Count - 1
                            'if empty cell then add  zero
                            tmpline.Add(If(tb.Cells(i, j).Value Is Nothing, 0.0, tb.Cells(i, j).TextString.Length))
                        Next
                        tbcontent.Add(tmpline)
                    Next
                    Dim raws As New List(Of Double)()
                    For j As Integer = 0 To tb.Columns.Count - 1
                        Dim tmp As New List(Of Double)()
                        For i As Integer = 0 To tbcontent.Count - 1
                            Dim tmpline As List(Of Double) = tbcontent(i)
                            Dim twid As Double = tmpline(j) * lwd
                            tmp.Add(twid)
                        Next
                        raws.Add(tmp.Max())
                    Next
                    'open for write     
                    tb.UpgradeOpen()
                    'aplly new column width   
                    For i As Integer = 0 To raws.Count - 1
                        tb.Columns(i).Width = raws(i)
                    Next
                    tb.Width = raws.Sum()
                    'optional, set table common with   
                    tb.UpgradeOpen()
                    tr.Commit()
                End Using
            Catch ex As System.Exception
                Autodesk.AutoCAD.ApplicationServices.Application.ShowAlertDialog(vbLf & ex.Message & vbLf & ex.StackTrace)
            Finally
            End Try
        End Sub

77
Tables / Create part reference table
« on: June 24, 2012, 08:55:35 PM »
The real world example, based on the drawing from there:
http://forums.augi.com/showthread.php?136467-lisp-table-help&p=1167872&viewfull=1#post1167872

~'J'~

78
Polylines / Extend curve
« on: June 22, 2012, 10:34:19 PM »
Code: [Select]
        [CommandMethod("ExtendCurve", "exc", CommandFlags.Modal)]
        static public void testExtendCurve()
        {
            Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;

            Editor ed = doc.Editor;

            Database db = doc.Database;

            try
            {
                using (Transaction tr = db.TransactionManager.StartTransaction())
                {
                    PromptEntityOptions peo = new PromptEntityOptions("\nSelect boundary edge... >>");

                    PromptEntityResult exres;
                    exres = ed.GetEntity(peo);
                    if (exres.Status != PromptStatus.OK)
                        return;

                    Entity exent = (Entity)tr.GetObject(exres.ObjectId, OpenMode.ForRead);
                    if (exent == null)
                        return;
                    Curve excur = exent as Curve;
                    peo = new PromptEntityOptions("\nSelect curve to extend >>");

                    PromptEntityResult res;
                    res = ed.GetEntity(peo);
                    if (res.Status != PromptStatus.OK)
                        return;

                    Entity ent = (Entity)tr.GetObject(res.ObjectId, OpenMode.ForRead);
                    if (ent == null)
                        return;

                    if (ent.GetRXClass().DxfName == "SPLINE")
                    {
                        ed.WriteMessage("\nCould not extend the spline");
                        return;
                    }
                    Curve cur = ent as Curve;
                    Point3dCollection pts = new Point3dCollection();
                    cur.IntersectWith(excur, Intersect.ExtendThis, pts, 0, 0);
                    if (pts.Count == 0)
                    {
                       ed.WriteMessage("\nCurves aren't intersects each other");
                        return;
                    }

                    Point3d pt = pts[0];// ought be to correct this point with circle and closed polyline
                   
                    if (!cur.IsWriteEnabled)
                        cur.UpgradeOpen();

                    Point3d pp = cur.GetClosestPointTo(res.PickedPoint, false);

                    bool sofar = false;

                    if (pp.DistanceTo(pt) < pt.DistanceTo(cur.EndPoint))
                        sofar = true;

                    if (sofar)
                    {
                        cur.Extend(true, pt);
                    }
                    else
                    {
                        cur.Extend(false, pt);
                    }
                   
                    tr.Commit();
                }
            }
            catch (System.Exception ex)
            {
                ed.WriteMessage(ex.Message );
            }

        }

~'J'~

79
Layouts and printing / Get the layout an entity belongs to
« on: June 22, 2012, 07:26:01 PM »
Code: [Select]
  // based on code from:
  // http://adndevblog.typepad.com/autocad/2012/06/get-the-layout-an-entity-belongs-to.html
  [CommandMethod("EntityLayoutName","enl", CommandFlags.Modal)]
        static public void GetEntityLayout()
        {
            Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;

            Editor ed = doc.Editor;

            Database db = doc.Database;

            using (Transaction tr = db.TransactionManager.StartTransaction())
            {
                PromptEntityOptions peo = new PromptEntityOptions("\nSelect object >>");

                PromptEntityResult res;

                res = ed.GetEntity(peo);

                if (res.Status != PromptStatus.OK)
                    return;

                Entity ent = (Entity)tr.GetObject(res.ObjectId, OpenMode.ForRead);

                if (ent == null)
                    return;

                BlockTableRecord btr = tr.GetObject(ent.OwnerId, OpenMode.ForRead, true) as BlockTableRecord;

                Layout lt = tr.GetObject(btr.LayoutId, OpenMode.ForRead, true) as Layout;

                string layoutName = lt.LayoutName;

                ed.WriteMessage("\nThe layout the selected entity belongs to is {0}", layoutName);

            }
        }

80
Hatching / Intersect an outerloop of hatch with curves
« on: June 17, 2012, 03:43:16 PM »
This code will work with associative hatch only

Code: [Select]
        [CommandMethod("hat", CommandFlags.Modal)]
        public static void IntersectHatchWithCurves()
        {

            Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
            Editor ed = doc.Editor;
            Database db = doc.Database;

            Transaction tr = db.TransactionManager.StartTransaction();
            using (tr)
            {
                try
                {
                    BlockTableRecord btr = (BlockTableRecord)tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite, false) as BlockTableRecord;
                    PromptEntityOptions peo = new PromptEntityOptions("\nSelect a hatch: ");
                    peo.SetRejectMessage("Select hatch only!");
                    peo.AddAllowedClass(typeof(Hatch), true);
                    PromptEntityResult res = doc.Editor.GetEntity(peo);
                    if (res.Status != PromptStatus.OK) return;
                    // Point3d pt = res.PickedPoint;
                    Entity ent = tr.GetObject(res.ObjectId, OpenMode.ForRead, false) as Entity;
                    Hatch hat = ent as Hatch;
                    if (hat == null)
                    {
                        Autodesk.AutoCAD.ApplicationServices.Application.ShowAlertDialog("No luck, mate...");
                        return;
                    }
                    // get outer loop of hatch
                    HatchLoop loops = hat.GetLoopAt(0);
                    Polyline pline = new Polyline();
                 if (loops.IsPolyline)
                 {
                     DoubleCollection bulgcoll=new DoubleCollection();
                     Point2dCollection pts=new Point2dCollection();
                     BulgeVertexCollection bulges =  loops.Polyline;

                    for (int i=0;i<bulges.Count;i++)
                    {
                        BulgeVertex bulg = bulges[i];
                        bulgcoll.Add(bulg.Bulge);
                        pts.Add(bulg.Vertex);
                    }
                     // create polyline around of the hatch
                     pline = new Polyline(bulges.Count);
                    for (int n = 0; n < pts.Count; n++)
                    {
                        pline.AddVertexAt(n, pts[n], bulgcoll[n], 0, 0);
                    }
                     // commented lines used just for debug only
                    //btr.AppendEntity(pline);
                    //tr.AddNewlyCreatedDBObject(pline, true);
                    //pline.ColorIndex = 5;
                 }

                    // select all intersection curves on layer "0"
                 TypedValue[] tvs = new TypedValue[] {
              new TypedValue((int) DxfCode.Start, "arc,circle,line,lwpolyline,spline"),
              new TypedValue((int) DxfCode.LayerName, "0")
            };
                 SelectionFilter sf = new SelectionFilter(tvs);
                 PromptSelectionOptions pso = new PromptSelectionOptions();
                    pso.MessageForRemoval="\nwrong object selected!";
                 pso.MessageForAdding = "\nSelect curves separately one by another: ";
                 PromptSelectionResult psr = ed.GetSelection(pso,sf);
                 int count = 0;
                 if (psr.Status == PromptStatus.OK)
                 {
                     count = psr.Value.GetObjectIds().Length;

                     ed.WriteMessage("\nSelected:    " + count.ToString());

                 }
                 else
                 {
                     ed.WriteMessage("\nBad selection");
                     return;

                 }

                 foreach (SelectedObject selobj in psr.Value)
                 {
                     
                         DBObject obj = tr.GetObject(selobj.ObjectId, OpenMode.ForRead) as DBObject;
                         Curve curv = obj as Curve;
                         if (obj.ObjectId != pline.ObjectId)
                         {
                         Point3dCollection ipts = new Point3dCollection();
                         // next line is may have another syntax for other Acad release
                         pline.IntersectWith(curv, Intersect.OnBothOperands, ipts, (int)IntPtr.Zero, (int)IntPtr.Zero);

                         if (ipts.Count > 0)
                         {
                             foreach (Point3d pt in ipts)
                             {
                                 // draw circles in intersection for dispaying the result
                                 Circle circ = new Circle(pt, Vector3d.ZAxis, 0.5);
                                 btr.AppendEntity(circ);
                                 tr.AddNewlyCreatedDBObject(circ, true);
                                 circ.ColorIndex = 2;
                             }
                         }
                     }
                 }
                    tr.Commit();
                }
                catch (Autodesk.AutoCAD.Runtime.Exception ex)
                {
                    ed.WriteMessage("\n" + ex.Message + "\n" + ex.StackTrace);

                }
                finally
                {

                }
            }
        }

~'J'~

81
Colors and linetypes / Using AutoCAD dialogs
« on: June 17, 2012, 10:34:21 AM »
Code: [Select]
       using Autodesk.AutoCAD.Runtime;
        using Autodesk.AutoCAD.ApplicationServices;
        using Autodesk.AutoCAD.DatabaseServices;
        using Autodesk.AutoCAD.Geometry;
        using Autodesk.AutoCAD.EditorInput;
        using Autodesk.AutoCAD.EditorInput;
        using Autodesk.AutoCAD.Windows;
        //________________________________________//

        [Obsolete]//   just for use ObjectId.Open method below
        [CommandMethod("setlt")]
        public static void SetLinetype()
        {
            var db = HostApplicationServices.WorkingDatabase;
            var ld = new Autodesk.AutoCAD.Windows.LinetypeDialog();
            if (ld.ShowDialog() != DialogResult.OK) return;
            var ed = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor;           
            LinetypeTableRecord ltr = ld.Linetype.Open(OpenMode.ForRead, false) as LinetypeTableRecord;
            ed.WriteMessage("\nSelected linetype: " + ltr.Name);
            db.Celtype = ld.Linetype;
        }


        [CommandMethod("setc")]
        public static void SetColor()
        {
            var db = HostApplicationServices.WorkingDatabase;
            var cd = new Autodesk.AutoCAD.Windows.ColorDialog();
            if (cd.ShowDialog() != DialogResult.OK) return;
            var ed = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor;
            ed.WriteMessage("\nSelected color: " + cd.Color);
            db.Cecolor = cd.Color;

        }
   
        [CommandMethod("setlw")]
        public static void SetLineWeight()
        {
            var db = HostApplicationServices.WorkingDatabase;
            var lw = new Autodesk.AutoCAD.Windows.LineWeightDialog();
            if (lw.ShowDialog() != DialogResult.OK) return;
            var ed = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor;
            LineWeight lwt = lw.LineWeight;
            ed.WriteMessage("\nSelected linetype: " + lwt.ToString());
            db.Celweight = lwt;
        }

~'J'~

82
Blocks / Get block name by subentity
« on: June 16, 2012, 12:16:41 PM »
Code: [Select]
        [CommandMethod("bnm")]
        // expired by Barbara Hun:
        // http://adndevblog.typepad.com/autocad/2012/05/get-block-that-entities-are-included-in.html#tpe-action-posted-6a0167607c2431970b0167674896a4970b
        public static void getBlockNameFromItsSubentity()
        {
            Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;

            Editor ed = doc.Editor;

            Database db = doc.Database;

            Matrix3d ucs = ed.CurrentUserCoordinateSystem;

            PromptNestedEntityOptions pno = new PromptNestedEntityOptions("\nSelect an subentity inside an INSERT: ");

            PromptNestedEntityResult nres = ed.GetNestedEntity(pno);

            if (nres.Status != PromptStatus.OK)
            {
                ed.WriteMessage("\nEntsel failed");
                return;
            }

            try
            {
                Transaction tr = db.TransactionManager.StartTransaction();

                using (tr)
                {
                    Point3d pickPt = nres.PickedPoint.TransformBy(ucs);

                    ed.WriteMessage("\nPicked point is {0}", pickPt);

                    ObjectId selId = nres.ObjectId;

                    List<ObjectId> objIds = new List<ObjectId>(nres.GetContainers());

                    // Reverse the "containers" list

                    // Now append the selected entity

                    objIds.Add(selId);

                    objIds.Reverse();

                    // Retrieve the sub-entity path for this entity

                    SubentityId subEnt = new SubentityId(SubentityType.Null, 0);

                    FullSubentityPath path = new FullSubentityPath(objIds.ToArray(), subEnt);

                    // Open the outermost container, relying on the open

                    // transaction...

                    Entity subent = tr.GetObject(objIds[0], OpenMode.ForRead, false) as Entity;

                    // Output the class name of the sub entity

                    ed.WriteMessage("\nThe sub entity is of type {0}", subent.GetType().Name);

                    // Get the object id of the owner block

                    ObjectId eid = subent.OwnerId;

                    DBObject bowner = tr.GetObject(eid, OpenMode.ForRead, false) as DBObject;

                    // Output the class name of the owner block

                    ed.WriteMessage("\nThe owner is of type {0}",

                    bowner.GetType().Name);

                    string blkname = string.Empty;

                    // Output the information of the block definition

                    BlockTableRecord btrec = bowner as BlockTableRecord;

                    if (btrec != null)
                    {

                        blkname = btrec.Name;


                        ed.WriteMessage("\nBlock Record name is {0}", blkname);

                    }
                    BlockReference bref = bowner as BlockReference;

                    if (bref != null)
                    {
                        bowner = tr.GetObject(bref.BlockTableRecord, OpenMode.ForRead, false) as BlockTableRecord;

                        if (bref.IsDynamicBlock)
                        {
                            btrec = tr.GetObject(bref.DynamicBlockTableRecord, OpenMode.ForRead, false) as BlockTableRecord;

                            blkname = btrec.Name;
                        }
                        else
                        {
                            blkname = bref.Name;
                        }

                        ed.WriteMessage("\nBlock Reference name is {0}", blkname);

                    }
                    tr.Commit();
                }
            }
            catch (Autodesk.AutoCAD.Runtime.Exception ex)
            {
                ed.WriteMessage("\n" + ex.Message + "\n" + ex.StackTrace);
            }
            finally
            {

            }
        }

83
Blocks / Get all block references on a particular layout
« on: June 06, 2012, 07:01:24 PM »

Code: [Select]
      //inspired by Xiaodong Liang
      [CommandMethod("finb")]
        public static void FindBlokRefInLayout()
        {
            SelectionSet ss;

            string lName = "Layout1";

            Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
            Editor ed = doc.Editor;
            Database db = doc.Database;
            // switch to the Layout1
            Autodesk.AutoCAD.ApplicationServices.Application.SetSystemVariable("ctab", lName);

            Transaction tr = db.TransactionManager.StartTransaction();

            using (tr)
            {
                try
                {
                    BlockTable bt = tr.GetObject(db.BlockTableId, OpenMode.ForWrite) as BlockTable;

                    foreach (ObjectId id in bt)
                    {

                        BlockTableRecord btr;

                        btr = tr.GetObject(id, OpenMode.ForRead) as BlockTableRecord;

                        // if this is a layout

                        if (btr.IsLayout)
                        {

                            ObjectId lid = btr.LayoutId;

                            Layout lt = tr.GetObject(lid, OpenMode.ForWrite) as Layout;

                            List<ObjectId> objs = new List<ObjectId>();

                            // get name of the layout

                            if (lt.LayoutName != lName)
                            { 
                                continue;
                            }
                            else
                            {

                                // select all blocks on Layout1

                                RXClass etype = RXObject.GetClass(typeof(BlockReference));

                                // iterate the entities within the layout

                                foreach (ObjectId eid in btr)
                                {
                                    Entity ent;

                                    ent = tr.GetObject(eid, OpenMode.ForRead) as Entity;

                                    // cast if this is a block reference

                                    if (eid.ObjectClass.IsDerivedFrom(etype))
                                    {

                                        objs.Add(eid);

                                        // highlight entity
                                       
                                        ent.Highlight();

                                    }

                                }
                            }
                            // populate the selectionset

                                ed.SetImpliedSelection(objs.ToArray<ObjectId>());

                            // perform the selection

                                PromptSelectionResult res = ed.SelectImplied();

                           
                                if (res.Status == PromptStatus.OK)
                                {

                                    ss = res.Value;
                                    // display information for user
                                    ed.WriteMessage("\n\t---\tSelected: {0} block instances", ss.GetObjectIds().Length);
                                }
                                else
                                {
                                    ed.WriteMessage("\nEmpty selection!");
                                   // return;
                                }

                        }

                    }
                    tr.Commit();
                }
                catch (System.Exception ex)
                {
                    ed.WriteMessage("\n" + ex.Message + "\n" + ex.StackTrace);
                }
            }
        }

~'J'~

84
Blocks / Get constant attributes example
« on: May 29, 2012, 07:40:02 PM »
 
Code: [Select]
       [CommandMethod("gatt", CommandFlags.Modal | CommandFlags.Session)]
        public static void GetAttributesTest()
        {
            Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
            Database db = doc.Database;
            Editor ed = doc.Editor;
            using (DocumentLock docloc = doc.LockDocument())
            {
                using (Transaction tr = db.TransactionManager.StartTransaction())
                {
                    try
                    {
                        BlockTable bt = db.BlockTableId.GetObject(OpenMode.ForRead) as BlockTable;                       
                        PromptSelectionOptions pso = new PromptSelectionOptions();
                        pso.MessageForRemoval = "\nWrong objects selected or Nothing selected";
                        pso.MessageForAdding = "\nSelect Blocks";
                        TypedValue[] tvs = new TypedValue[] { new TypedValue(0, "INSERT") };
                        SelectionFilter filt = new SelectionFilter(tvs);
                        PromptSelectionResult psr = ed.GetSelection(pso, filt);
                        if (!(psr.Status == PromptStatus.OK))
                            return;
                        if (psr.Value.Count == 0)
                        {
                            ed.WriteMessage("\nCount: {0} blocks",  psr.Value.Count);
                            return;
                        }

                        foreach (SelectedObject sobj in psr.Value)
                        {
                            BlockReference bref = (BlockReference)tr.GetObject(sobj.ObjectId, OpenMode.ForRead);
                            BlockTableRecord btrec = (BlockTableRecord)tr.GetObject(bref.BlockTableRecord, OpenMode.ForRead);
                            StringBuilder sb = new StringBuilder();
                            //Get constant attributes from BlockDefinition object
                            foreach (ObjectId eid in btrec)
                            {
                                DBObject obj = (Entity)tr.GetObject(eid, OpenMode.ForRead);
                                if (obj is AttributeDefinition)
                                {
                                    AttributeDefinition atdef = obj as AttributeDefinition;
                                    if (atdef.Constant)
                                    {
                                        sb.AppendLine(atdef.TextString);
                                    }
                                }


                            }
                            //Get visible attributes from BlockReference object
                            Autodesk.AutoCAD.DatabaseServices.AttributeCollection attcoll = bref.AttributeCollection;

                            foreach (ObjectId id in attcoll)
                            {
                                AttributeReference atref = (AttributeReference)tr.GetObject(id, OpenMode.ForRead);
                                sb.AppendLine(atref.TextString);
                            }
                            ed.WriteMessage(sb.ToString() + "\n");

                        }
                        tr.Commit();
                    }
                    catch (Autodesk.AutoCAD.Runtime.Exception ex)
                    {
                        ed.WriteMessage("\n" + ex.Message + "\n" + ex.StackTrace);
                    }
                }
            }
        }

~'J'~

85
Blocks / Sample code to renumber blocks
« on: May 29, 2012, 05:41:56 PM »
 [CommandMethod("BlocksRenumbering", "brenum", CommandFlags.Modal | CommandFlags.Session | CommandFlags.Redraw)]
        public static void TestRenumberBlocks()
        {
            // objects initializing
            Document doc = acadApp.DocumentManager.MdiActiveDocument;

            Editor ed = doc.Editor;

            Database db = doc.Database;

            try
            {
                using (doc.LockDocument())
                {
                    using (Transaction tr = db.TransactionManager.StartTransaction())
                    {
                        PromptStringOptions psto = new PromptStringOptions("\nEnter a  block name: ");

                        psto.AllowSpaces = true;

                        psto.DefaultValue = "Door";// change default block name here

                        PromptResult stres;

                        stres = ed.GetString(psto);

                        if (stres.Status != PromptStatus.OK)
                            return;

                        string oldblock = stres.StringResult;

                        ed.WriteMessage("\nBlock Name Entered:\t{0}\n", oldblock);

                        psto = new PromptStringOptions("\nEnter a tag name: ");

                        psto.AllowSpaces = true;

                        psto.DefaultValue = "SYM.";//change default tag name here

                        stres = ed.GetString(psto);

                        if (stres.Status != PromptStatus.OK)

                            return;

                        string tagname = stres.StringResult;

                        ed.WriteMessage("\nTag Name Entered:\t{0}\n", tagname);
                       
                        PromptIntegerOptions pio = new PromptIntegerOptions("\nEnter an initial attribute value: ");

                        pio.AllowNegative = false;

                        pio.AllowNone = true;

                        pio.AllowZero = false;

                        pio.DefaultValue = 1;

                        PromptIntegerResult ires = ed.GetInteger(pio);

                        if (ires.Status != PromptStatus.OK)

                            return;

                        int init = ires.Value;

                        ed.WriteMessage("\nInitial Value Entered:\t{0}\n", init);
                       
                        BlockTable bt = tr.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable;

                        if (!bt.Has(oldblock)) return;

                        ObjectId newblkId = bt[oldblock];

                        acadApp.SetSystemVariable("nomutt", 0);

                        TypedValue[] tvs = { new TypedValue(0, "insert"), new TypedValue(2, oldblock) };

                        SelectionFilter filt = new SelectionFilter(tvs);

                        PromptSelectionOptions pso = new PromptSelectionOptions();

                        pso.MessageForRemoval = "You must select the blocks only!";

                        pso.MessageForAdding = "\nSelect blocks in the right order: ";


                        PromptSelectionResult res = ed.GetSelection(pso, filt);

                        if (res.Status != PromptStatus.OK) return;

                        BlockTableRecord btr = tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite) as BlockTableRecord;

                        SelectionSet sset = res.Value;

                        foreach (SelectedObject obj in sset)
                        {
                            Entity ent = (Entity)obj.ObjectId.GetObject(OpenMode.ForWrite, false, true) as Entity;

                            BlockReference oldblk = ent as BlockReference;

                            Autodesk.AutoCAD.DatabaseServices.AttributeCollection atts =
                                oldblk.AttributeCollection;

                            foreach (ObjectId id in atts)
                            {
                                Autodesk.AutoCAD.DatabaseServices.AttributeReference atref =
                                    id.GetObject(OpenMode.ForWrite, false, true) as Autodesk.AutoCAD.DatabaseServices.AttributeReference;

                                if (atref.Tag == tagname.ToUpper())
                                {
                                    atref.TextString = init.ToString();
                                    init += 1;
                                    break;
                                }
                            }
                        }
                        tr.Commit();
                    }

                }
            }
            catch (System.Exception ex)
            {
                ed.WriteMessage(ex.Message + "\n" + ex.StackTrace);
            }
            finally
            {
                acadApp.SetSystemVariable("nomutt", 0);


            }

        }

86
Polylines / Import multyline styles from source drawing
« on: May 28, 2012, 01:21:00 PM »
Code: [Select]
       [CommandMethod("ImportMlineStyles", "imls", CommandFlags.Modal | CommandFlags.Session)]
        public void MilneStylesList()
        {
            string filename = "C:\\Test\\Mult.dwg";//<-- change a source drawing name here
            Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
            Database db = HostApplicationServices.WorkingDatabase;
            Editor ed = doc.Editor;

            // define list of string to store multileader style names
            List<string> mstyleList = new List<string>();

            //define boolean variable for future use
            bool result = true;

            // use LockDocument to avoid eLockViolatioException because we're use CommandFlags.Session
            using (DocumentLock docloc = doc.LockDocument())
            {
                // create new database
                using (Database exdb = new Database(false, true))
                {
                    exdb.ReadDwgFile(filename, FileOpenMode.OpenForReadAndAllShare, false, "");
                    //exdb.ReadDwgFile(filename, System.IO.FileShare.Read, True, "")
                    try
                    {
                        ObjectIdCollection ids = new ObjectIdCollection();
                        // Start a transaction
                        using (Transaction tr = db.TransactionManager.StartTransaction())
                        {
                            // Start a source transaction
                            using (Transaction extr = exdb.TransactionManager.StartTransaction())
                            {
                                // Open the MlineStyle dictionary for read
                                DBDictionary dictms = default(DBDictionary);

                                // Open the MlineStyle dictionary for read                             
                                dictms = (DBDictionary)extr.GetObject(exdb.MLStyleDictionaryId, OpenMode.ForRead);

                                // step through the
                                // get every DictionaryEntry in the dictionary

                                foreach (DictionaryEntry id in dictms)
                                {
                                    // Get every object using Objectid then cast DBobject as MlineStyle
                                    MlineStyle mlst = (MlineStyle)extr.GetObject((ObjectId)id.Value, OpenMode.ForRead);
                                    ids.Add((ObjectId)id.Value);
                                    mstyleList.Add(mlst.Name);
                                    // add multileader style name to the list
                                }
                                IdMapping imap = new IdMapping();
                                // Perform WblockCloneObjects method
                                db.WblockCloneObjects(ids, db.MLStyleDictionaryId, imap, DuplicateRecordCloning.Replace, false);
                                // Commit external transaction
                                extr.Commit();
                            }
                            //  Dispose of the external transaction
                            // Commit transaction
                            tr.Commit();
                        }
                        //  Dispose of the  transaction
                        // handling exception

                    }
                    catch (Autodesk.AutoCAD.Runtime.Exception ex)
                    {
                        // Display error message
                        ed.WriteMessage("\n" + ex.Message + "\n" + ex.StackTrace);
                        // set result to false
                        result = false;
                    }
                    finally
                    {
                        if (result)
                        {
                            ed.WriteMessage("\nProgram ended up with: {0}", result);
                            foreach (string ms in mstyleList)
                            {
                                ed.WriteMessage("\n" + ms);
                            }
                        }
                    }
                }
                //  Dispose external database
            }
            //  Dispose of the LockDocument
        }

~'J'~

87
Colors and linetypes / Set color from Pantone color book
« on: May 25, 2012, 07:58:57 AM »
Code: [Select]
       [CommandMethod("TestColorPantone","tcp", CommandFlags.Modal | CommandFlags.UsePickSet | CommandFlags.Redraw)]
        public static void TestPantoneColorBook()
        {
            Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;

            Editor ed = doc.Editor;

            Database db = doc.Database;

            PromptEntityOptions optEnt = new PromptEntityOptions("\nSelect object: ");

            optEnt.SetRejectMessage("\nSelect object only!");

            optEnt.AddAllowedClass(typeof(Entity), false);

            PromptEntityResult res = ed.GetEntity(optEnt);

            if (res.Status != PromptStatus.OK) return;

            ObjectId id = res.ObjectId;

            using (Transaction tr = db.TransactionManager.StartTransaction())
            {
                BlockTableRecord btr = (BlockTableRecord)tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite, false);

                Entity ent = tr.GetObject(id, OpenMode.ForWrite) as Entity;

                // Change color from PANTONE color book, e.g.:

                // ent.Color = Color.FromNames("PANTONE Magenta 2582 C","PANTONE(R) solid coated");

                ent.Color = Color.FromNames("RAL 230 30 15", "RAL DESIGN");// etc...

                tr.Commit();

            }
        }

~'J'~

88
Dimensions / Move dimension text up or down
« on: May 23, 2012, 07:37:45 AM »
   
Code: [Select]
    [CommandMethod("cdimup")]
        public static void TestDimUp()
        {
            Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;

            Editor ed = doc.Editor;

            Database db = HostApplicationServices.WorkingDatabase;

            using (Transaction tr = db.TransactionManager.StartTransaction())
            {
                // Select a dimension

                try
                {

                    PromptEntityOptions peo = new PromptEntityOptions("\nSelect a Dimension >>");
                    peo.SetRejectMessage("\nYou have to select the Dimension only >>");
                    peo.AddAllowedClass(typeof(Dimension), false);
                    PromptEntityResult res;
                    res = ed.GetEntity(peo);
                    if (res.Status != PromptStatus.OK)
                        return;
                    Entity ent = (Entity)tr.GetObject(res.ObjectId, OpenMode.ForRead);
                    if (ent == null)
                        return;
                    Dimension dim = (Dimension)ent as Dimension;
                    if (dim == null) return;

                    if (!dim.IsWriteEnabled) dim.UpgradeOpen();

                    // Add Xdata:

                    dim.XData = new ResultBuffer(

                    new TypedValue((int)DxfCode.ExtendedDataRegAppName, "ACAD"),

                    new TypedValue((int)DxfCode.ExtendedDataAsciiString, "DSTYLE"),

                    new TypedValue((int)DxfCode.ExtendedDataControlString, "{"),

                    new TypedValue((int)DxfCode.ExtendedDataInteger16, 77),

                    new TypedValue((int)DxfCode.ExtendedDataInteger16, 1),

                    new TypedValue((int)DxfCode.ExtendedDataControlString, "}")

                          );

                    dim.DowngradeOpen();

                    tr.Commit();
                }
                catch (System.Exception ex)
                {
                    Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor.WriteMessage(ex.Message);
                }

            }

        }

   
Code: [Select]
    [CommandMethod("cdimdown")]
        public static void TestDimDown()
        {
            Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;

            Editor ed = doc.Editor;

            Database db = HostApplicationServices.WorkingDatabase;

            using (Transaction tr = db.TransactionManager.StartTransaction())
            {
                // Select a dimension

                try
                {

                    PromptEntityOptions peo = new PromptEntityOptions("\nSelect a Dimension >>");
                    peo.SetRejectMessage("\nYou have to select the Dimension only >>");
                    peo.AddAllowedClass(typeof(Dimension), false);
                    PromptEntityResult res;
                    res = ed.GetEntity(peo);
                    if (res.Status != PromptStatus.OK)
                        return;
                    Entity ent = (Entity)tr.GetObject(res.ObjectId, OpenMode.ForRead);
                    if (ent == null)
                        return;
                    Dimension dim = (Dimension)ent as Dimension;
                    if (dim == null) return;

                    if (!dim.IsWriteEnabled) dim.UpgradeOpen();

                    // Add Xdata:

                    dim.XData = new ResultBuffer(

                    new TypedValue((int)DxfCode.ExtendedDataRegAppName, "ACAD"),

                    new TypedValue((int)DxfCode.ExtendedDataAsciiString, "DSTYLE"),

                    new TypedValue((int)DxfCode.ExtendedDataControlString, "{"),

                    new TypedValue((int)DxfCode.ExtendedDataInteger16, 77),

                    new TypedValue((int)DxfCode.ExtendedDataInteger16, 4),

                    new TypedValue((int)DxfCode.ExtendedDataControlString, "}")

                          );

                    dim.DowngradeOpen();
               
                    tr.Commit();
                }
                catch (System.Exception ex)
                {
                    Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor.WriteMessage(ex.Message);
                }

            }

        }

~'J'~

89
Blocks / Replace block and change value of conterminous attributes
« on: May 22, 2012, 06:40:26 PM »
         
Code: [Select]
        [CommandMethod("TestReplace")]
        public static void TestReplaceWithAttributes()
        {
            Database db = HostApplicationServices.WorkingDatabase;
            Document doc = acadApp.DocumentManager.MdiActiveDocument;
            Editor ed = doc.Editor;
            try
            {
            using (Transaction tr = db.TransactionManager.StartTransaction())
            {
                //----------------------------------------------------------
                PromptEntityOptions peo = new PromptEntityOptions("\nSelect the block instance >>");
                peo.SetRejectMessage("\nYou have to select the block instance only >>");
                peo.AddAllowedClass(typeof(BlockReference), false);
                PromptEntityResult res;
                res = ed.GetEntity(peo);
                if (res.Status != PromptStatus.OK)
                    return;
                Entity ent = (Entity)tr.GetObject(res.ObjectId, OpenMode.ForRead);
                if (ent == null)
                    return;
                BlockReference bref = (BlockReference)ent as BlockReference;
                if (bref == null) return;

                //----------------------------------------------------------
                PromptStringOptions pso = new PromptStringOptions("\nEnter a block name to replace : ");
                pso.AllowSpaces = true;
                pso.UseDefaultValue = true;
                pso.DefaultValue = "newblock";//  <---    change a new block name here
                PromptResult stres;
                string repblk = string.Empty;
                stres = ed.GetString(pso);
                if (stres.Status == PromptStatus.OK)
                {
                    repblk = stres.StringResult;
                }
                if (stres.Status == PromptStatus.None)
                {
                    repblk = "newblock";//  <---    change a new block name here
                }
                //----------------------------------------------------------
               
                BlockTable bt = tr.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable;

                if (!bt.Has(repblk)) return;

                BlockTableRecord btrec = null;

                if (bref.IsDynamicBlock)
                {
                    btrec = tr.GetObject(bref.BlockTableRecord, OpenMode.ForRead) as BlockTableRecord;

                    if (btrec.IsAnonymous)
                    {
                        btrec = tr.GetObject(bref.DynamicBlockTableRecord, OpenMode.ForRead) as BlockTableRecord;                 
                    }

                }
                else
                {
                    btrec = tr.GetObject(bref.BlockTableRecord,   OpenMode.ForRead) as BlockTableRecord;   
                }
                //----------------------------------------------------------
               BlockTableRecord btr =  tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite) as BlockTableRecord;
               //----------------------------------------------------------
               Dictionary<string, string> attdic = new Dictionary<string, string>();

               if (btrec.HasAttributeDefinitions)
               {
                 AttributeCollection atts=  bref.AttributeCollection;
                 foreach (ObjectId id in atts)
                 {
                     DBObject obj = tr.GetObject(id, OpenMode.ForRead) as DBObject;
                     AttributeReference atref = obj as AttributeReference;
                     if (atref != null)
                         attdic.Add(atref.Tag.ToUpper(), atref.TextString);
                 }

               }
               //----------------------------------------------------------
               BlockTableRecord newbtrec =  tr.GetObject(bt[repblk], OpenMode.ForRead) as BlockTableRecord;
               Point3d inspt = bref.Position;
               BlockReference newbref = new BlockReference(inspt, bt[repblk]);
               if (!newbref.IsWriteEnabled) newbref.UpgradeOpen();
               newbref.BlockUnit = bref.BlockUnit;
               newbref.Layer = bref.Layer;
               newbref.Rotation = bref.Rotation;
               newbref.ScaleFactors = bref.ScaleFactors;
                btr.AppendEntity(newbref);
                tr.AddNewlyCreatedDBObject(newbref, true);
                //----------------------------------------------------------
                if (attdic.Count > 0)
                {
                    if (newbtrec.HasAttributeDefinitions)
                    {
                        AttributeCollection atcoll = newbref.AttributeCollection;

                        foreach (ObjectId subid in newbtrec)
                        {
                            Entity subent = (Entity)subid.GetObject(OpenMode.ForRead);

                            AttributeDefinition attDef = subent as AttributeDefinition;

                            if (attDef != null)
                            {                               

                                AttributeReference attRef = new AttributeReference();

                                attRef.SetPropertiesFrom(attDef);

                                attRef.Visible = attDef.Visible;

                                attRef.SetAttributeFromBlock(attDef, bref.BlockTransform);

                                attRef.HorizontalMode = attDef.HorizontalMode;

                                attRef.VerticalMode = attDef.VerticalMode;

                                attRef.Rotation = attDef.Rotation;

                                attRef.TextStyle = attDef.TextStyle;//  <---    A2009 syntax

                                attRef.Position = attDef.Position+inspt.GetAsVector();

                                attRef.Tag = attDef.Tag;

                                attRef.FieldLength = attDef.FieldLength;

                                if (attdic.ContainsKey(attRef.Tag.ToUpper()))
                                {
                                    attRef.TextString = attdic[attRef.Tag.ToUpper()];
                                }
                                else
                                {
                                    attRef.TextString = attDef.TextString;
                                }

                                attRef.Justify = attDef.Justify;

                                attRef.AdjustAlignment(db);

                                atcoll.AppendAttribute(attRef);

                                tr.AddNewlyCreatedDBObject(attRef, true);

                            }

                        }
                    }
                }
                //----------------------------------------------------------
                if (!bref.IsWriteEnabled) bref.UpgradeOpen();
                bref.Erase();
                btr.UpdateAnonymousBlocks();
                tr.Commit();
                }
            }
            catch (System.Exception ex)
            {
                ed.WriteMessage("Error:\n{0}\nTrace:\n{1}", ex.Message, ex.StackTrace);
            }
            finally
            {
                //do whatever you need

            }
        }

~'J'~

90
Polylines / Break all Lines
« on: May 21, 2012, 09:30:45 PM »
 
Code: [Select]
      [CommandMethod("bral", CommandFlags.UsePickSet | CommandFlags.Redraw)]
        public static void TestIntersectAllLines()
        {

            Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
            Database db = doc.Database;
            Editor ed = doc.Editor;
            try
            {
                using (Transaction tr = db.TransactionManager.StartTransaction())
                {
                    TypedValue[] tvs = new TypedValue[] { new TypedValue(0, "line") };

                    SelectionFilter sf = new SelectionFilter(tvs);
                    PromptSelectionResult sres = ed.GetSelection(sf);
                    if (sres.Status != PromptStatus.OK)
                    {
                        ed.WriteMessage("\nWrong selection!");
                        return;
                    }

                    if (sres.Value.Count == 0)
                    {
                        ed.WriteMessage("\nNothing selected!");
                        return;
                    }
                    ObjectId[] objs = sres.Value.GetObjectIds();

                    List<ObjectId> rids = new List<ObjectId>();

                    rids.AddRange(objs);

                    BlockTableRecord btr = tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite) as BlockTableRecord;
                    Entity ent = null;

                    foreach (SelectedObject subid in sres.Value)
                    {
                        ent = tr.GetObject(subid.ObjectId, OpenMode.ForRead, false) as Entity;
                        Line ln1 = ent as Line;
                        List<Point3d> points = new List<Point3d>();
                        Point3dCollection pts = new Point3dCollection();
                        foreach (ObjectId id in rids)
                        {
                            if (id == subid.ObjectId)
                                continue;
                            Entity next = tr.GetObject(id, OpenMode.ForRead, false) as Entity;
                            Line ln2 = next as Line;
                            ln1.IntersectWith(ln2, Intersect.OnBothOperands, pts, 0, 0);
                            //ln1.IntersectWith(ln2, Intersect.OnBothOperands, pts, IntPtr.Zero, IntPtr.Zero);// <-- might be other syntax
                        }

                        foreach (Point3d p in pts)
                            points.Add(p);
                        Point3d sp = ln1.StartPoint;
                        Point3d ep = ln1.EndPoint;
                        if (!points.Contains(sp))
                            points.Add(sp);
                        if (!points.Contains(ep))
                            points.Add(ep);

                        points.Sort(delegate(Point3d a, Point3d b)
                        {
                            return Convert.ToInt32(
                                    Convert.ToDouble(sp.DistanceTo(a).CompareTo(
                       Convert.ToDouble(sp.DistanceTo(b)))));
                        }
                        );

                        for (int n = 0; n < points.Count - 1; n++)
                        {
                            Line lin = new Line(points[n], points[n + 1]);
                            lin.SetPropertiesFrom(ln1);
                            lin.ColorIndex = n;
                            btr.AppendEntity(lin);
                            tr.AddNewlyCreatedDBObject(lin, true);
                        }

                    }
                    foreach (SelectedObject subid in sres.Value)
                    {
                        ent = tr.GetObject(subid.ObjectId, OpenMode.ForRead) as Entity;
                        if (!ent.IsWriteEnabled)
                            ent.UpgradeOpen();
                        ent.Erase();
                    }
                    tr.Commit();
                }
            }
            catch (System.Exception ex)
            {
                ed.WriteMessage(ex.Message + "\n" + ex.StackTrace);
            }
        }

~'J'~

Pages: 1 ... 4 5 [6] 7