protected override bool WorldDraw(Autodesk.AutoCAD.GraphicsInterface.WorldDraw draw) { _inMemorySet.Add(_setToBlock(Explode())); foreach (var ent in _inMemorySet) { draw.Geometry.Draw(ent); } foreach (var ent in _inMemorySet) { /*ent.Dispose();*/ var btrId = ((BlockReference)ent).BlockTableRecord; BlockTableRecord btr = btrId.GetObjectForRead <BlockTableRecord>(); BlockReference br = ent.Id.GetObjectForRead <BlockReference>(); ent.UpgradeOpen(); ent.Erase(true); ent.DowngradeOpen(); //btr.UpgradeOpen(); foreach (var item in btr) { DBObject obj = item.GetObjectForWrite <DBObject>(); obj.Erase(true); } //btr.DowngradeOpen(); } _inMemorySet.Clear(); return(true); }
public void MyPurgeMethod() { Document activeDoc = Autodesk.AutoCAD.ApplicationServices.Core.Application.DocumentManager.MdiActiveDocument; Database db = activeDoc.Database; using (Transaction Tx = db.TransactionManager.StartTransaction()) { BlockTable table = Tx.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable; ObjectIdCollection blockIds = new ObjectIdCollection(); do { blockIds.Clear(); foreach (ObjectId id in table) { blockIds.Add(id); } db.Purge(blockIds); foreach (ObjectId id in blockIds) { DBObject obj = Tx.GetObject(id, OpenMode.ForWrite); obj.Erase(); } } while (blockIds.Count != 0); Tx.Commit(); } }
public static void PurgeLayers(Document doc) { Database db = doc.Database; Editor ed = doc.Editor; using (Transaction Tx = db.TransactionManager.StartTransaction()) { LayerTable table = Tx.GetObject(db.LayerTableId, OpenMode.ForRead) as LayerTable; ObjectIdCollection layIds = new ObjectIdCollection(); foreach (ObjectId id in table) { layIds.Add(id); } //this function will remove all layers which are used in the drawing file db.Purge(layIds); foreach (ObjectId id in layIds) { DBObject obj = Tx.GetObject(id, OpenMode.ForWrite); try { obj.Erase(); } catch { } } Tx.Commit(); } }
public static void EraseObjectsCollection(ObjectIdCollection objectIdCollection) { Document acDoc = Autodesk.AutoCAD.ApplicationServices.Core.Application.DocumentManager.MdiActiveDocument; Database acCurrDb = acDoc.Database; Editor acEditor = acDoc.Editor; using (Transaction acTrans = acCurrDb.TransactionManager.StartTransaction()) { try { foreach (ObjectId acObjectID in objectIdCollection) { DBObject acDbObject = acTrans.GetObject(acObjectID, OpenMode.ForWrite); acDbObject.Erase(); } acTrans.Commit(); acEditor.Regen(); return; } catch (Autodesk.AutoCAD.Runtime.Exception acException) { Autodesk.AutoCAD.ApplicationServices.Application.ShowAlertDialog ("The following exception was caught: \n" + acException.Message + "\nError erasing objects!\n"); acTrans.Abort(); return; } } }
public void Delete(string LayerName) { Editor ed = Application.DocumentManager.MdiActiveDocument.Editor; //System.Data.DataTable LayerTable1 = Atend.Base.Design.DLayer.SelectByDesignCode(Atend.Control.Common.SelectedDesignCode); //Database db = HostApplicationServices.WorkingDatabase; Database db = Application.DocumentManager.MdiActiveDocument.Database; using (DocumentLock dLock = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.LockDocument()) { using (Transaction tr = db.TransactionManager.StartTransaction()) { LayerTable lt = (LayerTable)tr.GetObject(db.LayerTableId, OpenMode.ForWrite); if (lt.Has(LayerName)) { // layer exist DBObject dbobject = lt[LayerName].GetObject(OpenMode.ForWrite, true); dbobject.Erase(); //tr.AddNewlyCreatedDBObject(ltr, true); } tr.Commit(); } } //ed.WriteMessage("Layers Setting Done. \n"); }
/// <summary> /// 删除单个对象 /// </summary> /// <param name="obj">要删除对象</param> public static void RemoveObj(DBObject obj) { Database db = obj.Database; using (Transaction trans = db.TransactionManager.StartTransaction()) { obj.Erase(); trans.Commit(); } }
public static bool RemoveSymbol(ObjectId tblId, string name, Database db = null) { db = (db ?? Autodesk.AutoCAD.ApplicationServices.Core.Application.DocumentManager.MdiActiveDocument.Database); using (Transaction trans = db.TransactionManager.StartTransaction()) { SymbolTable tbl = trans.GetObject(tblId, OpenMode.ForWrite) as SymbolTable; if (!tbl.Has(name)) { return(false); } SymbolTableRecord inUse2 = null; ObjectId inUseId = ObjectId.Null; if (tbl is LayerTable) { inUseId = db.Clayer; } else if (tbl is TextStyleTable) { inUseId = db.Textstyle; } else if (tbl is DimStyleTable) { inUseId = db.Dimstyle; } else if (tbl is LinetypeTable) { inUseId = db.Celtype; } if (inUseId.IsValid) { inUse2 = (trans.GetObject(inUseId, OpenMode.ForRead) as SymbolTableRecord); if (inUse2.Name.ToUpper() == name.ToUpper()) { return(false); } } DBObject record = trans.GetObject(tbl[name], OpenMode.ForWrite); if (record.IsErased) { return(false); } ObjectIdCollection idCol = new ObjectIdCollection { record.ObjectId }; db.Purge(idCol); if (idCol.Count == 0) { return(false); } record.Erase(); trans.Commit(); } return(true); }
public void PythonScriptCmdLine() { // PythonScript(true); Document doc = Application.DocumentManager.MdiActiveDocument; Autodesk.AutoCAD.DatabaseServices.Database db = doc.Database; Editor ed = doc.Editor; using (doc.LockDocument()) { using (db) { using (Transaction t = db.TransactionManager.StartTransaction()) { BlockTable bt = t.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable; BlockTableRecord btr = t.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord; short fd = (short)Application.GetSystemVariable("FILEDIA"); // As the user to select a .py file PromptStringOptions pso = new PromptStringOptions("Insert First Handle"); pso.AllowSpaces = true; PromptResult pr = ed.GetString(pso); string handle1 = pr.StringResult.Replace("\"", ""); pso = new PromptStringOptions("Insert Second Handle"); pso.AllowSpaces = true; pr = ed.GetString(pso); string handle2 = pr.StringResult.Replace("\"", ""); ObjectId oid1 = db.GetObjectId(false, new Handle(Convert.ToInt64(handle1, 16)), 0); ObjectId oid2 = db.GetObjectId(false, new Handle(Convert.ToInt64(handle2, 16)), 0); DBObject ent1 = t.GetObject(oid1, OpenMode.ForWrite); DBObject ent2 = t.GetObject(oid2, OpenMode.ForWrite); ent2.SwapIdWith(oid1, true, true); ent1.Erase(); Application.SetSystemVariable("FILEDIA", fd); t.Commit(); } } } }
public static void RemoveLayer(ObjectId id) { // using (DocumentLock docLock = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.LockDocument()) { Editor ed = Application.DocumentManager.MdiActiveDocument.Editor; using (Transaction trans = ed.Document.Database.TransactionManager.StartTransaction()) { DBObject ent = trans.GetObject(id, OpenMode.ForWrite); ent.Erase(); trans.Commit(); trans.Dispose(); } } }
public void Delete() { OwnSolution.PipeLines.Remove(this.BaseObjectId); Editor ed = Application.DocumentManager.MdiActiveDocument.Editor; using (DocumentLock docLock = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.LockDocument()) { using (Transaction trans = ed.Document.Database.TransactionManager.StartTransaction()) { DBObject ent = trans.GetObject(BaseObjectId, OpenMode.ForWrite); ent.Erase(); trans.Commit(); trans.Dispose(); } } }
private void RemoveDictionary(Database db, Transaction t) { try { DBDictionary dBDictionary = base.ParentDataset.Open(db, t, this.DictionaryName, (OpenMode)1); if (dBDictionary.Contains(this.AcadDictionaryID)) { dBDictionary.Remove(this.AcadDictionaryID); DBObject @object = t.GetObject(this.AcadDictionaryID, (OpenMode)1); @object.Erase(); } } catch { } }
private void EraseProxies(Database db) { RXClass zombieEntity = RXClass.GetClass(typeof(ProxyEntity)); RXClass zombieObject = RXClass.GetClass(typeof(ProxyObject)); ObjectId id; for (long l = db.BlockTableId.Handle.Value; l < db.Handseed.Value; l++) { if (!db.TryGetObjectId(new Handle(l), out id)) { continue; } if (id.ObjectClass.IsDerivedFrom(zombieObject) && !id.IsErased) { try { using (DBObject proxy = id.Open(OpenMode.ForWrite)) { proxy.Erase(); } } catch { using (DBDictionary newDict = new DBDictionary()) using (DBObject proxy = id.Open(OpenMode.ForWrite)) { try { proxy.HandOverTo(newDict, true, true); } catch { } } } } else if (id.ObjectClass.IsDerivedFrom(zombieEntity) && !id.IsErased) { try { using (DBObject proxy = id.Open(OpenMode.ForWrite)) { proxy.Erase(); } } catch { } } } }
deleteObj(ObjectId objID) { Entity ent = null; try { using (BaseObjs._acadDoc.LockDocument()) { using (Transaction tr = BaseObjs.startTransactionDb()) { if (objID.IsValid && !objID.IsEffectivelyErased && !objID.IsErased) { try { DBObject dbObj = (DBObject)tr.GetObject(objID, OpenMode.ForWrite); if (dbObj is Entity) { ent = (Entity)dbObj; if (ent != null) { ent.Erase(true); } } else { dbObj.Erase(); } } catch (System.Exception ex) { BaseObjs.writeDebug(ex.Message + " Misc.cs: line: 393"); } } else { return; } tr.Commit(); } // end using } } catch (System.Exception ex) { BaseObjs.writeDebug(ex.Message + " Misc.cs: line: 404"); } }
public static void AddToBackground() { Document acDoc = Application.DocumentManager.MdiActiveDocument; Database acCurDb = acDoc.Database; Editor acEditor = acDoc.Editor; if (CurrentOpen != null) { using (Transaction tr = acCurDb.TransactionManager.StartTransaction()) { BlockTable bt = (BlockTable)tr.GetObject(acCurDb.BlockTableId, OpenMode.ForRead); //get the backgroung block ObjectId backgroundBlock = bt[CurrentOpen.PlotTypeName + "Background"]; ObjectIdCollection objectsToTransfer = new ObjectIdCollection(); //Select objects to be added PromptSelectionResult acSSPrompt = acDoc.Editor.GetSelection(); SelectionSet acSSet = acSSPrompt.Value; foreach (SelectedObject acSSObj in acSSet) { objectsToTransfer.Add(acSSObj.ObjectId); } // Copy the entities to the block using deepclone IdMapping acMapping = new IdMapping(); acCurDb.DeepCloneObjects(objectsToTransfer, backgroundBlock, acMapping, false); foreach (ObjectId oid in objectsToTransfer) { DBObject e = tr.GetObject(oid, OpenMode.ForWrite); e.Erase(); } tr.Commit(); } //Triggeer regen to update blocks display //alternatively http://adndevblog.typepad.com/autocad/2012/05/redefining-a-block.html Application.DocumentManager.CurrentDocument.Editor.Regen(); } else { acEditor.WriteMessage("No Plot Type currently open\n"); } }
public void Erase(SelectionSet SSet) { List <DBObject> objects = new List <DBObject>(); acBlkTbl = acTrans.GetObject(acCurDb.BlockTableId, OpenMode.ForWrite) as BlockTable; acBlkTblRec = acTrans.GetObject(acBlkTbl[btr], OpenMode.ForWrite) as BlockTableRecord; for (int i = 0; i < SSet.Count; i++) { DBObject dbo = acTrans.GetObject(SSet[i].ObjectId, OpenMode.ForWrite) as DBObject; dbo.Erase(); } }
private void DelBlock_Click(object sender, RoutedEventArgs e) { //Check if there any selected block in lvBlocks if (lvBlocks.SelectedIndex == -1) { MessageBox.Show("Select one block first.", "Delete Block", MessageBoxButton.OK, MessageBoxImage.Exclamation); return; } BlockModel objBlock = lvBlocks.SelectedValue as BlockModel; //Ask to user MessageBoxResult result = MessageBox.Show("Are you sure to delete the block \"" + objBlock.Name + "\".", "Delete Block", MessageBoxButton.YesNo, MessageBoxImage.Exclamation); if (result == MessageBoxResult.No) { return; } //Delet BlockModel BlockGroupModel objBlockGroup = cbMain.SelectedValue as BlockGroupModel; objBlockGroup.LstBlock.Remove(objBlock); //Delet BlockDWG using (Database dbRef = new Database(false, true)) { // Read the DWG dbRef.ReadDwgFile(ArCaRefMgrController.DBPath, FileShare.ReadWrite, true, ""); using (Transaction trRef = dbRef.TransactionManager.StartTransaction()) { BlockTable bt = trRef.GetObject(dbRef.BlockTableId, OpenMode.ForRead) as BlockTable; DBObject obj = trRef.GetObject(bt[objBlock.Name], OpenMode.ForWrite); obj.Erase(); trRef.Commit(); } dbRef.SaveAs(ArCaRefMgrController.DBPath, DwgVersion.Current); } //Write XML ArCaRefMgrParser.WriteXML(); //MessageBox.Show("Block \"" + objBlock.Name + "\" was successfully deleted.", "Block Deleted", MessageBoxButton.OK, MessageBoxImage.Information); }
public static int PurgeDatabase(Database db) { int idCount = 0; Transaction tr = db.TransactionManager.StartTransaction(); using (tr) { // Create the list of objects to "purge" ObjectIdCollection idsToPurge = new ObjectIdCollection(); // Add all the Registered Application names RegAppTable rat = (RegAppTable)tr.GetObject(db.RegAppTableId, OpenMode.ForRead); foreach (ObjectId raId in rat) { if (raId.IsValid) { idsToPurge.Add(raId); } } // Call the Purge function to filter the list db.Purge(idsToPurge); Document doc = Application.DocumentManager.MdiActiveDocument; Editor ed = doc.Editor; //ed.WriteMessage("\nRegistered applications being purged: "); //// Erase each of the objects we've been allowed to foreach (ObjectId id in idsToPurge) { DBObject obj = tr.GetObject(id, OpenMode.ForWrite); // Let's just add to me "debug" code to list the registered applications we're erasing RegAppTableRecord ratr = obj as RegAppTableRecord; if (ratr != null) { ed.WriteMessage("\"{0}\" ", ratr.Name); } obj.Erase(); } // Return the number of objects erased // (i.e. purged) idCount = idsToPurge.Count; tr.Commit(); } return(idCount); }
public override void Run(string filename, Database db) { using (Transaction tr = db.TransactionManager.StartTransaction()) { try { BlockTableRecord btr = (BlockTableRecord)tr.GetObject(SymbolUtilityServices.GetBlockModelSpaceId(db), OpenMode.ForRead); foreach (ObjectId id in btr) { DBObject obj = tr.GetObject(id, OpenMode.ForWrite); obj.Erase(true); } } catch (System.Exception ex) { OnError(ex); } tr.Commit(); } }
public static bool DelBlock(Document doc, Transaction transaction, BlockTableRecord BlockTableRecord_) { try { if (BlockTableRecord_.ObjectId != ObjectId.Null) { DBObject obj = transaction.GetObject(BlockTableRecord_.ObjectId, OpenMode.ForWrite); if (obj != null) { obj.Erase(); return(true); } return(false); } return(false); } catch (Autodesk.AutoCAD.Runtime.Exception) { return(false); } }
private void searchSubDictionary( Transaction trans, DBDictionary dic) { foreach (DBDictionaryEntry dicEntry in dic) { DBObject subDicObj = trans.GetObject( dicEntry.Value, OpenMode.ForRead); if (subDicObj.IsAProxy) { ed.WriteMessage(string.Format("\nНайден прокси подобъект: {0}", dicEntry.Key)); subDicObj.UpgradeOpen(); // for several Proxy Entities the // Erase is not allowed without the // Object Enabler throw an exception, // just treat try { subDicObj.Erase(); continue; } catch { ed.WriteMessage("Прокси недоступен для удаления"); //try again latter _NODEntriesForErase.Add(subDicObj.ObjectId); } } else { //if this key is not proxy, let go into sub keys DBDictionary subDic = subDicObj as DBDictionary; if (subDic != null) { searchSubDictionary(trans, subDic); } } } }
public static void EraseEntities(Database db, IEnumerable <ObjectId> items) { using (CurrentDB curr = new CurrentDB(db)) { using (Transaction tr = db.TransactionManager.StartTransaction()) { try { foreach (ObjectId id in items) { DBObject item = tr.GetObject(id, OpenMode.ForWrite); item.Erase(); } } catch { ; } tr.Commit(); } } }
public static void DeleteAllObj(string layerName) { TypedValue[] tvs = { new TypedValue((int)DxfCode.LayerName, layerName) }; SelectionFilter filter = new SelectionFilter(tvs); ObjectId[] ids = MySelection.SelectAll(filter); if (ids == null) { return; } using (Transaction trans = HostApplicationServices.WorkingDatabase.TransactionManager.StartTransaction()) { for (int i = 0; i < ids.Length; ++i) { DBObject obj = trans.GetObject(ids[i], OpenMode.ForWrite); obj.Erase(); } trans.Commit(); } }
DefineNewBlockRec(string blkName) { Debug.Assert(m_trans != null); BlockTableRecord blkRec = null; BlockTable tbl = (BlockTable)m_trans.GetObject(m_db.BlockTableId, OpenMode.ForWrite); // if it already exists, we are re-defining it and we need to // erase all the existing entities if (tbl.Has(blkName)) { blkRec = (BlockTableRecord)m_trans.GetObject(tbl[blkName], OpenMode.ForWrite); // erase all DBObject tmpObj = null; foreach (ObjectId objId in blkRec) { tmpObj = m_trans.GetObject(objId, OpenMode.ForWrite); if (tmpObj != null) { tmpObj.Erase(true); } } } else { blkRec = new BlockTableRecord(); blkRec.Name = blkName; tbl.Add(blkRec); m_trans.AddNewlyCreatedDBObject(blkRec, true); } return(blkRec); }
public static void DeleteEntity(ObjectId id) { if (ObjectId.Null == id || id.IsErased) { return; } using (Application.DocumentManager.MdiActiveDocument.LockDocument()) { Database db = Application.DocumentManager.MdiActiveDocument.Database; // start new transaction using (Transaction trans = db.TransactionManager.StartTransaction()) { using (DBObject obj = trans.GetObject(id, OpenMode.ForWrite)) { if (null != obj && !obj.IsErased) { obj.Erase(); } } // finish trans.Commit(); } } }
//https://www.keanw.com/2007/08/purging-registe.html public static int PurgeDatabase(Database db, Transaction tr) { int idCount = 0; // Create the list of objects to "purge" ObjectIdCollection idsToPurge = new ObjectIdCollection(); // Add all the Registered Application names RegAppTable rat = (RegAppTable)tr.GetObject(db.RegAppTableId, OpenMode.ForRead); foreach (ObjectId raId in rat) { if (raId.IsValid) { idsToPurge.Add(raId); } } // Call the Purge function to filter the list db.Purge(idsToPurge); // Erase each of the objects we've been // allowed to foreach (ObjectId id in idsToPurge) { DBObject obj = tr.GetObject(id, OpenMode.ForWrite); // Let's just add to me "debug" code // to list the registered applications // we're erasing RegAppTableRecord ratr = obj as RegAppTableRecord; obj.Erase(); } // Return the number of objects erased // (i.e. purged) idCount = idsToPurge.Count; return(idCount); }
public static void PurgeAll(this Database currentDatabase) { Transaction acTrans = currentDatabase.TransactionManager.TopTransaction; bool toBePurged = true; while (toBePurged) { // Create the list of objects to "purge" ObjectIdCollection collection = new ObjectIdCollection(); LayerTable lt = acTrans.GetObject(currentDatabase.LayerTableId, OpenMode.ForRead) as LayerTable; foreach (ObjectId layer in lt) { collection.Add(layer); } LinetypeTable ltt = acTrans.GetObject(currentDatabase.LinetypeTableId, OpenMode.ForRead) as LinetypeTable; foreach (ObjectId linetype in ltt) { collection.Add(linetype); } TextStyleTable tst = acTrans.GetObject(currentDatabase.TextStyleTableId, OpenMode.ForRead) as TextStyleTable; foreach (ObjectId text in tst) { collection.Add(text); } BlockTable bt = acTrans.GetObject(currentDatabase.BlockTableId, OpenMode.ForRead) as BlockTable; foreach (ObjectId block in bt) { collection.Add(block); } DBDictionary tsd = acTrans.GetObject(currentDatabase.TableStyleDictionaryId, OpenMode.ForRead) as DBDictionary; foreach (DBDictionaryEntry ts in tsd) { collection.Add(ts.Value); } // Call the Purge function to filter the list currentDatabase.Purge(collection); if (collection.Count > 0) { // Erase each of the objects we've been allowed to foreach (ObjectId id in collection) { DBObject obj = acTrans.GetObject(id, OpenMode.ForWrite); obj.Erase(); } } else { toBePurged = false; } } }
static public void RenameDrawingsLayersByExcel() { Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument; Editor ed = doc.Editor; //string[] filePath = FileOps.getFilePaths("Select layer Excel file", "Excel files | *.xlsx", false); //if(filePath != null) //{ string excelFile = "D:\\cad_layer_update_test.xlsx"; Dictionary <string, Dictionary <string, string> > data = Excel.getDwgLayerSetup(excelFile); foreach (KeyValuePair <string, Dictionary <string, string> > d in data) { string file = d.Key; Dictionary <string, string> layers = d.Value; if (File.Exists(file)) { ed.WriteMessage($"Rename layers for {file}\n"); try { Database db = new Database(false, true); ObjectIdCollection layIdsToBeRemoved = new ObjectIdCollection(); using (db) { db.ReadDwgFile(file, System.IO.FileShare.ReadWrite, true, null); Transaction tr = db.TransactionManager.StartTransaction(); using (tr) { ed.WriteMessage($"Start transition....\n"); #region ///look into BlockTable and saved object id Dictionary <string, ObjectIdCollection> objLayers = new Dictionary <string, ObjectIdCollection>(); //key = layer name; value = ObjectIdCollection var blockTable = (BlockTable)tr.GetObject(db.BlockTableId, OpenMode.ForRead); //get all ObjectIdCollection in database foreach (ObjectId btrId in blockTable) { var btr = (BlockTableRecord)tr.GetObject(btrId, OpenMode.ForRead); foreach (ObjectId id in btr) { Entity obj = tr.GetObject(id, OpenMode.ForRead) as Entity; string layerName = obj.Layer.Trim().ToUpper(); if (objLayers.ContainsKey(layerName)) { objLayers[layerName].Add(id);//add the objectId to ObjectIdCollection if it is already exist } else { ObjectIdCollection col = new ObjectIdCollection(); col.Add(id); objLayers.Add(layerName, col);//add first item } } } #endregion #region get layer table LayerTable lt = tr.GetObject(db.LayerTableId, OpenMode.ForRead) as LayerTable; //set layer 0 as current layer db.Clayer = lt["0"]; foreach (ObjectId lyId in lt) { LayerTableRecord l = tr.GetObject(lyId, OpenMode.ForWrite) as LayerTableRecord;//get LayerTableRecord //only do something when the layer is not in xref if (!l.IsDependent) { string name = l.Name; string oldLayerName = name.Trim().ToUpper(); //clean up the layer name if (layers.ContainsKey(oldLayerName)) { string newLayerName = layers[oldLayerName]; if (string.IsNullOrEmpty(newLayerName)) { continue; } if (lt.Has(newLayerName)) { #region move the entities that is in the oldLayerName to the newLayerName if this new Layer already exist //if this new layer name is already exists //move geometries in this old layer into that right layer if (objLayers.ContainsKey(oldLayerName)) { ObjectIdCollection col = objLayers[oldLayerName]; foreach (ObjectId objId in col) { Entity ent = tr.GetObject(objId, OpenMode.ForWrite) as Entity; ent.Layer = newLayerName; } #endregion //add the old layer to the layIdsToBeRemoved layIdsToBeRemoved.Add(lyId); } } else { //if this new layer name is not already exists //change current layer name to new name l.Name = newLayerName; } } } } #endregion #region remove layers foreach (ObjectId id in layIdsToBeRemoved) { DBObject obj = tr.GetObject(id, OpenMode.ForWrite); obj.Erase(); } #endregion tr.Commit(); ed.WriteMessage($"End transition....\n"); } ed.WriteMessage("\n Finish update " + System.IO.Path.GetFileName(file) + ".\n"); db.SaveAs(file, DwgVersion.Current);//save changes } } catch (Autodesk.AutoCAD.Runtime.Exception ex) { ed.WriteMessage(ex.ToString() + Environment.NewLine); } } else { ed.WriteMessage("File " + file + " does not exist.\n"); } } //} }
string dgnLsDictName = "ACAD_DGNLINESTYLECOMP";// this distionary has been deleted public void DgnDeleting(List <string> allDwgPath) { HostMgdApp.Application ncadMgpApp = Marshal.GetActiveObject("nanocad.Application") as HostMgdApp.Application; foreach (string oneDwg in allDwgPath) { HostMgdApp.Document docMgb; try { docMgb = HostMgdApp.Application.DocumentManager.Open(oneDwg, false); } catch (System.Exception ex) { MessageBox.Show("Ошибка: " + ex.Message); return; } Database db = docMgb.Database; ObjectIdCollection objIdColl = new ObjectIdCollection(); bool dgnSt; using (Transaction tr = db.TransactionManager.StartTransaction()) { var nod = (DBDictionary)tr.GetObject(db.NamedObjectsDictionaryId, OpenMode.ForRead); if ((ObjectId)nod[dgnLsDictName] != ObjectId.Null) { dgnSt = true; DBDictionary dgnLsDict = (DBDictionary)tr.GetObject((ObjectId)nod[dgnLsDictName], OpenMode.ForWrite); dgnLsDict.Erase(); //dgnLsDict.Remove(dgnLsDictName); tr.Commit(); } else { dgnSt = false; tr.Commit(); } } // был ли словарь if (dgnSt == false) { docMgb.Dispose(); mcObj.McDocument mcDocClose = mcObj.McDocument.ActiveDocument; mcDocClose.Close(); continue; } docMgb.Database.Save(); docMgb.Dispose(); mcObj.McDocument mcDoc = mcObj.McDocument.ActiveDocument; mcDoc.Save(); mcDoc.Close(); HostMgdApp.Document docMgbItem = HostMgdApp.Application.DocumentManager.Open(oneDwg, false); Database dbItem = docMgbItem.Database; ObjectIdCollection objIdCollItem = new ObjectIdCollection(); using (Transaction trItem = dbItem.TransactionManager.StartTransaction()) { LinetypeTable LnTb; LnTb = trItem.GetObject(dbItem.LinetypeTableId, OpenMode.ForRead) as LinetypeTable; foreach (ObjectId oneObjId in LnTb) { objIdCollItem.Add(oneObjId); } dbItem.Purge(objIdCollItem); trItem.Commit(); } dbItem.Purge(objIdCollItem); using (Transaction t = dbItem.TransactionManager.StartTransaction()) { foreach (ObjectId ltypeId in objIdCollItem) { DBObject ltype = t.GetObject(ltypeId, OpenMode.ForWrite); ltype.Erase(); } t.Commit(); } dbItem.ReclaimMemoryFromErasedObjects(objIdCollItem); docMgbItem.Database.Save(); docMgbItem.Dispose(); mcObj.McDocument mcDocItem = mcObj.McDocument.ActiveDocument; mcDocItem.Save(); mcDocItem.Close(); } }
private void method_1(ObjectId[] objectId_0, double double_1, ref int int_1, ref int int_2, ref int int_3) { Database workingDatabase = HostApplicationServices.WorkingDatabase; Editor arg_15_0 = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor; ProgressMeter progressMeter = new ProgressMeter(); MessageFilter messageFilter = new MessageFilter(); System.Windows.Forms.Application.AddMessageFilter(messageFilter); progressMeter.SetLimit(objectId_0.Length); progressMeter.Start("Simplifying polylines"); try { using (Transaction transaction = workingDatabase.TransactionManager.StartTransaction()) { BlockTable blockTable = (BlockTable)transaction.GetObject(workingDatabase.BlockTableId, (OpenMode)1); BlockTableRecord blockTableRecord = (BlockTableRecord)transaction.GetObject(blockTable[BlockTableRecord.ModelSpace], (OpenMode)1); for (int i = 0; i < objectId_0.Length; i++) { try { progressMeter.MeterProgress(); messageFilter.CheckMessageFilter((long)i, 10); DBObject @object = transaction.GetObject(objectId_0[i], (OpenMode)1); bool flag = false; Polyline polyline = @object as Polyline; if (polyline != null) { flag = polyline.Closed; } Polyline2d polyline2d = @object as Polyline2d; if (polyline2d != null) { flag = polyline2d.Closed; } Polyline3d polyline3d = @object as Polyline3d; if (polyline3d != null) { flag = polyline3d.Closed; } List <ngeometry.VectorGeometry.Point> p = PointGeneration.SubdividePolyline(@object, transaction, 0.0).ToList(); int_1 += Conversions.GetNumberOfPoyllineVertices(@object); List <ngeometry.VectorGeometry.Point> list = this.method_2(p, double_1); int_2 += list.Count; Point3dCollection point3dCollection = Conversions.ToPoint3dCollection(list); Polyline3d polyline3d2 = new Polyline3d(0, point3dCollection, flag); polyline3d2.SetPropertiesFrom((Entity)@object); if (PLine.string_2 == "N" & [email protected]) { @object.Erase(); } blockTableRecord.AppendEntity(polyline3d2); transaction.AddNewlyCreatedDBObject(polyline3d2, true); } catch (System.Exception ex) { int_3++; } } transaction.Commit(); } progressMeter.Stop(); } catch (System.Exception ex) { progressMeter.Stop(); throw ex; } }
public override void Run(string filename, Database db) { List <ObjectId> tables = new List <ObjectId>(); if (purgeBlocks) { tables.Add(db.BlockTableId); } if (purgeDimensionStyles) { tables.Add(db.DimStyleTableId); } if (purgeLayers) { tables.Add(db.LayerTableId); } if (purgeLinetypes) { tables.Add(db.LinetypeTableId); } if (purgeTextStyles || purgeShapes) { tables.Add(db.TextStyleTableId); } if (purgeUCSSettings) { tables.Add(db.UcsTableId); } if (purgeViewports) { tables.Add(db.ViewportTableId); } if (purgeViews) { tables.Add(db.ViewTableId); } List <ObjectId> dictionaries = new List <ObjectId>(); if (purgeGroups) { dictionaries.Add(db.GroupDictionaryId); } if (purgeMaterials) { dictionaries.Add(db.MaterialDictionaryId); } if (purgeMlineStyles) { dictionaries.Add(db.MLStyleDictionaryId); } if (purgeMultileaderStyles) { dictionaries.Add(db.MLeaderStyleDictionaryId); } if (purgePlotStyles) { dictionaries.Add(db.PlotStyleNameDictionaryId); } if (purgeTableStyles) { dictionaries.Add(db.TableStyleDictionaryId); } if (purgeVisualStyles) { dictionaries.Add(db.VisualStyleDictionaryId); } if (purgeDetailViewStyles) { dictionaries.Add(db.DetailViewStyleDictionaryId); } if (purgeSectionViewStyles) { dictionaries.Add(db.SectionViewStyleDictionaryId); } using (Transaction tr = db.TransactionManager.StartTransaction()) { try { ObjectIdCollection idList = new ObjectIdCollection(); string s = ""; // Symbol tables foreach (ObjectId tableID in tables) { foreach (ObjectId id in CollectTableIds(tr, db, tableID)) { if (id.ObjectClass.UnmanagedObject == RXClass.GetClass(typeof(TextStyleTableRecord)).UnmanagedObject) { // Seperate font styles and shapes TextStyleTableRecord style = (TextStyleTableRecord)tr.GetObject(id, OpenMode.ForRead); if (purgeTextStyles && !style.IsShapeFile) { idList.Add(id); } else if (purgeShapes && style.IsShapeFile) { idList.Add(id); } } else { idList.Add(id); } } } System.IO.File.WriteAllText("D:\\log.txt", s); // Dictionary entries foreach (ObjectId dictionaryID in dictionaries) { foreach (ObjectId id in CollectDictionaryIds(tr, db, dictionaryID)) { idList.Add(id); } } // Reg apps if (purgeRegApps) { RegAppTable regAppTable = (RegAppTable)tr.GetObject(db.RegAppTableId, OpenMode.ForRead); foreach (ObjectId id in regAppTable) { if (id.IsValid) { idList.Add(id); } } } // Empty text objects or zero length geometry if (purgeEmptyTexts | purgeZeroLengthGeometry) { ObjectIdCollection blockIDs = new ObjectIdCollection(); blockIDs.Add(SymbolUtilityServices.GetBlockModelSpaceId(db)); DBDictionary layoutDict = (DBDictionary)tr.GetObject(db.LayoutDictionaryId, OpenMode.ForRead); foreach (DBDictionaryEntry entry in layoutDict) { if (entry.Key.ToUpperInvariant() != "MODEL") { Layout layout = (Layout)tr.GetObject(entry.Value, OpenMode.ForRead); blockIDs.Add(layout.BlockTableRecordId); } } int textCount = 0; int zeroLengthCount = 0; foreach (ObjectId blockID in blockIDs) { var btr = (BlockTableRecord)tr.GetObject(blockID, OpenMode.ForRead); foreach (ObjectId id in btr) { // Empty text objects if (purgeEmptyTexts && id.ObjectClass.UnmanagedObject == RXClass.GetClass(typeof(DBText)).UnmanagedObject) { DBText text = (DBText)tr.GetObject(id, OpenMode.ForRead); if (string.IsNullOrEmpty(text.TextString)) { text.UpgradeOpen(); text.Erase(true); textCount++; } } else if (purgeEmptyTexts && id.ObjectClass.UnmanagedObject == RXClass.GetClass(typeof(MText)).UnmanagedObject) { MText text = (MText)tr.GetObject(id, OpenMode.ForRead); if (string.IsNullOrEmpty(text.Text)) { text.UpgradeOpen(); text.Erase(true); textCount++; } } // Zero length geometry else if (purgeZeroLengthGeometry && id.ObjectClass.IsDerivedFrom(RXObject.GetClass(typeof(Curve)))) { Curve curve = (Curve)tr.GetObject(id, OpenMode.ForRead); if (curve.GetLength() < zeroLengthGeometryTolerance) { curve.UpgradeOpen(); curve.Erase(true); zeroLengthCount++; } } } } } // Filter purgables db.Purge(idList); // Step through the returned ObjectIdCollection // and erase each unreferenced symbol int purgeCount = 0; foreach (ObjectId id in idList) { DBObject obj = tr.GetObject(id, OpenMode.ForWrite); obj.Erase(true); purgeCount++; } } catch (System.Exception ex) { OnError(ex); } tr.Commit(); } }