コード例 #1
0
        public static void SelectInsideCommand()
        {
            var _e = new Point3d(double.MinValue, double.MinValue, double.MinValue);

            try {
                var options = new PromptEntityOptions("\nSelect a point on a polyline: ");
                options.SetRejectMessage("Invalid Object.");
                options.AddAllowedClass(typeof(Curve), false);
                options.AllowObjectOnLockedLayer = false;

                var result = Quick.Editor.GetEntity(options);
                if (result.Status != PromptStatus.OK)
                {
                    return;
                }
                var curveId = result.ObjectId;

                using (var tr = new QuickTransaction()) {
                    var ent = (Polyline)tr.GetObject(curveId, OpenMode.ForRead, false);
                    var c   = Quick.Editor.SelectAll().Value.GetObjectIds().Select(o => tr.GetObject(o, OpenMode.ForRead, true)).Where(o => ent.IsInsidePolygon(o.GetPosition(_e))).ToArray();
                    c.SetSelected();
                    //ent.BreakOnPoint(result.PickedPoint.ToPoint2D(), tr, true).SetSelected();
                }
            } catch (Autodesk.AutoCAD.Runtime.Exception ex) {
                Application.ShowAlertDialog(ex.Message + "\n" + ex.StackTrace);
            }
        }
コード例 #2
0
        public void ToTransactionTest()
        {
            var categoryFactory = new RegularCategoryFactory();
            var accountFactory  = new RegularAccountFactory();

            var quickTransaction = new QuickTransaction
            {
                Account = accountFactory.CreateAccount(
                    "TestAccount", "Description", "USD"),
                Category     = categoryFactory.CreateCategory("TestAccount", "Description", 0L, null),
                Name         = "TestName",
                AskForWeight = false,
                AskForTotal  = false,
                Total        = 2.34m,
                Weight       = 1
            };

            var transaction =
                QuickTransactionConverter.ToTransaction(new RegularTransactionFactory(), quickTransaction);

            Assert.AreEqual(quickTransaction.Account, transaction.Account);
            Assert.AreEqual(quickTransaction.Category, transaction.Category);
            Assert.AreEqual(quickTransaction.Total, transaction.Total);
            Assert.AreEqual(quickTransaction.Weight, transaction.Weight);
            Assert.AreEqual(quickTransaction.Name, transaction.Name);
        }
コード例 #3
0
        public static void ApplyAttributes(Database db, QuickTransaction tr, BlockReference bref)
        {
            if (bref == null)
            {
                return;
            }
            var _brec = tr.GetObject(bref.BlockTableRecord, OpenMode.ForRead);
            var btrec = _brec as BlockTableRecord;

            if (btrec == null)
            {
                return;
            }
            if (btrec.HasAttributeDefinitions)
            {
                var atcoll = bref.AttributeCollection;
                foreach (var subid in btrec)
                {
                    var ent    = (Entity)subid.GetObject(OpenMode.ForRead);
                    var attDef = ent as AttributeDefinition;
                    if (attDef != null)
                    {
                        var attRef = new AttributeReference();
                        attRef.SetDatabaseDefaults(); //optional
                        attRef.SetAttributeFromBlock(attDef, bref.BlockTransform);
                        attRef.Position = attDef.Position.TransformBy(bref.BlockTransform);
                        attRef.Tag      = attDef.Tag;
                        attRef.AdjustAlignment(db);
                        atcoll.AppendAttribute(attRef);
                        tr.AddNewlyCreatedDBObject(attRef, true);
                    }
                }
            }
        }
コード例 #4
0
        public static void LineToPoly(this QuickTransaction tr, PromptSelectionResult psRes = null)
        {
            var psOpts = new PromptSelectionOptions();

            psOpts.MessageForAdding  = "\nSelect lines to convert: ";
            psOpts.MessageForRemoval = "\n...Remove lines: ";
            TypedValue[] filter   = { new TypedValue(0, "LINE") };
            var          ssfilter = new SelectionFilter(filter);

            psRes = (psRes?.Status == PromptStatus.OK ? psRes : null) ?? tr.GetSelection(psOpts, ssfilter);
            if (psRes.Status != PromptStatus.OK)
            {
                return;
            }
            foreach (var id in psRes.Value.GetObjectIds())
            {
                var line = (Line)tr.GetObject(id, OpenMode.ForWrite);
                var poly = new Polyline();
                poly.AddVertexAt(0, new Point2d(line.StartPoint.X, line.StartPoint.Y), 0, 0, 0);
                poly.AddVertexAt(1, new Point2d(line.EndPoint.X, line.EndPoint.Y), 0, 0, 0);
                poly.LayerId = line.LayerId;
                tr.BlockTableRecordCurrentSpace.AppendEntity(poly);
                tr.AddNewlyCreatedDBObject(poly, true);
                line.Erase();
            }
        }
コード例 #5
0
 /// <summary>
 ///     Checks if entity is writable, if not - calls <see cref="QuickTransaction.GetObject"/> and returns writable one.
 /// </summary>
 public static T EnsureWritable <T>(this QuickTransaction tr, T entity) where T : Entity
 {
     if (!entity.IsWriteEnabled)
     {
         entity = (T)tr.GetObject(entity.ObjectId, OpenMode.ForWrite);
     }
     return(entity);
 }
コード例 #6
0
        public static Polyline SplineToPoly(this QuickTransaction tr, Spline c)
        {
            var p = c.ToPolyline();

            tr.BlockTableRecordCurrentSpace.AppendEntity(p);
            tr.AddNewlyCreatedDBObject(p, true);
            c.Erase();
            return((Polyline)p);
        }
コード例 #7
0
        public static Entity[] BreakOnPoint(this Curve ent, Point2d at, QuickTransaction tr, bool commitAtEnd = false)
        {
            if (ent == null)
            {
                throw new ArgumentNullException(nameof(ent));
            }
            if (tr == null)
            {
                throw new ArgumentNullException(nameof(tr));
            }
            try {
                var     btr = (BlockTableRecord)tr.GetObject(tr.Db.CurrentSpaceId, OpenMode.ForWrite);
                Point3d att = at.ToPoint3D();
                att.TransformBy(tr.Editor.CurrentUserCoordinateSystem.Inverse());
                // Check that the point is on the curve
                att = ent.GetClosestPointTo(att, false);
                var breakPoints = new Point3dCollection();
                var newCurves   = new DBObjectCollection();
                // Get the segments according to the trim points
                breakPoints.Add(att);
                newCurves = ent.GetSplitCurves(breakPoints);
                if (newCurves == null)
                {
                    tr.Editor.WriteMessage("\nGetSplitCurves failed :  Error");
                    return(new Entity[0]);
                }
                var ret = new List <Entity>();

                // Here we add the segments to the database with different colors
                for (var i = 0; i < newCurves.Count; i++)
                {
                    var pent = (Entity)newCurves[i];
                    pent.SetPropertiesFrom(ent);
                    btr.AppendEntity(pent);
                    tr.AddNewlyCreatedDBObject(pent, true);
                    ret.Add(pent);
                }

                ent.UpgradeOpen();
                ent.Erase();
                if (commitAtEnd)
                {
                    tr.Commit();
                }
                return(ret.ToArray());
            } catch (Exception ex) {
                Autodesk.AutoCAD.ApplicationServices.Core.Application.ShowAlertDialog(ex.Message + "\n" + ex.StackTrace);
                return(new Entity[0]);
            } finally { }
        }
コード例 #8
0
        public static Polyline ArcToPoly(this QuickTransaction tr, Arc arc)
        {
            var btr = tr.BlockTableRecordCurrentSpace;

            arc = tr.EnsureWritable(arc);
            var poly = new Polyline();

            poly.AddVertexAt(0, new Point2d(arc.StartPoint.X, arc.StartPoint.Y), arc.GetArcBulge(), 0, 0);
            poly.AddVertexAt(1, new Point2d(arc.EndPoint.X, arc.EndPoint.Y), 0, 0, 0);
            poly.LayerId = arc.LayerId;
            btr.AppendEntity(poly);
            tr.AddNewlyCreatedDBObject(poly, true);
            arc.Erase();
            return(poly);
        }
コード例 #9
0
        public static Polyline ConvertToPolyline(this Polyline2d pl2d, QuickTransaction tr)
        {
            var mSpace = (BlockTableRecord)SymbolUtilityServices.GetBlockModelSpaceId(tr.Db).GetObject(OpenMode.ForWrite);

            if (pl2d.PolyType == Poly2dType.CubicSplinePoly || pl2d.PolyType == Poly2dType.QuadSplinePoly)
            {
                return(null);
            }
            var pline = new Polyline();

            pline.ConvertFrom(pl2d, false);
            mSpace.AppendEntity(pline);
            tr.AddNewlyCreatedDBObject(pline, true);
            pl2d.Erase();
            return(pline);
        }
コード例 #10
0
        public IQuickTransaction CreateQuickTransaction(IAccount account, ICategory category,
                                                        string name, decimal total, long id, decimal weight, bool askForTotal, bool askForWeight)
        {
            var quickTransaction = new QuickTransaction
            {
                Id           = id,
                Account      = account,
                Category     = category,
                Name         = name,
                Total        = total,
                Weight       = weight,
                AskForTotal  = askForTotal,
                AskForWeight = askForWeight
            };

            return(quickTransaction);
        }
コード例 #11
0
        public void ToTransactionIncompleteAccountTransactionTest()
        {
            var categoryFactory  = new RegularCategoryFactory();
            var quickTransaction = new QuickTransaction
            {
                Category     = categoryFactory.CreateCategory("TestAccount", "Description", 0L, null),
                Name         = "TestName",
                AskForWeight = false,
                AskForTotal  = false,
                Total        = 2.34m,
                Weight       = 1
            };

            var result = QuickTransactionValidator.IsRequireInteractionForTransaction(quickTransaction);

            Assert.IsTrue(result, "Interaction required");
        }
コード例 #12
0
        public static void SelectInsideIntersectCommand()
        {
            var _e = new Point3d(double.MinValue, double.MinValue, double.MinValue);

            try {
                var imp = Quick.GetImpliedOrSelect();
                if (imp == null)
                {
                    Quick.WriteLine("[sii] No objects were selected.");
                    return;
                }
                var options = new PromptEntityOptions("\nSelect a point on a polyline: ");
                options.SetRejectMessage("Invalid Object.");
                options.AddAllowedClass(typeof(Curve), false);
                options.AllowObjectOnLockedLayer = false;

                var result = Quick.Editor.GetEntity(options);
                if (result.Status != PromptStatus.OK)
                {
                    return;
                }
                var curveId = result.ObjectId;

                using (var tr = new QuickTransaction()) {
                    var pl = (Polyline)tr.GetObject(curveId, OpenMode.ForRead, false);
                    var c  = imp.GetObjectIds()
                             .Select(o => tr.GetObject(o, OpenMode.ForRead, true))
                             .AreInsidePolyline(tr, pl)
                             .ToArray()
                             .ToSelectionSet()
                             .SetSelected();

                    /*var rest = c.Cast<DBObject>()
                     *  .IntersectBy(imp.Cast<SelectedObject>().Select(o=>tr.GetObject(o.ObjectId,false)).ToArray(), o => o.ObjectId.Handle.Value)
                     *  .Select(o => o.ObjectId)
                     *  .ToSelectionSet(SelectionMethod.Crossing)
                     *  .SetSelected();
                     */
                    //ent.BreakOnPoint(result.PickedPoint.ToPoint2D(), tr, true).SetSelected();
                }
            } catch (Autodesk.AutoCAD.Runtime.Exception ex) {
                Autodesk.AutoCAD.ApplicationServices.Core.Application.ShowAlertDialog(ex.Message + "\n" + ex.StackTrace);
            }
        }
コード例 #13
0
        public static void WidthCommand()
        {
            var set = Quick.GetImpliedOrSelect();

            if (set == null || set.Count == 0)
            {
                Quick.WriteLine($"[{Quick.CurrentCommand}] No objects were selected.");
                return;
            }

            using (var tr = new QuickTransaction()) {
                var col = set.GetObjectIds().Select(o => tr.GetObject(o, true)).ToArray();
                var dbl = Quick.Editor.GetDouble(new PromptDoubleOptions("Please select width: ")
                {
                    AllowNegative = false, DefaultValue = Quick.Bag.Get("[w]width", 0.4d)
                });
                if (dbl.Status != PromptStatus.OK)
                {
                    Quick.WriteLine($"[{Quick.CurrentCommand}] Failed selecting double.");
                    return;
                }
                var val = (double)(Quick.Bag["[w]width"] = dbl.Value);
                //tr.Command("_.pedit", "_m", set, "_n", "_w", dbl.Value.ToString(), "");
                for (var i = 0; i < col.Length; i++)
                {
                    var e  = col[i];
                    var ee = e;
                    if (ee is Polyline2d)
                    {
                        ee     = ee.ConvertToPolyline(tr);
                        col[i] = ee;
                    }
                    if (ee is Polyline == false)
                    {
                        continue;
                    }
                    ((Polyline)ee).SetGlobalWidth(val);
                }
                tr.Commit();
            }
        }
コード例 #14
0
 public static void MRotateCommand()
 {
     using (var tr = new QuickTransaction()) {
         // objects initializing
         var nomutt = Convert.ToInt32(Autodesk.AutoCAD.ApplicationServices.Core.Application.GetSystemVariable("nomutt"));
         try {
             // Get the current document and database
             // Start a transaction
             // Open the Block table for read
             var _sel = Quick.GetImpliedOrSelect();
             if (_sel == null || _sel.Count == 0)
             {
                 tr.Editor.WriteMessage("Nothing was selected.");
                 return;
             }
             var howmuch = tr.Editor.GetAngle("How many degrees (Anti Clockwise) to add (Negative will go Clockwise)");
             if (howmuch.Status == PromptStatus.Cancel)
             {
                 return;
             }
             var curUCSMatrix = tr.Doc.Editor.CurrentUserCoordinateSystem;
             var curUCS       = curUCSMatrix.CoordinateSystem3d;
             foreach (SelectedObject o in _sel)
             {
                 var obj    = (BlockReference)tr.GetObject(o.ObjectId) ?? throw new NullReferenceException("obj");
                 var matrix = Matrix3d.Rotation(howmuch.Value, curUCS.Zaxis, obj.Position);
                 obj.TransformBy(matrix);
             }
             // Add the new object to the block table record and the transaction
             // Save the new objects to the database
             tr.Commit();
             Quick.SetSelected(_sel);
         } catch (Exception ex) {
             Quick.WriteLine(ex.Message + "\n" + ex.StackTrace);
         } finally {
             Autodesk.AutoCAD.ApplicationServices.Core.Application.SetSystemVariable("nomutt", nomutt);
         }
     }
 }
コード例 #15
0
        public static void BreakOnPointCommand()
        {
            try {
                var options = new PromptEntityOptions("\nSelect a point on a polyline: ");
                options.SetRejectMessage("Invalid Object.");
                options.AddAllowedClass(typeof(Curve), false);
                options.AllowObjectOnLockedLayer = false;

                var result = Quick.Editor.GetEntity(options);
                if (result.Status != PromptStatus.OK)
                {
                    return;
                }
                var curveId = result.ObjectId;

                using (var tr = new QuickTransaction()) {
                    var ent = (Curve)tr.GetObject(curveId, OpenMode.ForRead, false);
                    ent.BreakOnPoint(result.PickedPoint.ToPoint2D(), tr, true).SetSelected();
                }
            } catch (Autodesk.AutoCAD.Runtime.Exception ex) {
                Autodesk.AutoCAD.ApplicationServices.Core.Application.ShowAlertDialog(ex.Message + "\n" + ex.StackTrace);
            }
        }
コード例 #16
0
        public static Polyline CircleToPoly(this QuickTransaction tr, Circle c)
        {
            var r = c.Radius;

            new Ellipse();
            var top       = c.Center.Add(new Vector3d(0, r, 0));
            var bottom    = c.Center.Add(new Vector3d(0, -r, 0));
            var right     = c.Center.Add(new Vector3d(r, 0, 0));
            var left      = c.Center.Add(new Vector3d(-r, 0, 0));
            var right_cir = new CircularArc3d(bottom, right, top);
            var left_cir  = new CircularArc3d(top, left, bottom);
            var poly      = new Polyline();

            poly.AddVertexAt(0, new Point2d(right_cir.StartPoint.X, right_cir.StartPoint.Y), right_cir.GetArcBulge(), 0, 0);
            poly.AddVertexAt(1, new Point2d(right_cir.EndPoint.X, right_cir.EndPoint.Y), 0, 0, 0);
            poly.AddVertexAt(2, new Point2d(left_cir.StartPoint.X, left_cir.StartPoint.Y), left_cir.GetArcBulge(), 0, 0);
            poly.AddVertexAt(3, new Point2d(left_cir.EndPoint.X, left_cir.EndPoint.Y), 0, 0, 0);
            poly.LayerId = c.LayerId;
            tr.BlockTableRecordCurrentSpace.AppendEntity(poly);
            tr.AddNewlyCreatedDBObject(poly, true);
            c.Erase();
            return(poly);
        }
コード例 #17
0
 public static Polyline ConvertToPolyline(this QuickTransaction tr, ObjectId id)
 {
     return(ConvertToPolyline(tr, tr.GetObject(id, OpenMode.ForWrite) as Entity ?? throw new InvalidOperationException("The given object id is not an entity!")));
 }
コード例 #18
0
 public static Entity GetObject(this ObjectId id, QuickTransaction tr, bool writable = true)
 {
     return(GetObject(tr, id, writable));
 }
コード例 #19
0
 public static SelectionSet GetImpliedOrSelect(this QuickTransaction tr)
 {
     return(Quick.GetImpliedOrSelect());
 }
コード例 #20
0
 public static void SetSelected(this QuickTransaction tr, SelectionSet ss, bool runsssetfirst = false)
 {
     Quick.SetSelected(ss, runsssetfirst);
 }
コード例 #21
0
 public static SelectionSet GetImpliedOrSelect(this QuickTransaction tr, PromptSelectionOptions f, SelectionFilter ff)
 {
     return(Quick.GetImpliedOrSelect(f, ff));
 }
コード例 #22
0
 public static SelectionSet GetImpliedOrSelect(this QuickTransaction tr, SelectionFilter f)
 {
     return(Quick.GetImpliedOrSelect(f));
 }
コード例 #23
0
        public static IEnumerable <DBObject> AreInsidePolyline(this IEnumerable <DBObject> objs, QuickTransaction tr, Polyline pl)
        {
            Point3dCollection pntCol = new Point3dCollection();

            for (int i = 0; i < pl.NumberOfVertices - 1; i++)
            {
                pntCol.Add(pl.GetPoint3dAt(i));
            }

            int numOfEntsFound = 0;
            //new PointCollector();
            var pmtSelRes = Quick.Editor.SelectWindowPolygon(pntCol);

            if (pmtSelRes.Status != PromptStatus.OK)
            {
                yield break;
            }
            // May not find entities in the UCS area
            // between p1 and p3 if not PLAN view
            // pmtSelRes =
            //    ed.SelectCrossingWindow(p1, p3, selFilter);
            var _objs = objs.ToArray();

            if (pmtSelRes.Status == PromptStatus.OK)
            {
                foreach (ObjectId objId in pmtSelRes.Value.GetObjectIds())
                {
                    numOfEntsFound++;
                    if (_objs.Any(o => o.ObjectId.Handle.Value == objId.Handle.Value))
                    {
                        yield return(tr.GetObject(objId, false));
                    }
                }
                Quick.Editor.WriteMessage("Entities found " + numOfEntsFound.ToString());
            }
            else
            {
                Quick.Editor.WriteMessage("\nDid not find entities");
            }
        }
コード例 #24
0
 public static IEnumerable <DBObject> AreInsidePolyline(this IEnumerable <ObjectId> objs, QuickTransaction tr, Polyline pl)
 {
     return(AreInsidePolyline(objs.Select(o => tr.GetObject(o, OpenMode.ForRead)), tr, pl));
 }
コード例 #25
0
 public static Polyline ConvertToPolyline(this Entity id, QuickTransaction tr)
 {
     return(ConvertToPolyline(tr, id));
 }
コード例 #26
0
        public static void AddCurveCommand()
        {
            double GetAngle(Point2d a, Point2d b)
            {
                double xDiff = b.X - a.X;
                double yDiff = b.Y - a.Y;

                return(Math.Atan2(yDiff, xDiff) * 180.0d / Math.PI);
            }

            try {
                var options = new PromptEntityOptions("\nSelect a point on a polyline: ");
                options.SetRejectMessage("Invalid Object.");
                options.AddAllowedClass(typeof(Polyline), true);
                options.AddAllowedClass(typeof(Polyline2d), true);
                options.AddAllowedClass(typeof(Polyline3d), true);

                var result = Quick.Editor.GetEntity(options);
                if (result.Status != PromptStatus.OK)
                {
                    return;
                }
                var lineId    = result.ObjectId;
                var pickpoint = result.PickedPoint.ToPoint2D();
                var qtarget   = Quick.Editor.GetPoint(new PromptPointOptions("Pick the strech point.")
                {
                    AllowNone = false, BasePoint = pickpoint.ToPoint3D(), UseBasePoint = true, UseDashedLine = true
                });
                if (qtarget.Status != PromptStatus.OK)
                {
                    return;
                }
                var target = qtarget.Value.ToPoint2D();
                using (var tr = new QuickTransaction()) {
                    try {
                        var poly = (Curve)tr.GetObject(lineId, OpenMode.ForWrite);
                        if (poly is Polyline2d)
                        {
                            poly = poly.ConvertToPolyline(tr);
                        }
                        if (poly is Polyline3d)
                        {
                            throw new InvalidCastException("Can't be applied on polyline of type Polyline3d.");
                        }
                        var distance = target.GetDistanceTo(pickpoint);

                        var pointRight = poly.OffsetToEnd(result.PickedPoint, distance);
                        var pointLeft  = poly.OffsetToStart(result.PickedPoint, distance);
                        if (!pointRight.Item2 || !pointLeft.Item2)
                        {
                            return;
                        }

                        var rightcut = poly.BreakOnPoint(pointRight.Item1, tr, false);
                        poly = (Polyline)rightcut[0];  //right poly
                        var rightpoly = (Polyline)rightcut[1];
                        var leftcut   = poly.BreakOnPoint(pointLeft.Item1, tr, false);
                        var leftpoly  = (Polyline)leftcut[0];
                        leftcut[1].UpgradeOpen();
                        leftcut[1].Erase();

                        var buldge = Math.Tan((90d * 0.85 * Deg2Rad) / 4);
                        leftpoly.AddVertexAt(leftpoly.NumberOfVertices, target, 0, leftpoly.GetStartWidthAt(leftpoly.NumberOfVertices - 1), leftpoly.GetEndWidthAt(leftpoly.NumberOfVertices - 1));
                        leftpoly.SetBulgeAt(leftpoly.NumberOfVertices - 2, buldge);
                        rightpoly.AddVertexAt(0, target, buldge, leftpoly.GetStartWidthAt(0), leftpoly.GetEndWidthAt(0));

                        void setdir(bool right)
                        {
                            if (right)
                            {
                                leftpoly.SetBulgeAt(leftpoly.NumberOfVertices - 2, buldge);
                                rightpoly.SetBulgeAt(0, buldge);
                            }
                            else
                            {
                                leftpoly.SetBulgeAt(leftpoly.NumberOfVertices - 2, -buldge);
                                rightpoly.SetBulgeAt(0, -buldge);
                            }
                        }

                        setdir(Settings.addcurve_direction as bool? ?? true);

                        tr.Transaction.TransactionManager.QueueForGraphicsFlush();

                        // ReSharper disable once AssignmentInConditionalExpression
                        var ask = (bool?)Quick.AskQuestion("Reverse Direction?", false) ?? false;
                        if (ask)
                        {
                            Settings.addcurve_direction = !(Settings.addcurve_direction as bool? ?? false);
                            setdir(Settings.addcurve_direction);
                        }
                        tr.Transaction.TransactionManager.QueueForGraphicsFlush();


                        // ReSharper disable once AssignmentInConditionalExpression
                        if (Settings["addcurve_join"] = Quick.AskQuestion("Join Polylines?", (Settings["addcurve_join"]) ?? !true))
                        {
                            new[] { leftpoly.Join(rightpoly, tr) }.SetSelected();
                        }
                        else
                        {
                            new[] { leftpoly, rightpoly }.SetSelected();
                        }
                        tr.Commit();
                    } catch (Exception ex) {
                        Quick.WriteLine(ex.Message + "\n" + ex.StackTrace);
                    }
                }
            } catch (Exception ex) {
                Quick.WriteLine(ex.Message + "\n" + ex.StackTrace);
            }
        }
コード例 #27
0
        public static void MagicReplaceCommand()
        {
            // objects initializing
            var nomutt = Convert.ToInt32(Autodesk.AutoCAD.ApplicationServices.Core.Application.GetSystemVariable("nomutt"));
            var doc    = Autodesk.AutoCAD.ApplicationServices.Core.Application.DocumentManager.MdiActiveDocument;
            var ed     = doc.Editor;
            var db     = doc.Database;

            try {
                using (doc.LockDocument()) {
                    using (var tr = new QuickTransaction()) {
                        var toreplace = tr.GetImpliedOrSelect(new PromptSelectionOptions());
                        if (toreplace == null)
                        {
                            return;
                        }
                        ed.WriteMessage("\nSelect destinion block: ");
                        var totype = Quick.SelectSingle();
                        ed.WriteMessage("\n");
                        if (totype == null)
                        {
                            return;
                        }
                        var masterblock = (BlockTableRecord)tr.GetObject(((BlockReference)tr.GetObject(totype ?? ObjectId.Null, OpenMode.ForWrite)).BlockTableRecord, OpenMode.ForRead);
                        var bt          = tr.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable;
                        var @new        = bt[masterblock.Name];
                        Autodesk.AutoCAD.ApplicationServices.Core.Application.SetSystemVariable("nomutt", 0);
                        var notparsed = 0;
                        var flattern  = false;
                        var objs      = toreplace.Cast <SelectedObject>().Select(o => tr.GetObject(o.ObjectId, OpenMode.ForRead) as Entity).ToArray();
                        if (objs.Any(o => (o as BlockReference)?.Position.Z > 0))
                        {
                            flattern = Quick.AskQuestion("Should flattern blocks with Z value", true) ?? false;
                        }
                        var os = new List <ObjectId>();
                        foreach (var ent in objs)
                        {
                            var oldblk = ent as BlockReference;
                            if (oldblk == null)
                            {
                                //not block..
                                notparsed++;
                                continue;
                            }
                            var p      = oldblk.Position;
                            var ip     = flattern ? new Point3d(p.X, p.Y, 0) : p;
                            var scl    = oldblk.ScaleFactors;
                            var rot    = oldblk.Rotation;
                            var newblk = new BlockReference(ip, @new);
                            newblk.SetPropertiesFrom(ent);
                            newblk.Rotation     = rot;
                            newblk.ScaleFactors = scl;
                            tr.BlockTableRecordCurrentSpace.AppendEntity(newblk);
                            tr.AddNewlyCreatedDBObject(newblk, true);
                            ApplyAttributes(db, tr, newblk);
                            oldblk.UpgradeOpen();
                            oldblk.Erase();
                            oldblk.Dispose();
                            os.Add(newblk.ObjectId);
                        }
                        Autodesk.AutoCAD.ApplicationServices.Core.Application.SetSystemVariable("nomutt", 1);
                        tr.Commit();
                        if (notparsed > 0)
                        {
                            ed.WriteMessage($"{notparsed} are not blocks and were not replaced.\n");
                        }
                        ed.WriteMessage($"{toreplace.Count} were replaced to block {masterblock.Name} successfully.\n");
                        Quick.SetSelected(os.ToArray());
                    }
                }
            } catch (Exception ex) {
                ed.WriteMessage(ex.Message + "\n" + ex.StackTrace);
            } finally {
                Autodesk.AutoCAD.ApplicationServices.Core.Application.SetSystemVariable("nomutt", nomutt);
            }
        }
コード例 #28
0
 public static Entity GetObject(this QuickTransaction tr, ObjectId id, bool writable = true)
 {
     return((Entity)tr.GetObject(id, writable ? OpenMode.ForWrite : OpenMode.ForRead));
 }
コード例 #29
0
 /// <summary>
 ///     Checks if entity is writable, if not - calls <see cref="QuickTransaction.GetObject"/> and returns writable one.
 /// </summary>
 public static T EnsureWritable <T>(this T entity, QuickTransaction tr) where T : Entity
 {
     return(EnsureWritable(tr, entity)); //overload...
 }
コード例 #30
0
 public static Polyline EllipseToPoly(this QuickTransaction tr, Ellipse c)
 {
     return(null);
 }