public void AddExtensionDictionary(ObjectId obj) { DBObject dbObj = tr.openObject(obj, OpenMode.ForRead) as DBObject; ObjectId dicObj = dbObj.ExtensionDictionary; if (dicObj == ObjectId.Null) { dbObj.UpgradeOpen(); dbObj.CreateExtensionDictionary(); dicObj = dbObj.ExtensionDictionary; } tr.closeObject(); tr.start_Transaction(); DBDictionary dbDic = tr.AC_Tr.GetObject(dicObj, OpenMode.ForRead) as DBDictionary; if (!dbDic.Contains("DIMINC_LINE")) { dbDic.UpgradeOpen(); Xrecord xr = new Xrecord(); ResultBuffer rb = new ResultBuffer(new TypedValue((int)DxfCode.ExtendedDataAsciiString, GUID)); xr.Data = rb; dbDic.SetAt("DIMINC_LINE", xr); tr.AC_Tr.AddNewlyCreatedDBObject(xr, true); } tr.AC_Tr.Commit(); tr.AC_Tr.Dispose(); }
private DBDictionary GetDict(Transaction tr) { DBDictionary dict = null; DBDictionary db_dict = tr.GetObject(AcadFuncs.GetActiveDb().NamedObjectsDictionaryId, OpenMode.ForRead) as DBDictionary; if (null == db_dict) { tr.Dispose(); return(null); } if (!db_dict.Contains(DICT_NAME)) { dict = new DBDictionary(); dict.TreatElementsAsHard = true; db_dict.UpgradeOpen(); db_dict.SetAt(DICT_NAME, dict); tr.AddNewlyCreatedDBObject(dict, true); db_dict.DowngradeOpen(); } else { dict = tr.GetObject((ObjectId)db_dict[DICT_NAME], OpenMode.ForRead) as DBDictionary; } return(dict); }
public static bool addXrecord(ObjectId dbObjectId, string key, ResultBuffer data) { Document acDoc = Autodesk.AutoCAD.ApplicationServices.Core.Application.DocumentManager.MdiActiveDocument; Database acCurrDb = acDoc.Database; Editor acEditor = acDoc.Editor; using (Transaction acTrans = acCurrDb.TransactionManager.StartTransaction()) { try { DBObject acDbObj = acTrans.GetObject(dbObjectId, OpenMode.ForRead); DBDictionary acExtDict = (DBDictionary)acTrans.GetObject(acDbObj.ExtensionDictionary, OpenMode.ForWrite); Xrecord xrecFFL = new Xrecord(); // ResultBuffer xrecData = new ResultBuffer(); xrecFFL.Data = data; acExtDict.SetAt(key, xrecFFL); acTrans.AddNewlyCreatedDBObject(xrecFFL, true); } catch (Autodesk.AutoCAD.Runtime.Exception acException) { Autodesk.AutoCAD.ApplicationServices.Application.ShowAlertDialog ("The following exception was caught: \n" + acException.Message + "\nError adding Xrecord!\n"); acTrans.Dispose(); acTrans.Commit(); return(false); } acTrans.Commit(); } return(true); }
/// <summary> /// Agrega un xrecord en un diccionario /// </summary> /// <param name="dictionaryName">El nombre del diccionario</param> /// <param name="dicId">El id del diccionario.</param> /// <returns>El object id del xrecord recien creado</returns> public static ObjectId AddXRecord(ObjectId dicId, String XrecordName) { Database db = AcadApp.DocumentManager.MdiActiveDocument.Database; ObjectId id = new ObjectId(); using (Transaction tr = db.TransactionManager.StartTransaction()) { try { DBDictionary oldD = (DBDictionary)dicId.GetObject(OpenMode.ForWrite); Xrecord x = new Xrecord(); oldD.SetAt(XrecordName, x); tr.AddNewlyCreatedDBObject(x, true); id = x.ObjectId; tr.Commit(); } catch (AcadExc exc) { ed.WriteMessage(exc.Message); tr.Abort(); } catch (System.Exception exc) { ed.WriteMessage(exc.Message); tr.Abort(); } } return(id); }
/// <summary> /// 创建一个新的多线样式 /// </summary> /// <param name="db">数据库对象</param> /// <param name="styleName">多线样式名</param> /// <param name="elements">加入到多线样式的元素集合</param> /// <returns>返回加入的多线样式的Id</returns> public static ObjectId CreateMLineStyle(this Database db, string styleName, List <MlineStyleElement> elements) { //打开当前数据库的多线样式字典对象 DBDictionary dict = (DBDictionary)db.MLStyleDictionaryId.GetObject(OpenMode.ForRead); if (dict.Contains(styleName)) // 如果已经存在指定名称的多线样式 { return((ObjectId)dict[styleName]); // 返回该多线样式的Id } MlineStyle mStyle = new MlineStyle(); // 创建一个多线样式对象 mStyle.Name = styleName; //设置多线样式的名称 //为多线样式添加新的元素 foreach (var element in elements) { mStyle.Elements.Add(element, true); } dict.UpgradeOpen(); //切换多线字典为写 //在多线样式字典中加入新创建的多线样式对象,并指定搜索关键字为styleName dict.SetAt(styleName, mStyle); //通知事务处理完成多线样式对象的加入 db.TransactionManager.AddNewlyCreatedDBObject(mStyle, true); dict.DowngradeOpen(); //为了安全,将多线样式字典切换成读 return(mStyle.ObjectId); // 返回该多线样式的Id }
// Função para gravar os dados no Extension Dictionary do objeto dado. public void RecOnXDict(DBObject dbObj, string location, DxfCode dxfC, dynamic data, Transaction tr) { // Pega o Id do XDic do objeto. ObjectId extId = dbObj.ExtensionDictionary; // Se não existe um XDic, cria-o if (extId == ObjectId.Null) { dbObj.CreateExtensionDictionary(); extId = dbObj.ExtensionDictionary; } // Pega o XDic a partir do seu Id. DBDictionary dbExt = (DBDictionary)tr.GetObject(extId, OpenMode.ForWrite); // Cria um XRecord, que guardará a informação Xrecord xRec = new Xrecord(); ResultBuffer rb = new ResultBuffer(); rb.Add(new TypedValue((int)dxfC, data)); xRec.Data = rb; // Adiciona a informação no XDic do objeto. dbExt.SetAt(location, xRec); tr.AddNewlyCreatedDBObject(xRec, true); }
public static void WriteState(Document doc, string key, string state) { // https://adndevblog.typepad.com/autocad/2012/05/how-can-i-store-my-custom-information-in-a-dwg-file.html var db = doc.Database; Xrecord xRecord; using (doc.LockDocument()) { using (Transaction trans = db.TransactionManager.StartTransaction()) { // Find the NOD in the database DBDictionary nod = (DBDictionary)trans.GetObject(db.NamedObjectsDictionaryId, OpenMode.ForWrite); if (nod.Contains(key)) { ObjectId objectId = nod.GetAt(key); xRecord = (Xrecord)trans.GetObject(objectId, OpenMode.ForWrite); xRecord.Data = state.ToResultBuffer(); } else { xRecord = new Xrecord(); xRecord.Data = state.ToResultBuffer(); nod.SetAt(key, xRecord); trans.AddNewlyCreatedDBObject(xRecord, true); } trans.Commit(); } } }
/// <summary> /// Create an anonymous group from objects /// </summary> /// <param name="objects"></param> public static void CreateAnonymousGroup(IList <Dyn.Object> objects) { if (objects is null) { throw new System.ArgumentNullException("Objects"); } var first = objects.FirstOrDefault(); if (first is null) { return; } Database db = first.InternalObjectId.Database; Document adoc = Application.DocumentManager.GetDocument(db); using (DocumentContext context = new DocumentContext(adoc)) { Transaction tr = context.Transaction; DBDictionary groupDic = tr.GetObject (db.GroupDictionaryId, OpenMode.ForWrite) as DBDictionary; Group anonyGroup = new Group(); groupDic.SetAt("*", anonyGroup); foreach (var obj in objects) { anonyGroup.Append(obj.InternalObjectId); } tr.AddNewlyCreatedDBObject(anonyGroup, true); } }
addXRec(ObjectId idDict, string nameApp, ResultBuffer rb) { try { using (BaseObjs._acadDoc.LockDocument()) { using (Transaction tr = BaseObjs.startTransactionDb()) { DBDictionary dict = (DBDictionary)idDict.GetObject(OpenMode.ForWrite); //if (dict.Contains(nameApp)) // dict.Remove(nameApp); Xrecord xrec = new Xrecord(); xrec.XlateReferences = true; xrec.Data = rb; dict.SetAt(nameApp, xrec); tr.AddNewlyCreatedDBObject(xrec, true); tr.Commit(); } } } catch (System.Exception ex) { BaseObjs.writeDebug(ex.Message + " Dict.cs: line: 100"); } }
/// <summary> /// 为图形添加一个新的表格样式 /// </summary> /// <param name="db">数据库对象</param> /// <param name="styleName">表格样式的名称</param> /// <returns>返回表格样式的Id</returns> public static ObjectId AddTableStyle(this Database db, string styleName) { ObjectId styleId; using (Transaction trans = db.TransactionManager.StartTransaction()) { //打开表格样式字典 DBDictionary dict = (DBDictionary)trans.GetObject(db.TableStyleDictionaryId, OpenMode.ForRead); //判断是否存在指定的表格样式 if (dict.Contains(styleName)) { styleId = dict.GetAt(styleName);//如果存在则返回表格样式的Id } else { //新建一个表格样式 TableStyle style = new TableStyle(); dict.UpgradeOpen();//切换表格样式字典为写的状态 //将新的表格样式添加到样式字典并获取其 Id styleId = dict.SetAt(styleName, style); //将新建的表格样式添加到事务处理中 trans.AddNewlyCreatedDBObject(style, true); trans.Commit(); } } return(styleId);//返回表格样式的Id }
addXRec(ObjectId idDict, string nameApp, TypedValue[] TVs) { ResultBuffer RB = null; try { using (Transaction tr = BaseObjs.startTransactionDb()) { try { RB = new ResultBuffer(TVs); } catch (System.Exception ex) { BaseObjs.writeDebug(ex.Message + " Dict.cs: line: 124"); } DBDictionary dict = (DBDictionary)idDict.GetObject(OpenMode.ForRead); Xrecord xrec = new Xrecord(); xrec.XlateReferences = true; xrec.Data = RB; dict.UpgradeOpen(); dict.SetAt(nameApp, xrec); dict.DowngradeOpen(); tr.AddNewlyCreatedDBObject(xrec, true); tr.Commit(); } } catch (System.Exception ex) { BaseObjs.writeDebug(ex.Message + " Dict.cs: line: 139"); } }
public void CreateEmployee() { Database db = HostApplicationServices.WorkingDatabase; Transaction trans = db.TransactionManager.StartTransaction(); try { BlockTable bt = (BlockTable)(trans.GetObject(db.BlockTableId, OpenMode.ForWrite)); BlockTableRecord btr = (BlockTableRecord)trans.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite); //Create the block reference...use the return from CreateEmployeeDefinition directly! BlockReference br = new BlockReference(new Point3d(10, 10, 0), CreateEmployeeDefinition()); btr.AppendEntity(br); //Add the reference to ModelSpace trans.AddNewlyCreatedDBObject(br, true); //Let the transaction know about it //Create the custom per-employee data Xrecord xRec = new Xrecord(); //We want to add 'Name', 'Salary' and 'Division' information. Here is how: xRec.Data = new ResultBuffer( new TypedValue((int)DxfCode.Text, "Earnest Shackleton"), new TypedValue((int)DxfCode.Real, 72000), new TypedValue((int)DxfCode.Text, "Sales")); //Next, we need to add this data to the 'Extension Dictionary' of the employee. br.CreateExtensionDictionary(); DBDictionary brExtDict = (DBDictionary)trans.GetObject(br.ExtensionDictionary, OpenMode.ForWrite, false); brExtDict.SetAt("EmployeeData", xRec); //Set our XRecord in the dictionary at 'EmployeeData'. trans.AddNewlyCreatedDBObject(xRec, true); trans.Commit(); } finally { trans.Dispose(); } }
private void createGroup(string groupName) { Editor ed = Application.DocumentManager.MdiActiveDocument.Editor; Database db = HostApplicationServices.WorkingDatabase; using (Transaction trans = db.TransactionManager.StartTransaction()) { //新建一个组对象 Group gp = new Group(groupName, true); //打开当前数据库的组字典对象以加入新建的组对象 DBDictionary dict = (DBDictionary)trans.GetObject(db.GroupDictionaryId, OpenMode.ForWrite); //在组字典中将组对象作为一个新条目加入,并指定它的搜索关键字为groupName dict.SetAt(groupName, gp); //下面的操作用来选择组中要包含的对象 PromptSelectionOptions opt = new PromptSelectionOptions(); opt.MessageForAdding = "请选择组中要包含的对象"; PromptSelectionResult res = ed.GetSelection(opt); if (res.Status != PromptStatus.OK) { return; } //获取所选择对象的ObjectId集合 SelectionSet ss = res.Value; ObjectIdCollection ids = new ObjectIdCollection(ss.GetObjectIds()); //在组对象中加入所选择的对象 gp.Append(ids); //通知事务处理完成组对象的加入 trans.AddNewlyCreatedDBObject(gp, true); trans.Commit(); } }
public static string AssignWKT(Document doc, string wktString) { if (string.IsNullOrEmpty(wktString)) { return(wktString); } if (wktString == "<Undefined>") { return(wktString); } if (MSCPrj.IsWKID(wktString)) { return(""); } string result; try { using (doc.LockDocument((DocumentLockMode)20, null, null, false)) { using (Transaction transaction = doc.Database.TransactionManager.StartTransaction()) { Database database = doc.Database; Xrecord xrecord = new Xrecord(); TypedValue typedValue = new TypedValue(1, wktString); xrecord.Data = (new ResultBuffer(new TypedValue[] { typedValue })); DBDictionary dBDictionary = (DBDictionary)transaction.GetObject(database.NamedObjectsDictionaryId, (OpenMode)1, false); ObjectId acadId = dBDictionary.SetAt("ESRI_PRJ", xrecord); xrecord.DisableUndoRecording(true); transaction.AddNewlyCreatedDBObject(xrecord, true); transaction.Commit(); AfaDocData.ActiveDocData.DocPRJ.WKT = wktString; AfaDocData.ActiveDocData.DocPRJ.AcadId = acadId; foreach (MSCMapService current in AfaDocData.ActiveDocData.DocDataset.MapServices.Values) { current.RefreshConnectedService(); } foreach (MSCImageService current2 in AfaDocData.ActiveDocData.DocDataset.ImageServices.Values) { current2.RefreshConnectedService(); } result = wktString; } } } catch (SystemException ex) { string arg_186_0 = ex.Message; result = ""; } catch (Autodesk.AutoCAD.Runtime.Exception ex2) { string arg_199_0 = ex2.Message; result = ""; } return(result); }
/// <summary> /// Agrega un diccionario al diccionario de AutoCAD /// </summary> /// <param name="dictionaryName">El nombre del diccionario</param> /// <returns>El object id del diccionario recien creado</returns> public static ObjectId AddDictionary(String dictionaryName) { Database db = AcadApp.DocumentManager.MdiActiveDocument.Database; ObjectId id = new ObjectId(); using (Transaction tr = db.TransactionManager.StartTransaction()) { try { DBDictionary NOD = (DBDictionary)db.NamedObjectsDictionaryId.GetObject(OpenMode.ForWrite); DBDictionary d = new DBDictionary(); NOD.SetAt(dictionaryName, d); tr.AddNewlyCreatedDBObject(d, true); id = d.ObjectId; tr.Commit(); } catch (AcadExc exc) { ed.WriteMessage(exc.Message); tr.Abort(); } catch (System.Exception exc) { ed.WriteMessage(exc.Message); tr.Abort(); } } return(id); }
/// <summary> /// 添加扩展记录 /// </summary> /// <param name="id">对象的Id</param> /// <param name="searchKey">扩展记录名称</param> /// <param name="values">扩展记录的内容</param> /// <returns>返回添加的扩展记录的Id</returns> public static ObjectId AddXrecord(this ObjectId id, string searchKey, TypedValueList values) { DBObject obj = id.GetObject(OpenMode.ForRead);//打开对象 // 判断对象是否已经拥有扩展字典,若无扩展字典,则 if (obj.ExtensionDictionary.IsNull) { obj.UpgradeOpen(); // 切换对象为写的状态 obj.CreateExtensionDictionary(); // 为对象创建扩展字典 obj.DowngradeOpen(); // 为了安全,将对象切换成读的状态 } // 打开对象的扩展字典 DBDictionary dict = (DBDictionary)obj.ExtensionDictionary.GetObject(OpenMode.ForRead); // 如果扩展字典中已包含指定的扩展记录对象,则返回 if (dict.Contains(searchKey)) { return(ObjectId.Null); } Xrecord xrec = new Xrecord(); // 为对象新建一个扩展记录 xrec.Data = values; // 指定扩展记录的内容 dict.UpgradeOpen(); // 将扩展字典切换成写的状态 //在扩展字典中加入新建的扩展记录,并指定它的搜索关键字 ObjectId idXrec = dict.SetAt(searchKey, xrec); id.Database.TransactionManager.AddNewlyCreatedDBObject(xrec, true); dict.DowngradeOpen(); // 为了安全,将扩展字典切换成读的状态 return(idXrec); // 返回添加的扩展记录的的Id }
public static void CreateGroup(string groupName, ObjectIdCollection ids) { //Document doc =Application.DocumentManager.MdiActiveDocument; Database db = HostApplicationServices.WorkingDatabase; //Editor ed = doc.Editor; Transaction tr = db.TransactionManager.StartTransaction(); using (tr) { // Get the group dictionary from the drawing DBDictionary gd = (DBDictionary)tr.GetObject(db.GroupDictionaryId, OpenMode.ForRead); // Check the group name, to see whether it's // A variable for the group's name string grpName = ""; try { // Validate the provided symbol table name SymbolUtilityServices.ValidateSymbolName(groupName, false); // Only set the block name if it isn't in use if (gd.Contains(groupName)) { //ed.WriteMessage("\nA group with this name already exists."); //throw new System.Exception("A group with this name already exists."); AddIds2Group(groupName, ids, tr); return; } else { grpName = groupName; } } catch { // An exception has been thrown, indicating the // name is invalid //ed.WriteMessage("\nInvalid group name."); } // Create our new group... Group grp = new Group("Test group", true); // Add the new group to the dictionary gd.UpgradeOpen(); ObjectId grpId = gd.SetAt(grpName, grp); tr.AddNewlyCreatedDBObject(grp, true); //grp.InsertAt(0, ids); AddIds2Group(grp, ids); // Commit the transaction tr.Commit(); // Report what we've done //ed.WriteMessage("\nCreated group named \"{0}\" containing entities.",grpName); } }
// Group objects // <param name="idCol"></param> // <param name="groupName"></param> // <returns>id of group object</returns> public static ObjectId createGroup(ObjectIdCollection idCol, String groupName) { ObjectId groupId; Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument; Database db = doc.Database; Editor ed = doc.Editor; Transaction tr = db.TransactionManager.StartTransaction(); using (tr) { DBDictionary gd = (DBDictionary)tr.GetObject(db.GroupDictionaryId, OpenMode.ForRead); Group group = new Group("my group", true); gd.UpgradeOpen(); ObjectId grpId = gd.SetAt(groupName, group); tr.AddNewlyCreatedDBObject(group, true); BlockTableRecord btr = (BlockTableRecord)tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite); btr.AssumeOwnershipOf(idCol); group.InsertAt(0, idCol); tr.Commit(); tr.Dispose(); groupId = grpId; } return(groupId); }
/// <summary> /// Retrieve or create an Entry with the given name into the Extension Dictionary of the passed-in object. /// </summary> /// <param name="id">The object hosting the Extension Dictionary</param> /// <param name="entryName">The name of the dictionary entry to get or set</param> /// <returns>The ObjectId of the diction entry, old or new</returns> public static ObjectId GetSetExtensionDictionaryEntry(ObjectId id, string entryName) { ObjectId ret = ObjectId.Null; using (Transaction tr = HostApplicationServices.WorkingDatabase.TransactionManager.StartTransaction()) { DBObject obj = (DBObject)tr.GetObject(id, OpenMode.ForRead); if (obj.ExtensionDictionary == ObjectId.Null) { obj.UpgradeOpen(); obj.CreateExtensionDictionary(); obj.DowngradeOpen(); } DBDictionary dict = (DBDictionary)tr.GetObject(obj.ExtensionDictionary, OpenMode.ForRead); if (!dict.Contains(entryName)) { Xrecord xRecord = new Xrecord(); dict.UpgradeOpen(); dict.SetAt(entryName, xRecord); tr.AddNewlyCreatedDBObject(xRecord, true); ret = xRecord.ObjectId; } else { ret = dict.GetAt(entryName); } tr.Commit(); } return(ret); }
/// <summary> /// <para>Add a group to the current autocad document</para> /// <para>Return: Group</para> /// </summary> /// <param name="name">Group name</param> /// <param name="DbObjs">Object Collection to associate with group</param> /// <param name="autorename"><para>if a group has already the specified name</para> /// <para>This let the function assign an unique generated name</para></param> /// <returns></returns> public ObjectId addGroup(string name, DBObjectCollection DbObjs, bool autorename) { Group grp = new Group(name, true); ObjectIdCollection ids = new ObjectIdCollection(); start_Transaction(); DBDictionary gd = openGroupDictionary(OpenMode.ForWrite); if (gd.Contains(name)) { if (autorename) { name = name + "_" + Guid.NewGuid().ToString(); } else { return(ObjectId.Null); } } gd.SetAt(name, grp); AC_Tr.AddNewlyCreatedDBObject(grp, true); openBlockTables(OpenMode.ForRead, OpenMode.ForWrite); foreach (Entity ent in DbObjs) { ObjectId id = Commit(ent); ids.Add(id); } grp.InsertAt(0, ids); gd.Dispose(); Dispose(); return(grp.ObjectId); }
private static ObjectId getDictionaryId(string dictionaryName) { using (DocumentLock doclock = Application.DocumentManager.MdiActiveDocument.LockDocument()) { using (Transaction trans = HostApplicationServices.WorkingDatabase.TransactionManager.StartTransaction()) { DBDictionary nod = trans.GetObject(HostApplicationServices.WorkingDatabase.NamedObjectsDictionaryId, OpenMode.ForRead) as DBDictionary; DBDictionary dictRoot; if (!nod.Contains(DictionaryRoot)) { dictRoot = new DBDictionary(); nod.UpgradeOpen(); nod.SetAt(DictionaryRoot, dictRoot); trans.AddNewlyCreatedDBObject(dictRoot, true); } else { dictRoot = trans.GetObject(nod.GetAt(DictionaryRoot), OpenMode.ForWrite) as DBDictionary; } if (!dictRoot.Contains(dictionaryName)) { DBDictionary dictEntry = new DBDictionary(); dictRoot.SetAt(dictionaryName, dictEntry); trans.AddNewlyCreatedDBObject(dictEntry, true); } trans.Commit(); return(dictRoot.GetAt(dictionaryName)); } } }
private static ObjectId getDictionaryId(ObjectId id, string dictionaryName) { using (DocumentLock doclock = Application.DocumentManager.MdiActiveDocument.LockDocument()) { using (Transaction trans = HostApplicationServices.WorkingDatabase.TransactionManager.StartTransaction()) { DBObject dbo = trans.GetObject(id, OpenMode.ForRead); if (dbo.ExtensionDictionary == ObjectId.Null) { dbo.UpgradeOpen(); dbo.CreateExtensionDictionary(); } DBDictionary dictRoot = trans.GetObject(dbo.ExtensionDictionary, OpenMode.ForRead) as DBDictionary; if (!dictRoot.Contains(dictionaryName)) { dictRoot.UpgradeOpen(); DBDictionary dictEntry = new DBDictionary(); dictRoot.SetAt(dictionaryName, dictEntry); trans.AddNewlyCreatedDBObject(dictEntry, true); } trans.Commit(); return(dictRoot.GetAt(dictionaryName)); } } }
public void MarkCurrentDrawingAsCivil3D() { Document doc = Application.DocumentManager.MdiActiveDocument; using (Transaction trans = doc.TransactionManager.StartTransaction()) { Transaction tr = doc.TransactionManager.TopTransaction; // Find the NOD in the database DBDictionary nod = (DBDictionary)tr.GetObject(doc.Database.NamedObjectsDictionaryId, OpenMode.ForWrite); // We use Xrecord class to store data in Dictionaries Xrecord plotXRecord = new Xrecord(); ResultBuffer rb = new ResultBuffer(); TypedValue tv = new TypedValue((int)DxfCode.Bool, true); rb.Add(tv); plotXRecord.Data = rb; // Create the entry in the Named Object Dictionary string id = this.GetType().FullName + "Civil3DRequired"; nod.SetAt(id, plotXRecord); tr.AddNewlyCreatedDBObject(plotXRecord, true); trans.Commit(); } }
/// <summary> /// Adds a new DBDictionary to the nod Collection of the drawing. /// </summary> /// <param name="transaction">Running transaction.</param> /// <param name="name">Name of the Dictionary to add to the collection.</param> public static DBDictionary AddNamedObjectsDictionary(Transaction transaction, string name) { Database db = Active.Database; DBDictionary newNod = null; DBDictionary nod_collection = GetNodCollection(transaction); if (!nod_collection.Contains(name)) { using (new WriteEnabler(nod_collection)) { if (nod_collection.IsWriteEnabled) { newNod = new DBDictionary(); nod_collection.SetAt(name, newNod); transaction.AddNewlyCreatedDBObject(newNod, true); } else { string err_message = string.Format("DBDictionary named: '{0}' could not be created.", name); throw new XRecordHandlerException(err_message); } } } return(newNod); }
/// <summary> /// 为图形添加一个新的表格样式 /// </summary> /// <param name="db">数据库对象</param> /// <param name="styleName">表格样式的名称</param> /// <returns>返回表格样式的Id</returns> public static ObjectId AddTableStyle(this Database db, string styleName, double txtHeight) { ObjectId styleId; using (Transaction trans = db.TransactionManager.StartTransaction()) { //打开表格样式字典 DBDictionary dict = (DBDictionary)trans.GetObject(db.TableStyleDictionaryId, OpenMode.ForRead); //判断是否存在指定的表格样式 if (dict.Contains(styleName)) { styleId = dict.GetAt(styleName);//如果存在则返回表格样式的Id } else { //新建一个表格样式 TableStyle style = new TableStyle(); style.SetTextHeight(txtHeight, TableTools.AllRows); style.SetColor(Color.FromColorIndex(ColorMethod.ByAci, 6), TableTools.AllRows); style.SetGridColor(Color.FromColorIndex(ColorMethod.ByAci, 1), (int)GridLineType.AllGridLines, TableTools.AllRows); dict.UpgradeOpen(); //切换表格样式字典为写的状态 //将新的表格样式添加到样式字典并获取其 Id styleId = dict.SetAt(styleName, style); //将新建的表格样式添加到事务处理中 trans.AddNewlyCreatedDBObject(style, true); trans.Commit(); } } return(styleId);//返回表格样式的Id }
} //einde method //---------------------------------------------------------------------------------- private static ObjectId SaveXRecord(DBObject o, ResultBuffer buffer, string key, Transaction trans) { if (o.ExtensionDictionary == ObjectId.Null) { o.CreateExtensionDictionary(); } using (DBDictionary dict = trans.GetObject(o.ExtensionDictionary, OpenMode.ForWrite, false) as DBDictionary) { if (dict.Contains(key)) { Xrecord xRecord = (Xrecord)trans.GetObject(dict.GetAt(key), OpenMode.ForWrite); xRecord.Data = buffer; return(xRecord.ObjectId); } else { Xrecord xRecord = new Xrecord(); xRecord.Data = buffer; dict.SetAt(key, xRecord); trans.AddNewlyCreatedDBObject(xRecord, true); return(xRecord.ObjectId); } } }
// This function creates a new BlockReference to the "EmployeeBlock" object, // and adds it to ModelSpace. private ObjectId CreateEmployee(string name, string division, double salary, Point3d pos) { // get the current working database Database db = HostApplicationServices.WorkingDatabase; using (Transaction trans = db.TransactionManager.StartTransaction()) { BlockTable bt = (BlockTable)(trans.GetObject(db.BlockTableId, OpenMode.ForWrite)); BlockTableRecord btr = (BlockTableRecord)trans.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite); // Create the block reference...use the return from CreateEmployeeDefinition directly! BlockReference br = new BlockReference(pos, CreateEmployeeDefinition()); AttributeReference attRef = new AttributeReference(); // Iterate the employee block and find the attribute definition BlockTableRecord empBtr = (BlockTableRecord)trans.GetObject(bt["EmployeeBlock"], OpenMode.ForRead); foreach (ObjectId id in empBtr) { Entity ent = (Entity)trans.GetObject(id, OpenMode.ForRead, false); // Use it to open the current object! if (ent is AttributeDefinition) // We use .NET's RunTimeTypeInformation (RTTI) to establish type. { // Set the properties from the attribute definition on our attribute reference AttributeDefinition attDef = ((AttributeDefinition)(ent)); attRef.SetPropertiesFrom(attDef); attRef.Position = new Point3d(attDef.Position.X + br.Position.X, attDef.Position.Y + br.Position.Y, attDef.Position.Z + br.Position.Z); attRef.Height = attDef.Height; attRef.Rotation = attDef.Rotation; attRef.Tag = attDef.Tag; attRef.TextString = name; } } // Add the reference to ModelSpace btr.AppendEntity(br); // Add the attribute reference to the block reference br.AttributeCollection.AppendAttribute(attRef); // let the transaction know trans.AddNewlyCreatedDBObject(attRef, true); trans.AddNewlyCreatedDBObject(br, true); // Create the custom per-employee data Xrecord xRec = new Xrecord(); // We want to add 'Name', 'Salary' and 'Division' information. Here is how: xRec.Data = new ResultBuffer( new TypedValue((int)DxfCode.Text, name), new TypedValue((int)DxfCode.Real, salary), new TypedValue((int)DxfCode.Text, division)); // Next, we need to add this data to the 'Extension Dictionary' of the employee. br.CreateExtensionDictionary(); DBDictionary brExtDict = (DBDictionary)trans.GetObject(br.ExtensionDictionary, OpenMode.ForWrite, false); brExtDict.SetAt("EmployeeData", xRec); //Set our XRecord in the dictionary at 'EmployeeData'. trans.AddNewlyCreatedDBObject(xRec, true); ObjectId retId = br.ObjectId; trans.Commit(); return(retId); } }
public static void SaveTechProsess(CamDocument camDocument) { if (camDocument.Hash == 0 && !camDocument.TechProcessList.Any()) { return; } try { const int kMaxChunkSize = 127; using (var resultBuffer = new ResultBuffer()) { using (MemoryStream stream = new MemoryStream()) { BinaryFormatter formatter = new BinaryFormatter(); formatter.Serialize(stream, camDocument.TechProcessList); stream.Position = 0; for (int i = 0; i < stream.Length; i += kMaxChunkSize) { int length = (int)Math.Min(stream.Length - i, kMaxChunkSize); byte[] datachunk = new byte[length]; stream.Read(datachunk, 0, length); resultBuffer.Add(new TypedValue((int)DxfCode.Text, Convert.ToBase64String(datachunk))); } } var newHash = resultBuffer.ToString().GetHashCode(); if (newHash == camDocument.Hash) { return; } using (DocumentLock acLckDoc = Acad.ActiveDocument.LockDocument()) using (Transaction tr = Acad.Database.TransactionManager.StartTransaction()) using (DBDictionary dict = tr.GetObject(Acad.Database.NamedObjectsDictionaryId, OpenMode.ForWrite) as DBDictionary) { if (dict.Contains(DataKey)) { using (var xrec = tr.GetObject(dict.GetAt(DataKey), OpenMode.ForWrite) as Xrecord) xrec.Data = resultBuffer; } else { using (var xrec = new Xrecord { Data = resultBuffer }) { dict.SetAt(DataKey, xrec); tr.AddNewlyCreatedDBObject(xrec, true); //xrec.ObjectClosed += new ObjectClosedEventHandler(OnDataModified); } } tr.Commit(); } } } catch (Exception e) { Acad.Alert($"Ошибка при сохранении техпроцессов", e); } }
//纹理测试 static private void createMaterial(Database db, Transaction myT) { DBDictionary dic = (DBDictionary)myT.GetObject(db.MaterialDictionaryId, OpenMode.ForWrite, false); ImageFileTexture imfttr = new ImageFileTexture(); imfttr.SourceFileName = @"D:\Geological Project\Geological Source\dbFiles\aaaaa.jpg"; double uScale = 1.0; double vScale = 1.0; double uOffset = 0; double vOffset = 0; double[] p = new double[] { uScale, 0, 0, uScale *uOffset, 0, vScale, 0, vScale *vOffset, 0, 0, 1, 0, 0, 0, 0, 1 }; Matrix3d mx = new Matrix3d(p); Mapper mapper = new Mapper(Projection.Planar, Tiling.Crop, Tiling.Crop, AutoTransform.TransformObject, mx); MaterialMap map = new MaterialMap(Source.File, imfttr, 1, mapper); EntityColor eclr = new EntityColor(150, 150, 150); MaterialColor mc = new MaterialColor(Method.Override, 1, eclr); MaterialDiffuseComponent mdc = new MaterialDiffuseComponent(mc, map); MaterialSpecularComponent mck = new MaterialSpecularComponent(mc, map, 0.5); MaterialOpacityComponent moc = new MaterialOpacityComponent(1, map); MaterialRefractionComponent mrfr = new MaterialRefractionComponent(2, map); Material Mat = new Material(); Mat.Name = "My Material"; Mat.Description = "New Material"; Mat.Diffuse = mdc; Mat.Specular = mck; Mat.Refraction = mrfr; Mat.Reflectivity = 1; Mat.Reflection = map; Mat.Opacity = moc; Mat.Ambient = mc; Mat.Bump = map; Mat.SelfIllumination = 1; // MaterialDiffuseComponent diffuseColor = new MaterialDiffuseComponent(color, map); // material.Diffuse = diffuseColor; // material.Mode = Mode.Realistic; dic.SetAt(Mat.Name, Mat); }
public static void save(MyDB2 mydb) { Document doc = Application.DocumentManager.MdiActiveDocument; Database db = doc.Database; Editor ed = doc.Editor; try { using (Transaction trans = db.TransactionManager.StartTransaction()) { // Find the NOD in the database DBDictionary nod = (DBDictionary)trans.GetObject( db.NamedObjectsDictionaryId, OpenMode.ForWrite); BinaryFormatter bf = new BinaryFormatter(); MemoryStream ms = new MemoryStream(); bf.Serialize(ms, mydb); ResultBuffer rf = new ResultBuffer(); byte[] buf = ms.GetBuffer(); int position = 0; int remaining = buf.Length; while (remaining > 0) { if (remaining >= 255) { byte[] chunk = new byte[255]; Buffer.BlockCopy(buf, position, chunk, 0, 255); rf.Add(new TypedValue((int)DxfCode.BinaryChunk, chunk)); remaining -= 255; position += 255; } else { byte[] chunk = new byte[remaining]; Buffer.BlockCopy(buf, position, chunk, 0, remaining); rf.Add(new TypedValue((int)DxfCode.BinaryChunk, chunk)); remaining = 0; } } Xrecord myXrecord = new Xrecord(); myXrecord.Data = rf; nod.SetAt("TerrainComputeC", myXrecord); trans.AddNewlyCreatedDBObject(myXrecord, true); trans.Commit(); } // using } catch (System.Exception e) { ed.WriteMessage(e.ToString()); } }
public static ObjectId CreateDivision(String division, String manager) { Database db = HostApplicationServices.WorkingDatabase; using (Transaction trans = db.TransactionManager.StartTransaction()) { //Define a corporate level dictionary DBDictionary acmeDict; //First, get the NOD... DBDictionary NOD = (DBDictionary)trans.GetObject(db.NamedObjectsDictionaryId, OpenMode.ForRead, false); try { //if it exists, just get it acmeDict = (DBDictionary)trans.GetObject(NOD.GetAt("ACME_DIVISION"), OpenMode.ForRead); } catch { //Doesn//t exist, so create one NOD.UpgradeOpen(); acmeDict = new DBDictionary(); NOD.SetAt("ACME_DIVISION", acmeDict); trans.AddNewlyCreatedDBObject(acmeDict, true); } //Now get the division we want from acmeDict DBDictionary divDict; try { divDict = (DBDictionary)trans.GetObject(acmeDict.GetAt(division), OpenMode.ForWrite); } catch { acmeDict.UpgradeOpen(); divDict = new DBDictionary(); //Division doesn//t exist, create one acmeDict.SetAt(division, divDict); trans.AddNewlyCreatedDBObject(divDict, true); } //Now get the manager info from the division //We need to add the name of the division supervisor. We//ll do this with another XRecord. Xrecord mgrXRec; try { mgrXRec = (Xrecord)trans.GetObject(divDict.GetAt("Department Manager"), OpenMode.ForWrite); } catch { mgrXRec = new Xrecord(); mgrXRec.Data = new ResultBuffer(new TypedValue((int)DxfCode.Text, manager)); divDict.SetAt("Department Manager", mgrXRec); trans.AddNewlyCreatedDBObject(mgrXRec, true); } trans.Commit(); //return the department manager XRecord return mgrXRec.ObjectId; } }
private ObjectId CreateDivision(string division, string manager) { ObjectId retId = ObjectId.Null; Database db = HostApplicationServices.WorkingDatabase; using (Transaction trans = db.TransactionManager.StartTransaction()) { // First, get the Named Objects Dictionary (NOD)... DBDictionary NOD = (DBDictionary)trans.GetObject(db.NamedObjectsDictionaryId, OpenMode.ForWrite); // Define a corporate level dictionary DBDictionary acmeDict; // here's another way to check to see if an entry exists, using try/catch instead of has[] try { // Just throw if it doesn't exist...do nothing else acmeDict = (DBDictionary)trans.GetObject(NOD.GetAt("ACME_DIVISION"), OpenMode.ForRead); } catch { //Doesn't exist, so create one, and set it in the NOD?/font> acmeDict = new DBDictionary(); NOD.SetAt("ACME_DIVISION", acmeDict); trans.AddNewlyCreatedDBObject(acmeDict, true); } // Now get the division we want from acmeDict DBDictionary divDict; try { divDict = (DBDictionary)trans.GetObject(acmeDict.GetAt(division), OpenMode.ForWrite); } catch { divDict = new DBDictionary(); //Division doesn't exist, create one acmeDict.UpgradeOpen(); acmeDict.SetAt(division, divDict); trans.AddNewlyCreatedDBObject(divDict, true); } // Now get the manager info from the division // We need to add the name of the division supervisor. We'll do this with another XRecord. Xrecord mgrXRec; try { mgrXRec = (Xrecord)trans.GetObject(divDict.GetAt("Department Manager"), OpenMode.ForWrite); } catch { mgrXRec = new Xrecord(); mgrXRec.Data = new ResultBuffer(new TypedValue((int)DxfCode.Text, manager)); divDict.SetAt("Department Manager", mgrXRec); trans.AddNewlyCreatedDBObject(mgrXRec, true); } // Return the department manager XRecord retId = mgrXRec.ObjectId; trans.Commit(); } return retId; }
private void CreateDivision() { Database db = HostApplicationServices.WorkingDatabase; using (Transaction trans = db.TransactionManager.StartTransaction()) { //First, get the NOD... DBDictionary NOD = (DBDictionary)trans.GetObject(db.NamedObjectsDictionaryId, OpenMode.ForWrite); //Define a corporate level dictionary DBDictionary acmeDict; try { //Just throw if it doesn't exist...do nothing else acmeDict = (DBDictionary)trans.GetObject(NOD.GetAt("ACME_DIVISION"), OpenMode.ForRead); } catch { //Doesn't exist, so create one, and set it in the NOD?/font> acmeDict = new DBDictionary(); NOD.SetAt("ACME_DIVISION", acmeDict); trans.AddNewlyCreatedDBObject(acmeDict, true); } //Now get the division we want from acmeDict DBDictionary divDict; try { divDict = (DBDictionary)trans.GetObject(acmeDict.GetAt("Sales"), OpenMode.ForWrite); } catch { divDict = new DBDictionary(); //Division doesn't exist, create one acmeDict.UpgradeOpen(); acmeDict.SetAt("Sales", divDict); trans.AddNewlyCreatedDBObject(divDict, true); } //Now get the manager info from the division //We need to add the name of the division supervisor. We'll do this with another XRecord. Xrecord mgrXRec; try { mgrXRec = (Xrecord)trans.GetObject(divDict.GetAt("Department Manager"), OpenMode.ForWrite); } catch { mgrXRec = new Xrecord(); mgrXRec.Data = new ResultBuffer(new TypedValue((int)DxfCode.Text, "Randolph P. Brokwell")); divDict.SetAt("Department Manager", mgrXRec); trans.AddNewlyCreatedDBObject(mgrXRec, true); } trans.Commit(); } }
public void AddInNOD() { Editor ed = Application.DocumentManager.MdiActiveDocument.Editor; ed.WriteMessage("����������ʵ����������\n"); Database db = HostApplicationServices.WorkingDatabase; using (Transaction trans = db.TransactionManager.StartTransaction()) { //��ȡ��������ʵ䣨NOD) DBDictionary NOD =trans.GetObject(db.NamedObjectsDictionaryId, OpenMode.ForWrite) as DBDictionary ; // ����һ���µĴʵ� DBDictionary copyrightDict; // �ж��Ƿ����COPYRIGHT�ʵ䣬û���� try { // ��ȡCOPYRIGHT�ʵ� copyrightDict = (DBDictionary)trans.GetObject(NOD.GetAt("COPYRIGHT"), OpenMode.ForRead); } catch { //��NOD�´���COPYRIGHT�ʵ� copyrightDict = new DBDictionary(); NOD.SetAt("COPYRIGHT", copyrightDict); trans.AddNewlyCreatedDBObject(copyrightDict, true); } // ��copyrightDict�У���ȡ�� "author" �ʵ� DBDictionary authorDict; try { authorDict = (DBDictionary)trans.GetObject(copyrightDict.GetAt("Author"), OpenMode.ForWrite); } catch { authorDict = new DBDictionary(); //"author" doesn't exist, create one copyrightDict.UpgradeOpen(); copyrightDict.SetAt("Author", authorDict); trans.AddNewlyCreatedDBObject(authorDict, true); } // ͨ��Xrecord��ResultBuffer�����չ���� Xrecord authorRec; try { authorRec = (Xrecord)trans.GetObject(authorDict.GetAt("AuthorInfo"), OpenMode.ForWrite); } catch { authorRec = new Xrecord(); authorRec.Data = new ResultBuffer(new TypedValue((int)DxfCode.Text, "����")); authorDict.SetAt("AuthorInfo", authorRec); trans.AddNewlyCreatedDBObject(authorRec, true); } trans.Commit(); } }