Exemplo n.º 1
0
        static public void DynamicBlockProps()
        {
            _AcAp.Document doc = _AcAp.Application.DocumentManager.MdiActiveDocument;
            _AcDb.Database db  = doc.Database;
            _AcEd.Editor   ed  = doc.Editor;

            _AcEd.PromptStringOptions pso = new _AcEd.PromptStringOptions("\nEnter dynamic block name or enter to select: ");
            pso.AllowSpaces = true;
            _AcEd.PromptResult pr = ed.GetString(pso);

            if (pr.Status != _AcEd.PromptStatus.OK)
            {
                return;
            }

            _AcDb.Transaction tr = db.TransactionManager.StartTransaction();
            using (tr)
            {
                _AcDb.BlockReference br = null;
                // If a null string was entered allow entity selection
                if (pr.StringResult == "")
                {
                    // Select a block reference
                    _AcEd.PromptEntityOptions peo = new _AcEd.PromptEntityOptions("\nSelect dynamic block reference: ");
                    peo.SetRejectMessage("\nEntity is not a block.");
                    peo.AddAllowedClass(typeof(_AcDb.BlockReference), false);

                    _AcEd.PromptEntityResult per = ed.GetEntity(peo);
                    if (per.Status != _AcEd.PromptStatus.OK)
                    {
                        return;
                    }

                    // Access the selected block reference
                    br = tr.GetObject(per.ObjectId, _AcDb.OpenMode.ForRead) as _AcDb.BlockReference;
                }

                else
                {
                    // Otherwise we look up the block by name
                    _AcDb.BlockTable bt = tr.GetObject(db.BlockTableId, _AcDb.OpenMode.ForRead) as _AcDb.BlockTable;
                    if (!bt.Has(pr.StringResult))
                    {
                        ed.WriteMessage("\nBlock \"" + pr.StringResult + "\" does not exist.");
                        return;
                    }

                    // Create a new block reference referring to the block
                    br = new _AcDb.BlockReference(new _AcGe.Point3d(), bt[pr.StringResult]);
                }

                _AcDb.BlockTableRecord btr = (_AcDb.BlockTableRecord)tr.GetObject(br.DynamicBlockTableRecord, _AcDb.OpenMode.ForRead);

                // Call our function to display the block properties
                DisplayDynBlockProperties(ed, br, btr.Name);

                // Committing is cheaper than aborting
                tr.Commit();
            }
        }
Exemplo n.º 2
0
 private static void GetAllFgsAbzsAndRbs(string rbName, string fgLayer, string afLayer, _AcDb.Database db, _AcDb.Transaction tr, List <_AcDb.Entity> fgs, List <_AcDb.Entity> azf, List <_AcDb.Entity> rbs)
 {
     _AcDb.BlockTable       bt  = (_AcDb.BlockTable)tr.GetObject(db.BlockTableId, _AcDb.OpenMode.ForRead);
     _AcDb.BlockTableRecord btr = (_AcDb.BlockTableRecord)tr.GetObject(bt[_AcDb.BlockTableRecord.ModelSpace], _AcDb.OpenMode.ForRead);
     foreach (_AcDb.ObjectId objId in btr)
     {
         _AcDb.Entity ent  = (_AcDb.Entity)tr.GetObject(objId, _AcDb.OpenMode.ForRead);
         var          poly = ent as _AcDb.Polyline;
         if (poly != null)
         {
             if (string.Compare(poly.Layer, fgLayer, StringComparison.OrdinalIgnoreCase) == 0)
             {
                 fgs.Add(ent);
             }
             else if (string.Compare(poly.Layer, afLayer, StringComparison.OrdinalIgnoreCase) == 0)
             {
                 azf.Add(ent);
             }
         }
         else
         {
             var block = ent as _AcDb.BlockReference;
             if (block != null)
             {
                 if (string.Compare(block.Name, rbName, StringComparison.OrdinalIgnoreCase) == 0)
                 {
                     rbs.Add(ent);
                 }
             }
         }
     }
 }
Exemplo n.º 3
0
        private void GetAllMsXrefs(_AcDb.Database db, List <_AcDb.ObjectId> allXrefsInMs)
        {
            log.Debug("GetAllMsXrefs");
            using (_AcDb.Transaction tr = _TransMan.StartTransaction())
            {
                _AcDb.BlockTable bt = (_AcDb.BlockTable)tr.GetObject(db.BlockTableId, _AcDb.OpenMode.ForRead);

                _AcDb.BlockTableRecord btr = (_AcDb.BlockTableRecord)tr.GetObject(_AcDb.SymbolUtilityServices.GetBlockModelSpaceId(db), _AcDb.OpenMode.ForRead);

                foreach (var oid in btr)
                {
                    var br = tr.GetObject(oid, _AcDb.OpenMode.ForRead) as _AcDb.BlockReference;
                    if (br != null)
                    {
                        var bd = (_AcDb.BlockTableRecord)tr.GetObject(br.BlockTableRecord, _AcDb.OpenMode.ForRead);
                        if (bd.IsFromExternalReference)
                        {
                            allXrefsInMs.Add(br.ObjectId);
                        }
                    }
                }

                tr.Commit();
            }
        }
Exemplo n.º 4
0
        public List <_AcDb.ObjectId> GetAllBlocksInModelSpaceWith(Func <_AcDb.BlockReference, bool> checkFunc, string blockName)
        {
            var oids = new List <_AcDb.ObjectId>();
            var doc  = Application.DocumentManager.MdiActiveDocument;
            var db   = doc.Database;

            using (_AcDb.Transaction tr = doc.TransactionManager.StartTransaction())
            {
                _AcDb.BlockTable       bt  = (_AcDb.BlockTable)tr.GetObject(db.BlockTableId, _AcDb.OpenMode.ForRead);
                _AcDb.BlockTableRecord btr = (_AcDb.BlockTableRecord)tr.GetObject(bt[_AcDb.BlockTableRecord.ModelSpace], _AcDb.OpenMode.ForRead);

                foreach (var oid in btr)
                {
                    var blockRef = tr.GetObject(oid, _AcDb.OpenMode.ForRead) as _AcDb.BlockReference;
                    if (blockRef != null)
                    {
                        if (string.Compare(blockRef.Name, blockName, StringComparison.OrdinalIgnoreCase) == 0)
                        {
                            if (checkFunc(blockRef))
                            {
                                oids.Add(oid);
                            }
                        }
                    }
                }
                tr.Commit();
            }

            return(oids);
        }
Exemplo n.º 5
0
        public static void ReplaceAttributeBlock(AcDb.ObjectId idBlock,
                                                 string tag,
                                                 string newValue,
                                                 Boolean visible)
        {
            try
            {
                //using (AcDb.Transaction tr = db.TransactionManager.StartTransaction())
                //{
                //    DBObject dbObj = tr.GetObject(idBlock, AcDb.OpenMode.ForRead) as DBObject;
                //    AcDb.BlockReference blockReference = dbObj as BlockReference;
                //    ReplaceAttributeBlock(blockReference, tag, newValue, visible);
                //}


                using (AcDb.Transaction tr = db.TransactionManager.StartTransaction())
                {
                    AcDb.BlockTable acBlockTable = (AcDb.BlockTable)tr.GetObject(db.BlockTableId, AcDb.OpenMode.ForRead);
                    if (acBlockTable == null)
                    {
                        return;
                    }

                    AcDb.BlockTableRecord acBlockTableRecord = (AcDb.BlockTableRecord)
                                                               tr.GetObject(acBlockTable[AcDb.BlockTableRecord.ModelSpace], AcDb.OpenMode.ForRead);
                    if (acBlockTableRecord == null)
                    {
                        return;
                    }

                    //foreach (var blkId in acBlockTableRecord)
                    //{
                    AcDb.BlockReference acBlock = (AcDb.BlockReference)tr.GetObject(idBlock, AcDb.OpenMode.ForRead);
                    //if (acBlock == null) continue;
                    //if (!acBlock.Name.Equals(blockName, StringComparison.CurrentCultureIgnoreCase)) continue;
                    foreach (AcDb.ObjectId attId in acBlock.AttributeCollection)
                    {
                        AcDb.AttributeReference acAtt = (AcDb.AttributeReference)tr.GetObject(attId, AcDb.OpenMode.ForRead);
                        if (acAtt == null)
                        {
                            continue;
                        }

                        if (!acAtt.Tag.Equals(tag, StringComparison.CurrentCultureIgnoreCase))
                        {
                            continue;
                        }

                        acAtt.UpgradeOpen();
                        acAtt.TextString = newValue;
                    }
                    //}
                    tr.Commit();
                }
            }
            catch //(System.Exception exc)
            {
            }
        }
Exemplo n.º 6
0
        public static void ManualInsertbAttribute(string nameBlock)
        {
            using (AcDb.Transaction tr = db.TransactionManager.StartTransaction())
            {
                AcDb.BlockTable blockTable = (AcDb.BlockTable)tr.GetObject(db.BlockTableId, AcDb.OpenMode.ForRead);
                if (!blockTable.Has(nameBlock))
                {
                    ed.WriteMessage("\nНезнайдено блок '{0}' у таблиці блоків креслення.", nameBlock);
                    return;
                }
                AcDb.BlockTableRecord curSpace       = (AcDb.BlockTableRecord)tr.GetObject(db.CurrentSpaceId, AcDb.OpenMode.ForWrite);
                AcDb.BlockReference   blockReference = new AcDb.BlockReference(AcGe.Point3d.Origin, blockTable[nameBlock]);
                blockReference.TransformBy(ed.CurrentUserCoordinateSystem);
                curSpace.AppendEntity(blockReference);
                tr.AddNewlyCreatedDBObject(blockReference, true);

                AcDb.BlockTableRecord btr = (AcDb.BlockTableRecord)tr.GetObject(blockTable[nameBlock], AcDb.OpenMode.ForRead);
                AcDb.DBText           text;
                foreach (AcDb.ObjectId id in btr)
                {
                    if (id.ObjectClass.Name == "AcDbAttributeDefinition")
                    {
                        AcDb.AttributeDefinition attDef =
                            (AcDb.AttributeDefinition)tr.GetObject(id, AcDb.OpenMode.ForRead);

                        text = new AcDb.DBText
                        {
                            TextString = "jig_test"
                        };

                        TextPlacementJig jig = new TextPlacementJig(text);

                        //PromptResult pr = ed.Drag(jig);

                        AcEd.PromptStatus stat = AcEd.PromptStatus.Keyword;
                        while (stat == AcEd.PromptStatus.Keyword)
                        {
                            AcEd.PromptResult pr = ed.Drag(jig);
                            stat = pr.Status;
                            if (stat != AcEd.PromptStatus.OK && stat != AcEd.PromptStatus.Keyword)
                            {
                                return;
                            }
                        }

                        AcDb.AttributeReference attRef = new AcDb.AttributeReference();
                        attRef.SetAttributeFromBlock(attDef, blockReference.BlockTransform);
                        AcDb.ObjectId attId = blockReference.AttributeCollection.AppendAttribute(attRef);
                        tr.AddNewlyCreatedDBObject(attRef, true);


                        tr.Commit();
                        //if (pr.Status != PromptStatus.OK) blockReference.Erase();
                    }
                }

                //tr.Commit();
            }
        }
Exemplo n.º 7
0
        public _CONNECTION()
        {
            _doc   = _Ap.Application.DocumentManager.MdiActiveDocument;
            _db    = _doc.Database;
            _ed    = _doc.Editor;
            _trans = _db.TransactionManager.StartTransaction();

            _blockTable = _trans.GetObject(_db.BlockTableId, _Db.OpenMode.ForWrite) as _Db.BlockTable;
            _modelSpace = _trans.GetObject(_Db.SymbolUtilityServices.GetBlockModelSpaceId(_db), _Db.OpenMode.ForWrite) as _Db.BlockTableRecord;
        }
Exemplo n.º 8
0
        public static void DrawOrder_MoveToTop(AcDb.ObjectIdCollection collection)
        {
            using (AcDb.Transaction tr = db.TransactionManager.StartTransaction())
            {
                AcDb.BlockTable       bt  = (AcDb.BlockTable)tr.GetObject(db.BlockTableId, AcDb.OpenMode.ForRead);
                AcDb.BlockTableRecord btr = (AcDb.BlockTableRecord)tr.GetObject(bt[AcDb.BlockTableRecord.ModelSpace], AcDb.OpenMode.ForWrite);

                AcDb.DrawOrderTable dot = (AcDb.DrawOrderTable)tr.GetObject(btr.DrawOrderTableId, AcDb.OpenMode.ForWrite);
                dot.MoveToTop(collection);
            }
        }
Exemplo n.º 9
0
        public static void EditeAttributeBlock(string blockName, string tag, string newValue)
        {
            using (AcDb.Transaction tr = db.TransactionManager.StartTransaction())
            {
                AcDb.BlockTable acBlockTable = (AcDb.BlockTable)tr.GetObject(db.BlockTableId, AcDb.OpenMode.ForRead);
                if (acBlockTable == null)
                {
                    return;
                }

                AcDb.BlockTableRecord acBlockTableRecord = (AcDb.BlockTableRecord)tr.GetObject(acBlockTable[AcDb.BlockTableRecord.ModelSpace], AcDb.OpenMode.ForRead);
                if (acBlockTableRecord == null)
                {
                    return;
                }

                foreach (var blkId in acBlockTableRecord)
                {
                    try
                    {
                        AcDb.BlockReference acBlock = (AcDb.BlockReference)tr.GetObject(blkId, AcDb.OpenMode.ForRead);
                        if (acBlock == null)
                        {
                            continue;
                        }
                        if (!acBlock.Name.Equals(blockName, StringComparison.CurrentCultureIgnoreCase))
                        {
                            continue;
                        }
                        foreach (AcDb.ObjectId attId in acBlock.AttributeCollection)
                        {
                            var acAtt = tr.GetObject(attId, AcDb.OpenMode.ForRead) as AcDb.AttributeReference;
                            if (acAtt == null)
                            {
                                continue;
                            }

                            if (!acAtt.Tag.Equals(tag, StringComparison.CurrentCultureIgnoreCase))
                            {
                                continue;
                            }

                            acAtt.UpgradeOpen();
                            acAtt.TextString = newValue;
                        }
                    }
                    catch
                    {
                    }
                }

                tr.Commit();
            }
        }
Exemplo n.º 10
0
        public void TestTrans()
        {
            try
            {
                //System.Windows.Forms.MessageBox.Show(string.Format(CultureInfo.InvariantCulture, "_test = {0}", _test));
                //_test = 0;



                _AcDb.Database           db      = _AcAp.Application.DocumentManager.MdiActiveDocument.Database;
                _AcDb.TransactionManager dbTrans = db.TransactionManager;
                using (_AcDb.Transaction trans = dbTrans.StartTransaction())
                {
                    // create a line
                    _AcDb.Line       ln = new _AcDb.Line(new _AcGe.Point3d(0.0, 0.0, 0.0), new _AcGe.Point3d(1.0, 1.0, 0.0));
                    _AcDb.BlockTable bt = dbTrans.GetObject(db.BlockTableId, _AcDb.OpenMode.ForRead, false) as _AcDb.BlockTable;
                    if (bt == null)
                    {
                        return;
                    }
                    //ObjectId id = bt[BlockTableRecord.ModelSpace];
                    _AcDb.BlockTableRecord btr = dbTrans.GetObject(bt[_AcDb.BlockTableRecord.ModelSpace], _AcDb.OpenMode.ForWrite, false) as _AcDb.BlockTableRecord;
                    if (btr == null)
                    {
                        return;
                    }
                    //Add it to the model space block table record.
                    btr.AppendEntity(ln);
                    //Make sure that the transaction knows about this new object.    tm.AddNewlyCreatedDBObject(line, True)
                    dbTrans.AddNewlyCreatedDBObject(ln, true);


                    //'Add some hyperlinks.    Dim hyper As New HyperLink()    hyper.Name = "www.autodesk.com"    line.Hyperlinks.Add(hyper)
                    _AcDb.HyperLink hyper = new _AcDb.HyperLink();
                    hyper.Name = "www.facebook.com";
                    ln.Hyperlinks.Add(hyper);
                    if (ln.Hyperlinks.Contains(hyper))
                    {
                        hyper.Name = "www.gotdotnet.com";
                    }
                    ln.Hyperlinks.Add(hyper);
                    foreach (var hl in ln.Hyperlinks)
                    {
                        System.Diagnostics.Debug.WriteLine(hl.ToString());
                    }
                    trans.Commit();
                }
            }
            catch (System.Exception ex)
            {
                System.Windows.Forms.MessageBox.Show(ex.Message);
            }
        }
Exemplo n.º 11
0
        private bool getBlockFromMaster(ref List <string> missingBlocks)
        {
            _Db.Database sourceDb       = new _Db.Database(false, true);
            string       sourceFileName = @"C:\Brics_pealeehitus\master.dwg";

            if (!File.Exists(sourceFileName))
            {
                sourceFileName = @"C:\Users\aleksandr.ess\Dropbox\DMT\Brics_testimine\master.dwg";
                if (!File.Exists(sourceFileName))
                {
                    sourceFileName = @"C:\Users\Alex\Dropbox\DMT\Brics_testimine\master.dwg";
                }
            }

            sourceDb.ReadDwgFile(sourceFileName, System.IO.FileShare.Read, true, "");
            _Db.ObjectIdCollection blockIds = new _Db.ObjectIdCollection();


            using (_Db.Transaction sourceTrans = sourceDb.TransactionManager.StartTransaction())
            {
                _Db.BlockTable sourceBlockTable = sourceTrans.GetObject(sourceDb.BlockTableId, _Db.OpenMode.ForRead, false) as _Db.BlockTable;

                foreach (_Db.ObjectId sourceObject in sourceBlockTable)
                {
                    _Db.BlockTableRecord btr = sourceTrans.GetObject(sourceObject, _Db.OpenMode.ForRead, false) as _Db.BlockTableRecord;

                    if (!btr.IsAnonymous && !btr.IsLayout)
                    {
                        if (missingBlocks.Contains(btr.Name))
                        {
                            blockIds.Add(sourceObject);
                            missingBlocks.Remove(btr.Name);
                            write("[SETUP] " + btr.Name); // TODO REMOVE
                        }
                    }

                    btr.Dispose();
                }
            }

            if (missingBlocks.Count > 0)
            {
                return(false);
            }

            _Db.IdMapping mapping = new _Db.IdMapping();
            sourceDb.WblockCloneObjects(blockIds, _c.blockTable.Id, mapping, _Db.DuplicateRecordCloning.Replace, false);
            sourceDb.Dispose();

            write("[SETUP] Kõik puuduvad blockid on lisatud 'master' failist");
            return(true);
        }
Exemplo n.º 12
0
        public static void ReplaceAttributeBlock(AcDb.BlockReference blockReference,
                                                 Dictionary <string, string> tags,
                                                 Boolean visible)
        {
            using (AcDb.Transaction trAdding = db.TransactionManager.StartTransaction())
            {
                AcDb.BlockTable       btTable  = (AcDb.BlockTable)trAdding.GetObject(db.BlockTableId, AcDb.OpenMode.ForRead);
                AcDb.BlockTableRecord btrTable =
                    (AcDb.BlockTableRecord)btTable[blockReference.Name].GetObject(AcDb.OpenMode.ForRead);

                if (btrTable.HasAttributeDefinitions)
                {
                    var attDefs = btrTable.Cast <AcDb.ObjectId>()
                                  .Where(n => n.ObjectClass.Name == "AcDbAttributeDefinition")
                                  .Select(n => (AcDb.AttributeDefinition)n.GetObject(AcDb.OpenMode.ForRead));

                    foreach (AcDb.AttributeDefinition attDef in attDefs)
                    {
                        AcDb.AttributeReference attRef = new AcDb.AttributeReference();
                        attRef.SetAttributeFromBlock(attDef, blockReference.BlockTransform);

                        foreach (var tag in tags)
                        {
                            attRef.UpgradeOpen();
                            if (tag.Key.ToUpper() == attRef.Tag)
                            {
                                attRef.TextString = tag.Value;
                            }
                            else
                            {
                                attRef.TextString = "NoneValue";
                            }
                            attRef.Visible  = visible;
                            attRef.Rotation = 0;
                        }

                        blockReference.AttributeCollection.AppendAttribute(attRef);
                        trAdding.AddNewlyCreatedDBObject(attRef, false);
                    }
                }
                else
                {
                    ed.WriteMessage("\n < ERROR > ");
                }

                trAdding.Commit();
            }
        }
Exemplo n.º 13
0
        private void ExplodeBlocks(_AcDb.Database db, List <_AcDb.ObjectId> allXrefsInMs, List <_AcDb.ObjectId> newlyCreatedObjects, bool deleteRef, bool deleteBtr)
        {
            log.Debug("ExplodeXRefs");
            using (_AcDb.Transaction tr = _TransMan.StartTransaction())
            {
                _AcDb.BlockTable bt = (_AcDb.BlockTable)tr.GetObject(db.BlockTableId, _AcDb.OpenMode.ForRead);

                _AcDb.BlockTableRecord btr = (_AcDb.BlockTableRecord)tr.GetObject(_AcDb.SymbolUtilityServices.GetBlockModelSpaceId(db), _AcDb.OpenMode.ForWrite);


                foreach (var oid in allXrefsInMs)
                {
                    _AcDb.DBObjectCollection objs  = new _AcDb.DBObjectCollection();
                    _AcDb.BlockReference     block = (_AcDb.BlockReference)tr.GetObject(oid, _AcDb.OpenMode.ForRead);
                    log.DebugFormat(CultureInfo.CurrentCulture, "Explode von Block '{0}'.", block.Name);
                    block.Explode(objs);
                    log.DebugFormat(CultureInfo.CurrentCulture, "Block enthält {0} Entities.", objs.Count);
                    _AcDb.ObjectId blockRefTableId = block.BlockTableRecord;


                    foreach (_AcDb.DBObject obj in objs)
                    {
                        _AcDb.Entity ent = (_AcDb.Entity)obj;
                        btr.AppendEntity(ent);
                        tr.AddNewlyCreatedDBObject(ent, true);

                        newlyCreatedObjects.Add(ent.ObjectId);
                    }

                    if (deleteRef)
                    {
                        log.DebugFormat(CultureInfo.CurrentCulture, "Lösche Block '{0}'.", block.Name);
                        block.UpgradeOpen();
                        block.Erase();
                    }

                    if (deleteBtr)
                    {
                        log.DebugFormat("DeleteBtr");
                        // funkt nicht -> xref würde gelöscht
                        var bd = (_AcDb.BlockTableRecord)tr.GetObject(blockRefTableId, _AcDb.OpenMode.ForWrite);
                        bd.Erase();
                        log.DebugFormat("Endof DeleteBtr");
                    }
                }
                tr.Commit();
            }
        }
Exemplo n.º 14
0
        private static bool SetAttValues(_AcDb.Database db)
        {
            bool ok = true;

            try
            {
                using (_AcDb.Transaction tr = db.TransactionManager.StartTransaction())
                {
                    _AcDb.BlockTable bt = (_AcDb.BlockTable)tr.GetObject(db.BlockTableId, _AcDb.OpenMode.ForRead);
                    foreach (var id in bt)
                    {
                        _AcDb.BlockTableRecord btr = (_AcDb.BlockTableRecord)tr.GetObject(id, _AcDb.OpenMode.ForRead);
                        if (btr.IsLayout)
                        {
                            foreach (var oid in btr)
                            {
                                var ent = tr.GetObject(oid, _AcDb.OpenMode.ForRead);
                                _AcDb.BlockReference bref = ent as _AcDb.BlockReference;
                                if (bref != null)
                                {
                                    bool sameName = false;
                                    try
                                    {
                                        sameName = (bref.Name == _BlockName);
                                    }
                                    catch (Exception)
                                    {
                                        log.WarnFormat("Invalid block with handle {0}!", bref.Handle);
                                    }
                                    if (sameName)
                                    {
                                        SetAttValues(bref, tr);
                                    }
                                }
                            }
                        }
                    }

                    tr.Commit();
                }
            }
            catch (System.Exception ex)
            {
                log.Error(string.Format(CultureInfo.CurrentCulture, "Fehler beim Ändern der Attribute: {0}", ex.Message), ex);
                ok = false;
            }
            return(ok);
        }
Exemplo n.º 15
0
        /// <summary>
        /// Öffnen einer Dwg ohne Editor
        /// </summary>
        //[_AcTrx.CommandMethod("Plan2TestSideDb")]
        static public void Plan2TestSideDb()
        {
            _AcAp.Document doc = _AcAp.Application.DocumentManager.MdiActiveDocument;
            _AcEd.Editor   ed  = doc.Editor;
            // Ask the user to select a file
            _AcEd.PromptResult res = ed.GetString("\nEnter the path of a DWG or DXF file: ");
            if (res.Status == _AcEd.PromptStatus.OK)
            {
                // Create a database and try to load the file
                _AcDb.Database db = new _AcDb.Database(false, true);
                using (db)
                {
                    try
                    {
                        db.ReadDwgFile(res.StringResult, System.IO.FileShare.Read, false, "");
                    }
                    catch (System.Exception)
                    {
                        ed.WriteMessage("\nUnable to read drawing file.");
                        return;
                    }

                    _AcDb.Transaction tr = db.TransactionManager.StartTransaction();
                    using (tr)
                    {
                        // Open the blocktable, get the modelspace
                        _AcDb.BlockTable       bt  = (_AcDb.BlockTable)tr.GetObject(db.BlockTableId, _AcDb.OpenMode.ForRead);
                        _AcDb.BlockTableRecord btr = (_AcDb.BlockTableRecord)tr.GetObject(bt[_AcDb.BlockTableRecord.ModelSpace], _AcDb.OpenMode.ForRead);

                        // Iterate through it, dumping objects
                        foreach (_AcDb.ObjectId objId in btr)
                        {
                            _AcDb.Entity ent = (_AcDb.Entity)tr.GetObject(objId, _AcDb.OpenMode.ForRead);

                            // Let's get rid of the standard namespace
                            const string prefix     = "Autodesk.AutoCAD.DatabaseServices.";
                            string       typeString = ent.GetType().ToString();
                            if (typeString.Contains(prefix))
                            {
                                typeString = typeString.Substring(prefix.Length);
                            }
                            ed.WriteMessage("\nEntity " + ent.ObjectId.ToString() + " of type " + typeString + " found on layer " +
                                            ent.Layer + " with colour " + ent.Color.ToString());
                        }
                    }
                }
            }
        }
Exemplo n.º 16
0
        public static string CreateBlock(
            AcDb.DBObjectCollection blockElements,
            string nameBlock)
        {
            using (AcDb.Transaction tr = db.TransactionManager.StartTransaction())
            {
                AcDb.BlockTable blockTable   = tr.GetObject(db.BlockTableId, AcDb.OpenMode.ForRead) as AcDb.BlockTable;
                string          oldNameBlock = nameBlock;
                int             iNameBlock   = 0;
mark_reNameBlock:
                if (blockTable.Has(nameBlock))
                {
                    iNameBlock++;
                    nameBlock = oldNameBlock + iNameBlock.ToString("_000");
                    goto mark_reNameBlock;
                }


                AcDb.BlockTableRecord blockTableRecord = new AcDb.BlockTableRecord
                {
                    Name = nameBlock
                };
                blockTable.UpgradeOpen();
                AcDb.ObjectId btrId = blockTable.Add(blockTableRecord);
                tr.AddNewlyCreatedDBObject(blockTableRecord, true);

                foreach (AcDb.Entity ent in blockElements)
                {
                    blockTableRecord.AppendEntity(ent);
                    tr.AddNewlyCreatedDBObject(ent, true);
                }

                tr.Commit();
            }

            return(nameBlock);
        }
Exemplo n.º 17
0
        public static AcDb.ObjectId InsertBlock(
            string nameBlock,
            AcGe.Point3d insertionPoint,
            double scale,
            double rotation,
            AcDb.ObjectId layerId,
            Dictionary <string, string> tags)
        {
            AcDb.ObjectId idBlock = AcDb.ObjectId.Null;
            using (AcDb.Transaction tr = db.TransactionManager.StartTransaction())
            {
                AcDb.BlockTable blockTable = (AcDb.BlockTable)tr.GetObject(db.BlockTableId, AcDb.OpenMode.ForRead);
                if (!blockTable.Has(nameBlock))
                {
                    ed.WriteMessage("\nНезнайдено блок '{0}' у таблиці блоків креслення.", nameBlock);
                    return(idBlock);
                }
                AcDb.BlockTableRecord curSpace       = (AcDb.BlockTableRecord)tr.GetObject(db.CurrentSpaceId, AcDb.OpenMode.ForWrite);
                AcDb.BlockReference   blockReference = new AcDb.BlockReference(insertionPoint, blockTable[nameBlock])
                {
                    LayerId      = layerId,
                    ScaleFactors = new AcGe.Scale3d(scale, scale, scale),
                    Rotation     = rotation
                };
                blockReference.TransformBy(ed.CurrentUserCoordinateSystem);
                curSpace.AppendEntity(blockReference);
                tr.AddNewlyCreatedDBObject(blockReference, true);
                if (tags != null)
                {
                    ReplaceAttributeBlock(blockReference, tags, true);
                }
                idBlock = blockReference.ObjectId;

                tr.Commit();
            }
            return(idBlock);
        }
Exemplo n.º 18
0
        public static AcDb.ObjectId ManualInsertBlock(string nameBlock,
                                                      double scaleBlock,
                                                      Dictionary <string, string> tags)
        {
            AcDb.ObjectId idBlock = AcDb.ObjectId.Null;
            using (AcDb.Transaction tr = db.TransactionManager.StartTransaction())
            {
                AcDb.BlockTable blockTable = (AcDb.BlockTable)tr.GetObject(db.BlockTableId, AcDb.OpenMode.ForRead);
                if (!blockTable.Has(nameBlock))
                {
                    ed.WriteMessage("\nНезнайдено блок '{0}' у таблиці блоків креслення.", nameBlock);
                    return(idBlock);
                }
                AcDb.BlockTableRecord curSpace       = (AcDb.BlockTableRecord)tr.GetObject(db.CurrentSpaceId, AcDb.OpenMode.ForWrite);
                AcDb.BlockReference   blockReference = new AcDb.BlockReference(AcGe.Point3d.Origin, blockTable[nameBlock])
                {
                    ScaleFactors = new AcGe.Scale3d(scaleBlock, scaleBlock, scaleBlock)
                };
                blockReference.TransformBy(ed.CurrentUserCoordinateSystem);
                curSpace.AppendEntity(blockReference);

                tr.AddNewlyCreatedDBObject(blockReference, true);

                AcDb.BlockTableRecord btr = (AcDb.BlockTableRecord)tr.GetObject(blockTable[nameBlock], AcDb.OpenMode.ForRead);
                BlockPlacementJig     jig = new BlockPlacementJig(blockReference, tags);
                AcEd.PromptResult     pr  = ed.Drag(jig);

                if (pr.Status != AcEd.PromptStatus.OK)
                {
                    blockReference.Erase();
                }

                tr.Commit();
            }

            return(idBlock);
        }
Exemplo n.º 19
0
        public static void Plan2LayerAufteil()
        {
            var acadApp = (Autodesk.AutoCAD.Interop.AcadApplication)_AcAp.Application.AcadApplication;

            _AcAp.Document doc = _AcAp.Application.DocumentManager.MdiActiveDocument;
            _Db = doc.Database;
            _AcEd.Editor ed = doc.Editor;
            try
            {
                _Tr = _Db.TransactionManager.StartTransaction();
                using (_Tr)
                {
                    // Open the blocktable, get the modelspace
                    _AcDb.BlockTable bt = (_AcDb.BlockTable)_Tr.GetObject(_Db.BlockTableId, _AcDb.OpenMode.ForRead);

                    foreach (var btrOid in bt)
                    {
                        _AcDb.BlockTableRecord btr = (_AcDb.BlockTableRecord)_Tr.GetObject(btrOid, _AcDb.OpenMode.ForRead);
                        log.InfoFormat("Blocktable: {0}", btr.Name);
                        foreach (_AcDb.ObjectId objId in btr)
                        {
                            _AcDb.Entity ent = (_AcDb.Entity)_Tr.GetObject(objId, _AcDb.OpenMode.ForRead);
                            if (ent.GetType() == typeof(_AcDb.AttributeDefinition) ||
                                ent.GetType() == typeof(_AcDb.DBText) ||
                                ent.GetType() == typeof(_AcDb.MText) ||
                                ent.GetType() == typeof(_AcDb.Leader) ||
                                Regex.IsMatch(ent.GetType().Name, "Dimension", RegexOptions.IgnoreCase)
                                )
                            {
                                Correction(ent, suffix: "_T", isContinuous: true);
                            }
                            else
                            {
                                var blockRef = ent as _AcDb.BlockReference;
                                if (blockRef != null)
                                {
                                    Correction(ent, suffix: "_B", isContinuous: true);
                                }
                                else
                                {
                                    var hatch = ent as _AcDb.Hatch;
                                    if (hatch != null)
                                    {
                                        if (Regex.IsMatch(hatch.PatternName, "SOLID", RegexOptions.IgnoreCase))
                                        {
                                            Correction(ent, suffix: "_F", isContinuous: true);
                                        }
                                        else
                                        {
                                            Correction(ent, suffix: "_S", isContinuous: true);
                                        }
                                    }
                                    else
                                    {
                                        var solid = ent as _AcDb.Solid;
                                        if (solid != null)
                                        {
                                            Correction(ent, suffix: "_F", isContinuous: true);
                                        }
                                        else
                                        {
                                            CorrectionRest(ent);
                                        }
                                    }
                                }
                            }
                        }
                    }

                    _Tr.Commit();
                }
            }
            catch (System.Exception ex)
            {
                string msg = string.Format(CultureInfo.CurrentCulture, "Fehler in (Plan2LayerAufteil): {0}", ex.Message);
                ed.WriteMessage("\n" + msg);
                System.Windows.Forms.MessageBox.Show(ex.Message, "Plan2LayerAufteil");
            }
        }
Exemplo n.º 20
0
        //[_AcTrx.CommandMethod("SaveView")]
        //public static void SaveView()
        //{
        //    Globs.SaveView("Test");
        //}
        //[_AcTrx.CommandMethod("RestoreView")]
        //public static void RestoreView()
        //{
        //    Globs.RestoreView("Test");
        //}

        //[_AcTrx.CommandMethod("TestMakeLayer")]
        public void TestMakeLayer()
        {
            var doc      = _AcAp.Application.DocumentManager.MdiActiveDocument;
            var db       = doc.Database;
            var layerOid = CreateNewLayer(doc, db);

            using (_AcDb.Transaction trans = doc.TransactionManager.StartTransaction())
            {
                _AcDb.BlockTable blkTable = (_AcDb.BlockTable)trans.GetObject(db.BlockTableId, _AcDb.OpenMode.ForRead);
                foreach (var id in blkTable)
                {
                    _AcDb.BlockTableRecord btRecord = (_AcDb.BlockTableRecord)trans.GetObject(id, _AcDb.OpenMode.ForRead);
                    //if (!btRecord.IsLayout)
                    //{
                    //Access to the block (not model/paper space)
                    System.Diagnostics.Debug.WriteLine(string.Format(CultureInfo.CurrentCulture, "Block: {0}", btRecord.Name));
                    //MgdAcApplication.DocumentManager.MdiActiveDocument.Editor.WriteMessage(string.Format("\nBlock name: {0}", btRecord.Name));

                    btRecord.UpgradeOpen();

                    foreach (var entId in btRecord)
                    {
                        _AcDb.Entity entity = (_AcDb.Entity)trans.GetObject(entId, _AcDb.OpenMode.ForRead);

                        entity.UpgradeOpen();

                        //Access to the entity
                        //MgdAcApplication.DocumentManager.MdiActiveDocument.Editor.WriteMessage(string.Format("\nHandle: {0}", entity.Handle));
                        //System.Diagnostics.Debug.WriteLine(string.Format(CultureInfo.CurrentCulture, "Handle: {0}, Layer: {1}", entity.Handle, entity.Layer));
                        entity.Layer = "MyTest";

                        _AcDb.BlockReference block = entity as _AcDb.BlockReference;
                        if (block != null)
                        {
                            foreach (var att in block.AttributeCollection)
                            {
                                _AcDb.ObjectId           attOid = (_AcDb.ObjectId)att;
                                _AcDb.AttributeReference attrib = trans.GetObject(attOid, _AcDb.OpenMode.ForWrite) as _AcDb.AttributeReference;
                                if (attrib != null)
                                {
                                    //attrib.UpgradeOpen();
                                    attrib.Layer = "MyTest";
                                }
                            }
                        }
                    }

                    //}
                }

                // Layouts iterieren
                _AcDb.DBDictionary layoutDict = (_AcDb.DBDictionary)trans.GetObject(db.LayoutDictionaryId, _AcDb.OpenMode.ForRead);
                foreach (var loEntry in layoutDict)
                {
                    if (loEntry.Key.ToUpperInvariant() == "MODEL")
                    {
                        continue;
                    }
                    _AcDb.Layout lo = (_AcDb.Layout)trans.GetObject(loEntry.Value, _AcDb.OpenMode.ForRead, false);
                    if (lo == null)
                    {
                        continue;
                    }
                    System.Diagnostics.Debug.WriteLine(string.Format(CultureInfo.CurrentCulture, "Layout: {0}", lo.LayoutName));

                    _AcDb.BlockTableRecord btRecord = (_AcDb.BlockTableRecord)trans.GetObject(lo.BlockTableRecordId, _AcDb.OpenMode.ForRead);
                    foreach (var entId in btRecord)
                    {
                        _AcDb.Entity entity = (_AcDb.Entity)trans.GetObject(entId, _AcDb.OpenMode.ForRead);

                        entity.UpgradeOpen();

                        //Access to the entity
                        //MgdAcApplication.DocumentManager.MdiActiveDocument.Editor.WriteMessage(string.Format("\nHandle: {0}", entity.Handle));
                        //System.Diagnostics.Debug.WriteLine(string.Format(CultureInfo.CurrentCulture, "Handle: {0}, Layer: {1}", entity.Handle, entity.Layer));
                        entity.Layer = "MyTest";

                        _AcDb.BlockReference block = entity as _AcDb.BlockReference;
                        if (block != null)
                        {
                            foreach (var att in block.AttributeCollection)
                            {
                                _AcDb.ObjectId           attOid = (_AcDb.ObjectId)att;
                                _AcDb.AttributeReference attrib = trans.GetObject(attOid, _AcDb.OpenMode.ForWrite) as _AcDb.AttributeReference;
                                if (attrib != null)
                                {
                                    //attrib.UpgradeOpen();
                                    attrib.Layer = "MyTest";
                                }
                            }
                        }
                    }
                }



                trans.Commit();
            }
        }
Exemplo n.º 21
0
        private static void GetAllXRefFullPaths(string[] files, List <string> usedXRefFullPaths)
        {
            foreach (var fileName in files)
            {
                _AcDb.Database db = new _AcDb.Database(false, true);
                using (db)
                {
                    db.ReadDwgFile(fileName, System.IO.FileShare.Read, allowCPConversion: false, password: "");

                    using (_AcDb.Transaction tr = db.TransactionManager.StartTransaction())
                    {
                        _AcDb.BlockTable bt = (_AcDb.BlockTable)tr.GetObject(db.BlockTableId, _AcDb.OpenMode.ForRead);
                        foreach (var id in bt)
                        {
                            _AcDb.BlockTableRecord btr = (_AcDb.BlockTableRecord)tr.GetObject(id, _AcDb.OpenMode.ForRead);
                            if (btr.IsLayout)
                            {
                                foreach (var oid in btr)
                                {
                                    var ent = tr.GetObject(oid, _AcDb.OpenMode.ForRead);
                                    _AcDb.BlockReference bref = ent as _AcDb.BlockReference;
                                    if (bref != null)
                                    {
                                        if (bref.BlockTableRecord == default(_AcDb.ObjectId))
                                        {
                                            try
                                            {
                                                log.WarnFormat(CultureInfo.CurrentCulture, "Block in '{0}' hat keinen Blocktable-Record. Handle = {1}", bref.BlockName, bref.Handle);
                                            }
                                            catch (Exception ex)
                                            {
                                                log.Error(ex.Message, ex);
                                            }
                                        }
                                        else
                                        {
                                            var bd = (_AcDb.BlockTableRecord)tr.GetObject(bref.BlockTableRecord, _AcDb.OpenMode.ForRead);
                                            if (bd.IsFromExternalReference)
                                            {
                                                string xpath        = bd.PathName;
                                                string completePath = string.Empty;
                                                if (!System.IO.Path.IsPathRooted(xpath))
                                                {
                                                    // relativer pfad
                                                    string cpath = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(fileName), xpath);
                                                    completePath = System.IO.Path.GetFullPath(cpath);
                                                }
                                                else
                                                {
                                                    // absoluter pfad
                                                    completePath = System.IO.Path.GetFullPath(xpath);
                                                }
                                                completePath = completePath.ToUpperInvariant();
                                                if (!usedXRefFullPaths.Contains(completePath))
                                                {
                                                    usedXRefFullPaths.Add(completePath);
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        tr.Commit();
                    }
                }
            }
        }
Exemplo n.º 22
0
        private void SubVarianLoadRaster()
        {
            String PIC_NAME = "C:\\_Temp_\\5525.TIF";

            AcDb.Database CurDb = AcAp.Application.DocumentManager.MdiActiveDocument.Database;


            using (AcDb.Transaction acTrans = CurDb.TransactionManager.StartTransaction())
            {
                try
                {
                    AcDb.ObjectId dictId = AcDb.RasterImageDef.GetImageDictionary(CurDb);
                    if (dictId == null)
                    {
                        dictId = AcDb.RasterImageDef.CreateImageDictionary(CurDb);
                    }

                    AcDb.DBDictionary   dict    = acTrans.GetObject(dictId, AcDb.OpenMode.ForRead) as AcDb.DBDictionary;
                    String              recName = "5525";
                    AcDb.RasterImageDef rid     = new AcDb.RasterImageDef
                    {
                        SourceFileName = PIC_NAME
                    };
                    dict.UpgradeOpen();
                    AcDb.ObjectId defId = dict.SetAt(recName, rid);

                    rid.Load();

                    acTrans.AddNewlyCreatedDBObject(rid, true);
                    AcDb.RasterImage ri = new AcDb.RasterImage
                    {
                        ImageDefId  = defId,
                        ShowImage   = true,
                        Orientation = new AcGe.CoordinateSystem3d(new AcGe.Point3d(200, 300, 0), new AcGe.Vector3d(1, 0, 0), new AcGe.Vector3d(0, 1, 0))
                    };
                    AcDb.BlockTable       bt  = acTrans.GetObject(CurDb.BlockTableId, AcDb.OpenMode.ForRead, false) as AcDb.BlockTable;
                    AcDb.BlockTableRecord btr = acTrans.GetObject(bt[AcDb.BlockTableRecord.ModelSpace], AcDb.OpenMode.ForWrite, false) as AcDb.BlockTableRecord;
                    btr.AppendEntity(ri);
                    acTrans.AddNewlyCreatedDBObject(ri, true);
                    ri.AssociateRasterDef(rid);
                    ri.TransformBy(AcGe.Matrix3d.Scaling(1000, new AcGe.Point3d(200, 300, 0)));
                }
                catch
                {
                    return;
                }
            }

            /*
             *     Try
             *              Dim PIC_NAME As String = original_picture_name
             *              Dim dictId As ObjectId = RasterImageDef.GetImageDictionary(Db)
             *              If dictId = Nothing Then
             *                  dictId = RasterImageDef.CreateImageDictionary(Db)
             *              End If
             *              Dim dict As DBDictionary = CType(acTrans.GetObject(dictId, OpenMode.ForRead), DBDictionary)
             *              Dim recName As String = Picture_name_in_drawing
             *              Dim rid As RasterImageDef = New RasterImageDef
             *              rid.SourceFileName = PIC_NAME
             *              dict.UpgradeOpen()
             *              Dim defId As ObjectId = dict.SetAt(recName, rid)
             *              rid.Load()
             *              acTrans.AddNewlyCreatedDBObject(rid, True)
             *              Dim ri As RasterImage = New RasterImage
             *              ri.ImageDefId = defId
             *              ri.ShowImage = True
             *              ri.Orientation = New CoordinateSystem3d(New Point3d(x1, y1, 0), New Vector3d(1, 0, 0), New Vector3d(0, 1, 0))
             *              Dim bt As BlockTable
             *              Dim btr As BlockTableRecord
             *              bt = acTrans.GetObject(Db.BlockTableId, OpenMode.ForRead, False)
             *              btr = acTrans.GetObject(bt(BlockTableRecord.ModelSpace), OpenMode.ForWrite, False)
             *              btr.AppendEntity(ri)
             *              acTrans.AddNewlyCreatedDBObject(ri, True)
             *              ri.AssociateRasterDef(rid)
             *              ri.TransformBy(Matrix3d.Scaling(picture_scale, New Point3d(x1, y1, 0)))
             *       Catch
             *
             *              Exit Sub
             *       End Try
             *
             */
        }
Exemplo n.º 23
0
        private void ReplaceLayerInEntities(Dictionary <string, string> substDict, _AcDb.Transaction trans, _AcDb.Database db)
        {
            //string oldLayer = linfo.OldLayer;
            //string newLayer = linfo.NewLayer;

            _AcDb.BlockTable blkTable = (_AcDb.BlockTable)trans.GetObject(db.BlockTableId, _AcDb.OpenMode.ForRead);
            foreach (var id in blkTable)
            {
                _AcDb.BlockTableRecord btRecord = (_AcDb.BlockTableRecord)trans.GetObject(id, _AcDb.OpenMode.ForRead);
                //System.Diagnostics.Debug.WriteLine(string.Format(CultureInfo.CurrentCulture, "Block: {0}", btRecord.Name));

                //btRecord.UpgradeOpen();

                foreach (var entId in btRecord)
                {
                    _AcDb.Entity entity = (_AcDb.Entity)trans.GetObject(entId, _AcDb.OpenMode.ForWrite);

                    CheckSetLayer(substDict, entity);
                    //if (string.Compare(entity.Layer, oldLayer, StringComparison.OrdinalIgnoreCase) == 0)
                    //{
                    //    entity.Layer = newLayer;
                    //}

                    _AcDb.BlockReference block = entity as _AcDb.BlockReference;
                    if (block != null)
                    {
                        // sequend correction
                        string saveLay = block.Layer;
                        block.Layer = "0";
                        block.Layer = saveLay;

                        foreach (var att in block.AttributeCollection)
                        {
                            _AcDb.ObjectId           attOid = (_AcDb.ObjectId)att;
                            _AcDb.AttributeReference attrib = trans.GetObject(attOid, _AcDb.OpenMode.ForWrite) as _AcDb.AttributeReference;
                            if (attrib != null)
                            {
                                CheckSetLayer(substDict, attrib);
                                //if (string.Compare(attrib.Layer, oldLayer, StringComparison.OrdinalIgnoreCase) == 0)
                                //{
                                //    attrib.Layer = newLayer;
                                //}
                            }
                        }
                    }
                }

                //}
            }

            // Layouts iterieren
            _AcDb.DBDictionary layoutDict = (_AcDb.DBDictionary)trans.GetObject(db.LayoutDictionaryId, _AcDb.OpenMode.ForRead);
            foreach (var loEntry in layoutDict)
            {
                if (loEntry.Key.ToUpperInvariant() == "MODEL")
                {
                    continue;
                }
                _AcDb.Layout lo = (_AcDb.Layout)trans.GetObject(loEntry.Value, _AcDb.OpenMode.ForRead, false);
                if (lo == null)
                {
                    continue;
                }
                //System.Diagnostics.Debug.WriteLine(string.Format(CultureInfo.CurrentCulture, "Layout: {0}", lo.LayoutName));

                _AcDb.BlockTableRecord btRecord = (_AcDb.BlockTableRecord)trans.GetObject(lo.BlockTableRecordId, _AcDb.OpenMode.ForRead);
                foreach (var entId in btRecord)
                {
                    _AcDb.Entity entity = (_AcDb.Entity)trans.GetObject(entId, _AcDb.OpenMode.ForWrite);

                    CheckSetLayer(substDict, entity);

                    //if (string.Compare(entity.Layer, oldLayer, StringComparison.OrdinalIgnoreCase) == 0)
                    //{
                    //    entity.Layer = newLayer;
                    //}

                    _AcDb.BlockReference block = entity as _AcDb.BlockReference;
                    if (block != null)
                    {
                        string saveLay = block.Layer;
                        block.Layer = "0";
                        block.Layer = saveLay;

                        foreach (var att in block.AttributeCollection)
                        {
                            _AcDb.ObjectId           attOid = (_AcDb.ObjectId)att;
                            _AcDb.AttributeReference attrib = trans.GetObject(attOid, _AcDb.OpenMode.ForWrite) as _AcDb.AttributeReference;
                            if (attrib != null)
                            {
                                CheckSetLayer(substDict, attrib);
                                //if (string.Compare(attrib.Layer, oldLayer, StringComparison.OrdinalIgnoreCase) == 0)
                                //{

                                //    //attrib.UpgradeOpen();
                                //    attrib.Layer = newLayer;
                                //}
                            }
                        }
                    }
                }
            }
        }
Exemplo n.º 24
0
        public static void AttachRasterImage(LandRasterImage landRastr)
        {
            AcEd.Editor ed = AcApp.DocumentManager.MdiActiveDocument.Editor;

            //bool bRasterDefCreated = false;

            AcDb.Database curDb = AcApp.DocumentManager.MdiActiveDocument.Database;

            using (AcDb.Transaction tr = curDb.TransactionManager.StartTransaction())
            {
                AcDb.RasterImageDef rasterDef;
                AcDb.ObjectId       imgDefId;
                AcDb.ObjectId       imgDctID = AcDb.RasterImageDef.GetImageDictionary(curDb);
                if (imgDctID.IsNull)
                {
                    imgDctID = AcDb.RasterImageDef.CreateImageDictionary(curDb);
                }

                AcDb.DBDictionary imgDict = (AcDb.DBDictionary)tr.GetObject(imgDctID, AcDb.OpenMode.ForRead);

                if (imgDict.Contains(landRastr.ImageName))
                {
                    imgDefId  = imgDict.GetAt(landRastr.ImageName);
                    rasterDef = (AcDb.RasterImageDef)tr.GetObject(imgDefId, AcDb.OpenMode.ForWrite);
                    if (rasterDef.IsLoaded)
                    {
                        //return;
                    }
                }
                else
                {
                    AcPApp.AcadApplication app    = AcApp.AcadApplication as AcPApp.AcadApplication;
                    AcPApp.AcadDocument    doc    = app.ActiveDocument;
                    AcPDb.AcadModelSpace   mSpace = doc.ModelSpace;
                    AcPDb.AcadRasterImage  ri     = mSpace.AddRaster(landRastr.FileName, landRastr.InsertPoint.ToArray(), 1000, 0);
                    ri.Name         = landRastr.ImageName;
                    ri.Transparency = true;
                    ServiceCAD.CreateLayer(landRastr.Layer);
                    ri.Layer       = landRastr.Layer;
                    ri.ImageHeight = 1000;
                    ri.ImageWidth  = 1000;

                    tr.Commit();
                    return;
                }

                AcDb.BlockTable blkTbl =
                    (AcDb.BlockTable)tr.GetObject(curDb.BlockTableId, AcDb.OpenMode.ForRead);

                AcDb.BlockTableRecord acBlkTblRec =
                    (AcDb.BlockTableRecord)tr.GetObject(blkTbl[AcDb.BlockTableRecord.ModelSpace], AcDb.OpenMode.ForWrite);

                using (AcDb.RasterImage rasterImage = new AcDb.RasterImage())
                {
                    rasterImage.ImageDefId = imgDefId;

                    AcGe.Vector3d width;
                    AcGe.Vector3d height;

                    AcGe.Matrix3d ucs  = ed.CurrentUserCoordinateSystem;
                    double        size = 1000;

                    width  = new AcGe.Vector3d(size, 0, 0);
                    height = new AcGe.Vector3d(0, size, 0);


                    AcGe.Point3d            insPt            = landRastr.InsertPoint;
                    AcGe.CoordinateSystem3d coordinateSystem = new AcGe.CoordinateSystem3d(insPt.TransformBy(ucs), width.TransformBy(ucs), height.TransformBy(ucs));
                    rasterImage.Orientation = coordinateSystem;
                    rasterImage.Rotation    = 0;
                    rasterImage.ShowImage   = true;

                    acBlkTblRec.AppendEntity(rasterImage);
                    tr.AddNewlyCreatedDBObject(rasterImage, true);

                    rasterImage.AssociateRasterDef(rasterDef);
                }
                tr.Commit();
            }
        }
Exemplo n.º 25
0
        public static void ImportLayout(string layoutName, string filename)
        {
            // Get the current document and database
            _AcAp.Document acDoc   = _AcAp.Application.DocumentManager.MdiActiveDocument;
            _AcDb.Database acCurDb = acDoc.Database;

            // Specify the layout name and drawing file to work with
            //string layoutName = "MAIN AND SECOND FLOOR PLAN";
            //string filename = "C:\\AutoCAD\\Sample\\Sheet Sets\\Architectural\\A-01.dwg";

            // Create a new database object and open the drawing into memory
            _AcDb.Database acExDb = new _AcDb.Database(false, true);
            acExDb.ReadDwgFile(filename, Autodesk.AutoCAD.DatabaseServices.FileOpenMode.OpenForReadAndAllShare, true, "");

            // Create a transaction for the external drawing
            using (_AcDb.Transaction acTransEx = acExDb.TransactionManager.StartTransaction())
            {
                // Get the layouts dictionary
                _AcDb.DBDictionary layoutsEx = acTransEx.GetObject(acExDb.LayoutDictionaryId, _AcDb.OpenMode.ForRead) as _AcDb.DBDictionary;

                // Check to see if the layout exists in the external drawing
                if (layoutsEx.Contains(layoutName) == true)
                {
                    // Get the layout and block objects from the external drawing
                    _AcDb.Layout           layEx       = layoutsEx.GetAt(layoutName).GetObject(_AcDb.OpenMode.ForRead) as _AcDb.Layout;
                    _AcDb.BlockTableRecord blkBlkRecEx = acTransEx.GetObject(layEx.BlockTableRecordId, _AcDb.OpenMode.ForRead) as _AcDb.BlockTableRecord;

                    // Get the objects from the block associated with the layout
                    _AcDb.ObjectIdCollection idCol = new _AcDb.ObjectIdCollection();
                    foreach (_AcDb.ObjectId id in blkBlkRecEx)
                    {
                        idCol.Add(id);
                    }

                    // Create a transaction for the current drawing
                    using (_AcDb.Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
                    {
                        // Get the block table and create a new block
                        // then copy the objects between drawings
                        _AcDb.BlockTable blkTbl = acTrans.GetObject(acCurDb.BlockTableId, _AcDb.OpenMode.ForWrite) as _AcDb.BlockTable;
                        using (_AcDb.BlockTableRecord blkBlkRec = new _AcDb.BlockTableRecord())
                        {
                            int layoutCount = layoutsEx.Count - 1;

                            blkBlkRec.Name = "*Paper_Space" + layoutCount.ToString();
                            blkTbl.Add(blkBlkRec);
                            acTrans.AddNewlyCreatedDBObject(blkBlkRec, true);
                            acExDb.WblockCloneObjects(idCol, blkBlkRec.ObjectId, new _AcDb.IdMapping(), _AcDb.DuplicateRecordCloning.Ignore, false);

                            // Create a new layout and then copy properties between drawings
                            _AcDb.DBDictionary layouts = acTrans.GetObject(acCurDb.LayoutDictionaryId, _AcDb.OpenMode.ForWrite) as _AcDb.DBDictionary;
                            using (_AcDb.Layout lay = new _AcDb.Layout())
                            {
                                lay.LayoutName = layoutName;
                                lay.AddToLayoutDictionary(acCurDb, blkBlkRec.ObjectId);
                                acTrans.AddNewlyCreatedDBObject(lay, true);
                                lay.CopyFrom(layEx);

                                _AcDb.DBDictionary plSets = acTrans.GetObject(acCurDb.PlotSettingsDictionaryId, _AcDb.OpenMode.ForRead) as _AcDb.DBDictionary;

                                // Check to see if a named page setup was assigned to the layout,
                                // if so then copy the page setup settings
                                if (lay.PlotSettingsName != "")
                                {
                                    // Check to see if the page setup exists
                                    if (plSets.Contains(lay.PlotSettingsName) == false)
                                    {
                                        plSets.UpgradeOpen();

                                        using (_AcDb.PlotSettings plSet = new _AcDb.PlotSettings(lay.ModelType))
                                        {
                                            plSet.PlotSettingsName = lay.PlotSettingsName;
                                            plSet.AddToPlotSettingsDictionary(acCurDb);
                                            acTrans.AddNewlyCreatedDBObject(plSet, true);

                                            _AcDb.DBDictionary plSetsEx = acTransEx.GetObject(acExDb.PlotSettingsDictionaryId, _AcDb.OpenMode.ForRead) as _AcDb.DBDictionary;

                                            _AcDb.PlotSettings plSetEx = plSetsEx.GetAt(lay.PlotSettingsName).GetObject(_AcDb.OpenMode.ForRead) as _AcDb.PlotSettings;

                                            plSet.CopyFrom(plSetEx);
                                        }
                                    }
                                }
                            }
                        }

                        // Regen the drawing to get the layout tab to display
                        acDoc.Editor.Regen();

                        // Save the changes made
                        acTrans.Commit();
                    }
                }
                else
                {
                    // Display a message if the layout could not be found in the specified drawing
                    acDoc.Editor.WriteMessage("\nLayout '" + layoutName +
                                              "' could not be imported from '" + filename + "'.");
                }

                // Discard the changes made to the external drawing file
                acTransEx.Abort();
            }

            // Close the external drawing file
            acExDb.Dispose();
        }
Exemplo n.º 26
0
        public void Fill()
        {
            _raumBlockInfos.Clear();
            _wohnungBlockInfos.Clear();
            _projektBlockInfo = null;

            var doc = Application.DocumentManager.MdiActiveDocument;
            var db  = doc.Database;

            using (_AcDb.Transaction tr = doc.TransactionManager.StartTransaction())
            {
                _AcDb.BlockTable       bt  = (_AcDb.BlockTable)tr.GetObject(db.BlockTableId, _AcDb.OpenMode.ForRead);
                _AcDb.BlockTableRecord btr = (_AcDb.BlockTableRecord)tr.GetObject(bt[_AcDb.BlockTableRecord.ModelSpace], _AcDb.OpenMode.ForRead);

                foreach (var oid in btr)
                {
                    var blockRef = tr.GetObject(oid, _AcDb.OpenMode.ForRead) as _AcDb.BlockReference;
                    if (blockRef != null)
                    {
                        if (string.Compare(blockRef.Name, Globs.RaumBlockName, StringComparison.OrdinalIgnoreCase) == 0)
                        {
                            var attDict   = Globs.GetAttributes(blockRef, tr);
                            var blockInfo = new BlockInfo
                            {
                                BlockRef   = blockRef,
                                Attributes = attDict,
                            };
                            _raumBlockInfos.Add(blockInfo);
                        }
                        else if (string.Compare(blockRef.Name, Globs.GstinfoBlockName, StringComparison.OrdinalIgnoreCase) == 0)
                        {
                            //if (_projektInfo == null) _projektInfo = _factory.CreateProjectInfo(); // new AcadPari.ProjektInfo();
                            //var attDict = Globs.GetAttributesUcKey(blockRef);
                            //_projektInfo.Bauvorhaben = Globs.GetValOrEmpty("BAUVORHABEN", attDict);
                            //_projektInfo.Katastralgemeinde = Globs.GetValOrEmpty("KATASTRALGEMEINDE", attDict);
                            //_projektInfo.EZ = Globs.GetValOrEmpty("EZ", attDict);

                            //var subInfo = _factory.CreateSubInfo(); // new AcadPari.ProjektInfo.SubInfo();
                            //subInfo.Gstnr = Globs.GetValOrEmpty("GRUNDSTÜCKSNUMMER", attDict);
                            //subInfo.Flaeche = Globs.GetValOrEmpty("FLACHE", attDict);
                            //subInfo.AcadHandle = blockRef.Handle.ToString();
                            //_projektInfo.SubInfos.Add(subInfo);
                        }
                        else if (string.Compare(blockRef.Name, Globs.WohnunginfoBlockName, StringComparison.OrdinalIgnoreCase) == 0)
                        {
                            var attDict     = Globs.GetAttributes(blockRef, tr);
                            var wohnungInfo = new BlockInfo()
                            {
                                BlockRef   = blockRef,
                                Attributes = attDict,
                            };
                            _wohnungBlockInfos.Add(wohnungInfo);
                        }
                    }
                }

                // PKV Wohnungen
                var pkwWohnungsInfos = new List <BlockInfo>();
                foreach (var raumBlockInfo in _raumBlockInfos)
                {
                    var begrundung      = raumBlockInfo.Attributes[attBegrundung];
                    var valBegrundung   = begrundung.TextString;
                    var valBegrundungUc = valBegrundung.ToUpperInvariant();

                    var top      = raumBlockInfo.Attributes[attTop];
                    var valTop   = top.TextString;
                    var valTopUc = valTop.ToUpperInvariant();

                    var raum      = raumBlockInfo.Attributes[attRaum];
                    var valRaum   = raum.TextString;
                    var valRaumUc = valRaum.ToUpperInvariant();

                    if (valBegrundungUc.Contains("PKW"))
                    {
                        var wohnungsInfoBlock = GetWohnungsInfoBlock(valTopUc);
                        if (wohnungsInfoBlock == null)
                        {
                            throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, "Kein Wohnungsinfoblock für Raumblock '{2}'('{1}','{0}')!", raumBlockInfo.BlockRef.Handle.ToString(), valTop, valRaum));
                        }
                        if (!pkwWohnungsInfos.Contains(wohnungsInfoBlock))
                        {
                            pkwWohnungsInfos.Add(wohnungsInfoBlock);
                        }
                    }
                }


                foreach (var raumBlockInfo in _raumBlockInfos)
                {
                    var bIsZuschlag = false;
                    var bIsZubehör  = false;

                    var begrundung      = raumBlockInfo.Attributes[attBegrundung];
                    var valBegrundung   = begrundung.TextString;
                    var valBegrundungUc = valBegrundung.ToUpperInvariant();

                    var top      = raumBlockInfo.Attributes[attTop];
                    var valTop   = top.TextString;
                    var valTopUc = valTop.ToUpperInvariant();

                    var raum      = raumBlockInfo.Attributes[attRaum];
                    var valRaum   = raum.TextString;
                    var valRaumUc = valRaum.ToUpperInvariant();

                    var wohnungsInfoBlock = GetWohnungsInfoBlock(valTopUc);
                    if (wohnungsInfoBlock == null)
                    {
                        throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, "Kein Wohnungsinfoblock für Raumblock '{2}'('{1}','{0}')!", raumBlockInfo.BlockRef.Handle.ToString(), valTop, valRaum));
                    }


                    // Excel_Begrundung
                    var excelBegrundung = raumBlockInfo.Attributes[attExcelBegrundung];
                    excelBegrundung.UpgradeOpen();
                    if (string.IsNullOrEmpty(valBegrundung.Trim()) || valBegrundungUc.Contains("ALLG") ||
                        valBegrundungUc.Contains("PKW"))
                    {
                        excelBegrundung.TextString = "als Wohnungseigentumsobjekt";
                    }
                    else
                    {
                        excelBegrundung.TextString = valBegrundung;
                    }
                    excelBegrundung.DowngradeOpen();


                    // NW_PariAls
                    var nwPariAls = raumBlockInfo.Attributes[attNW_PariAls];
                    nwPariAls.UpgradeOpen();
                    if (valBegrundungUc.Contains("ALS ZUBEHÖR"))
                    {
                        nwPariAls.TextString = "Als Wohnungseigentumszubehör";
                    }
                    else if (valBegrundungUc.Contains("ALS ZUSCHLAG"))
                    {
                        nwPariAls.TextString = "Als Wohnungseigentumszuschlag";
                    }
                    else
                    {
                        nwPariAls.TextString = "Als Wohnungseigentumsobjekt";
                    }
                    nwPariAls.DowngradeOpen();

                    // IsZuschlag
                    var isZuschlag = raumBlockInfo.Attributes[attIsZuschlag];
                    isZuschlag.UpgradeOpen();
                    if (valBegrundungUc.Contains("ALS ZUSCHLAG"))
                    {
                        bIsZuschlag           = true;
                        isZuschlag.TextString = "x";
                    }
                    else
                    {
                        isZuschlag.TextString = "";
                    }

                    // IsZubehör
                    var isZubehoer = raumBlockInfo.Attributes[attIsZubehoer];
                    isZubehoer.UpgradeOpen();
                    if (valBegrundungUc.Contains("ALS ZUBEHÖR"))
                    {
                        bIsZubehör            = true;
                        isZubehoer.TextString = "x";
                    }
                    else
                    {
                        isZubehoer.TextString = "";
                    }
                    isZubehoer.DowngradeOpen();

                    // NF_SummeBez, NF_SummeWidmung
                    var nfSummeBez = raumBlockInfo.Attributes[attNF_SummeBez];
                    nfSummeBez.UpgradeOpen();
                    var nfSummeWidmung = raumBlockInfo.Attributes[attNF_SummeWidmung];
                    nfSummeWidmung.UpgradeOpen();
                    if (pkwWohnungsInfos.Contains(wohnungsInfoBlock))
                    {
                        nfSummeBez.TextString     = "PKW - ABSTELLPLÄTZE";
                        nfSummeWidmung.TextString = "";
                    }
                    else if (valTopUc.Contains("ALLG"))
                    {
                        nfSummeBez.TextString     = "Allgemeinflächen";
                        nfSummeWidmung.TextString = "";
                    }
                    else
                    {
                        nfSummeBez.TextString     = valTop;
                        nfSummeWidmung.TextString = wohnungsInfoBlock.Attributes[attWohnWidmung].TextString;
                    }
                    nfSummeWidmung.DowngradeOpen();
                    nfSummeBez.DowngradeOpen();

                    // NF_AllgemeinGruppe
                    var nfAllgemeinGruppe = raumBlockInfo.Attributes[attNF_AllgemeinGruppe];
                    nfAllgemeinGruppe.UpgradeOpen();
                    if (valTopUc.Trim() == "TOP ALLG")
                    {
                        nfAllgemeinGruppe.TextString = "TOP";
                    }
                    else if (valTopUc.Trim() == "ALLG")
                    {
                        nfAllgemeinGruppe.TextString = "AUSSENANLAGEN";
                    }
                    nfAllgemeinGruppe.DowngradeOpen();

                    // NF_SpecialHandling
                    // NF_SpecialZuschlagBez
                    var specialHandling = raumBlockInfo.Attributes[attNF_SpecialHandling];
                    specialHandling.UpgradeOpen();
                    var specZuschlagBez = raumBlockInfo.Attributes[attNF_SpecialZuschlagBez];
                    specZuschlagBez.UpgradeOpen();
                    if (pkwWohnungsInfos.Contains(wohnungsInfoBlock))
                    {
                        specialHandling.TextString = "Abstellplätze";
                        if (bIsZuschlag)
                        {
                            specZuschlagBez.TextString = valRaum + " " + valBegrundung;
                        }
                        else
                        {
                            specZuschlagBez.TextString = "";
                        }
                    }
                    else
                    {
                        //specialHandling.TextString = "";
                        //specZuschlagBez.TextString = "";
                    }
                    specialHandling.DowngradeOpen();
                    specZuschlagBez.DowngradeOpen();


                    // NW_Widmung
                    var nwWidmung = raumBlockInfo.Attributes[attNW_Widmung];
                    nwWidmung.UpgradeOpen();
                    if (valTopUc.Contains("ALLG"))
                    {
                        nwWidmung.TextString = "";
                    }
                    else if (bIsZuschlag || bIsZubehör)
                    {
                        nwWidmung.TextString = valRaum;
                    }
                    else
                    {
                        nwWidmung.TextString = wohnungsInfoBlock.Attributes[attWohnWidmung].TextString;
                    }
                    nwWidmung.DowngradeOpen();
                }

                tr.Commit();
            }

            _raumBlockInfos.Clear();
            _wohnungBlockInfos.Clear();
            _projektBlockInfo = null;
        }
Exemplo n.º 27
0
        public void ReadBlocksFromModelspace()
        {
            _blockInfos.Clear();
            _wohnungInfos.Clear();
            _projektInfo = null;

            var doc = Application.DocumentManager.MdiActiveDocument;
            var db  = doc.Database;

            using (_AcDb.Transaction tr = doc.TransactionManager.StartTransaction())
            {
                _AcDb.BlockTable       bt  = (_AcDb.BlockTable)tr.GetObject(db.BlockTableId, _AcDb.OpenMode.ForRead);
                _AcDb.BlockTableRecord btr = (_AcDb.BlockTableRecord)tr.GetObject(bt[_AcDb.BlockTableRecord.ModelSpace], _AcDb.OpenMode.ForRead);

                foreach (var oid in btr)
                {
                    var blockRef = tr.GetObject(oid, _AcDb.OpenMode.ForRead) as _AcDb.BlockReference;
                    if (blockRef != null)
                    {
                        if (string.Compare(blockRef.Name, Globs.RaumBlockName, StringComparison.OrdinalIgnoreCase) == 0)
                        {
                            var attDict   = Globs.GetAttributesUcKey(blockRef);
                            var blockInfo = new BlockInfo
                            {
                                Raum       = Globs.GetValOrEmpty("RAUM", attDict),
                                Flaeche    = Globs.GetValOrEmpty("FLÄCHE", attDict),
                                Zusatz     = Globs.GetValOrEmpty("ZUSATZ", attDict),
                                Top        = Globs.GetValOrEmpty("TOP", attDict),
                                Geschoss   = Globs.GetValOrEmpty("GESCHOSS", attDict),
                                Nutzwert   = Globs.GetValOrEmpty("NUTZWERT", attDict),
                                Begrundung = Globs.GetValOrEmpty("BEGRUNDUNG", attDict),
                                Handle     = blockRef.Handle.ToString()
                            };
                            _blockInfos.Add(blockInfo);
                        }
                        else if (string.Compare(blockRef.Name, Globs.GstinfoBlockName, StringComparison.OrdinalIgnoreCase) == 0)
                        {
                            if (_projektInfo == null)
                            {
                                _projektInfo = _factory.CreateProjectInfo();                       // new AcadPari.ProjektInfo();
                            }
                            var attDict = Globs.GetAttributesUcKey(blockRef);
                            _projektInfo.Bauvorhaben       = Globs.GetValOrEmpty("BAUVORHABEN", attDict);
                            _projektInfo.Katastralgemeinde = Globs.GetValOrEmpty("KATASTRALGEMEINDE", attDict);
                            _projektInfo.EZ = Globs.GetValOrEmpty("EZ", attDict);

                            var subInfo = _factory.CreateSubInfo(); // new AcadPari.ProjektInfo.SubInfo();
                            subInfo.Gstnr      = Globs.GetValOrEmpty("GRUNDSTÜCKSNUMMER", attDict);
                            subInfo.Flaeche    = Globs.GetValOrEmpty("FLACHE", attDict);
                            subInfo.AcadHandle = blockRef.Handle.ToString();
                            _projektInfo.SubInfos.Add(subInfo);
                        }
                        else if (string.Compare(blockRef.Name, Globs.WohnunginfoBlockName, StringComparison.OrdinalIgnoreCase) == 0)
                        {
                            var attDict     = Globs.GetAttributesUcKey(blockRef);
                            var wohnungInfo = new WohnungInfo
                            {
                                Top      = Globs.GetValOrEmpty("TOP", attDict),
                                Typ      = Globs.GetValOrEmpty("TYP", attDict),
                                Widmung  = Globs.GetValOrEmpty("WIDMUNG", attDict),
                                Nutzwert = Globs.GetValOrEmpty("NUTZWERT", attDict),
                            };
                            _wohnungInfos.Add(wohnungInfo);
                        }
                    }
                }
                tr.Commit();
            }

            WidmungNutzwertBegrundungCorrection();
        }