Exemplo n.º 1
0
        private static List <List <Pair <string, ObjectId> > > GetRefLayout(ref ObjectIdCollection coll, ref Database db)
        {
            // Database db = HostApplicationServices.WorkingDatabase;
            List <Pair <string, ObjectId> > PRE = new List <Pair <string, ObjectId> >();

            foreach (ObjectId ID in coll)
            {
                PRE.Add(new Pair <string, ObjectId>("-1", ID));
            }

            List <List <Pair <string, ObjectId> > > REZ = new List <List <Pair <string, ObjectId> > >();

            using (Transaction acTrans = db.TransactionManager.StartTransaction())
            {
                BlockTable acBlkTbl = acTrans.GetObject(db.BlockTableId, OpenMode.ForWrite) as BlockTable;
                foreach (ObjectId btrId in acBlkTbl)
                {
                    BlockTableRecord btr = (BlockTableRecord)acTrans.GetObject(btrId, OpenMode.ForWrite);
                    if (btr.IsLayout)
                    {
                        ObjectIdCollection anIds = btr.GetAnonymousBlockIds();

                        List <Pair <string, ObjectId> > mas = new List <Pair <string, ObjectId> >();
                        Layout lo = (Layout)acTrans.GetObject(btr.LayoutId, OpenMode.ForWrite);

                        foreach (Pair <string, ObjectId> ID in PRE)
                        {
                            if (ID.First == "-1")
                            {
                                BlockReference ghbref = acTrans.GetObject(ID.Second, OpenMode.ForRead) as BlockReference;
                                if (ExistObjectIDInLayout(ref btr, ID.Second))
                                {
                                    mas.Add(new Pair <string, ObjectId>(lo.LayoutName, ID.Second));
                                }
                            }
                        }

                        if (mas.Count > 0)
                        {
                            REZ.Add(mas);
                        }
                    }
                }
            }
            List <Pair <string, ObjectId> > Mas = new List <Pair <string, ObjectId> >();

            foreach (Pair <string, ObjectId> ID in PRE)
            {
                if (ID.First == "-1")
                {
                    Mas.Add(ID);
                }
            }
            if (Mas.Count > 0)
            {
                REZ.Add(Mas);
            }

            return(REZ);
        }
Exemplo n.º 2
0
        public static IEnumerable <ObjectId> GetAllBlockReferenceIds(this BlockTableRecord btr, bool directOnly)
        {
            IEnumerable <ObjectId> brefIds = btr
                                             .GetBlockReferenceIds(directOnly, false)
                                             .Cast <ObjectId>()
                                             .Concat(
                btr.GetAnonymousBlockIds()
                .Cast <ObjectId>()
                .SelectMany(
                    n => ((BlockTableRecord)n.GetObject(OpenMode.ForRead))
                    .GetBlockReferenceIds(directOnly, false)
                    .Cast <ObjectId>()));

            return(brefIds);
        }
        /// <summary>
        /// Возвращает ObjectId всех вхождений блока. В том числе если блок динамический
        /// </summary>
        /// <param name="btr">BlockTableRecord блока, чьи вхождения надо искать</param>
        /// <returns>Коллекцию вхождений блока, в том числе динамических</returns>
        public static IEnumerable <ObjectId> GetAllBlockReferenceIds(this BlockTableRecord btr, bool directOnly)
        {
            Database db = btr.Database;
            IEnumerable <ObjectId> brefIds = btr
                                             .GetBlockReferenceIds(directOnly, false)
                                             .Cast <ObjectId>()
                                             .Concat(
                btr.GetAnonymousBlockIds()
                .Cast <ObjectId>()
                .SelectMany(
                    n => n.GetObject <BlockTableRecord>()
                    .GetBlockReferenceIds(directOnly, false)
                    .Cast <ObjectId>()));

            return(brefIds);
        }
Exemplo n.º 4
0
        public static void UpdateParam()
        {
            //Get active document of drawing with Dynamic block
            var doc = Application.DocumentManager.MdiActiveDocument;
            var db  = doc.Database;

            // read input parameters from JSON file
            InputParams inputParams = JsonConvert.DeserializeObject <InputParams>(File.ReadAllText("params.json"));

            using (Transaction t = db.TransactionManager.StartTransaction())
            {
                var bt = t.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable;

                foreach (ObjectId btrId in bt)
                {
                    //get the blockDef and check if is anonymous
                    BlockTableRecord btr = (BlockTableRecord)t.GetObject(btrId, OpenMode.ForRead);
                    if (btr.IsDynamicBlock)
                    {
                        //get all anonymous blocks from this dynamic block
                        ObjectIdCollection anonymousIds = btr.GetAnonymousBlockIds();
                        ObjectIdCollection dynBlockRefs = new ObjectIdCollection();
                        foreach (ObjectId anonymousBtrId in anonymousIds)
                        {
                            //get the anonymous block
                            BlockTableRecord anonymousBtr = (BlockTableRecord)t.GetObject(anonymousBtrId, OpenMode.ForRead);
                            //and all references to this block
                            ObjectIdCollection blockRefIds = anonymousBtr.GetBlockReferenceIds(true, true);
                            foreach (ObjectId id in blockRefIds)
                            {
                                dynBlockRefs.Add(id);
                            }
                        }
                        if (dynBlockRefs.Count > 0)
                        {
                            //Get the first dynamic block reference, we have only one Dyanmic Block reference in Drawing
                            var dBref = t.GetObject(dynBlockRefs[0], OpenMode.ForWrite) as BlockReference;
                            UpdateDynamicProperties(dBref, inputParams);
                        }
                    }
                }
                t.Commit();
            }
            LogTrace("Saving file...");
            db.SaveAs("outputFile.dwg", DwgVersion.Current);
        }
Exemplo n.º 5
0
        /// <summary>
        ///     Get all references to the given BlockTableRecord, including
        ///     references to anonymous dynamic BlockTableRecords.
        /// </summary>
        public static IEnumerable <BlockReference> GetBlockReferences(
            this BlockTableRecord btr,
            OpenMode mode   = OpenMode.ForRead,
            bool directOnly = true)
        {
            if (btr == null)
            {
                throw new ArgumentNullException("btr");
            }
            var tr = btr.Database.TransactionManager.TopTransaction;

            if (tr == null)
            {
                throw new InvalidOperationException("No transaction");
            }
            var ids = btr.GetBlockReferenceIds(directOnly, true);
            var cnt = ids.Count;

            for (var i = 0; i < cnt; i++)
            {
                yield return((BlockReference)
                             tr.GetObject(ids[i], mode, false, false));
            }
            if (btr.IsDynamicBlock)
            {
                BlockTableRecord btr2 = null;
                var blockIds          = btr.GetAnonymousBlockIds();
                cnt = blockIds.Count;
                for (var i = 0; i < cnt; i++)
                {
                    btr2 = (BlockTableRecord)tr.GetObject(blockIds[i],
                                                          OpenMode.ForRead, false, false);
                    ids = btr2.GetBlockReferenceIds(directOnly, true);
                    var cnt2 = ids.Count;
                    for (var j = 0; j < cnt2; j++)
                    {
                        yield return((BlockReference)
                                     tr.GetObject(ids[j], mode, false, false));
                    }
                }
            }
        }
Exemplo n.º 6
0
        /// <summary>
        /// Method for getting all blockreference Ids
        /// </summary>
        /// <param name="btr">The BTR.</param>
        /// <param name="trx">The TRX.</param>
        /// <param name="directOnly">if set to <c>true</c> [direct only].</param>
        /// <param name="forceValidity">if set to <c>true</c> [force validity].</param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public static ObjectIdCollection GetAllBlockReferenceIds(this BlockTableRecord btr, Transaction trx,
                                                                 bool directOnly, bool forceValidity)
        {
            if (trx == null)
            {
                throw new Exception(ErrorStatus.NoActiveTransactions);
            }

            ObjectIdCollection blockReferenceIds = btr.GetBlockReferenceIds(directOnly, forceValidity);

            if (!btr.IsDynamicBlock)
            {
                return(blockReferenceIds);
            }
            foreach (ObjectId id in btr.GetAnonymousBlockIds())
            {
                BlockTableRecord record = trx.GetObject(id, OpenMode.ForRead) as BlockTableRecord;
                blockReferenceIds.Add(record.GetBlockReferenceIds(directOnly, forceValidity));
            }
            return(blockReferenceIds);
        }
Exemplo n.º 7
0
 public static void Update(this BlockTableRecord btr)
 {
     Tools.StartTransaction(() =>
     {
         if (btr.Id != ObjectId.Null)
         {
             btr = btr.Id.GetObjectForRead <BlockTableRecord>(false);
             btr.UpgradeOpen();
             foreach (ObjectId id in btr.GetBlockReferenceIds(true, false))
             {
                 BlockReference br = id.GetObjectForWrite <BlockReference>(false);
                 br.RecordGraphicsModified(true);
                 btr.Database.TransactionManager.QueueForGraphicsFlush();
             }
             foreach (ObjectId id in btr.GetAnonymousBlockIds())
             {
                 BlockReference br = id.GetObjectForWrite <BlockReference>(false);
                 br.RecordGraphicsModified(true);
                 btr.Database.TransactionManager.QueueForGraphicsFlush();
             }
         }
     });
 }
Exemplo n.º 8
0
        public double GetMspaceSlidingDoorArea()
        {
            Document doc       = Application.DocumentManager.MdiActiveDocument;
            Database db        = doc.Database;
            Editor   ed        = doc.Editor;
            double   area      = 0.0;
            Point3d  dMinPoint = new Point3d();
            Point3d  dMaxPoint = new Point3d();

            // ObjectId layerId = GetLayerId("4 AREA-Glazing Area");
            using (DocumentLock acLock = doc.LockDocument())
            {
                using (Transaction tr = db.TransactionManager.StartTransaction())
                {
                    BlockTable bt = (BlockTable)tr.GetObject(db.BlockTableId, OpenMode.ForRead);
                    // string blkName1 = "Altwood Garage Door - 8'";
                    //  string blkName2 = "Door - Single";
                    string blkName = "Sliding Door";
                    foreach (var btrId in bt)
                    {
                        if (true)
                        {
                        }
                        BlockTableRecord block = tr.GetObject(bt[blkName], OpenMode.ForRead) as BlockTableRecord;
                        if (!block.IsDynamicBlock)
                        {
                            continue;
                        }

                        var anonymousIds = block.GetAnonymousBlockIds();
                        var dynBlockRefs = new ObjectIdCollection();
                        int count        = 0;
                        foreach (ObjectId anonymousBtrId in anonymousIds)
                        {
                            var anonymousBtr = (BlockTableRecord)tr.GetObject(anonymousBtrId, OpenMode.ForRead);
                            var blockRefIds  = anonymousBtr.GetBlockReferenceIds(true, true);
                            foreach (ObjectId id in blockRefIds)
                            {
                                dynBlockRefs.Add(id);
                                count = dynBlockRefs.Count;
                                string name = anonymousBtr.Name;
                            }
                        }
                        BlockReference blk;
                        if (count > 0)
                        {
                            foreach (ObjectId id in dynBlockRefs)
                            {
                                BlockReference oEnt = (BlockReference)tr.GetObject(id, OpenMode.ForRead);
                                blk = (BlockReference)oEnt;
                                Extents3d extents = blk.GeometricExtents;
                                dMinPoint = extents.MinPoint;
                                dMaxPoint = extents.MaxPoint;
                                double w = extents.MaxPoint.X - extents.MinPoint.X;
                                double h = extents.MaxPoint.Y - extents.MinPoint.Y;
                                area = w * h;
                                //area = Math.Round(w*h / 144, 2);
                            }
                        }
                    }
                    BlockTableRecord acblkTblRec = tr.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord;
                    using (Polyline acPoly = new Polyline())
                    {
                        acPoly.SetDatabaseDefaults();
                        acPoly.AddVertexAt(0, new Point2d(dMinPoint.X, dMinPoint.Y), 0, 0, 0);
                        acPoly.AddVertexAt(1, new Point2d(dMaxPoint.X, dMinPoint.Y), 0, 0, 0);
                        acPoly.AddVertexAt(2, new Point2d(dMaxPoint.X, dMaxPoint.Y), 0, 0, 0);
                        acPoly.AddVertexAt(3, new Point2d(dMinPoint.X, dMaxPoint.Y), 0, 0, 0);
                        acPoly.AddVertexAt(4, new Point2d(dMinPoint.X, dMinPoint.Y), 0, 0, 0);
                        // acPoly.SetLayerId(layerId, true);
                        acblkTblRec.AppendEntity(acPoly);
                        tr.AddNewlyCreatedDBObject(acPoly, true);
                    }
                    tr.Commit();
                }
            }
            return(area);
        }
        private void bw_DoWork(object sender, DoWorkEventArgs e)
        {
            foreach (string filePath in fileList)
            {
                progress++;

                Database sideDB = new Database(false, true);

                using (sideDB)
                {
                    try
                    {
                        sideDB.ReadDwgFile(filePath, System.IO.FileShare.ReadWrite, false, "");
                    }
                    catch (System.Exception)
                    {
                        ed.WriteMessage("Could not open drawing file.");
                        return;
                    }

                    Transaction tr = sideDB.TransactionManager.StartTransaction();
                    using (tr)
                    {
                        BlockTable bt = (BlockTable)tr.GetObject(sideDB.BlockTableId, OpenMode.ForRead);

                        if (smartSearch)
                        {
                            int numObjects = IO_CardNames.Count;
                            int currentObj = 0;

                            foreach (string name in IO_CardNames)
                            {
                                currentObj++;
                                bw.ReportProgress((int)(((float)currentObj / numObjects) * ((float)1 / numFiles) * 100 + ((float)(progress - 1) / numFiles) * 100));

                                try
                                {
                                    BlockTableRecord   btr         = (BlockTableRecord)tr.GetObject(bt[name], OpenMode.ForRead);
                                    ObjectIdCollection objIdCol    = btr.GetBlockReferenceIds(true, false);
                                    ObjectIdCollection annobjIdCol = btr.GetAnonymousBlockIds();

                                    foreach (ObjectId objId in objIdCol)
                                    {
                                        bool     IO_block         = false;
                                        string[] portDescriptions = new string[32];
                                        string   rack             = "";
                                        string   slot             = "";
                                        string   partNumber       = "";

                                        try
                                        {
                                            BlockReference br = (BlockReference)tr.GetObject(objId, OpenMode.ForRead);
                                            if (br != null)
                                            {
                                                foreach (ObjectId arId in br.AttributeCollection)
                                                {
                                                    DBObject           obj = tr.GetObject(arId, OpenMode.ForRead);
                                                    AttributeReference ar  = (AttributeReference)obj;

                                                    if (ar != null)
                                                    {
                                                        if (ar.Tag.ToUpper().Equals("RACK"))
                                                        {
                                                            rack = ar.TextString;
                                                        }
                                                        else if (ar.Tag.ToUpper().Equals("SLOT"))
                                                        {
                                                            slot = ar.TextString;
                                                        }
                                                        else if (ar.Tag.ToUpper().Equals("PARTNUMBER"))
                                                        {
                                                            partNumber = ar.TextString;
                                                        }
                                                        else
                                                        {
                                                            for (int i = 0; i < 32; i++)
                                                            {
                                                                if (ar.Tag.ToUpper().Contains("PORT" + i + "DESC"))
                                                                {
                                                                    IO_block            = true;
                                                                    portDescriptions[i] = ar.TextString;
                                                                }
                                                            }
                                                        }
                                                    }
                                                }
                                                if (IO_block)
                                                {
                                                    IO_Block to_Store = new IO_Block();
                                                    to_Store.partNumber       = partNumber;
                                                    to_Store.rack             = rack;
                                                    to_Store.slot             = slot;
                                                    to_Store.portDescriptions = portDescriptions;
                                                    IO_Blocks.Add(to_Store);
                                                }
                                            }
                                        }
                                        catch
                                        {
                                            continue;
                                        }
                                        if (bw.CancellationPending)
                                        {
                                            e.Cancel = true;
                                            return;
                                        }
                                    }

                                    foreach (ObjectId id in annobjIdCol)
                                    {
                                        BlockTableRecord   annbtr    = (BlockTableRecord)tr.GetObject(id, OpenMode.ForRead);
                                        ObjectIdCollection blkRefIds = annbtr.GetBlockReferenceIds(true, false);
                                        foreach (ObjectId objId in blkRefIds)
                                        {
                                            bool     IO_block         = false;
                                            string[] portDescriptions = new string[40];
                                            string   rack             = "";
                                            string   slot             = "";
                                            string   partNumber       = "";

                                            try
                                            {
                                                BlockReference br = (BlockReference)tr.GetObject(objId, OpenMode.ForRead);
                                                if (br != null)
                                                {
                                                    foreach (ObjectId arId in br.AttributeCollection)
                                                    {
                                                        DBObject           obj = tr.GetObject(arId, OpenMode.ForRead);
                                                        AttributeReference ar  = (AttributeReference)obj;

                                                        if (ar != null)
                                                        {
                                                            if (ar.Tag.ToUpper().Equals("RACK"))
                                                            {
                                                                rack = ar.TextString;
                                                            }
                                                            else if (ar.Tag.ToUpper().Equals("SLOT"))
                                                            {
                                                                slot = ar.TextString;
                                                            }
                                                            else if (ar.Tag.ToUpper().Equals("PARTNUMBER"))
                                                            {
                                                                partNumber = ar.TextString;
                                                            }
                                                            else
                                                            {
                                                                for (int i = 0; i < 40; i++)
                                                                {
                                                                    if (ar.Tag.ToUpper().Contains("PORT" + i + "DESC"))
                                                                    {
                                                                        IO_block            = true;
                                                                        portDescriptions[i] = ar.TextString;
                                                                    }
                                                                }
                                                            }
                                                        }
                                                    }
                                                    if (IO_block)
                                                    {
                                                        IO_Block to_Store = new IO_Block();
                                                        to_Store.partNumber       = partNumber;
                                                        to_Store.rack             = rack;
                                                        to_Store.slot             = slot;
                                                        to_Store.portDescriptions = portDescriptions;
                                                        IO_Blocks.Add(to_Store);
                                                    }
                                                }
                                            }
                                            catch
                                            {
                                                continue;
                                            }

                                            if (bw.CancellationPending)
                                            {
                                                e.Cancel = true;
                                                return;
                                            }
                                        }
                                    }
                                }
                                catch
                                {
                                    continue;
                                }
                            }
                        }
                        else
                        {
                            int numObjects = 0;
                            int currentObj = 0;

                            try
                            {
                                BlockTableRecord btr = (BlockTableRecord)tr.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForRead);

                                foreach (ObjectId id in btr)
                                {
                                    numObjects++;
                                }

                                foreach (ObjectId objId in btr)
                                {
                                    currentObj++;
                                    bw.ReportProgress((int)(((float)currentObj / numObjects) * ((float)1 / numFiles) * 100 + ((float)(progress - 1) / numFiles) * 100));

                                    bool     IO_block         = false;
                                    string[] portDescriptions = new string[32];
                                    string   rack             = "";
                                    string   slot             = "";
                                    string   partNumber       = "";

                                    try
                                    {
                                        BlockReference br = (BlockReference)tr.GetObject(objId, OpenMode.ForRead);
                                        if (br != null)
                                        {
                                            foreach (ObjectId arId in br.AttributeCollection)
                                            {
                                                DBObject           obj = tr.GetObject(arId, OpenMode.ForRead);
                                                AttributeReference ar  = (AttributeReference)obj;

                                                if (ar != null)
                                                {
                                                    if (ar.Tag.ToUpper().Equals("RACK"))
                                                    {
                                                        rack = ar.TextString;
                                                    }
                                                    else if (ar.Tag.ToUpper().Equals("SLOT"))
                                                    {
                                                        slot = ar.TextString;
                                                    }
                                                    else if (ar.Tag.ToUpper().Equals("PARTNUMBER"))
                                                    {
                                                        partNumber = ar.TextString;
                                                    }
                                                    else
                                                    {
                                                        for (int i = 0; i < 32; i++)
                                                        {
                                                            if (ar.Tag.ToUpper().Contains("PORT" + i + "DESC"))
                                                            {
                                                                IO_block            = true;
                                                                portDescriptions[i] = ar.TextString;
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                            if (IO_block)
                                            {
                                                IO_Block to_Store = new IO_Block();
                                                to_Store.partNumber       = partNumber;
                                                to_Store.rack             = rack;
                                                to_Store.slot             = slot;
                                                to_Store.portDescriptions = portDescriptions;
                                                IO_Blocks.Add(to_Store);
                                            }
                                        }
                                    }
                                    catch
                                    {
                                        continue;
                                    }
                                    if (bw.CancellationPending)
                                    {
                                        e.Cancel = true;
                                        return;
                                    }
                                }
                            }
                            catch
                            {
                                continue;
                            }
                        }
                    }
                }
            }
        }
Exemplo n.º 10
0
        private void bw_ReadTitleBlocks_DoWork(object sender, DoWorkEventArgs e)
        {
            Transaction tr = db.TransactionManager.StartTransaction();

            using (tr)
            {
                BlockTable       bt  = (BlockTable)tr.GetObject(db.BlockTableId, OpenMode.ForRead);
                BlockTableRecord btr = new BlockTableRecord();
                try
                {
                    btr = (BlockTableRecord)tr.GetObject(bt[TITLE_BLOCK_NAME], OpenMode.ForRead);
                }
                catch (Autodesk.AutoCAD.Runtime.Exception acadexc)
                {
                    if (acadexc.ErrorStatus == Autodesk.AutoCAD.Runtime.ErrorStatus.KeyNotFound)
                    {
                        MessageBox.Show("Command was unable to find the Haskell ARCH D title block.  Please verify the name of the block in AutoCAD and try again.", "Haskell ARCH D Not Found", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        tr.Commit();
                    }
                    return;
                }
                ObjectIdCollection objIdCol    = btr.GetBlockReferenceIds(true, false);
                ObjectIdCollection annobjIdCol = btr.GetAnonymousBlockIds();

                //Finds all non-dynamic blocks
                #region FIND NONDYNAMIC
                foreach (ObjectId objId in objIdCol)
                {
                    Title_Blocks.Add(new Title_Block(objId));
                    try
                    {
                        BlockReference br = (BlockReference)tr.GetObject(objId, OpenMode.ForRead);
                        if (br != null)
                        {
                            //Loop through dynamic attributes/properties
                            DynamicBlockReferencePropertyCollection pc = br.DynamicBlockReferencePropertyCollection;
                            foreach (DynamicBlockReferenceProperty prop in pc)
                            {
                                if (prop.PropertyName.ToUpper().Equals("STAMP"))
                                {
                                    Title_Blocks[Title_Blocks.Count - 1].Stamp = prop.Value.ToString();
                                }
                            }

                            //Loop through all attributes
                            foreach (ObjectId arId in br.AttributeCollection)
                            {
                                DBObject           obj = tr.GetObject(arId, OpenMode.ForRead);
                                AttributeReference ar  = (AttributeReference)obj;

                                if (ar != null)
                                {
                                    string attributeTag = ar.Tag.ToUpper();

                                    if (attributeTag.Equals("SHEET_NUMBER"))
                                    {
                                        Title_Blocks[Title_Blocks.Count - 1].PageNumber = ar.TextString;
                                    }
                                    else if (ar.Tag.ToUpper().Equals("SHEET_TITLE"))
                                    {
                                        Title_Blocks[Title_Blocks.Count - 1].PageTitle = ar.TextString;
                                    }
                                    else if (attributeTag.Equals("DRAWNBY"))
                                    {
                                        Title_Blocks[Title_Blocks.Count - 1].DrawnBy = ar.TextString;
                                    }
                                    else if (attributeTag.Equals("CHECKEDBY"))
                                    {
                                        Title_Blocks[Title_Blocks.Count - 1].CheckedBy = ar.TextString;
                                    }
                                    else if (attributeTag.Equals("REV#"))
                                    {
                                        Title_Blocks[Title_Blocks.Count - 1].RevisionNumber = ar.TextString;
                                    }
                                    else
                                    {
                                        for (int i = 1; i <= 15; i++)
                                        {
                                            if (attributeTag.Equals(i.ToString()))
                                            {
                                                Title_Blocks[Title_Blocks.Count - 1].RevisionInfo[i, 1] = ar.TextString;
                                            }
                                            else if (attributeTag.Equals("ISSUE" + i.ToString() + "-TITLE"))
                                            {
                                                Title_Blocks[Title_Blocks.Count - 1].RevisionInfo[i, 2] = ar.TextString;
                                            }
                                            else if (attributeTag.Equals("ISSUE" + i.ToString() + "-DATE"))
                                            {
                                                Title_Blocks[Title_Blocks.Count - 1].RevisionInfo[i, 3] = ar.TextString;
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                    catch
                    {
                    }
                }
                #endregion

                //Finds all dynamic blocks
                #region FIND DYNAMIC
                foreach (ObjectId id in annobjIdCol)
                {
                    BlockTableRecord   annbtr    = (BlockTableRecord)tr.GetObject(id, OpenMode.ForRead);
                    ObjectIdCollection blkRefIds = annbtr.GetBlockReferenceIds(true, false);
                    foreach (ObjectId objId in blkRefIds)
                    {
                        Title_Blocks.Add(new Title_Block(objId));
                        try
                        {
                            BlockReference br = (BlockReference)tr.GetObject(objId, OpenMode.ForRead);
                            if (br != null)
                            {
                                //Loop through dynamic attributes/properties
                                DynamicBlockReferencePropertyCollection pc = br.DynamicBlockReferencePropertyCollection;
                                foreach (DynamicBlockReferenceProperty prop in pc)
                                {
                                    if (prop.PropertyName.ToUpper().Equals("STAMP"))
                                    {
                                        Title_Blocks[Title_Blocks.Count - 1].Stamp = prop.Value.ToString();
                                    }
                                }

                                //Loop through all attributes
                                foreach (ObjectId arId in br.AttributeCollection)
                                {
                                    DBObject           obj = tr.GetObject(arId, OpenMode.ForRead);
                                    AttributeReference ar  = (AttributeReference)obj;

                                    if (ar != null)
                                    {
                                        string attributeTag = ar.Tag.ToUpper();

                                        if (attributeTag.Equals("SHEET_NUMBER"))
                                        {
                                            Title_Blocks[Title_Blocks.Count - 1].PageNumber = ar.TextString;
                                        }
                                        else if (ar.Tag.ToUpper().Equals("SHEET_TITLE"))
                                        {
                                            Title_Blocks[Title_Blocks.Count - 1].PageTitle = ar.TextString;
                                        }
                                        else if (ar.Tag.ToUpper().Equals("PROJECTNUM"))
                                        {
                                            Title_Blocks[Title_Blocks.Count - 1].ProjectNumber = ar.TextString;
                                        }
                                        else if (attributeTag.Equals("DRAWNBY"))
                                        {
                                            Title_Blocks[Title_Blocks.Count - 1].DrawnBy = ar.TextString;
                                        }
                                        else if (attributeTag.Equals("CHECKEDBY"))
                                        {
                                            Title_Blocks[Title_Blocks.Count - 1].CheckedBy = ar.TextString;
                                        }
                                        else if (attributeTag.Equals("REV#"))
                                        {
                                            Title_Blocks[Title_Blocks.Count - 1].RevisionNumber = ar.TextString;
                                        }
                                        else
                                        {
                                            for (int i = 0; i < 15; i++)
                                            {
                                                if (attributeTag.Equals((i + 1).ToString()))
                                                {
                                                    Title_Blocks[Title_Blocks.Count - 1].RevisionInfo[i, 0] = ar.TextString;
                                                    break;
                                                }
                                                else if (attributeTag.Equals("ISSUE" + (i + 1).ToString() + "-TITLE"))
                                                {
                                                    Title_Blocks[Title_Blocks.Count - 1].RevisionInfo[i, 1] = ar.TextString;
                                                    break;
                                                }
                                                else if (attributeTag.Equals("ISSUE" + (i + 1).ToString() + "-DATE"))
                                                {
                                                    Title_Blocks[Title_Blocks.Count - 1].RevisionInfo[i, 2] = ar.TextString;
                                                    break;
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        catch
                        {
                        }
                    }
                }
                #endregion
                tr.Commit();
            }
        }
        /// <summary>
        /// Синхронизация вхождений блоков с их определением
        /// via http://sites.google.com/site/bushmansnetlaboratory/moi-zametki/attsynch
        /// </summary>
        /// <param name="btr">Запись таблицы блоков, принятая за определение блока</param>
        /// <param name="directOnly">Следует ли искать только на верхнем уровне, или же нужно
        /// анализировать и вложенные вхождения, т.е. следует ли рекурсивно обрабатывать блок в блоке:
        /// true - только верхний; false - рекурсивно проверять вложенные блоки.</param>
        /// <param name="removeSuperfluous">
        /// Следует ли во вхождениях блока удалять лишние атрибуты (те, которых нет в определении блока).</param>
        /// <param name="setAttDefValues">
        /// Следует ли всем атрибутам, во вхождениях блока, назначить текущим значением значение по умолчанию.</param>
        public static void AttSync(this BlockTableRecord btr, bool directOnly, bool removeSuperfluous, bool setAttDefValues)
        {
            Database db = btr.Database;

//			using (Bushman.AutoCAD.DatabaseServices.WorkingDatabaseSwitcher wdb = new Bushman.AutoCAD.DatabaseServices.WorkingDatabaseSwitcher(db)) {
            using (Transaction t = db.TransactionManager.StartTransaction()) {
                BlockTable bt = (BlockTable)t.GetObject(db.BlockTableId, OpenMode.ForRead);

                //Получаем все определения атрибутов из определения блока
                IEnumerable <AttributeDefinition> attdefs = btr.Cast <ObjectId>()
                                                            .Where(n => n.ObjectClass.Name == "AcDbAttributeDefinition")
                                                            .Select(n => (AttributeDefinition)t.GetObject(n, OpenMode.ForRead))
                                                            .Where(n => !n.Constant);//Исключаем константные атрибуты, т.к. для них AttributeReference не создаются.

                //В цикле перебираем все вхождения искомого определения блока
                foreach (ObjectId brId in btr.GetBlockReferenceIds(directOnly, false))
                {
                    BlockReference br = (BlockReference)t.GetObject(brId, OpenMode.ForWrite);

                    //Проверяем имена на соответствие. В том случае, если вхождение блока "A" вложено в определение блока "B",
                    //то вхождения блока "B" тоже попадут в выборку. Нам нужно их исключить из набора обрабатываемых объектов
                    //- именно поэтому проверяем имена.
                    if (br.Name != btr.Name)
                    {
                        continue;
                    }

                    //Получаем все атрибуты вхождения блока
                    IEnumerable <AttributeReference> attrefs = br.AttributeCollection.Cast <ObjectId>()
                                                               .Select(n => (AttributeReference)t.GetObject(n, OpenMode.ForWrite));

                    //Тэги существующих определений атрибутов
                    IEnumerable <string> dtags = attdefs.Select(n => n.Tag);
                    //Тэги существующих атрибутов во вхождении
                    IEnumerable <string> rtags = attrefs.Select(n => n.Tag);

                    //Если требуется - удаляем те атрибуты, для которых нет определения
                    //в составе определения блока
                    if (removeSuperfluous)
                    {
                        foreach (AttributeReference attref in attrefs.Where(n => rtags
                                                                            .Except(dtags).Contains(n.Tag)))
                        {
                            attref.Erase(true);
                        }
                    }

                    //Свойства существующих атрибутов синхронизируем со свойствами их определений
                    foreach (AttributeReference attref in attrefs.Where(n => dtags
                                                                        .Join(rtags, a => a, b => b, (a, b) => a).Contains(n.Tag)))
                    {
                        AttributeDefinition ad = attdefs.First(n => n.Tag == attref.Tag);

                        //Метод SetAttributeFromBlock, используемый нами далее в коде, сбрасывает
                        //текущее значение многострочного атрибута. Поэтому запоминаем это значение,
                        //чтобы восстановить его сразу после вызова SetAttributeFromBlock.
                        string value = attref.TextString;
                        attref.SetAttributeFromBlock(ad, br.BlockTransform);
                        //Восстанавливаем значение атрибута
                        attref.TextString = value;

                        if (attref.IsMTextAttribute)
                        {
                        }

                        //Если требуется - устанавливаем для атрибута значение по умолчанию
                        if (setAttDefValues)
                        {
                            attref.TextString = ad.TextString;
                        }
                        attref.AdjustAlignment(db);
                    }

                    //Если во вхождении блока отсутствуют нужные атрибуты - создаём их
                    IEnumerable <AttributeDefinition> attdefsNew = attdefs.Where(n => dtags
                                                                                 .Except(rtags).Contains(n.Tag));

                    foreach (AttributeDefinition ad in attdefsNew)
                    {
                        AttributeReference attref = new AttributeReference();
                        attref.SetAttributeFromBlock(ad, br.BlockTransform);
                        attref.AdjustAlignment(db);
                        br.AttributeCollection.AppendAttribute(attref);
                        t.AddNewlyCreatedDBObject(attref, true);
                    }
                }
                btr.UpdateAnonymousBlocks();
                t.Commit();
            }
            //Если это динамический блок
            if (btr.IsDynamicBlock)
            {
                using (Transaction t = db.TransactionManager.StartTransaction()) {
                    foreach (ObjectId id in btr.GetAnonymousBlockIds())
                    {
                        BlockTableRecord _btr = (BlockTableRecord)t.GetObject(id, OpenMode.ForWrite);

                        //Получаем все определения атрибутов из оригинального определения блока
                        IEnumerable <AttributeDefinition> attdefs = btr.Cast <ObjectId>()
                                                                    .Where(n => n.ObjectClass.Name == "AcDbAttributeDefinition")
                                                                    .Select(n => (AttributeDefinition)t.GetObject(n, OpenMode.ForRead));

                        //Получаем все определения атрибутов из определения анонимного блока
                        IEnumerable <AttributeDefinition> attdefs2 = _btr.Cast <ObjectId>()
                                                                     .Where(n => n.ObjectClass.Name == "AcDbAttributeDefinition")
                                                                     .Select(n => (AttributeDefinition)t.GetObject(n, OpenMode.ForWrite));
                        //Определения атрибутов анонимных блоков следует синхронизировать
                        //с определениями атрибутов основного блока
                        //Тэги существующих определений атрибутов
                        IEnumerable <string> dtags  = attdefs.Select(n => n.Tag);
                        IEnumerable <string> dtags2 = attdefs2.Select(n => n.Tag);
                        //1. Удаляем лишние
                        foreach (AttributeDefinition attdef in attdefs2.Where(n => !dtags.Contains(n.Tag)))
                        {
                            attdef.Erase(true);
                        }
                        //2. Синхронизируем существующие
                        foreach (AttributeDefinition attdef in attdefs.Where(n => dtags
                                                                             .Join(dtags2, a => a, b => b, (a, b) => a).Contains(n.Tag)))
                        {
                            AttributeDefinition ad = attdefs2.First(n => n.Tag == attdef.Tag);
                            ad.Position = attdef.Position;
                            #if ACAD2009
                            ad.TextStyle = attdef.TextStyle;
                            #else
                            ad.TextStyleId = attdef.TextStyleId;
                            #endif
                            //Если требуется - устанавливаем для атрибута значение по умолчанию
                            if (setAttDefValues)
                            {
                                ad.TextString = attdef.TextString;
                            }
                            ad.Tag                 = attdef.Tag;
                            ad.Prompt              = attdef.Prompt;
                            ad.LayerId             = attdef.LayerId;
                            ad.Rotation            = attdef.Rotation;
                            ad.LinetypeId          = attdef.LinetypeId;
                            ad.LineWeight          = attdef.LineWeight;
                            ad.LinetypeScale       = attdef.LinetypeScale;
                            ad.Annotative          = attdef.Annotative;
                            ad.Color               = attdef.Color;
                            ad.Height              = attdef.Height;
                            ad.HorizontalMode      = attdef.HorizontalMode;
                            ad.Invisible           = attdef.Invisible;
                            ad.IsMirroredInX       = attdef.IsMirroredInX;
                            ad.IsMirroredInY       = attdef.IsMirroredInY;
                            ad.Justify             = attdef.Justify;
                            ad.LockPositionInBlock = attdef.LockPositionInBlock;
                            ad.MaterialId          = attdef.MaterialId;
                            ad.Oblique             = attdef.Oblique;
                            ad.Thickness           = attdef.Thickness;
                            ad.Transparency        = attdef.Transparency;
                            ad.VerticalMode        = attdef.VerticalMode;
                            ad.Visible             = attdef.Visible;
                            ad.WidthFactor         = attdef.WidthFactor;
                            ad.CastShadows         = attdef.CastShadows;
                            ad.Constant            = attdef.Constant;
                            ad.FieldLength         = attdef.FieldLength;
                            ad.ForceAnnoAllVisible = attdef.ForceAnnoAllVisible;
                            ad.Preset              = attdef.Preset;
                            ad.Prompt              = attdef.Prompt;
                            ad.Verifiable          = attdef.Verifiable;
                            ad.AdjustAlignment(db);
                        }
                        //3. Добавляем недостающие
                        foreach (AttributeDefinition attdef in attdefs.Where(n => !dtags2.Contains(n.Tag)))
                        {
                            AttributeDefinition ad = new AttributeDefinition();
                            ad.SetDatabaseDefaults();
                            ad.Position = attdef.Position;
                            #if ACAD2009
                            ad.TextStyle = attdef.TextStyle;
                            #else
                            ad.TextStyleId = attdef.TextStyleId;
                            #endif
                            ad.TextString          = attdef.TextString;
                            ad.Tag                 = attdef.Tag;
                            ad.Prompt              = attdef.Prompt;
                            ad.LayerId             = attdef.LayerId;
                            ad.Rotation            = attdef.Rotation;
                            ad.LinetypeId          = attdef.LinetypeId;
                            ad.LineWeight          = attdef.LineWeight;
                            ad.LinetypeScale       = attdef.LinetypeScale;
                            ad.Annotative          = attdef.Annotative;
                            ad.Color               = attdef.Color;
                            ad.Height              = attdef.Height;
                            ad.HorizontalMode      = attdef.HorizontalMode;
                            ad.Invisible           = attdef.Invisible;
                            ad.IsMirroredInX       = attdef.IsMirroredInX;
                            ad.IsMirroredInY       = attdef.IsMirroredInY;
                            ad.Justify             = attdef.Justify;
                            ad.LockPositionInBlock = attdef.LockPositionInBlock;
                            ad.MaterialId          = attdef.MaterialId;
                            ad.Oblique             = attdef.Oblique;
                            ad.Thickness           = attdef.Thickness;
                            ad.Transparency        = attdef.Transparency;
                            ad.VerticalMode        = attdef.VerticalMode;
                            ad.Visible             = attdef.Visible;
                            ad.WidthFactor         = attdef.WidthFactor;
                            ad.CastShadows         = attdef.CastShadows;
                            ad.Constant            = attdef.Constant;
                            ad.FieldLength         = attdef.FieldLength;
                            ad.ForceAnnoAllVisible = attdef.ForceAnnoAllVisible;
                            ad.Preset              = attdef.Preset;
                            ad.Prompt              = attdef.Prompt;
                            ad.Verifiable          = attdef.Verifiable;
                            _btr.AppendEntity(ad);
                            t.AddNewlyCreatedDBObject(ad, true);
                            ad.AdjustAlignment(db);
                        }
                        //Синхронизируем все вхождения данного анонимного определения блока
                        _btr.AttSync(directOnly, removeSuperfluous, setAttDefValues);
                    }
                    //Обновляем геометрию определений анонимных блоков, полученных на основе
                    //этого динамического блока
                    btr.UpdateAnonymousBlocks();
                    t.Commit();
                }
            }
//			}
        }
Exemplo n.º 12
0
        public static ObjectIdCollection SelectDynamicBlockReferences(ObjectId mSpaceId, string blockName = "ФорматM25")
        {
            Editor   ed = Active.Editor;
            Database db = Active.Database;

            ObjectIdCollection dynBlockRefs = new ObjectIdCollection();

            using (Transaction trans = db.TransactionManager.StartTransaction())
            {
                // получаем таблицу блоков и проходим по всем записям таблицы блоков
                BlockTable bt = (BlockTable)trans.GetObject(db.BlockTableId, OpenMode.ForRead);
                foreach (ObjectId btrId in bt)
                {
                    // получаем запись таблицы блоков и смотри анонимная ли она
                    BlockTableRecord btr = (BlockTableRecord)trans.GetObject(btrId, OpenMode.ForRead);
                    if (btr.IsDynamicBlock && btr.Name == blockName)
                    {
                        // получаем все анонимные блоки динамического блока
                        ObjectIdCollection anonymousIds = btr.GetAnonymousBlockIds();
                        // получаем все прямые вставки динамического блока
                        dynBlockRefs = btr.GetBlockReferenceIds(true, true);

                        foreach (ObjectId anonymousBtrId in anonymousIds)
                        {
                            // open the model space BlockTableRecord
                            //var modelSpace = (BlockTableRecord)tr.GetObject(blockTable[BlockTableRecord.ModelSpace], OpenMode.ForRead);

                            // получаем анонимный блок
                            BlockTableRecord anonymousBtr =
                                (BlockTableRecord)trans.GetObject(anonymousBtrId, OpenMode.ForRead);

                            // получаем все вставки этого блока
                            ObjectIdCollection blockRefIds = anonymousBtr.GetBlockReferenceIds(true, true);

                            foreach (ObjectId id in blockRefIds)
                            {
                                //var blockReference = (BlockReference)tr.GetObject(id, OpenMode.ForRead);
                                var e = (BlockReference)trans.GetObject(id, OpenMode.ForRead);

                                ObjectId ownerId = e.OwnerId;

                                if (ownerId == mSpaceId)
                                {
                                    ed.WriteMessage(e.ToString());

                                    dynBlockRefs.Add(id);

                                    ed.WriteMessage("\n \"{0}\" соответствуют {1} \n",
                                                    btr.Name, id);
                                }
                            }
                        }

                        // Что-нибудь делаем с созданным нами набором
                        //ed.WriteMessage("\nДинамическому блоку \"{0}\" соответствуют {1} анонимных блоков и {2} вставок блока\n",
                        //    btr.Name, anonymousIds.Count, dynBlockRefs.Count);
                    }
                }
            }
            return(dynBlockRefs);
        }
Exemplo n.º 13
0
        public static ObjectIdCollection GetBlockReferenceIds(ObjectId BtrId)
        {
            if (BtrId.IsNull)
            {
                throw new ArgumentException("null object id");
            }

            ObjectIdCollection result = new ObjectIdCollection();

            using (Transaction transaction = BtrId.Database.TransactionManager.StartTransaction())
            {
                try
                {
                    BlockTableRecord blockTableRecord =
                        transaction.GetObject(BtrId, OpenMode.ForRead) as BlockTableRecord;
                    if (blockTableRecord != null)
                    {
                        // Add the ids of all references to the BTR. Some dynamic blocks may
                        // reference the dynamic block directly rather than an anonymous block,
                        // so this will get those as well:
                        ObjectIdCollection BrefIds = blockTableRecord.GetBlockReferenceIds(true, false);
                        if (BrefIds != null)
                        {
                            foreach (ObjectId Id in BrefIds)
                            {
                                result.Add(Id);
                            }
                        }

                        // if this is not a dynamic block, we're done:

                        if (!blockTableRecord.IsDynamicBlock)
                        {
                            return(result);
                        }

                        // Get the ids of all anonymous block table records for the dynamic block

                        ObjectIdCollection anonBtrIds = blockTableRecord.GetAnonymousBlockIds();
                        if (anonBtrIds != null)
                        {
                            foreach (ObjectId anonBtrId in anonBtrIds)
                            {
                                // get all references to each anonymous block:

                                BlockTableRecord rec =
                                    transaction.GetObject(anonBtrId, OpenMode.ForRead) as BlockTableRecord;
                                if (rec != null)
                                {
                                    BrefIds = rec.GetBlockReferenceIds(false, true);
                                    if (BrefIds != null)
                                    {
                                        foreach (ObjectId id in BrefIds)
                                        {
                                            result.Add(id);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                finally
                {
                    transaction.Commit();
                }
            }
            return(result);
        }