public static bool EraseBlk(ObjectId blkId)
        {
            bool blkIsErased = false;

            if (blkId.IsNull)
            {
                return(false);
            }

            Database db = blkId.Database;

            if (db == null)
            {
                return(false);
            }

            using (Transaction tr = db.TransactionManager.StartTransaction())
            {
                BlockTableRecord blk = (BlockTableRecord)tr.GetObject(blkId, OpenMode.ForRead);
                var blkRefs          = blk.GetBlockReferenceIds(true, true);
                if (blkRefs == null || blkRefs.Count == 0)
                {
                    blk.UpgradeOpen();
                    blk.Erase();
                    blkIsErased = true;
                }
                tr.Commit();
            }
            return(blkIsErased);
        }
Ejemplo n.º 2
0
        private void DeleteBlocksWithPrefix(string prefix, Transaction tr)
        {
            BlockTable blockTable = tr.GetObject(Doc.Database.BlockTableId, OpenMode.ForRead) as BlockTable;

            foreach (ObjectId blockId in blockTable)
            {
                BlockTableRecord block = (BlockTableRecord)tr.GetObject(blockId, OpenMode.ForRead);
                if (block.Name.StartsWith(prefix))
                {
                    block.UpgradeOpen();
                    block.Erase();
                }
            }
        }
Ejemplo n.º 3
0
        // Erase the anonymous blocks referenced by an object

        private static void EraseReferencedAnonBlocks(
            Transaction tr, DBObject obj
            )
        {
            var refFiler = new ReferenceFiler();

            obj.DwgOut(refFiler);

            // Loop through the references and erase any
            // anonymous block definitions
            //
            foreach (ObjectId refid in refFiler.HardPointerIds)
            {
                BlockTableRecord btr =
                    tr.GetObject(refid, OpenMode.ForRead) as BlockTableRecord;
                if (btr != null && btr.IsAnonymous)
                {
                    btr.UpgradeOpen();
                    btr.Erase();
                }
            }
        }
        private void _createBlockRecord(string name, AnnotativeStates annotativeState, Point3d origin, bool eraseSource = true)
        {
            BlockTableRecord btr = new BlockTableRecord();

            btr.Name       = name;
            btr.Origin     = origin;
            btr.Annotative = annotativeState;

            if (eraseSource)
            {
                Tools.StartTransaction(() =>
                {
                    if (_blockRecordId != ObjectId.Null)
                    {
                        BlockTableRecord btrOld = _blockRecordId.GetObjectForWrite <BlockTableRecord>();
                        btrOld.Erase();
                    }
                });
            }

            Tools.StartTransaction(() =>
            {
                var bt = _db.BlockTableId.GetObjectForWrite <BlockTable>(false);

                bt.UpgradeOpen();
                ObjectId btrId = bt.Add(btr);

                _db.TransactionManager.TopTransaction.AddNewlyCreatedDBObject(btr, true);
                this._blockRecordId = btrId;

                foreach (Entity ent in _entities)
                {
                    btr.AppendEntity(ent);
                    _db.TransactionManager.TopTransaction.AddNewlyCreatedDBObject(ent, true);
                }
            });
        }
Ejemplo n.º 5
0
        public void _drawGridCartogramma()
        {
            double step = 20d;


            //Polyline3d border = null;

            /*ObjectId surfaceId = CivilSurfaces.SurfaceTools.PromptForTinSurface("\nУкажитье поверхность: ");
             * if (surfaceId.IsNull)
             *  return;
             * Tools.StartTransaction(() =>
             * {
             *  TinSurface surface = surfaceId.GetObjectForRead<CivilSurface>() as TinSurface;
             *  if (surface == null)
             *      return;
             *  var borders = surface.ExtractBorders().Select(l => (Polyline3d)l.Clone());
             *  //borders.SaveToDatebase();
             *  border = borders.First();
             * });*/

            Polyline border;

            if (!ObjectCollector.TrySelectAllowedClassObject(out border))
            {
                return;
            }

            if (border == null)
            {
                return;
            }

            border = border.Id.Open(OpenMode.ForRead).Clone() as Polyline;

            Matrix3d ucs = Tools.GetAcadEditor().CurrentUserCoordinateSystem;

            border.TransformBy(ucs);
            Extents3d bounds = border.Bounds.Value;

            Vector3d hVector = Matrix3d.Identity.CoordinateSystem3d.Xaxis.MultiplyBy((bounds.MaxPoint - bounds.MinPoint).X);
            Vector3d vVector = Matrix3d.Identity.CoordinateSystem3d.Yaxis.MultiplyBy((bounds.MaxPoint - bounds.MinPoint).Y);

            Polyline polygon = border; /*border.ConvertToPolyline();*/

            //((Entity)polygon.Clone()).SaveToDatebase();

            ObjectId btrId = ObjectId.Null;
            ObjectId brId  = ObjectId.Null;

            List <Entity>    rectgs        = null;
            CartogrammLabels labelsFactory = null;

            Action <Point3d> transformProcessor = startPoint =>
            {
                gride         = new SimpleGride(/*bounds.MinPoint*/ startPoint, vVector, hVector, step, step);
                labelsFactory = new CartogrammLabels(gride);

                int rowsCount   = SimpleGride.CalculateCeilingCount(vVector, step);
                int columnCount = SimpleGride.CalculateCeilingCount(hVector, step);

                rectgs = new List <Entity>(rowsCount * columnCount);
                for (int r = 0; r < rowsCount; r++)
                {
                    for (int c = 0; c < columnCount; c++)
                    {
                        Polyline line = gride.CalculateRectagle(r, c, polygon, true);
                        if (line != null)
                        {
                            line.TransformBy(ucs.Inverse());
                            rectgs.Add(line);
                        }

                        /*if (r == 0)
                         * {
                         *  var labels = labelsFactory.CreateTableColumn(c);
                         *  if (labels != null)
                         *      rectgs.AddRange(labels.Select(x => (Polyline)x.GetTransformedCopy(ucs.Inverse())));
                         * }*/
                    }
                }

                labelsFactory.CreateTeble(columnCount);
                for (int i = 0; i < columnCount; i++)
                {
                    labelsFactory.SetValueToField(i, (IgorKL.ACAD3.Model.Helpers.Math.Randoms.RandomGen.NextDouble() - 0.5) * 10000d, labelsFactory.TopRow);
                }

                if (!btrId.IsNull)
                {
                    Tools.StartTransaction(() =>
                    {
                        BlockTableRecord btr = btrId.GetObjectForWrite <BlockTableRecord>();
                        foreach (var id in btr)
                        {
                            Entity ent = id.GetObjectForWrite <DBObject>() as Entity;
                            if (ent != null)
                            {
                                ent.Erase(true);
                            }
                        }
                        BlockReference br = brId.GetObjectForWrite <BlockReference>();
                        br.Erase(true);
                        btr.Erase(true);

                        btrId = AcadBlocks.BlockTools.CreateBlockTableRecord("*U", startPoint.TransformBy(ucs.Inverse()), rectgs.Cast <Entity>(), AnnotativeStates.NotApplicable, false);
                        brId  = AcadBlocks.BlockTools.AppendBlockItem(startPoint.TransformBy(ucs.Inverse()), btrId, null);
                    }
                                           );
                }
            };

            transformProcessor(bounds.MinPoint);

            var points = labelsFactory._getGridElevationPoints(rectgs.Cast <Polyline>()).Select(x => new DBPoint(x));

            points.SaveToDatebase();

            rectgs.AddRange(labelsFactory.Entities.Select(x => x.GetTransformedCopy(ucs.Inverse())));



            btrId = AcadBlocks.BlockTools.CreateBlockTableRecord("*U", bounds.MinPoint.TransformBy(ucs.Inverse()), rectgs.Cast <Entity>(), AnnotativeStates.NotApplicable, false);
            brId  = AcadBlocks.BlockTools.AppendBlockItem(bounds.MinPoint.TransformBy(ucs.Inverse()), btrId, null);



            /*Tools.StartTransaction(() =>
             * {
             *  BlockReference br = brId.GetObjectForWrite<BlockReference>();
             *  CartogrammGride jigGrid = new CartogrammGride(bounds.MinPoint.TransformBy(ucs), br, transformProcessor);
             *  jigGrid.StartJig();
             * });*/


            //rectgs.Cast<Entity>().SaveToDatebase();
        }
Ejemplo n.º 6
0
        public void ExplodeBlockByNameCommand(Editor ed, Document doc, string blockToExplode)
        {
            Document bDwg  = doc;
            Database db    = bDwg.Database;
            Database olddb = HostApplicationServices.WorkingDatabase;

            HostApplicationServices.WorkingDatabase = db;
            Autodesk.AutoCAD.DatabaseServices.TransactionManager bTransMan = bDwg.TransactionManager;

            using (Transaction bTrans = bTransMan.StartTransaction())
            {
                try
                {
                    LayerTable lt = (LayerTable)bTrans.GetObject(db.LayerTableId, OpenMode.ForRead);
                    BlockTable bt = (BlockTable)bTrans.GetObject(db.BlockTableId, OpenMode.ForRead);

                    if (bt.Has(blockToExplode))
                    {
                        ObjectId           blkId   = bt[blockToExplode];
                        BlockTableRecord   btr     = (BlockTableRecord)bTrans.GetObject(blkId, OpenMode.ForRead);
                        ObjectIdCollection blkRefs = btr.GetBlockReferenceIds(true, true);

                        foreach (ObjectId blkXId in blkRefs)
                        {
                            //create collection for exploded objects
                            DBObjectCollection objs = new DBObjectCollection();

                            //handle as entity and explode
                            Entity ent = (Entity)bTrans.GetObject(blkXId, OpenMode.ForRead);
                            ent.Explode(objs);

                            //erase Block
                            ent.UpgradeOpen();
                            ent.Erase();

                            BlockTableRecord btrCs = (BlockTableRecord)bTrans.GetObject(db.CurrentSpaceId, OpenMode.ForWrite);

                            foreach (DBObject obj in objs)
                            {
                                Entity ent2 = (Entity)obj;
                                if (!ent2.Linetype.Equals("ByLayer", StringComparison.CurrentCultureIgnoreCase) &&
                                    !ent2.Linetype.Equals("Continuous", StringComparison.CurrentCultureIgnoreCase))
                                {
                                    string   layer = "EQUIPMENT-" + ent2.Linetype;
                                    ObjectId oid;
                                    if (!lt.Has(layer))
                                    {
                                        using (Transaction bTrans2 = bTransMan.StartTransaction())
                                        {
                                            ed.WriteMessage("\nCreating layer {0}", layer);
                                            using (LayerTableRecord ltr = new LayerTableRecord())
                                            {
                                                LayerTable lt2 = (LayerTable)bTrans2.GetObject(db.LayerTableId, OpenMode.ForWrite);
                                                ltr.Color            = Color.FromColorIndex(ColorMethod.ByAci, 3);
                                                ltr.Name             = layer;
                                                ltr.LinetypeObjectId = ent2.LinetypeId;
                                                oid = lt2.Add(ltr);
                                                bTrans2.AddNewlyCreatedDBObject(ltr, true);
                                                bTrans2.Commit();
                                            }
                                        }
                                        lt = (LayerTable)bTrans.GetObject(db.LayerTableId, OpenMode.ForRead);
                                    }
                                    else
                                    {
                                        oid = lt[layer];
                                    }
                                    ed.WriteMessage("\nSetting entity properties.");
                                    ent2.LayerId  = oid;
                                    ent2.Linetype = "ByLayer";
                                }
                                btrCs.AppendEntity(ent2);
                                bTrans.AddNewlyCreatedDBObject(ent2, true);
                            }
                        }

                        //purge block
                        ObjectIdCollection blockIds = new ObjectIdCollection();
                        blockIds.Add(btr.ObjectId);
                        db.Purge(blockIds);
                        btr.UpgradeOpen();
                        btr.Erase();
                    }
                    else
                    {
                        ed.WriteMessage("\nCould not find block named {0}", blockToExplode);
                    }

                    bTrans.Commit();
                }
                catch (System.Exception err)
                {
                    ed.WriteMessage("\nSomething went wrong: {0}", blockToExplode);
                    File.AppendAllText(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory) + "\\error.log", err.ToString());
                }
                finally
                {
                }
                bTrans.Dispose();
                bTransMan.Dispose();
                HostApplicationServices.WorkingDatabase = olddb;
                ed.WriteMessage("\n");
            }
        }
        private void btOk_Click(object sender, RoutedEventArgs e)
        {
            if (tbName.Text == "")
            {
                MessageBox.Show("The field \"Name\" must be filled.", "Field is not filled", MessageBoxButton.OK, MessageBoxImage.Exclamation);
                return;
            }
            if (cbCategory.SelectedIndex == -1)
            {
                MessageBox.Show("You must select one category.", "Category not selected", MessageBoxButton.OK, MessageBoxImage.Exclamation);
                return;
            }
            if (objIdColl.Count == 0)
            {
                MessageBox.Show("Select at least one object.", "Objects not selected", MessageBoxButton.OK, MessageBoxImage.Exclamation);
                return;
            }
            //Check ambiguous block name
            if (_objBlockModOld.Name != _objBlockModNew.Name)
            {
                using (Database dbRef = new Database(false, true))
                {
                    //Read dbRef
                    dbRef.ReadDwgFile(ArCaRefMgrController.DBPath, FileShare.ReadWrite, true, "");
                    using (Transaction trRef = dbRef.TransactionManager.StartTransaction())
                    {
                        BlockTable       btRef = trRef.GetObject(dbRef.BlockTableId, OpenMode.ForRead) as BlockTable;
                        BlockTableRecord btr;
                        foreach (ObjectId objId in btRef)
                        {
                            btr = trRef.GetObject(objId, OpenMode.ForRead) as BlockTableRecord;
                            if (btr.Name == _objBlockModNew.Name)
                            {
                                MessageBox.Show("The block called \"" + _objBlockModNew.Name + "\"  already exists in the library block. Choose another name.", "Invalid Name", MessageBoxButton.OK, MessageBoxImage.Exclamation);
                                trRef.Abort();
                                return;
                            }
                        }
                        trRef.Abort();
                    }
                }
            }

            Database dbLocal = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Database;

            Point3d basePoint = new Point3d(Convert.ToDouble(tbX.Text), Convert.ToDouble(tbY.Text), Convert.ToDouble(tbZ.Text));

            using (dbLocal)
            {
                //-----------------Add Mode--------------
                if (_IsAddMode)
                {
                    //-----------Selection Block Mode------------
                    if (_SelectionIsABlock)
                    {
                        //Start Transaction to change BlockTableRecord
                        using (Transaction trLocal = dbLocal.TransactionManager.StartTransaction())
                        {
                            Document Doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
                            using (DocumentLock dl = Doc.LockDocument())
                            {
                                BlockTable       bt      = trLocal.GetObject(dbLocal.BlockTableId, OpenMode.ForRead) as BlockTable;
                                BlockTableRecord BlocRec = trLocal.GetObject(bt[_objBlockModNew.Name], OpenMode.ForWrite) as BlockTableRecord;
                                //Change PreviewIcon
                                BlocRec.PreviewIcon = bmpPreview;
                            }
                            trLocal.Commit();
                        }
                        using (Database dbRef = new Database(false, true))
                        {
                            //Read dbRef
                            dbRef.ReadDwgFile(ArCaRefMgrController.DBPath, FileShare.ReadWrite, true, "");
                            // Copy blocks from source to destination database
                            IdMapping mapping = new IdMapping();
                            dbLocal.WblockCloneObjects(objIdColl, dbRef.BlockTableId, mapping, DuplicateRecordCloning.Replace, false);
                            //Save dbRef
                            dbRef.SaveAs(ArCaRefMgrController.DBPath, DwgVersion.Current);
                        }
                    }
                    //------------------Selection Objects Mode------------------
                    else
                    {
                        using (Database dbAux = new Database())
                        {
                            //Create dbAux (block)
                            dbLocal.Wblock(dbAux, objIdColl, basePoint, DuplicateRecordCloning.Ignore);
                            using (Database dbRef = new Database(false, true))
                            {
                                //Read dbRef
                                dbRef.ReadDwgFile(ArCaRefMgrController.DBPath, FileShare.ReadWrite, true, "");
                                //Insert dbAuc (Block) in dbRef
                                ObjectId obj = dbRef.Insert(_objBlockModNew.Name, dbAux, true);
                                //Start Transaction to change BlockTableRecord
                                using (Transaction trRef = dbRef.TransactionManager.StartTransaction())
                                {
                                    BlockTableRecord BlocRec = trRef.GetObject(obj, OpenMode.ForWrite) as BlockTableRecord;
                                    //Change PreviewIcon
                                    BlocRec.PreviewIcon = bmpPreview;
                                }
                                //Save dbRef
                                dbRef.SaveAs(ArCaRefMgrController.DBPath, DwgVersion.Current);
                            }
                        }
                    }
                }
                //----------------Edit Mode----------------
                else
                {
                    //-------------Selection was not changed-------------
                    if (_bDbIsInExternalDWG)
                    {
                        using (Database dbRef = new Database(false, true))
                        {
                            //Read dbRef
                            dbRef.ReadDwgFile(ArCaRefMgrController.DBPath, FileShare.ReadWrite, true, "");
                            //Start Transaction to change BlockTableRecord
                            using (Transaction trRef = dbRef.TransactionManager.StartTransaction())
                            {
                                BlockTable       btRef   = trRef.GetObject(dbRef.BlockTableId, OpenMode.ForRead) as BlockTable;
                                BlockTableRecord BlocRec = trRef.GetObject(btRef[_objBlockModOld.Name], OpenMode.ForWrite) as BlockTableRecord;
                                //Change Origin
                                BlocRec.Origin = basePoint;
                                //Chage Name
                                BlocRec.Name = _objBlockModNew.Name;
                                trRef.Commit();
                            }
                            //Save dbRef
                            dbRef.SaveAs(ArCaRefMgrController.DBPath, DwgVersion.Current);
                        }
                    }
                    //----------------Selection was changed------------------
                    else
                    {
                        using (Database dbAux = new Database())
                        {
                            //Create dbAux (block)
                            dbLocal.Wblock(dbAux, objIdColl, basePoint, DuplicateRecordCloning.Ignore);
                            using (Database dbRef = new Database(false, true))
                            {
                                //Read dbRef
                                dbRef.ReadDwgFile(ArCaRefMgrController.DBPath, FileShare.ReadWrite, true, "");
                                //*************Delete Old Block************
                                //Start Transaction to delet BlockTableRecord
                                using (Transaction trRef = dbRef.TransactionManager.StartTransaction())
                                {
                                    BlockTable       btRef   = trRef.GetObject(dbRef.BlockTableId, OpenMode.ForRead) as BlockTable;
                                    BlockTableRecord BlocRec = trRef.GetObject(btRef[_objBlockModOld.Name], OpenMode.ForWrite) as BlockTableRecord;
                                    //Delet BlockTableRecord
                                    BlocRec.Erase();
                                    trRef.Commit();
                                }
                                //************Insert New Block**************
                                //-----------Selection Block Mode------------
                                if (_SelectionIsABlock)
                                {
                                    //Start Transaction to change BlockTableRecord
                                    using (Transaction trLocal = dbLocal.TransactionManager.StartTransaction())
                                    {
                                        Document Doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
                                        using (DocumentLock dl = Doc.LockDocument())
                                        {
                                            BlockTable       btRef   = trLocal.GetObject(dbLocal.BlockTableId, OpenMode.ForRead) as BlockTable;
                                            BlockTableRecord BlocRec = trLocal.GetObject(btRef[_objBlockModNew.Name], OpenMode.ForWrite) as BlockTableRecord;
                                            //Change PreviewIcon
                                            BlocRec.PreviewIcon = bmpPreview;
                                        }
                                        trLocal.Commit();
                                    }

                                    // Copy blocks from source to destination database
                                    IdMapping mapping = new IdMapping();
                                    dbLocal.WblockCloneObjects(objIdColl, dbRef.BlockTableId, mapping, DuplicateRecordCloning.Replace, false);
                                    //Save dbRef
                                    dbRef.SaveAs(ArCaRefMgrController.DBPath, DwgVersion.Current);
                                }
                                //--------------Selection Objects Mode--------------
                                else
                                {
                                    //Insert dbAuc (Block) in dbRef
                                    ObjectId obj = dbRef.Insert(_objBlockModNew.Name, dbAux, true);
                                    //Start Transaction to change BlockTableRecord
                                    using (Transaction trRef = dbRef.TransactionManager.StartTransaction())
                                    {
                                        BlockTableRecord BlocRec = trRef.GetObject(obj, OpenMode.ForWrite) as BlockTableRecord;
                                        //Change PreviewIcon
                                        BlocRec.PreviewIcon = bmpPreview;
                                        //Change Origin
                                        BlocRec.Origin = basePoint;
                                        //Chage Name
                                        BlocRec.Name = _objBlockModNew.Name;
                                        trRef.Commit();
                                    }
                                }
                                //***********************************************
                                //Save dbRef
                                dbRef.SaveAs(ArCaRefMgrController.DBPath, DwgVersion.Current);
                            }
                        }
                    }
                }
            }

            var             lstFound      = ArCaRefMgrController.ObjMain.LstGroup.Where(objTag => objTag.Name.Equals((cbCategory.SelectedValue as BlockGroupModel).Name));
            BlockGroupModel objBlockGroup = lstFound.First();

            //Remove in all Lists
            bool IsInserted = false;

            foreach (BlockGroupModel objIt in ArCaRefMgrController.ObjMain.LstGroup)
            {
                if (objIt.LstBlock.Contains(_objBlockModOld))
                {
                    int position = objIt.LstBlock.IndexOf(_objBlockModOld);
                    objIt.LstBlock.Remove(_objBlockModOld);
                    if (objBlockGroup == objIt)
                    {
                        //Insert if is in the same group
                        objBlockGroup.LstBlock.Insert(position, _objBlockModNew);
                        IsInserted = true;
                    }
                }
            }

            //If not inset, add in correct group
            if (!IsInserted)
            {
                objBlockGroup.LstBlock.Add(_objBlockModNew);
            }


            //Write XML
            ArCaRefMgrParser.WriteXML();

            this.Close();
        }