private void CreateAndGroupBallon(Ballon ballon) { Document doc = AcAp.Application.DocumentManager.MdiActiveDocument; Database db = doc.Database; Transaction trans = doc.TransactionManager.StartTransaction(); using (trans) { try { PromptPointResult pPtRes; PromptPointOptions pPtOpts = new PromptPointOptions("Enter Base point[X,Y]: "); pPtRes = doc.Editor.GetPoint(pPtOpts); if (pPtRes.Status == PromptStatus.Cancel) { return; } Point3d startPoint = pPtRes.Value; //Line line = new Line(startPoint, endPoint); Line line = CreateLine(startPoint, ballon.Angle, ballon.Length, ballon.LayerName, ballon.ColorIndex); Circle cir = CreateCirle(line.EndPoint, ballon.Angle, ballon.Radius); DBText text = CreateText(cir.Center, ballon.StringInput); //Open the Layer table for read ObjectId oLineId = DatabaseHelper.AppendEntityToDatabase(line); ObjectId oCircleId = DatabaseHelper.AppendEntityToDatabase(cir); ObjectId oTextId = DatabaseHelper.AppendEntityToDatabase(text); Group grp = new Group("Test group description", true); // Add the new group to the dictionary DBDictionary gd = trans.GetObject(db.GroupDictionaryId, OpenMode.ForRead) as DBDictionary; gd.UpgradeOpen(); ObjectId grpId = gd.SetAt("GroupCaseStudy1", grp); trans.AddNewlyCreatedDBObject(grp, true); ObjectIdCollection ids = new ObjectIdCollection(); ids.Add(oLineId); ids.Add(oCircleId); ids.Add(oTextId); grp.InsertAt(0, ids); ResultBuffer rb = CreateBalloonBuffer(ballon, BALLON_XDATA_NAME); grp.XData = rb; rb.Dispose(); trans.Commit(); } catch (System.Exception e) { trans.Abort(); } } }
public void TestAppendWithTxn() { testName = "TestAppendWithTxn"; SetUpTest(true); string heapDBFileName = testHome + "/" + testName + ".db"; string heapDBName = Path.GetFileNameWithoutExtension(heapDBFileName); DatabaseEnvironmentConfig envConfig = new DatabaseEnvironmentConfig(); envConfig.Create = true; envConfig.UseTxns = true; envConfig.UseMPool = true; DatabaseEnvironment env = DatabaseEnvironment.Open( testHome, envConfig); Transaction txn = env.BeginTransaction(); HeapDatabaseConfig heapConfig = new HeapDatabaseConfig(); heapConfig.Creation = CreatePolicy.ALWAYS; heapConfig.Env = env; /* If environmnet home is set, the file name in * Open() is the relative path. */ HeapDatabase heapDB = HeapDatabase.Open( heapDBName, heapConfig, txn); DatabaseEntry data; int i = 1000; try { while (i > 0) { data = new DatabaseEntry( BitConverter.GetBytes(i)); heapDB.Append(data, txn); i--; } txn.Commit(); } catch { txn.Abort(); } finally { heapDB.Close(); env.Close(); } }
/// <summary> /// Closes the connection that might be opened against the database-alike service. /// <para>The framework invokes this method automatically when needed.</para> /// </summary> public override void Close() { if (Transaction != null && Transaction.IsActive) { Transaction.Abort(); } if (_DbConnection != null) { if (_DbConnection.State != ConnectionState.Closed) { _DbConnection.Close(); } _DbConnection.Dispose(); _DbConnection = null; } }
private void InsertFindAbortTest() { byte[] k = new byte[5]; byte[] r = new byte[5]; Transaction t = env.Begin(); db.Insert(t, k, r); db.Find(t, k); t.Abort(); try { db.Find(k); } catch (DatabaseException e) { Assert.AreEqual(UpsConst.UPS_KEY_NOT_FOUND, e.ErrorCode); } }
public void TraverseNamedDictionary() { #region 定义文档、数据库以及控制台。 //定义文档、数据库以及控制台。 Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument; Database database = doc.Database; Editor editor = doc.Editor; #endregion //开启事务。 Transaction transaction = database.TransactionManager.StartTransaction(); try { //获取数据库中 NamedDictionary 对应的 ObjectId。 ObjectId namedDictionaryId = database.NamedObjectsDictionaryId; //通过指定的 ObjectId 打开数据库的 NamedDictionary。 DBDictionary namedDictionary = (DBDictionary)transaction.GetObject(namedDictionaryId, OpenMode.ForRead); //输出 NamedDictionary 中的数据数量。 editor.WriteMessage("---------------命名对象词典---------------\r\n"); editor.WriteMessage(String.Format("当前词典中的数据量为: {0:G}\r\n", namedDictionary.Count)); //遍历 NamedDictionary 中的入口。 editor.WriteMessage("---------------词典入口---------------\r\n"); { int index = 0; foreach (DBDictionaryEntry entry in namedDictionary) { editor.WriteMessage(String.Format( "第 {0:G} 个入口,其键为: {1}, 其值为: {2}, 值的对象类型为: {3}\r\n", ++index, entry.Key, entry.Value.ToString(), transaction.GetObject(entry.Value, OpenMode.ForRead).GetType().Name )); } } transaction.Commit(); } catch (Autodesk.AutoCAD.Runtime.Exception e) { editor.WriteMessage(e.Message); //如果操作过程中产生了任何异常,则中止事务。 transaction.Abort(); } finally { //在final语句块中释放事务。 transaction.Dispose(); } }
public void TogglePlusMinus() //Функция переключает '+' или '-' перед выбранными однострочными текстами { //Выбрать объекты ed.WriteMessage("Выберите объекты - однострочные тексты"); PromptSelectionResult sr = ed.GetSelection(); if (sr.Status == PromptStatus.OK) { Transaction tr = acCurDb.TransactionManager.StartTransaction(); try { ObjectId[] objIds = sr.Value.GetObjectIds(); foreach (ObjectId asObjId in objIds) { DBObject dbo = tr.GetObject(asObjId, OpenMode.ForWrite); try { DBText txt = (DBText)dbo; string sTxt = txt.TextString; if (sTxt.StartsWith("+")) { sTxt = "-" + sTxt.Substring(1); } else if (sTxt.StartsWith("-")) { sTxt = "+" + sTxt.Substring(1); } else { sTxt = "-" + sTxt; } txt.TextString = sTxt; } catch { } } ; tr.Commit(); } catch (PlatformDb.Runtime.Exception ex) { ed.WriteMessage(ex.Message); tr.Abort(); }; } }
//////////////////////////// //// MATERIALS //////////////////////////// private void DisplayPropsMaterial() { Database db = Application.DocumentManager.MdiActiveDocument.Database; TransactionManager tm = db.TransactionManager; Transaction trans = db.TransactionManager.StartTransaction(); try { Application.DocumentManager.MdiActiveDocument.Editor.WriteMessage("=======================================\n"); Application.DocumentManager.MdiActiveDocument.Editor.WriteMessage("Get all the Display Properties and the Display components works with AecDbMaterialDef in ZAxis view\n"); Application.DocumentManager.MdiActiveDocument.Editor.WriteMessage("=======================================\n"); DisplayRepresentationManager drm = new DisplayRepresentationManager(db); Viewport vport = new Viewport(); BlockTableRecord btr = (BlockTableRecord)trans.GetObject(db.CurrentSpaceId, OpenMode.ForWrite, false); btr.AppendEntity(vport); trans.AddNewlyCreatedDBObject(vport, true); ObjectId viewportId = vport.ObjectId; Vector3d viewDirection = Vector3d.ZAxis; ObjectId setId = drm.DisplayRepresentationSet(viewportId, viewDirection); DisplaySet ds = trans.GetObject(setId, OpenMode.ForWrite) as DisplaySet; DisplayRepresentationIdCollection repIds = ds.DisplayRepresentationIds; DisplayRepresentation dr = null; foreach (ObjectId repId in repIds) { dr = trans.GetObject(repId, OpenMode.ForRead) as DisplayRepresentation; if (dr.WorksWith.Name == "AecDbMaterialDef") { ObjectId dpId = dr.DefaultDisplayPropertiesId; DisplayProperties dp = trans.GetObject(dpId, OpenMode.ForWrite) as DisplayProperties; ListDisplayProperties(dp); } } } catch (System.Exception e) { Application.DocumentManager.MdiActiveDocument.Editor.WriteMessage(e.Message + "\n"); trans.Abort(); } finally { trans.Dispose(); } return; }
public static void AttachDataToEntity(ObjectId entId, ResultBuffer rb, string AppName) { Document doc = Application.DocumentManager.MdiActiveDocument; Database db = doc.Database; Editor ed = doc.Editor; // now start a transaction using (Transaction trans = db.TransactionManager.StartTransaction()) { try { // Declare an Entity variable named ent. Entity ent = trans.GetObject(entId, OpenMode.ForRead) as Entity; // test the IsNull property of the ExtensionDictionary of the ent. if (ent.ExtensionDictionary.IsNull) { // Upgrade the open of the entity. ent.UpgradeOpen(); // Create the ExtensionDictionary ent.CreateExtensionDictionary(); } // variable as DBDictionary. DBDictionary extensionDict = (DBDictionary)trans.GetObject(ent.ExtensionDictionary, OpenMode.ForWrite); if (extensionDict != null) { // Create a new XRecord. Xrecord myXrecord = new Xrecord(); // Add the ResultBuffer to the Xrecord myXrecord.Data = rb; // Create the entry in the ExtensionDictionary. extensionDict.SetAt(AppName, myXrecord); // Tell the transaction about the newly created Xrecord trans.AddNewlyCreatedDBObject(myXrecord, true); } // all ok, commit it trans.Commit(); trans.Dispose(); } catch (System.Exception ex) { trans.Abort(); } } }
public ObjectId AddCivil2016BreaklineByTrans(ObjectId SurfaceId, ObjectId polyId, ObjectId siteId, string name) { ObjectId featureId = ObjectId.Null; C3DLandDb.FeatureLine feature = null; var layername = ""; Debug.WriteLine("Starting AddCivil2016BreaklineByTrans"); using (Application.DocumentManager.MdiActiveDocument.LockDocument()) { using (Transaction tr = CivilApplicationManager.StartTransaction()) { var checkPoly = polyId.GetObject (OpenMode.ForRead, false, true) as Polyline; if (checkPoly != null) { featureId = C3DLandDb.FeatureLine.Create (GetFeatureLineName(), polyId, siteId); layername = checkPoly.Layer; var color = checkPoly.Color; feature = featureId.GetObject(OpenMode.ForWrite) as C3DLandDb.FeatureLine; feature.Layer = layername; feature.Color = color; feature.Name += layername + "-" + String.Format("A{0:0#}A", feature.Area) + "-" + DateTime.Now.Millisecond; } else { tr.Abort(); Debug.WriteLine("Aborted AddCivil2016BreaklineByTrans " + layername + " Count: " + checkPoly.NumberOfVertices); } tr.Commit(); Debug.WriteLine("Ending AddCivil2016BreaklineByTrans" + layername + " Count: " + checkPoly.NumberOfVertices); return(featureId); } } }
public void makeCircle() { Circle circle = new Circle(Point3d.Origin, Vector3d.ZAxis, 10); CircleJig jigCir = new CircleJig(circle); for (int i = 0; i < 2; ++i) { jigCir.CurrentInput = i; Editor ed = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor; PromptResult prompt = ed.Drag(jigCir); if (prompt.Status == PromptStatus.Cancel || prompt.Status == PromptStatus.Error) { return; } } Database dwg = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Database; using (Transaction trans = dwg.TransactionManager.StartTransaction()) { try { // use the transaction to open these objects. // the transaction will automatically dispose these objects when done // so we don't have to worry about manually disposing them. BlockTable blk = trans.GetObject(dwg.BlockTableId, OpenMode.ForWrite) as BlockTable; if (blk == null) { return; } BlockTableRecord blkRecord = trans.GetObject(blk[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord; blkRecord.AppendEntity(circle); trans.AddNewlyCreatedDBObject(circle, true); trans.Commit(); } catch (System.Exception) { trans.Abort(); throw; } } }
// write the AC entity into the AC database public static void Add(Entity entity) { // get database reference Database db = Application.DocumentManager.MdiActiveDocument.Database; using (Transaction acTrans = db.TransactionManager.StartTransaction()) { Log.Append("> Start Transaction..."); try { // create a block table record BlockTableRecord acBTR = (BlockTableRecord)acTrans.GetObject( db.CurrentSpaceId, // space id (f.e. model space) OpenMode.ForWrite); // put entity into block table record acBTR.AppendEntity(entity); // put it into the transaction // |true add, false delete acTrans.AddNewlyCreatedDBObject(entity, true); // write data into the database completing the transaction acTrans.Commit(); Log.Append("> Transaction successfull!"); } // handle autocad exception catch (Autodesk.AutoCAD.Runtime.Exception ex) { acTrans.Abort(); Log.Append("*** error in transaction!"); Log.Append(ex.ToString()); } // clearing finally { GC.Collect(); // clear the memory } Log.Append("> completed!"); } }
/// <summary> /// Define una transacción que no regresa ningun valor. /// </summary> /// <param name="TransactionTask">La transacción a realizar.</param> public static void VoidTransaction(Action <Document, Transaction> TransactionTask) { var doc = Application.DocumentManager.MdiActiveDocument; using (Transaction tr = doc.Database.TransactionManager.StartTransaction()) { try { TransactionTask(doc, tr); tr.Commit(); } catch (Exception exc) { doc.Editor.WriteMessage(exc.Message); tr.Abort(); } } }
public void GenerateDeadlock() { Transaction txn = testLockStatsEnv.BeginTransaction(); try { testLockStatsDb.Put( new DatabaseEntry(BitConverter.GetBytes(100)), new DatabaseEntry(ASCIIEncoding.ASCII.GetBytes( Configuration.RandomString(200))), txn); DeadlockDidPut = 1; testLockStatsDb.Get(new DatabaseEntry( BitConverter.GetBytes(10)), txn); } catch (DeadlockException) { } // Abort unconditionally - we don't care about the transaction txn.Abort(); }
public static bool ReadEntityData(ObjectId entId, ref ResultBuffer rb, string AppName) { bool bRet = false; Document doc = Application.DocumentManager.MdiActiveDocument; Database db = doc.Database; Editor ed = doc.Editor; using (Transaction trans = db.TransactionManager.StartTransaction()) { try { // Declare an Entity variable named ent. if (entId.IsValid && entId.IsErased == false) { Entity ent = trans.GetObject(entId, OpenMode.ForRead) as Entity; if (ent != null && ent.ExtensionDictionary.IsValid && !ent.ExtensionDictionary.IsErased) { // Declare an Entity variable named ent. // variable as DBDictionary. DBDictionary extensionDict = trans.GetObject(ent.ExtensionDictionary, OpenMode.ForRead) as DBDictionary; if (extensionDict != null && extensionDict.Contains(AppName)) { // Check to see if the entry we are going to add is already there. ObjectId entryId = extensionDict.GetAt(AppName); // Extract the Xrecord. Declare an Xrecord variable. Xrecord myXrecord = default(Xrecord); // Instantiate the Xrecord variable myXrecord = (Xrecord)trans.GetObject(entryId, OpenMode.ForRead); if (myXrecord != null && myXrecord.Data != null) { rb = myXrecord.Data; } } } } trans.Commit(); } catch (System.Exception ex) { trans.Abort(); } } return(bRet); }
public ObjectIdCollection GetDuplicateVertexCurveIds() { var duplicateVertexCurveIds = new ObjectIdCollection(); var database = base.Editor.Document.Database; using (Transaction trans = database.TransactionManager.StartTransaction()) { var blockTable = (BlockTable)trans.GetObject(database.BlockTableId, OpenMode.ForRead); var modelSpace = (BlockTableRecord)trans.GetObject(blockTable[BlockTableRecord.ModelSpace], OpenMode.ForRead); var allCurves = new List <Curve>(); foreach (var objectId in modelSpace) { if (!objectId.IsValid) { continue; } // Get all specified layers curves from modelspace. var curve = trans.GetObject(objectId, OpenMode.ForRead) as Curve; if (curve != null) { //// Check if the curve is from specified layers. //if (_layers.Contains(curve.Layer) == false) // continue; allCurves.Add(curve); } } // Check Duplicate vertexs. foreach (Curve curve in allCurves) { if (HasDuplicateVertex(trans, curve, _tolerance)) { duplicateVertexCurveIds.Add(curve.ObjectId); } } trans.Abort(); } return(duplicateVertexCurveIds); }
// show the information of the given display configuration. private void ListDisplayConfig(DisplayConfiguration dc) { Database db = Application.DocumentManager.MdiActiveDocument.Database; Transaction trans = db.TransactionManager.StartTransaction(); try { Application.DocumentManager.MdiActiveDocument.Editor.WriteMessage("=======================================\n"); Application.DocumentManager.MdiActiveDocument.Editor.WriteMessage("Name: " + dc.Name + "\n"); Application.DocumentManager.MdiActiveDocument.Editor.WriteMessage("Description: " + dc.Description + "\n"); Application.DocumentManager.MdiActiveDocument.Editor.WriteMessage("Cut Plane Display Above: " + dc.CutPlaneAboveRange + "\n"); Application.DocumentManager.MdiActiveDocument.Editor.WriteMessage("Cut Plane Display Below: " + dc.CutPlaneBelowRange + "\n"); Application.DocumentManager.MdiActiveDocument.Editor.WriteMessage("Use View Port View Direction: " + dc.UseViewportViewDirection.ToString() + "\n"); Application.DocumentManager.MdiActiveDocument.Editor.WriteMessage("Is View Dependent: " + dc.IsViewDependent.ToString() + "\n"); Application.DocumentManager.MdiActiveDocument.Editor.WriteMessage("Hard View Direction: " + dc.HardViewDirection.ToString() + "\n"); Vector3d v; DisplaySet ds; foreach (ViewDependentCombination vd in dc.ViewDependentCombinations) { v = vd.Direction; ds = trans.GetObject(vd.SetId, OpenMode.ForRead) as DisplaySet; Application.DocumentManager.MdiActiveDocument.Editor.WriteMessage(v.ToString() + " " + ds.Name + "\n"); } // added. Default view set ds = trans.GetObject(dc.DefaultViewDependentViewSet, OpenMode.ForRead) as DisplaySet; Application.DocumentManager.MdiActiveDocument.Editor.WriteMessage("Default View Dependent View Set: " + ds.Name + "\n"); Application.DocumentManager.MdiActiveDocument.Editor.WriteMessage("=======================================\n"); trans.Commit(); } catch (System.Exception) { trans.Abort(); } finally { trans.Dispose(); } }
static public List <ObjectId> PickEnts() { using (AcadApp.Application.DocumentManager.MdiActiveDocument.LockDocument()) { using (Transaction tr = AcadFuncs.GetActiveDoc().TransactionManager.StartTransaction()) { PromptSelectionResult prmpt_ret = AcadFuncs.GetEditor().GetSelection(); if (PromptStatus.Cancel == prmpt_ret.Status) { tr.Abort(); tr.Dispose(); return(new List <ObjectId>()); } tr.Commit(); return(prmpt_ret.Value.GetObjectIds().ToList()); } } }
// Token: 0x060000C9 RID: 201 RVA: 0x0000A334 File Offset: 0x00008534 internal void c(ObjectId A_0, Transaction A_1) { try { if (!A_0.IsNull && !A_0.IsErased && A_0.IsValid) { DBObject @object = A_1.GetObject(A_0, 1, false, true); if (!(@object == null)) { this.b(@object, A_1); } } } catch { A_1.Abort(); ah.b("Объект не доступен для записи. Вероятно заблокирован слой."); } }
public static string LoadXData(ObjectId objId) { // Get the current database and start a transaction Database acCurDb; acCurDb = acApp.DocumentManager.MdiActiveDocument.Database; Document acDoc = acApp.DocumentManager.MdiActiveDocument; string msgstr = ""; using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction()) { // Open the selected object for read Entity acEnt = acTrans.GetObject(objId, OpenMode.ForRead) as Entity; // Get the extended data attached to each object for MY_APP ResultBuffer rb = acEnt.GetXDataForApplication(appName); // Make sure the Xdata is not empty if (rb != null) { // Get the values in the xdata foreach (TypedValue typeVal in rb) { if (typeVal.TypeCode == 1000) { msgstr = typeVal.Value.ToString(); } } } else { msgstr = ""; } // Ends the transaction and ensures any changes made are ignored acTrans.Abort(); // Dispose of the transaction } return(msgstr); }
public void SelectAlignment() { using (Transaction tr = db.TransactionManager.StartTransaction()) { try { PromptEntityOptions prEntOpts = new PromptEntityOptions("\nPlease select exsisting alignment: "); prEntOpts.AllowNone = true; prEntOpts.SetRejectMessage("\n Selected object must be an alignment type"); prEntOpts.AddAllowedClass(typeof(Alignment), true); PromptEntityResult prEntRes = ed.GetEntity(prEntOpts); if (prEntRes.Status != PromptStatus.OK) { MessageBox.Show("Please repeat selection", "Info", MessageBoxButtons.OK); } else { Alignment alig = tr.GetObject(prEntRes.ObjectId, OpenMode.ForRead) as Alignment; ed.WriteMessage("\n You selected alignment: " + alig.Name); selectedALig = alig; ObjectIdCollection profIds = selectedALig.GetProfileIds(); foreach (ObjectId id in profIds) { Autodesk.Civil.DatabaseServices.Profile prof = tr.GetObject(id, OpenMode.ForRead) as Autodesk.Civil.DatabaseServices.Profile; profiles.Add(prof); } tr.Commit(); } } catch (System.Exception ex) { ed.WriteMessage("Error encountered" + ex.Message); tr.Abort(); selectedALig = null; } } }
public static ObjectId GetStyleId(string styleName) { using (Transaction tr = CivilApplicationManager.StartTransaction()) { CivilDocument doc = CivilApplicationManager.ActiveCivilDocument; SurfaceStyleCollection styles = doc.Styles.SurfaceStyles; foreach (ObjectId styleId in styles) { SurfaceStyle style = styleId.GetObject(OpenMode.ForRead) as SurfaceStyle; if (styleName == style.Name) { tr.Commit(); return(styleId); } } tr.Abort(); } return(ObjectId.Null); }
private static void OnStateChangedEnded(object sender, EventArgs e) { if (modifiedEnts.Count == 0) { return; } Transaction acTrans = null; try { using (acTrans = Global.DB.TransactionManager?.StartTransaction()) { dicLock = true; foreach (ObjectId objId in modifiedEnts.Values) { if (!objId.IsErased && !objId.IsNull && objId.IsValid) { var ent = acTrans.GetObject(objId, OpenMode.ForRead) as Entity; if (ent != null) { if (ent is Curve) { ObjectsChangedEvent?.Invoke(ent); } } } } modifiedEnts.Clear(); dicLock = false; acTrans.Dispose(); } } catch (Exception err) { acTrans?.Abort(); Global.Editor.WriteMessage(err.ToString()); }; }
public override void Execute() { var db = HostApplicationServices.WorkingDatabase; var doc = Application.DocumentManager.MdiActiveDocument; using (var acLock = doc.LockDocument()) { using (var ent = CreateEntity()) { if (LayerName != null) { SetLayer(db, ent, LayerName, true); } using (Transaction tr = doc.TransactionManager.StartTransaction()) { try { var space = (BlockTableRecord)tr.GetObject(doc.Database.CurrentSpaceId, OpenMode.ForWrite); space.AppendEntity(ent); tr.AddNewlyCreatedDBObject(ent, true); if (OnCommitting(tr, space, ent)) { tr.Commit(); OnCommited(ent); WriteDictionary(ent.ObjectId, Data); } } catch (Exception ex) { if (!ent.IsDisposed) { ent.Dispose(); } tr.Abort(); throw ex; } } OnExecuted(ent); } } }
/* Perform bulk delete in primary db */ public void BulkDelete(int value) { Transaction txn = env.BeginTransaction(); try { if (dups == 0) { /* Delete a set of key/data pairs */ List <KeyValuePair <DatabaseEntry, DatabaseEntry> > pList = new List <KeyValuePair <DatabaseEntry, DatabaseEntry> >(); for (int i = 0; i < value; i++) { pList.Add( new KeyValuePair <DatabaseEntry, DatabaseEntry>( new DatabaseEntry(BitConverter.GetBytes(i)), new DatabaseEntry(getBytes(new DataVal(i))))); } MultipleKeyDatabaseEntry pairs = new MultipleKeyDatabaseEntry(pList, false); pdb.Delete(pairs, txn); } else { /* Delete a set of keys */ List <DatabaseEntry> kList = new List <DatabaseEntry>(); for (int i = 0; i < value; i++) { kList.Add(new DatabaseEntry( BitConverter.GetBytes(i))); } MultipleDatabaseEntry keySet = new MultipleDatabaseEntry(kList, false); pdb.Delete(keySet, txn); } txn.Commit(); } catch (DatabaseException e) { txn.Abort(); throw e; } }
public void DrawPline() { // Create the drawing document and database object Document doc = Application.DocumentManager.MdiActiveDocument; Database db = doc.Database; // Create the transaction object inside the using block using (Transaction trans = db.TransactionManager.StartTransaction()) { try { // Message doc.Editor.WriteMessage("\nDrawing a polyline!"); // Get the BlockTable object BlockTable bt; bt = trans.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable; BlockTableRecord btr; btr = trans.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord; // Specify the Poluline's coordinates Polyline pl = new Polyline(); pl.AddVertexAt(0, new Point2d(0, 0), 0, 0, 0); pl.AddVertexAt(1, new Point2d(10, 10), 0, 0, 0); pl.AddVertexAt(1, new Point2d(20, 20), 0, 0, 0); pl.AddVertexAt(1, new Point2d(30, 30), 0, 0, 0); pl.AddVertexAt(1, new Point2d(40, 40), 0, 0, 0); pl.AddVertexAt(1, new Point2d(50, 50), 0, 0, 0); pl.SetDatabaseDefaults(); btr.AppendEntity(pl); trans.AddNewlyCreatedDBObject(pl, true); trans.Commit(); } catch (System.Exception ex) { doc.Editor.WriteMessage("Error encountered : " + ex.Message); trans.Abort(); } } }
/// <summary> /// 新增或更新XData键值对 /// </summary> /// <param name="id"></param> /// <param name="regAppName"></param> /// <param name="key"></param> /// <param name="value"></param> public static void SetXData(this DBObject obj, string regAppName, string key, string value) { Database db = obj.Database; using (Transaction trans = db.TransactionManager.StartTransaction()) { try { obj.UpgradeOpen(); TypedValueList XData = obj.GetXDataForApplication(regAppName); if (XData == null) { XData = new TypedValueList(); XData.Add(DxfCode.ExtendedDataRegAppName, regAppName); } TypedValue tvKey = XData.FirstOrDefault(item => item.Value.Equals(key)); //查找key int indexKey = XData.IndexOf(tvKey); //Key索引 int indexValue = indexKey + 1; //Value索引 if (indexKey >= 0 && indexValue < XData.Count) { //键值对已存在,更新 TypedValue tvValue = XData[indexValue]; XData[indexValue] = new TypedValue(tvValue.TypeCode, value); } else { //键值对不存在,新增 XData.Add(new TypedValue((int)DxfCode.ExtendedDataAsciiString, key)); XData.Add(new TypedValue((int)DxfCode.ExtendedDataAsciiString, value)); } obj.XData = XData; // 覆盖原来的扩展数据,达到修改的目的 obj.DowngradeOpen(); trans.Commit(); } catch (Exception ex) { trans.Abort(); Logger.log("SetXData", ex.Message); } } }
public void DrawArc() { // Create the drawing document and database object Document doc = Application.DocumentManager.MdiActiveDocument; Database db = doc.Database; // Create the transaction object inside the using block using (Transaction trans = db.TransactionManager.StartTransaction()) { try { // Message doc.Editor.WriteMessage("\nDrawing an arc!"); // Get the BlockTable object BlockTable bt; bt = trans.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable; BlockTableRecord btr; btr = trans.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord; // Specify an arc parameters Point3d centerPt = new Point3d(10, 10, 0); double rad = 20; double startAngle = 1.0; double endAngle = 3.0; Arc arc = new Arc(centerPt, rad, startAngle, endAngle); // Set the default properties arc.SetDatabaseDefaults(); btr.AppendEntity(arc); trans.AddNewlyCreatedDBObject(arc, true); trans.Commit(); } catch (System.Exception ex) { doc.Editor.WriteMessage("Error encounterec : " + ex.Message); trans.Abort(); } } }
public static AcadGeo.Point3d PickPoint(string mess) { AcadApp.DocumentManager.MdiActiveDocument.Window.Focus(); using (AcadApp.DocumentManager.MdiActiveDocument.LockDocument()) { using (Transaction tr = AcadFuncs.GetActiveDoc().TransactionManager.StartTransaction()) { PromptPointOptions prmpt_pnt = new PromptPointOptions(mess); PromptPointResult prmpt_ret = AcadFuncs.GetEditor().GetPoint(prmpt_pnt); if (PromptStatus.Cancel == prmpt_ret.Status) { tr.Abort(); tr.Dispose(); throw new AcadRuntime.Exception(AcadRuntime.ErrorStatus.OK, "failed"); } tr.Commit(); return(prmpt_ret.Value); } } }
private ObjectId PickSingleEnt() { using (AcadApp.DocumentManager.MdiActiveDocument.LockDocument()) { using (Transaction tr = AcadFuncs.GetActiveDoc().TransactionManager.StartTransaction()) { PromptEntityResult prmpt_ret = AcadFuncs.GetEditor().GetEntity("Chọn một đối tượng line"); if (PromptStatus.Cancel == prmpt_ret.Status) { tr.Abort(); tr.Dispose(); return(ObjectId.Null); } ObjectId obj_id = prmpt_ret.ObjectId; tr.Commit(); return(obj_id); } } }
public Object Run(TransactionHandler task, Object[] input) { Database dwg = this.Doc.Database; Object result; using (Transaction tr = dwg.TransactionManager.StartTransaction()) { try { result = task(this.Doc, tr, input); tr.Commit(); } catch (System.Exception exc) { this.Ed.WriteMessage(exc.Message); tr.Abort(); throw exc; } } return(result); }