Beispiel #1
0
        public static ObjectIdCollection ExplodeBlock(this BlockReference br, Transaction tr, Database db,
                                                      bool erase = true)
        {
            // We'll collect the BlockReferences created in a collection
            var toExplode = new ObjectIdCollection();
            var objIds    = new ObjectIdCollection();

            // Define our handler to capture the nested block references
            void Handler(object s, ObjectEventArgs e)
            {
                switch (e.DBObject)
                {
                case BlockReference _:
                    toExplode.Add(e.DBObject.ObjectId);
                    break;

                default:
                    objIds.Add(e.DBObject.ObjectId);
                    break;
                }
            }

            // Add our handler around the explode call, removing it
            // directly afterwards

            db.ObjectAppended += Handler;
            br.ExplodeToOwnerSpace();
            db.ObjectAppended -= Handler;

            // Go through the results and recurse, exploding the
            // contents

            foreach (ObjectId bid in toExplode)
            {
                var nBr = (BlockReference)tr.GetObject(bid, OpenMode.ForRead);

                var exIds = nBr.ExplodeBlock(tr, db);

                foreach (ObjectId id in exIds)
                {
                    objIds.Add(id);
                }
            }


            // We might also just let it drop out of scope
            toExplode.Clear();

            // To replicate the explode command, we're delete the
            // original entity

            if (erase)
            {
                br.UpgradeOpen();
                br.Erase();
                br.DowngradeOpen();
            }

            return(objIds);
        }
        private BlockReference CreateBlockRef(DocumentModifier docMdf, BlockTableRecord space, BlockTableRecord blockDef, AttributeDefinition attDef,
                                              Point3d position)
        {
            BlockReference bref = new BlockReference(position, blockDef.Id);

            space.AppendEntity(bref);
            docMdf.acTransaction.AddNewlyCreatedDBObject(bref, true);
            //
            AttributeReference ar = new AttributeReference(attDef.Position.Add(position.GetAsVector()),
                                                           position.Z.ToString(), BlockAttributeName, style: attDef.TextStyleId);

            bref.AttributeCollection.AppendAttribute(ar);
            ar.DowngradeOpen();  //  AttributeReference 在 DowngradeOpen 后,才会立即显示,否则要通过Refresh等方法使其 DowngradeOpen 才能显示。
            bref.DowngradeOpen();
            return(bref);
        }
Beispiel #3
0
        //修改图块基点,现有同名块位置不变
        //[CommandMethod("BBI")]
        public void BBI()
        {
            Document doc = Application.DocumentManager.MdiActiveDocument;
            Database db  = doc.Database;
            Editor   ed  = doc.Editor;

            ed.WriteMessage("\n百福工具箱——修改图块基点,现有同名块位置不变");

            Point3d             basePoint = new Point3d();
            PromptEntityOptions peo       = new PromptEntityOptions("\n请选择要修改的图块");
            //peo.AddAllowedClass(typeof(BlockReference),false);
            PromptEntityResult per = ed.GetEntity(peo);

            if (per.Status == PromptStatus.OK)
            {
                ObjectId id = per.ObjectId;
                using (Transaction trans = db.TransactionManager.StartTransaction())
                {
                    BlockTable     bt  = (BlockTable)trans.GetObject(db.BlockTableId, OpenMode.ForRead);
                    BlockReference brf = (BlockReference)trans.GetObject(id, OpenMode.ForWrite);
                    basePoint = brf.Position;

                    PromptPointOptions ppo = new PromptPointOptions("\n请拾取新的插入点")
                    {
                        UseBasePoint = true,
                        BasePoint    = basePoint
                    };
                    PromptPointResult ppr = ed.GetPoint(ppo);
                    if (ppr.Status == PromptStatus.OK)
                    {
                        Point3d newBasePoint = ppr.Value;
                        using (DocumentLock dl = doc.LockDocument())
                        {
                            BlockTableRecord btr = (BlockTableRecord)trans.GetObject(brf.BlockTableRecord, OpenMode.ForWrite);

                            //修改块基点的代码不知道怎么写…………
                        }
                    }
                    brf.DowngradeOpen();
                    trans.Commit();
                }
            }
            else
            {
                return;
            }
        }
        public Entity GetBlockCondition(string s)
        {
            var entOpts = new PromptEntityOptions(s + "\n");

            var entRes = Ed.GetEntity(entOpts);

            ObjectId entId = ObjectId.Null;

            if (entRes.Status == PromptStatus.OK)
            {
                entId = entRes.ObjectId;
            }

            if (entId == ObjectId.Null)
            {
                return(null);
            }

            Entity br = null;

            using (var trans = Db.TransactionManager.StartTransaction())
            {
                br = trans.GetObject(entId, OpenMode.ForRead) as Entity;

                if (br == null)
                {
                    Application.ShowAlertDialog("一定要选择块定义");

                    trans.Commit();

                    return(null);
                }
                br.UpgradeOpen();

                br.Visible = false;

                //br.ColorIndex = 20;

                br.DowngradeOpen();


                trans.Commit();
            }

            return(br);
        }
Beispiel #5
0
        public void ExtractAttributesStart()
        {
            #region Init local vars
            List <Block> OriginalBlockDefs         = new List <Block>();
            List <Block> OriginalBlockRefs         = new List <Block>();
            SortedList <string, double> AttsTotals = new SortedList <string, double>();

            ObjectIdCollection OrigBlockRefsIds = new ObjectIdCollection();
            ObjectIdCollection OrigBlockDefsIds = new ObjectIdCollection();

            Document Doc = Application.DocumentManager.MdiActiveDocument;
            Database Db  = Doc.Database;
            Editor   Ed  = Doc.Editor;

            char[] badChars = { '\'', ' ', '-', '`', '~', '"', '_' };

            string dateFormat = "yyyy.MM.dd_HH.mm.ss";

            string[] stringSeparators = new string[] { "\\" };
            string[] fileNameExploded = Db.Filename.Split(stringSeparators, StringSplitOptions.None);

            string outputFileName = fileNameExploded[fileNameExploded.Length - 2] + "." + DateTime.Now.ToString(dateFormat) + ".xls";
            string outputDir      = Db.Filename.Remove(Db.Filename.LastIndexOf("\\") + 1);

            ExcelDocument document = new ExcelDocument();
            document.UserName = Environment.UserName;
            document.CodePage = CultureInfo.CurrentCulture.TextInfo.ANSICodePage;
            document.ColumnWidth(0, 120);
            document.ColumnWidth(1, 80);
            int XLSrows = 0;
            int XLScols = 0;

            document.WriteCell(XLSrows, 4, fileNameExploded[fileNameExploded.Length - 2]);
            XLSrows += 3;
            #endregion

            #region Prompt user for BlockRefs and dwg file/dir opts

            PromptEntityOptions PromptForBlocksOpts = new PromptEntityOptions("\nSelect single block");
            PromptForBlocksOpts.SetRejectMessage("\nYou can select blocks only.");
            PromptForBlocksOpts.AddAllowedClass(typeof(BlockReference), true);
            PromptForBlocksOpts.AllowNone = true;
            PromptEntityResult PromptForBlocksRes = Ed.GetEntity(PromptForBlocksOpts);
            if (PromptForBlocksRes.Status == PromptStatus.Cancel)
            {
                return;
            }

            // Prompt the user for blocks
            while (PromptForBlocksRes.Status == PromptStatus.OK)
            {
                using (Transaction Tr = Db.TransactionManager.StartTransaction())
                {
                    BlockReference Bref = (BlockReference)Tr.GetObject(PromptForBlocksRes.ObjectId, OpenMode.ForRead);
                    Bref.Highlight();         // highlight the selected BlockReference
                    OrigBlockRefsIds.Add(PromptForBlocksRes.ObjectId);

                    // extract the BlockTableRecord from the BlockReference
                    BlockTableRecord Btr = (BlockTableRecord)Tr.GetObject(Bref.BlockTableRecord, OpenMode.ForRead);

                    bool BlockIsAlreadyIn = false;
                    foreach (Block BlockDef in OriginalBlockDefs)
                    {
                        if (BlockDef.Name == Btr.Name)
                        {
                            BlockIsAlreadyIn = true;
                        }
                    }

                    if (!BlockIsAlreadyIn)
                    {
                        StringCollection AttributeTags = new StringCollection();
                        StringBuilder    Atts          = new StringBuilder();

                        foreach (ObjectId ObjId in Btr)
                        {
                            AttributeDefinition attDef = ObjId.GetObject(OpenMode.ForRead) as AttributeDefinition;
                            if (attDef != null)
                            {
                                Atts.Append(attDef.Tag + ";");
                                AttributeTags.Add(attDef.Tag);
                            }
                        }

                        if (AttributeTags.Count > 0)
                        {
                            OriginalBlockDefs.Add(new Block(Btr.Name));
                            OriginalBlockDefs[OriginalBlockDefs.Count - 1].AttributeTags = AttributeTags;

                            XLScols = 1;
                            foreach (string AttTag in AttributeTags)
                            {
                                document.WriteCell(XLSrows, XLScols, AttTag);
                                XLScols++;
                            }
                            XLSrows++;
                        }
                        else   // If a Block Def does not contain AttributeDefs - it is excluded
                        {
                            //ProcLogger.WriteToLog( "Block Definition ;" + Btr.Name + " was excluded becase it has no attributes" );
                        }
                    }
                    else
                    {
                        //ProcLogger.WriteToLog( "Block Definition not imported : ; already in." );
                    }
                    Tr.Commit();
                }

                #region If the user presses cancel in the middle
                //unhighlight all Block References and flush the collections

                PromptForBlocksRes = Ed.GetEntity(PromptForBlocksOpts);
                if (PromptForBlocksRes.Status == PromptStatus.Cancel)
                {
                    using (Transaction Tr = Db.TransactionManager.StartTransaction())
                    {
                        foreach (ObjectId BlockRefId in OrigBlockRefsIds)
                        {
                            BlockReference Bref = (BlockReference)Tr.GetObject(BlockRefId, OpenMode.ForWrite);
                            Bref.Unhighlight();
                            Bref.DowngradeOpen();
                        }

                        OriginalBlockDefs.Clear();
                        OriginalBlockRefs.Clear();

                        Tr.Commit();
                    }
                    return;
                }
                #endregion
            }

            #region Unhighlight all entities and get their BlockTableRecords ObjectIds
            using (Transaction Tr = Db.TransactionManager.StartTransaction())
            {
                foreach (ObjectId BlockRefId in OrigBlockRefsIds)
                {
                    BlockReference Bref = (BlockReference)Tr.GetObject(BlockRefId, OpenMode.ForRead);
                    Bref.Unhighlight();
                }
                Tr.Commit();
            }
            #endregion

            #region prompt for file or dir option
            PromptKeywordOptions KeywordsOpts = new PromptKeywordOptions("Scan current DWG or all files in DWGs dir?");
            KeywordsOpts.AllowArbitraryInput = false;
            KeywordsOpts.AllowNone           = false;
            KeywordsOpts.Keywords.Add("File");
            KeywordsOpts.Keywords.Add("Dir");
            PromptResult FileOrDirRes = Ed.GetKeywords(KeywordsOpts);
            // If the user pressed cancel - return with no error
            if (FileOrDirRes.Status != PromptStatus.OK)
            {
                return;
            }

            List <string> Files = new List <string>();
            string[]      tempFiles;
            if (FileOrDirRes.StringResult == "Dir")
            {
                string currFile = Db.Filename;
                string currDir  = currFile.Remove(currFile.LastIndexOf("\\") + 1);
                tempFiles = Directory.GetFiles(currDir, "*.dwg", SearchOption.AllDirectories);
                foreach (string tempFile in tempFiles)
                {
                    Files.Add(tempFile);
                }
            }
            else
            {
                Files.Add(Db.Filename);
            }

            // return;
            #endregion

            #endregion

            #region Traverse Dwgs and extract raw data
            Database UnopenedDb;

            Files.Sort();
            // Open every file
            foreach (string file in Files)
            {
                document.WriteCell(XLSrows, 0, file.Remove(0, file.LastIndexOf("\\") + 1));

                if (!file.EndsWith(".dwg", StringComparison.CurrentCultureIgnoreCase))
                {
                    continue;
                }

                // Open the Db from the file
                using (UnopenedDb = new Database(false, false))
                {
                    if (Db.Filename != file)
                    {
                        UnopenedDb.ReadDwgFile(file, FileShare.Read, true, "");
                    }
                    else
                    {
                        UnopenedDb = Db;
                    }

                    List <string>           AppendedTags    = new List <string>();
                    List <StringCollection> AttributeValues = new List <StringCollection>();
                    // open transaction to the db
                    using (Transaction Tr = UnopenedDb.TransactionManager.StartTransaction())
                    {
                        try
                        {
                            // Get the BlockTable
                            BlockTable Bt = (BlockTable)Tr.GetObject(UnopenedDb.BlockTableId, OpenMode.ForRead);

                            // Traverse all the layouts for Block References
                            foreach (ObjectId ObjId in Bt)
                            {
                                BlockTableRecord LayoutBtr = (BlockTableRecord)Tr.GetObject(ObjId, OpenMode.ForRead);
                                if (LayoutBtr.IsLayout)
                                {
                                    Layout currLayout = (Layout)Tr.GetObject(LayoutBtr.LayoutId, OpenMode.ForRead);
                                    if (!currLayout.LayoutName.Contains("Model"))
                                    {
                                        document.WriteCell(XLSrows++, 0, currLayout.LayoutName);
                                    }

                                    foreach (ObjectId LayoutObjId in LayoutBtr)
                                    {
                                        BlockReference Bref = Tr.GetObject(LayoutObjId, OpenMode.ForRead) as BlockReference;   // Dont tuch this!
                                        if (Bref != null)
                                        {
                                            StringCollection AttRefValuesForXLS = new StringCollection();
                                            foreach (Block BDef in OriginalBlockDefs)
                                            {
                                                if (Bref.Name == BDef.Name)
                                                {
                                                    for (int i = 0; i < Bref.AttributeCollection.Count; i++)
                                                    {
                                                        AttributeReference AttRef = (AttributeReference)Tr.GetObject(Bref.AttributeCollection[i], OpenMode.ForRead);

                                                        AttRefValuesForXLS.Add(AttRef.TextString.Trim(badChars).Trim());
                                                        continue;
                                                    }
                                                    AttributeValues.Add(AttRefValuesForXLS);
                                                }
                                            }
                                        }
                                    }

                                    #region // bubble sort the attributes by PartNr

                                    string tempAA     = "";
                                    string tempBB     = "";
                                    int    tempA      = 0;
                                    int    tempB      = 0;
                                    bool   parseAIsOk = false;
                                    bool   parseBIsOk = false;
                                    Match  MatchA;
                                    Match  MatchB;
                                    //string AlphaPattern = @"[a-z]|[A-Z]";
                                    string NumericPattern = @"[0-9]+";


                                    try
                                    {
                                        if (AttributeValues.Count > 1)
                                        {
                                            for (int j = 0; j < AttributeValues.Count; j++)
                                            {
                                                for (int i = 1; i < AttributeValues.Count; i++)
                                                {
                                                    tempBB = AttributeValues[i][0] = AttributeValues[i][0];
                                                    tempAA = AttributeValues[i - 1][0] = AttributeValues[i - 1][0];

                                                    MatchA = Regex.Match(tempAA, NumericPattern);
                                                    MatchB = Regex.Match(tempBB, NumericPattern);

                                                    parseAIsOk = Int32.TryParse(MatchA.ToString(), out tempA);
                                                    parseBIsOk = Int32.TryParse(MatchB.ToString(), out tempB);

                                                    if (parseAIsOk && parseBIsOk)
                                                    {
                                                        if (tempA > tempB)
                                                        {
                                                            StringCollection temp = AttributeValues[i];
                                                            AttributeValues[i]     = AttributeValues[i - 1];
                                                            AttributeValues[i - 1] = temp;
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                    catch (System.Exception Ex)
                                    {
                                        Ed.WriteMessage(Ex.Message + Ex.Source + Ex.StackTrace);
                                    }

                                    #endregion

                                    #region Parse and write the attribute collection to XLS file


                                    try
                                    {
                                        foreach (StringCollection BlockRefAttValues in AttributeValues)
                                        {
                                            if (!AttsTotals.Keys.Contains(BlockRefAttValues[4]))
                                            {
                                                double value;
                                                if (Double.TryParse(BlockRefAttValues[2], out value))
                                                {
                                                    AttsTotals.Add(BlockRefAttValues[4], value);
                                                }
                                                else
                                                {
                                                    AttsTotals.Add(BlockRefAttValues[4], 0);
                                                }
                                            }
                                            else
                                            {
                                                double value;
                                                double z;
                                                if (Double.TryParse(BlockRefAttValues[2], out value))
                                                {
                                                    z = value;
                                                }
                                                else
                                                {
                                                    z = 0;
                                                }
                                                double x;

                                                if (Double.TryParse(BlockRefAttValues[4], out value))
                                                {
                                                    x = value;
                                                }
                                                else
                                                {
                                                    x = 0;
                                                }

                                                //double total = AttsTotals[BlockRefAttValues[4]];
                                                //AttsTotals[BlockRefAttValues[4]] = total + z + x;
                                                AttsTotals[BlockRefAttValues[4]] += z + x;
                                            }

                                            XLScols = 1;
                                            foreach (string AttVal in BlockRefAttValues)
                                            {
                                                string tmp     = AttVal;
                                                double tempInt = 0;
                                                if (Double.TryParse(tmp, out tempInt))
                                                {
                                                    document.WriteCell(XLSrows, XLScols, tempInt);
                                                }
                                                else
                                                {
                                                    document.WriteCell(XLSrows, XLScols, tmp);
                                                }
                                                XLScols++;
                                            }
                                            XLSrows++;
                                        }
                                    }
                                    catch (System.Exception Ex)
                                    {
                                        MessageBox.Show(Ex.Message + "\n" + Ex.Source + "\n" + Ex.StackTrace);
                                    }
                                    #endregion
                                    AttributeValues.Clear();
                                }
                            }
                        }
                        catch (System.Exception Ex)
                        {
                            Ed.WriteMessage(Ex.Message + Ex.Source + Ex.StackTrace);
                        }
                    }
                }
                XLSrows += 3;
            }// foreach ( file in files )

            try
            {
                document.WriteCell(XLSrows, 5, "Parts");
                document.WriteCell(XLSrows, 3, "Totals");
                XLSrows++;

                foreach (KeyValuePair <string, double> Total in AttsTotals)
                {
                    //document.WriteCell(XLSrows, 5, Total.Key.ToString());
                    document.WriteCell(XLSrows, 5, Total.Key);
                    double value;
                    if (Double.TryParse(Total.Value.ToString(), out value))
                    {
                        document.WriteCell(XLSrows, 3, value);
                    }
                    else
                    {
                        document.WriteCell(XLSrows, 3, Total.Value.ToString());
                    }

                    document.WriteCell(XLSrows, 4, "Stk");
                    XLSrows++;
                }
            }
            catch (System.Exception Ex)
            {
                MessageBox.Show(Ex.Message + "\n" + Ex.Source + "\n" + Ex.StackTrace);
            }

            FileStream stream = new FileStream(outputDir + outputFileName, FileMode.Create);
            document.Save(stream);
            stream.Close();
            #endregion
        }
Beispiel #6
0
        // Thêm 1 block chứa bản vẽ của 1 file dwg vào bản vẽ hiện tại (có scale riêng)
        public static bool InsertDrawing(string partDwg, Scale3d scale, Point3d ipt, double angle, out ObjectId objectId)
        {
            Document doc       = AcAp.DocumentManager.MdiActiveDocument;
            Database curdb     = doc.Database; // Biến database của bản vẽ hện tại
            Editor   ed        = doc.Editor;
            string   blockname = Path.GetFileNameWithoutExtension(partDwg);
            bool     result    = false;

            objectId = ObjectId.Null;

            using (DocumentLock loc = doc.LockDocument())
            {
                ObjectId blkid = ObjectId.Null; // Biến lấy ID của file đọc vào
                try
                {
                    using (Database db = new Database(false, true))                  // Biến lấy database của file nạp vào
                    {
                        db.ReadDwgFile(partDwg, System.IO.FileShare.Read, true, ""); // Lấy database
                        blkid = curdb.Insert(partDwg, db, true);                     // Lấy ID
                    }
                }
                catch (IOException)
                {
                    return(false);
                }

                using (Transaction tr = doc.TransactionManager.StartTransaction())
                {
                    BlockTable bt = (BlockTable)tr.GetObject(curdb.BlockTableId, OpenMode.ForRead);
                    if (!bt.Has(blockname))
                    {
                        bt.UpgradeOpen();
                        BlockTableRecord btrec = blkid.GetObject(OpenMode.ForRead) as BlockTableRecord;
                        btrec.UpgradeOpen();    //nâng cấp để ghi
                        btrec.Name = blockname; //thêm tên
                        btrec.DowngradeOpen();  //hạ cấp, không cho ghi nữa
                        bt.DowngradeOpen();
                    }
                    blkid = bt[blockname];

                    //Thêm các hình vẽ ở bản vẽ cũ vào
                    using (BlockTableRecord btr = (BlockTableRecord)curdb.CurrentSpaceId.GetObject(OpenMode.ForWrite))
                    {
                        //Insert vật thể
                        using (BlockReference bref = new BlockReference(ipt, blkid))
                        {
                            Matrix3d mat = Matrix3d.Identity;
                            bref.TransformBy(mat);
                            bref.ScaleFactors = scale;
                            bref.Rotation     = angle;
                            btr.AppendEntity(bref);
                            tr.AddNewlyCreatedDBObject(bref, true);
                            bref.DowngradeOpen();
                            objectId = bref.ObjectId;
                        }
                    }

                    //Tạo lại bản vẽ???
                    ed.Regen();
                    tr.Commit();
                    result = true;
                }
            }

            return(result);
        }
Beispiel #7
0
        addBlockRef(string strName, Point3d pnt3dIns, double dblRotation, List <string> attValues)
        {
            Database db = BaseObjs._db;
            Editor   ed = BaseObjs._editor;

            BlockTableRecord btrx = null;
            BlockReference   br   = null;

            try
            {
                using (Transaction tr = BaseObjs.startTransactionDb())
                {
                    BlockTable bt = (BlockTable)db.BlockTableId.GetObject(OpenMode.ForRead);
                    if (!bt.Has(strName))
                    {
                        btrx = addBtr(strName);
                    }
                    else
                    {
                        btrx = (BlockTableRecord)bt[strName].GetObject(OpenMode.ForRead);
                    }

                    //---> debug only
                    foreach (ObjectId idObj in btrx)
                    {
                        Entity ent             = (Entity)idObj.GetObject(OpenMode.ForRead);
                        AttributeDefinition ad = ent as AttributeDefinition;

                        if (ad != null)
                        {
                            ed.WriteMessage(string.Format("\n{0}", ad.Tag));
                        }
                    }//<--- debug only

                    //BlockTableRecord Btr = (BlockTableRecord)DB.CurrentSpaceId.GetObject(OpenMode.ForWrite);

                    btrx.UpgradeOpen();

                    using (btrx)
                    {
                        br = new BlockReference(pnt3dIns, btrx.ObjectId);
                        using (br)
                        {
                            Matrix3d           ucsMatrix = ed.CurrentUserCoordinateSystem;
                            CoordinateSystem3d ucs       = ucsMatrix.CoordinateSystem3d;

                            Matrix3d mat3d = new Matrix3d();
                            mat3d = Matrix3d.Rotation(dblRotation, ucs.Zaxis, pnt3dIns);

                            br.TransformBy(mat3d);
                            br.ScaleFactors = new Scale3d(1, 1, 1);
                            btrx.AppendEntity(br);
                            tr.AddNewlyCreatedDBObject(br, true);

                            BlockTableRecord btratt = (BlockTableRecord)br.BlockTableRecord.GetObject(OpenMode.ForRead);
                            using (btratt)
                            {
                                Autodesk.AutoCAD.DatabaseServices.AttributeCollection ATTcol = br.AttributeCollection;

                                foreach (ObjectId subid in btratt)
                                {
                                    Entity ent             = (Entity)subid.GetObject(OpenMode.ForRead);
                                    AttributeDefinition ad = ent as AttributeDefinition;

                                    if (ad != null)
                                    {
                                        AttributeReference ar = new AttributeReference();
                                        ar.SetPropertiesFrom(ad);
                                        ar.SetAttributeFromBlock(ad, br.BlockTransform);
                                        ar.Visible = ad.Visible;

                                        ar.HorizontalMode = ad.HorizontalMode;
                                        ar.VerticalMode   = ad.VerticalMode;
                                        ar.Rotation       = ad.Rotation;
                                        ar.TextStyleId    = ad.TextStyleId;
                                        ar.Position       = ad.Position + pnt3dIns.GetAsVector();
                                        ar.Tag            = ad.Tag;
                                        ar.FieldLength    = ad.FieldLength;
                                        ar.AdjustAlignment(db);

                                        //if (ar.Tag == "TOPTXT")
                                        //    ar.TextString = strTop;

                                        //if (ar.Tag == "MIDTXT")
                                        //    ar.TextString = strMid;

                                        //if (ar.Tag == "BOTTXT")
                                        //    ar.TextString = strBot;

                                        ar.Position = ad.Position.TransformBy(br.BlockTransform);

                                        ATTcol.AppendAttribute(ar);
                                        tr.AddNewlyCreatedDBObject(ar, true);
                                    }
                                }
                            }
                            br.DowngradeOpen();
                        }

                        btrx.DowngradeOpen();
                    }
                    tr.Commit();
                }
            }
            catch (System.Exception ex)
            {
                BaseObjs.writeDebug(ex.Message + " Blocks.cs: line: 194");
            }
            return(br);
        }
Beispiel #8
0
        addBlockRef(string strName, string strTopNum, string strTopTxt, string strBotNum, string strBotTxt, Point3d pnt3dIns, double dblRotation)
        {
            Database DB = BaseObjs._db;
            Editor   ED = BaseObjs._editor;

            ObjectId         blkID = ObjectId.Null;
            BlockTableRecord Btrx  = null;

            using (Transaction tr = BaseObjs.startTransactionDb())
            {
                BlockTable BT = (BlockTable)DB.BlockTableId.GetObject(OpenMode.ForRead);
                if (!BT.Has(strName))
                {
                    blkID = insBlockRef(@"R:\Tset\Block\", "GradeTag.dwg");
                    Btrx  = (BlockTableRecord)blkID.GetObject(OpenMode.ForRead);
                    Btrx.UpgradeOpen();
                    Btrx.Name = "GradeTag";
                    Btrx.DowngradeOpen();
                }
                else
                {
                    Btrx = (BlockTableRecord)BT[strName].GetObject(OpenMode.ForRead);
                }

                //---> debug only
                foreach (ObjectId objID in Btrx)
                {
                    Entity ENT             = (Entity)objID.GetObject(OpenMode.ForRead);
                    AttributeDefinition AD = ENT as AttributeDefinition;

                    if (AD != null)
                    {
                        ED.WriteMessage(string.Format("\n{0}", AD.Tag));
                    }
                }//<--- debug only

                BlockTableRecord Btr = (BlockTableRecord)DB.CurrentSpaceId.GetObject(OpenMode.ForWrite);

                using (Btr)
                {
                    BlockReference BR = new BlockReference(pnt3dIns, Btrx.ObjectId);
                    using (BR)
                    {
                        Matrix3d           UCSMatrix = ED.CurrentUserCoordinateSystem;
                        CoordinateSystem3d UCS       = UCSMatrix.CoordinateSystem3d;

                        Matrix3d MAT3d = new Matrix3d();
                        MAT3d = Matrix3d.Rotation(dblRotation, UCS.Zaxis, pnt3dIns);

                        BR.TransformBy(MAT3d);
                        BR.ScaleFactors = new Scale3d(1, 1, 1);
                        Btr.AppendEntity(BR);
                        tr.AddNewlyCreatedDBObject(BR, true);

                        BlockTableRecord Btratt = (BlockTableRecord)BR.BlockTableRecord.GetObject(OpenMode.ForRead);
                        using (Btratt)
                        {
                            Autodesk.AutoCAD.DatabaseServices.AttributeCollection ATTcol = BR.AttributeCollection;

                            foreach (ObjectId subID in Btratt)
                            {
                                Entity ENT             = (Entity)subID.GetObject(OpenMode.ForRead);
                                AttributeDefinition AD = ENT as AttributeDefinition;

                                if (AD != null)
                                {
                                    AttributeReference AR = new AttributeReference();
                                    AR.SetPropertiesFrom(AD);
                                    AR.SetAttributeFromBlock(AD, BR.BlockTransform);
                                    AR.Visible = AD.Visible;

                                    AR.HorizontalMode = AD.HorizontalMode;
                                    AR.VerticalMode   = AD.VerticalMode;
                                    AR.Rotation       = AD.Rotation;
                                    AR.TextStyleId    = AD.TextStyleId;
                                    AR.Position       = AD.Position + pnt3dIns.GetAsVector();
                                    AR.Tag            = AD.Tag;
                                    AR.FieldLength    = AD.FieldLength;
                                    AR.AdjustAlignment(DB);

                                    if (AR.Tag == "TOPNUM")
                                    {
                                        AR.TextString = strTopNum;
                                    }

                                    if (AR.Tag == "TOPTXT")
                                    {
                                        AR.TextString = strTopTxt;
                                    }

                                    if (AR.Tag == "BOTNUM")
                                    {
                                        AR.TextString = strBotNum;
                                    }

                                    if (AR.Tag == "BOTTXT")
                                    {
                                        AR.TextString = strBotTxt;
                                    }

                                    AR.Position = AD.Position.TransformBy(BR.BlockTransform);

                                    ATTcol.AppendAttribute(AR);
                                    tr.AddNewlyCreatedDBObject(AR, true);
                                } // end if
                            }     //end foreach
                        }
                        BR.DowngradeOpen();
                    }

                    Btr.DowngradeOpen();
                }

                // BT.DowngradeOpen ();
                tr.Commit();
            }
            return(true);
        }