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; } }
public ObjectId InitialSave() { ObjectId TableID = ObjectId.Null; using (Transaction trans = db.TransactionManager.StartTransaction()) { try { DBDictionary dd = (DBDictionary)trans.GetObject(db.NamedObjectsDictionaryId, OpenMode.ForRead); if (dd.Contains(SaveName)) { TableID = dd.GetAt(SaveName); } else { DataTable dt = new DataTable(); dt.TableName = SaveName; dt.AppendColumn(CellType.Integer, SaveKey); DataCellCollection Row = new DataCellCollection(); DataCell Cell = new DataCell(); Cell.SetInteger(InitialNum); Row.Add(Cell); dt.AppendRow(Row, true); dd.UpgradeOpen(); TableID = dd.SetAt(SaveName, dt); trans.AddNewlyCreatedDBObject(dt, true); } trans.Commit(); } catch (Autodesk.AutoCAD.Runtime.Exception EX) { ed.WriteMessage("\n出错了!{0}", EX.ToString()); } finally { trans.Dispose(); } } return(TableID); }
/// <summary> /// 创建组 /// </summary> /// <param name="db">数据库对象</param> /// <param name="groupName">组名</param> /// <param name="ids">要加入实体的ObjectId集合</param> /// <returns>返回组的Id</returns> public static ObjectId CreateGroup(this Database db, string groupName, ObjectIdList ids) { //打开当前数据库的组字典对象 DBDictionary groupDict = (DBDictionary)db.GroupDictionaryId.GetObject(OpenMode.ForRead); //如果已经存在指定名称的组,则返回 if (groupDict.Contains(groupName)) { return(ObjectId.Null); } //新建一个组对象 Group group = new Group(groupName, true); groupDict.UpgradeOpen(); //切换组字典为写的状态 //在组字典中加入新创建的组对象,并指定它的搜索关键字为groupName groupDict.SetAt(groupName, group); //通知事务处理完成组对象的加入 db.TransactionManager.AddNewlyCreatedDBObject(group, true); group.Append(ids); // 在组对象中加入实体对象 groupDict.DowngradeOpen(); //为了安全,将组字典切换成写 return(group.ObjectId); //返回组的Id }
private void AddXRecord(Transaction tr, DBDictionary dict, string key, ObjectId id) { Xrecord xr = null; if (dict.Contains(key)) { // Update the existing lock object xr = tr.GetObject((ObjectId)dict[key], OpenMode.ForWrite) as Xrecord; xr.Data = SoftPointerForId(id); } else { // Create a new lock object xr = new Xrecord(); xr.XlateReferences = true; xr.Data = SoftPointerForId(id); dict.UpgradeOpen(); dict.SetAt(key, xr); tr.AddNewlyCreatedDBObject(xr, true); } }
protected DBDictionary WriteMapDictionary(DBDictionary parentDict, Transaction t) { DBDictionary result; try { parentDict.UpgradeOpen(); DBDictionary dBDictionary = new DBDictionary(); this.AcadDictionaryID = parentDict.SetAt(base.Name, dBDictionary); dBDictionary.DisableUndoRecording(true); t.AddNewlyCreatedDBObject(dBDictionary, true); DocUtil.WriteXRecord(t, dBDictionary, "AutoCADID", (DxfCode)330, base.RasterObjectId); DocUtil.WriteXRecord(t, dBDictionary, "ServiceFullName", (DxfCode)1, this.ServiceFullName); DocUtil.WriteXRecord(t, dBDictionary, "ConnectionName", (DxfCode)1, base.ConnectionName); DocUtil.WriteXRecord(t, dBDictionary, "ConnectionURL", (DxfCode)1, base.ConnectionURL); DocUtil.WriteXRecord(t, dBDictionary, "UserName", (DxfCode)1, base.UserName); if (base.Dynamic) { Xrecord xrecord = new Xrecord(); xrecord.Data = (new ResultBuffer(new TypedValue[] { new TypedValue(290, true) })); dBDictionary.SetAt("Dynamic", xrecord); xrecord.DisableUndoRecording(true); t.AddNewlyCreatedDBObject(xrecord, true); } DocUtil.WriteBoundingBox(t, dBDictionary, base.BoundaryExtent); DocUtil.WriteXRecord(t, dBDictionary, "ImageFormat", (DxfCode)1, base.ExportOptions.Format); result = dBDictionary; } catch (Exception ex) { string arg_122_0 = ex.Message; result = null; } return(result); }
//为当前图形添加一个新的表格样式 public static ObjectId AddTableStyle(string style) { ObjectId styleId; // 存储表格样式的Id Database db = HostApplicationServices.WorkingDatabase; using (Transaction trans = db.TransactionManager.StartTransaction()) { // 打开表格样式字典 DBDictionary dict = (DBDictionary)db.TableStyleDictionaryId.GetObject(OpenMode.ForRead); if (dict.Contains(style)) // 如果存在指定的表格样式 { styleId = dict.GetAt(style); // 获取表格样式的Id } else { TableStyle ts = new TableStyle(); // 新建一个表格样式 // 设置表格的标题行为灰色 //ts.SetBackgroundColor(Color.FromColorIndex(ColorMethod.ByAci, 8), (int)RowType.TitleRow); // 设置表格所有行的外边框的线宽为0.30mm ts.SetGridLineWeight(LineWeight.LineWeight030, (int)GridLineType.OuterGridLines, TableTools.AllRows); // 不加粗表格表头行的底部边框 ts.SetGridLineWeight(LineWeight.LineWeight000, (int)GridLineType.HorizontalBottom, (int)RowType.HeaderRow); // 不加粗表格数据行的顶部边框 ts.SetGridLineWeight(LineWeight.LineWeight000, (int)GridLineType.HorizontalTop, (int)RowType.DataRow); // 设置表格中所有行的文本高度为1 ts.SetTextHeight(1, TableTools.AllRows); // 设置表格中所有行的对齐方式为正中 ts.SetAlignment(CellAlignment.MiddleCenter, TableTools.AllRows); dict.UpgradeOpen();//切换表格样式字典为写的状态 // 将新的表格样式添加到样式字典并获取其Id styleId = dict.SetAt(style, ts); // 将新建的表格样式添加到事务处理中 trans.AddNewlyCreatedDBObject(ts, true); trans.Commit(); } } return(styleId); // 返回表格样式的Id }
//Creates a custom property in object contains number of floors and bars public void SaveToDB(ObjectId objectId, int floorNum, int numBars) { Document document = Application.DocumentManager.MdiActiveDocument; Database database = document.Database; using (Transaction transaction = database.TransactionManager.StartTransaction()) { DBObject databaseObject = transaction.GetObject(objectId, OpenMode.ForRead); ObjectId extId = databaseObject.ExtensionDictionary; if (extId == ObjectId.Null) { databaseObject.UpgradeOpen(); databaseObject.CreateExtensionDictionary(); extId = databaseObject.ExtensionDictionary; } DBDictionary dbExt = (DBDictionary)transaction.GetObject(extId, OpenMode.ForRead); if (!dbExt.Contains("CustomProp")) { dbExt.UpgradeOpen(); Xrecord xRec = new Xrecord(); ResultBuffer rb = new ResultBuffer { new TypedValue((int)DxfCode.ExtendedDataAsciiString, floorNum.ToString()), new TypedValue((int)DxfCode.ExtendedDataAsciiString, numBars.ToString()) }; xRec.Data = rb; dbExt.SetAt("CustomProp", xRec); transaction.AddNewlyCreatedDBObject(xRec, true); } transaction.Commit(); } }
/// <summary> /// Remove the named Dictionary Entry from the passed-in object if applicable. /// </summary> /// <param name="id">The object hosting the Extension Dictionary</param> /// <param name="entryName">The name of the Dictionary Entry to remove</param> /// <returns>True if really removed, false if not there at all</returns> public static bool RemoveExtensionDictionaryEntry(ObjectId id, string entryName) { bool ret = false; using (Transaction tr = HostApplicationServices.WorkingDatabase.TransactionManager.StartTransaction()) { DBObject obj = (DBObject)tr.GetObject(id, OpenMode.ForRead); if (obj.ExtensionDictionary != ObjectId.Null) { DBDictionary dict = (DBDictionary)tr.GetObject(obj.ExtensionDictionary, OpenMode.ForRead); if (dict.Contains(entryName)) { dict.UpgradeOpen(); dict.Remove(entryName); ret = true; } } tr.Commit(); } return(ret); }
/// <summary> /// Saves this instance. /// </summary> /// <param name="doc">The document.</param> /// <param name="tr">The tr.</param> public void Save(Document doc, Transaction tr) { DBDictionary NOD = (DBDictionary)doc.Database.NamedObjectsDictionaryId.GetObject(OpenMode.ForRead), tabalimDic; ObjectId dicId; //Se abre el diccionario if (this.TryGetEntry(NOD, TABALIM_DIC, out dicId)) { tabalimDic = (DBDictionary)dicId.GetObject(OpenMode.ForRead); } else { DBDictionary newDictionary = new DBDictionary(); NOD.UpgradeOpen(); NOD.SetAt(TABALIM_DIC, newDictionary); tr.AddNewlyCreatedDBObject(newDictionary, true); tabalimDic = newDictionary; } //Se abre el registro this.SaveRecord(tr, tabalimDic, TAG_HOR_REC, this.Rows.Select(x => x.GetHorizontalFormat())); this.SaveRecord(tr, tabalimDic, TAG_VER_REC, this.Rows.Select(x => x.GetVerticalFormat())); }
private static ObjectId getDict() { ObjectId idDic = ObjectId.Null; Database db = HostApplicationServices.WorkingDatabase; using (DBDictionary nod = (DBDictionary)db.NamedObjectsDictionaryId.Open(OpenMode.ForRead)) { if (!nod.Contains(_dicName)) { nod.UpgradeOpen(); using (var dic = new DBDictionary()) { idDic = nod.SetAt(_dicName, dic); dic.TreatElementsAsHard = true; } } else { idDic = nod.GetAt(_dicName); } } return(idDic); }
/// <summary> /// Guarda el registro de las filas dibujadas /// </summary> /// <param name="tr">La transacción activa.</param> /// <param name="tabalimDic">El diccionario Tabalim.</param> /// <param name="entryName">El nombre de la entrada</param> /// <param name="data">La información a guardar en el registro.</param> private void SaveRecord(Transaction tr, DBDictionary tabalimDic, string entryName, IEnumerable <string> data) { if (data.Count() > 0) { ObjectId entryId; Xrecord xRec; if (this.TryGetEntry(tabalimDic, entryName, out entryId)) { xRec = (Xrecord)entryId.GetObject(OpenMode.ForRead); } else { tabalimDic.UpgradeOpen(); Xrecord newXrecord = new Xrecord(); tabalimDic.SetAt(entryName, newXrecord); tr.AddNewlyCreatedDBObject(newXrecord, true); xRec = newXrecord; } xRec.UpgradeOpen(); TypedValue[] tpVal = data.Select(x => new TypedValue((int)DxfCode.Text, x)).ToArray(); xRec.Data = new ResultBuffer(tpVal); } }
public static void CreateAppNod() { Editor ed = Application.DocumentManager.MdiActiveDocument.Editor; Transaction trans = Application.DocumentManager.MdiActiveDocument.Database.TransactionManager.StartTransaction(); using (trans) { try { DBDictionary NOD = (DBDictionary)trans.GetObject(Application.DocumentManager.MdiActiveDocument.Database.NamedObjectsDictionaryId, OpenMode.ForRead); //try to add new dictonary to the NOD if it fails then create a new one try { ObjectId appDictionaryId = NOD.GetAt(APPDICTIONARYNAME); //no error so dictionary already exist AppDictionary = (DBDictionary)trans.GetObject(appDictionaryId, OpenMode.ForRead); ed.WriteMessage(APPDICTIONARYNAME + " Already Exists"); } catch { NOD.UpgradeOpen(); AppDictionary = new DBDictionary(); //insert new dictionary in NOD NOD.SetAt(APPDICTIONARYNAME, AppDictionary); trans.AddNewlyCreatedDBObject(AppDictionary, true); } trans.Commit(); } catch (Autodesk.AutoCAD.Runtime.Exception e) { Application.DocumentManager.MdiActiveDocument.Editor.WriteMessage("Error while opening Nod: " + e.Message); } } }
internal static void ExImportPlotSettings(this Database db, Transaction tr, PlotSettings plotSettings) { // Check to see if a named page setup was assigned to the layout, // if so then copy the page setup settings if (plotSettings == null || string.IsNullOrWhiteSpace(plotSettings.PlotSettingsName)) { return; } var plotSettingsName = plotSettings?.PlotSettingsName; DBDictionary plSets = tr.GetObject(db.PlotSettingsDictionaryId, OpenMode.ForRead) as DBDictionary; if (!plSets.Contains(plotSettingsName)) { plSets.UpgradeOpen(); using (PlotSettings plSet = new PlotSettings(plotSettings.ModelType)) { plSet.PlotSettingsName = plotSettingsName; plSet.AddToPlotSettingsDictionary(db); tr.AddNewlyCreatedDBObject(plSet, true); plSet.CopyFrom(plotSettings); } } }
public ObjectId CreateMyTablesytle() //创建表格样式 { //Editor ed = Application.DocumentManager.MdiActiveDocument.Editor; //Database db = Application.DocumentManager.MdiActiveDocument.Database; const string stylename = "GCLCurveElementsTableStyle"; ObjectId tsId = ObjectId.Null; using (Transaction trans = db.TransactionManager.StartTransaction()) { try { DBDictionary sd = (DBDictionary)trans.GetObject(db.TableStyleDictionaryId, OpenMode.ForRead); if (sd.Contains(stylename)) { tsId = sd.GetAt(stylename); } else { TableStyle ts = new TableStyle(); ts.FlowDirection = FlowDirection.LeftToRight; //这是10版.net的bug? ts.HorizontalCellMargin = 0; ts.VerticalCellMargin = 0; sd.UpgradeOpen(); tsId = sd.SetAt(stylename, ts); trans.AddNewlyCreatedDBObject(ts, true); } trans.Commit(); } catch (Autodesk.AutoCAD.Runtime.Exception EX) { ed.WriteMessage("\n出错了!" + EX.ToString()); } } return(tsId); }
public static void makeGroup() { Database currentDB = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Database; using (Transaction trans = currentDB.TransactionManager.StartTransaction()) { // get object DBDictionary and make the Group object. DBDictionary dbDict = trans.GetObject(currentDB.GroupDictionaryId, OpenMode.ForWrite) as DBDictionary; Group dbGroup = new Group(NameGroup, true); dbGroup.Description = IdentifyBalloon; // it is identification of balloon's type. // add group to Group Dictionary. dbDict.UpgradeOpen(); dbDict.SetAt(NameGroup, dbGroup); foreach (ObjectId id in LstObjectId) { dbGroup.Append(id); } trans.AddNewlyCreatedDBObject(dbGroup, true); trans.Commit(); } }
/// <summary> ///用于删除对象扩展字典中的指定的扩展记录 /// </summary> /// <param name="objId">对象id</param> /// <param name="xRecordSearchKey"> 扩展记录名称</param> public static bool DelObjXrecord(ObjectId objId, string xRecordSearchKey) { try { DocumentLock m_DocumentLock = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.LockDocument(); Document doc = Application.DocumentManager.MdiActiveDocument; Database db = doc.Database; using (Transaction tr = db.TransactionManager.StartTransaction()) { DBObject obj = objId.GetObject(OpenMode.ForRead); //以读的方式打开对象 ObjectId dictId = obj.ExtensionDictionary; //获取对象的扩展字典id if (dictId.IsNull) { tr.Commit(); m_DocumentLock.Dispose(); return(false);//若对象没有扩展字典,则返回 } //如果对象有扩展字典,则以读的方式打开 DBDictionary dict = dictId.GetObject(OpenMode.ForRead) as DBDictionary; if (dict.Contains(xRecordSearchKey)) //如果扩展字典中包含指定关键字的扩展记录,则删除; { dict.UpgradeOpen(); //切换为写的状态 dict.Remove(xRecordSearchKey); //删除扩展记录 dict.DowngradeOpen(); //切换为读的状态 } tr.Commit(); } m_DocumentLock.Dispose(); return(true); } catch (System.Exception ex) { System.Windows.Forms.MessageBox.Show("扩展属性删:" + ex.Message); return(false); } }
public void AttachRasterImage() { // Get the current database and start a transaction Database db = Application.DocumentManager.MdiActiveDocument.Database; using (Transaction tr = db.TransactionManager.StartTransaction()) { // Define the name and image to use string strImgName = "Organica_Logo"; string strFileName = @"E:\Munka\OrganiCad\DrawingTemplates\Images\Organica_Logo.png"; RasterImageDef acRasterDef; bool bRasterDefCreated = false; ObjectId acImgDefId; // Get the image dictionary ObjectId acImgDctID = RasterImageDef.GetImageDictionary(db); // Check to see if the dictionary does not exist, it not then create it if (acImgDctID.IsNull) { acImgDctID = RasterImageDef.CreateImageDictionary(db); } // Open the image dictionary DBDictionary acImgDict = tr.GetObject(acImgDctID, OpenMode.ForRead) as DBDictionary; // Check to see if the image definition already exists if (acImgDict.Contains(strImgName)) { acImgDefId = acImgDict.GetAt(strImgName); acRasterDef = tr.GetObject(acImgDefId, OpenMode.ForWrite) as RasterImageDef; } else { // Create a raster image definition RasterImageDef acRasterDefNew = new RasterImageDef(); // Set the source for the image file acRasterDefNew.SourceFileName = strFileName; // Load the image into memory acRasterDefNew.Load(); // Add the image definition to the dictionary acImgDict.UpgradeOpen(); acImgDefId = acImgDict.SetAt(strImgName, acRasterDefNew); tr.AddNewlyCreatedDBObject(acRasterDefNew, true); acRasterDef = acRasterDefNew; bRasterDefCreated = true; } // Open the Block table for read BlockTable bt = tr.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable; // Open the Block table record Model space for write BlockTableRecord btr = tr.GetObject(bt[BlockTableRecord.PaperSpace], OpenMode.ForWrite) as BlockTableRecord; // Create the new image and assign it the image definition using (RasterImage acRaster = new RasterImage()) { acRaster.ImageDefId = acImgDefId; // Use ImageWidth and ImageHeight to get the size of the image in pixels (1024 x 768). // Use ResolutionMMPerPixel to determine the number of millimeters in a pixel so you // can convert the size of the drawing into other units or millimeters based on the // drawing units used in the current drawing. // Define the width and height of the image Vector3d width; Vector3d height; // Check to see if the measurement is set to English (Imperial) or Metric units if (db.Measurement == MeasurementValue.English) { width = new Vector3d((acRasterDef.ResolutionMMPerPixel.X * acRaster.ImageWidth) / 25.4, 0, 0); height = new Vector3d(0, (acRasterDef.ResolutionMMPerPixel.Y * acRaster.ImageHeight) / 25.4, 0); } else { width = new Vector3d(acRasterDef.ResolutionMMPerPixel.X * acRaster.ImageWidth, 0, 0); height = new Vector3d(0, acRasterDef.ResolutionMMPerPixel.Y * acRaster.ImageHeight, 0); } // Define the position for the image Point3d insPt = new Point3d(12.0, 12.0, 0.0); // Define and assign a coordinate system for the image's orientation CoordinateSystem3d coordinateSystem = new CoordinateSystem3d(insPt, width * 2, height * 2); acRaster.Orientation = coordinateSystem; // Set the rotation angle for the image acRaster.Rotation = 0; // Add the new object to the block table record and the transaction btr.AppendEntity(acRaster); tr.AddNewlyCreatedDBObject(acRaster, true); // Connect the raster definition and image together so the definition // does not appear as "unreferenced" in the External References palette. RasterImage.EnableReactors(true); acRaster.AssociateRasterDef(acRasterDef); if (bRasterDefCreated) { acRasterDef.Dispose(); } } // Save the new object to the database tr.Commit(); // Dispose of the transaction } }
/// <summary> 向数据库中添加数据 </summary> public static void AddDataToNOD() { // get the editor object Editor ed = Application.DocumentManager.MdiActiveDocument.Editor; // pick entity to add data to! Transaction trans = ed.Document.Database.TransactionManager.StartTransaction(); try { // 26. Here we will add our data to the Named Objects Dictionary.(NOD). Declare a variable as a DBDictionary. (name it nod). DBDictionary nod = (DBDictionary)trans.GetObject(ed.Document.Database.NamedObjectsDictionaryId, OpenMode.ForRead); // 27. Check to see if the entry we are going to add to the NOD is already there. if (nod.Contains("MyData")) { // 28. Declare an ObjectId variable named entryId. Instantiate it by making it equal to the return of the GetAt method of the NOD (DBDictionary) ObjectId entryId = nod.GetAt("MyData"); // 29. If we are here, then the Name Object Dictionary already has our data. ed.WriteMessage("\n" + "This entity already has data..."); // 30. Get the the Xrecord from the NOD. Declare a variable as a new Xrecord Xrecord myXrecord = null; // 31. USe the Transaction (trans) and use the GetObject method to get the the Xrecord from the NOD. myXrecord = (Xrecord)trans.GetObject(entryId, OpenMode.ForRead); // 32. Print out the values of the Xrecord to the command line. foreach (TypedValue value in myXrecord.Data) { // 33. Use the WriteMessage method of the editor. ed.WriteMessage("\n" + value.TypeCode.ToString() + " . " + value.Value.ToString()); } } else { // 34. Our data is not in the Named Objects Dictionary so need to add it // upgrade the status of the NOD variable from step 26 to write status nod.UpgradeOpen(); // 35. Declare a varable as a new Xrecord. Xrecord myXrecord = new Xrecord(); // 36. Create the resbuf list. Declare a ResultBuffer variable. Instantiate it by creating a New ResultBuffer. ResultBuffer data = new ResultBuffer(new TypedValue((int)DxfCode.Int16, 1), new TypedValue((int)DxfCode.Text, "MyCompanyDefaultSettings"), new TypedValue((int)DxfCode.Real, 51.9), new TypedValue((int)DxfCode.Real, 100.0), new TypedValue((int)DxfCode.Real, 320.6)); // 37. Add the ResultBuffer to the Xrecord using the Data property of the Xrecord. myXrecord.Data = data; // 38. Create the entry in the ExtensionDictionary. Use the SetAt method of the Named Objects Dictionary from step 26. nod.SetAt(searchKey: "MyData", newValue: myXrecord); // 39. Tell the transaction about the newly created Xrecord. // 如果不将 myXrecord 添加到数据库中,在程序运行的过程中不会报错,但是,在保存文件时,会出现报错:此图形中的一个或多个对象无法保存为指定格式。操作未完成,因此未创建任何文件。 trans.AddNewlyCreatedDBObject(myXrecord, true); } // End of LAB 5 // all ok, commit it trans.Commit(); } catch (Exception ex) { ed.WriteMessage("a problem occurred because " + ex.Message); } finally { // whatever happens we must dispose the transaction trans.Dispose(); } }
/// <summary> 向 Entity 中添加数据 </summary> public static void AddDataToExtensionDictionary() { Editor ed = Application.DocumentManager.MdiActiveDocument.Editor; // pick entity to add data to! PromptEntityResult getEntityResult = ed.GetEntity("Pick an entity to add an Extension Dictionary to : "); // if all was ok if ((getEntityResult.Status == PromptStatus.OK)) { // now start a transaction Transaction trans = ed.Document.Database.TransactionManager.StartTransaction(); try { // Start of Lab5 // Here we will add XData to a selected entity. // 1. Declare an Entity variable named ent. Instantiate it using GetOBject of the Transaction created above. Entity ent = (Entity)trans.GetObject(getEntityResult.ObjectId, OpenMode.ForRead); // 2. Use an "if" statement and test the IsNull property of the ExtensionDictionary of the ent. if (ent.ExtensionDictionary.IsNull) { // 3. Upgrade the open of the entity. Because it does not have an extenstion dictionary and we want to add it the ent needs to be open for write. ent.UpgradeOpen(); // 4. Create the ExtensionDictionary by calling CreateExtensionDictionary of the entity. ent.CreateExtensionDictionary(); } // 5. Declare a variable as DBDictionary. Instantiate it by using the GetObject method of the Transaction created above. DBDictionary extensionDict = (DBDictionary)trans.GetObject(ent.ExtensionDictionary, OpenMode.ForRead); // 6. Check to see if the entry we are going to add to the dictionary is already there. Use the Contains property of the dictionary in an "if else statement. if (extensionDict.Contains("MyData")) { // 7. Declare an ObjectId variable named entryId and instantiate it using the GetAt method of the ExtenstionDictionary from step 5. Use "Mydata" for the entryName ObjectId entryId = extensionDict.GetAt("MyData"); // 8. If this line gets hit then data is already added. ed.WriteMessage("\nThis entity already has data..."); // 9. Now extract the Xrecord. Declare an Xrecord variable. Xrecord myXrecord = default(Xrecord); // 10. Instantiate the Xrecord variable using the GetObject method of the Transaction created above. myXrecord = (Xrecord)trans.GetObject(entryId, OpenMode.ForRead); // 11. Here print out the values in the Xrecord to the command line. ResultBuffer resBuff = myXrecord.Data; foreach (TypedValue value in resBuff) { // 12. Use the WriteMessage method of the Editor created above. (ed). ed.WriteMessage("\n" + value.TypeCode.ToString() + " . " + value.Value.ToString()); } } else { // 13. If the code gets to here then the data entry does not exist, upgrade the ExtensionDictionary created in step 5 to write by calling the UpgradeOpen() method extensionDict.UpgradeOpen(); // 14. Create a new XRecord. Declare an Xrecord variable as a New Xrecord Xrecord myXrecord = new Xrecord(); // 15. Create the resbuf list. Declare a ResultBuffer variable. Instantiate it by creating a New ResultBuffer. ResultBuffer data = new ResultBuffer( new TypedValue((int)DxfCode.Int16, 1), new TypedValue((int)DxfCode.Text, "MyStockData"), new TypedValue((int)DxfCode.Real, 51.9), new TypedValue((int)DxfCode.Real, 100.0), new TypedValue((int)DxfCode.Real, 320.6)); // 16. Add the ResultBuffer to the Xrecord using the Data property of the Xrecord. (make it equal the ResultBuffer from step 15) myXrecord.Data = data; // 17. Create the entry in the ExtensionDictionary. Use the SetAt method of the ExtensionDictionary from step 5. extensionDict.SetAt(searchKey: "MyData", newValue: myXrecord); // 18. Tell the transaction about the newly created Xrecord using the AddNewlyCreatedDBObject of the Transaction (trans) // 如果不将 myXrecord 添加到数据库中,在程序运行的过程中不会报错,但是,在保存文件时,会出现报错:此图形中的一个或多个对象无法保存为指定格式。操作未完成,因此未创建任何文件。 trans.AddNewlyCreatedDBObject(myXrecord, true); } // all ok, commit it trans.Commit(); } catch (Exception ex) { ed.WriteMessage("a problem occured because " + ex.Message); } finally { // whatever happens we must dispose the transaction trans.Dispose(); } } }
public void addData() { // get the editor object Editor ed = Application.DocumentManager.MdiActiveDocument.Editor; // pick entity to add data to! PromptEntityResult getEntityResult = ed.GetEntity("Pick an entity to add an Extension Dictionary to : "); // if all was ok if ((getEntityResult.Status == PromptStatus.OK)) { // now start a transaction Transaction trans = ed.Document.Database.TransactionManager.StartTransaction(); try { // Start of Lab5 // Here we will add XData to a selected entity. // 1. Declare an Entity variable named ent. Instantiate it using // GetOBject of the Transaction created above. (trans) For the // ObjectId parameter use the ObjectId property of the the // PromptEntityResult created above.(getEntityResult) Open the entity for read. Entity ent = (Entity)trans.GetObject(getEntityResult.ObjectId, OpenMode.ForRead); // 2. Use an "if" statement and test the IsNull property of the // ExtensionDictionary of the ent. If it is Null then we create // the ExtensionDictionary. // Note: Place the closing curly brace after step 4. if (ent.ExtensionDictionary.IsNull) { // 3. Upgrade the open of the entity. Because it does // not have an extenstion dictionary and we want to add it // the ent needs to be open for write. ent.UpgradeOpen(); // 4. Create the ExtensionDictionary by calling // CreateExtensionDictionary of the entity. ent.CreateExtensionDictionary(); } // 5. Declare a variable as DBDictionary. Instantiate it by using the // GetObject method of the Transaction created above. (trans). For the // ObjectId parameter use the ExtensionDictionary property of the ent // variable created in step 1. Open it for read DBDictionary extensionDict = (DBDictionary)trans.GetObject(ent.ExtensionDictionary, OpenMode.ForRead); // 6. Check to see if the entry we are going to add to the dictionary is // already there. Use the Contains property of the dictionary in an "if else // statement. // Note: Place the closing curly brace and the "else" after step 12. Place the // closing curly brace of the "else" after after step 25 if (extensionDict.Contains("MyData")) { // 7. Declare an ObjectId variable named entryId and instantiate it // using the GetAt method of the ExtenstionDictionary from step 5. Use // "Mydata" for the entryName ObjectId entryId = extensionDict.GetAt("MyData"); // 8. If this line gets hit then data is already added // Use the WriteMessage method of the Editor (ed) created above // to print the data. For the string argument use something like this: // "\nThis entity already has data..." ed.WriteMessage("\nThis entity already has data..."); // 9. Now extract the Xrecord. Declare an Xrecord variable. Xrecord myXrecord = default(Xrecord); // 10. Instantiate the Xrecord variable using the // GetObject method of the Transaction created above. (trans). // For the ObjectId argument use the ObjectId created in step 7 // open for read. myXrecord = (Xrecord)trans.GetObject(entryId, OpenMode.ForRead); // 11. Here print out the values in the Xrecord to the command line. // Use a "foreach" statement. For the Element type use a TypedValue. // (Use value for the name of the TypedValue) For the Group use the // Data property of the Xrecord // Note: Put the closing curly brace below step 12 foreach (TypedValue value in myXrecord.Data) { // 12. Use the WriteMessage method of the Editor created above. (ed). // for the string argument use something like this: // "\n" + value.TypeCode.ToString() + " . " + value.Value.ToString() ed.WriteMessage("\n" + value.TypeCode.ToString() + " . " + value.Value.ToString()); } } else { // 13. If the code gets to here then the data entry does not exist // upgrade the ExtensionDictionary created in step 5 to write by calling // the UpgradeOpen() method extensionDict.UpgradeOpen(); System.Type t = typeof(DBDictionary); // 14. Create a new XRecord. Declare an Xrecord variable as a New Xrecord Xrecord myXrecord = new Xrecord(); // 15. Create the resbuf list. Declare a ResultBuffer variable. Instantiate it // by creating a New ResultBuffer. For the ParamArray of TypeValue for the new // ResultBuffer use the following: //new TypedValue((int)DxfCode.Int16, 1), //new TypedValue((int)DxfCode.Text, "MyStockData"), //new TypedValue((int)DxfCode.Real, 51.9), //new TypedValue((int)DxfCode.Real, 100.0), //new TypedValue((int)DxfCode.Real, 320.6) ResultBuffer data = new ResultBuffer(new TypedValue((int)DxfCode.Int16, 1), new TypedValue((int)DxfCode.Text, "MyStockData"), new TypedValue((int)DxfCode.Real, 51.9), new TypedValue((int)DxfCode.Real, 100.0), new TypedValue((int)DxfCode.Real, 320.6)); // 16. Add the ResultBuffer to the Xrecord using the Data // property of the Xrecord. (make it equal the ResultBuffer // from step 15) myXrecord.Data = data; // 17. Create the entry in the ExtensionDictionary. Use the SetAt // method of the ExtensionDictionary from step 5. For the SearchKey // argument use "MyData". For the DBObject argument use the Xrecord // created in step 14. extensionDict.SetAt("MyData", myXrecord); // 18. Tell the transaction about the newly created Xrecord // using the AddNewlyCreatedDBObject of the Transaction (trans) trans.AddNewlyCreatedDBObject(myXrecord, true); // 19. Here we will populate the treeview control with the new data // Use an "if" statement to check to see if the // palette (myPalette created in Lab 4) is not equal to null. // (If not then it will crash) // Note: Put the closing curly brace after step 25 if (myPalette != null) { // 20. Create a foreach statement. Use node for the element name and // the type is System.Windows.Forms.Treenode. The group paramater is the Nodes in the // TreeView. (myPalette.treeView1.Nodes) // Note: put the closing curly brace after step 25 foreach (System.Windows.Forms.TreeNode node in myPalette.treeView1.Nodes) { // 21. Use an "if" statement. Test to see if the node Tag is the ObjectId // of the ent from step 1. Use the ObjectId. (ent.ObjectId.ToString) // Note: put the closing curly brace after step 25 if (node.Tag.ToString() == ent.ObjectId.ToString()) { // 22. Now add the new data to the treenode. Declare a variable as a // System.Windows.Forms.Treenode. (name it something like childNode). // Instantiate it by making it equal to the return of calling the Add // method of the Nodes collection of the node from the loop. // (node.Nodes.Add) For the string argument use "Extension Dictionary" System.Windows.Forms.TreeNode childNode = node.Nodes.Add("Extension Dictionary"); // 23. Now add the data. Create a foreach statement. Use value for the element // name and the type is TypedValue. Use the Data property of the Xrecord created in // step 14 for the group. // Note: put the closing curly brace after step 24 foreach (TypedValue value in myXrecord.Data) { // 24. Add the TypeValue from the For Each loop to the // TreeNode created in step 22. Use the Add method of the // Nodes Collection. (childNode.Nodes.Add) For the string // argument use the TypeValue from the loop. (value.ToString) childNode.Nodes.Add(value.ToString()); } // 25. Exit the for loop (all done - break out of the loop) break; } } } } // all ok, commit it trans.Commit(); } catch (Exception ex) { // a problem occured, lets print it ed.WriteMessage("a problem occured because " + ex.Message); } finally { // whatever happens we must dispose the transaction trans.Dispose(); } } }
public void Save() { if (WriteLock == true) { return; } if (BaseObjectId == ObjectId.Null) { return; } using (DocumentLock docLock = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.LockDocument()) { attrs.Clear(); this.GetAttributes(); if (attrs.ContainsKey("type")) { attrs["type"] = this.ModelType(); } else { attrs.Add("type", this.ModelType()); } if (attrs.ContainsKey("modelid")) { attrs["modelid"] = Utils.ModelIdManager.toString(this.BaseModelId); } else { attrs.Add("modelid", Utils.ModelIdManager.toString(this.BaseModelId)); } Dictionary <String, String> pairs = attrs; Editor ed = Application.DocumentManager.MdiActiveDocument.Editor; Transaction trans = ed.Document.Database.TransactionManager.StartTransaction(); try { DBObject ent = trans.GetObject(BaseObjectId, OpenMode.ForRead); if (ent.ExtensionDictionary.IsNull) { ent.UpgradeOpen(); ent.CreateExtensionDictionary(); } DBDictionary extensionDict = (DBDictionary)trans.GetObject(ent.ExtensionDictionary, OpenMode.ForRead); foreach (KeyValuePair <string, string> item in pairs) { String key = item.Key; String value = item.Value; Xrecord myXrecord; if (extensionDict.Contains(key)) { ObjectId entryId = extensionDict.GetAt(key); myXrecord = default(Xrecord); extensionDict.UpgradeOpen(); myXrecord = (Xrecord)trans.GetObject(entryId, OpenMode.ForWrite); ResultBuffer data = new ResultBuffer(new TypedValue((int)DxfCode.Text, value)); myXrecord.Data = data; } else { extensionDict.UpgradeOpen(); myXrecord = new Xrecord(); ResultBuffer data = new ResultBuffer(new TypedValue((int)DxfCode.Text, value)); myXrecord.Data = data; extensionDict.SetAt(key, myXrecord); trans.AddNewlyCreatedDBObject(myXrecord, true); } } trans.Commit(); } catch (System.Exception ex) { ed.WriteMessage("a problem occured because " + ex.Message); } finally { trans.Dispose(); } } }
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; }
WblockCloneObjects() { try { m_db = Utils.Db.GetCurDwg(); if (m_db == null) { return; } using (TransactionHelper trHlpr = new TransactionHelper()) { trHlpr.Start(); /// get the object to clone Objects objs = new Objects(trHlpr); if (objs.ShowDialog() != DialogResult.OK) { trHlpr.Abort(); return; } DBObject objToClone = trHlpr.Transaction.GetObject(objs.ObjectId, OpenMode.ForRead); if (objToClone is DBDictionary) { throw new System.Exception("Please select a record in a dictionary"); } AcadApp.Document activeDoc = AcadApp.Application.DocumentManager.MdiActiveDocument; /// get cloning options... /// //String message = "\nDuplicate Record Cloning Options:"; //Array enums = Enum.GetValues(typeof(DuplicateRecordCloning)); //foreach (int option in enums) { // message += string.Format("\n{0} = {1}", // option, // Enum.GetName(typeof(DuplicateRecordCloning), option)); //} //PromptIntegerOptions prOpts = new PromptIntegerOptions(message); //prOpts.LowerLimit = 0; //prOpts.UpperLimit = enums.Length; //Editor ed = activeDoc.Editor; //PromptIntegerResult prRes = ed.GetInteger(prOpts); //if (prRes.Status != PromptStatus.OK) // return; //DuplicateRecordCloning drc = (DuplicateRecordCloning)prRes.Value; //if (drc == DuplicateRecordCloning.NotApplicable || // drc == DuplicateRecordCloning.RefMangleName) { // ed.WriteMessage("Invalid Input"); // return; //} /// .... or not DuplicateRecordCloning drc = DuplicateRecordCloning.Ignore; if (objToClone.OwnerId == ObjectId.Null) /// object to clone is a root object, can't clone { return; } /// get the destination db Documents docs = new Documents(); docs.Text = "Destination database"; if (docs.ShowDialog() != DialogResult.OK) { return; } Database dbSrc = activeDoc.Database; Database dbDest = docs.Document.Database; if (dbDest == dbSrc) { throw new System.Exception("Please pick a destination database other than the source"); } /// find out parent dictionary ObjectId owningDictId = objToClone.OwnerId; DBDictionary owningDictSrc = trHlpr.Transaction.GetObject(owningDictId, OpenMode.ForRead) as DBDictionary; /// might be nested Stack owningDictNames = new Stack(); while (owningDictSrc.OwnerId != ObjectId.Null) { owningDictSrc = trHlpr.Transaction.GetObject(owningDictSrc.OwnerId, OpenMode.ForRead) as DBDictionary; String owningDictName = owningDictSrc.NameAt(owningDictId); owningDictNames.Push(owningDictName); owningDictId = owningDictSrc.ObjectId; } /// check if parent dictionary exists in dest. DBDictionary owningDictDest = null; using (Transaction trDest = dbDest.TransactionManager.StartTransaction()) { AcadApp.Application.DocumentManager.GetDocument(dbDest).LockDocument(); DBDictionary parentDictDest = trDest.GetObject(dbDest.NamedObjectsDictionaryId, OpenMode.ForRead) as DBDictionary; String owningDictName = owningDictNames.Peek().ToString(); if (parentDictDest.Contains(owningDictName)) { while (owningDictNames.Count != 0) { owningDictName = owningDictNames.Pop().ToString(); owningDictDest = trDest.GetObject(parentDictDest.GetAt(owningDictName), OpenMode.ForRead) as DBDictionary; parentDictDest = owningDictDest; } } else { /// dest doesnt have same structure , create it while (owningDictNames.Count != 0) { owningDictName = owningDictNames.Pop().ToString(); parentDictDest.UpgradeOpen(); owningDictDest = new DBDictionary(); parentDictDest.SetAt(owningDictName, owningDictDest); trDest.AddNewlyCreatedDBObject(owningDictDest, true); parentDictDest = owningDictDest; } } trDest.Commit(); } /// clone the objects over ObjectIdCollection objIds = new ObjectIdCollection(); objIds.Add(objToClone.ObjectId); IdMapping idMap = new IdMapping(); idMap.DestinationDatabase = dbDest; m_db.WblockCloneObjects(objIds, owningDictDest.ObjectId, idMap, drc, false); trHlpr.Commit(); } } catch (AcRx.Exception ex) { if (ex.ErrorStatus == AcRx.ErrorStatus.FileNotFound) { MessageBox.Show("No documents found in current session"); } else { MessageBox.Show(ex.Message); } } catch (System.Exception ex) { MessageBox.Show(ex.Message); } }
// add attributes to group object // <param name="groupId"></param> // <param name="pairs"></param> public static void addData(ObjectId groupId, Dictionary <String, String> pairs) { Editor ed = Application.DocumentManager.MdiActiveDocument.Editor; Transaction trans = ed.Document.Database.TransactionManager.StartTransaction(); try { Group ent = (Group)trans.GetObject(groupId, OpenMode.ForRead); if (ent.ExtensionDictionary.IsNull) { ent.UpgradeOpen(); ent.CreateExtensionDictionary(); } DBDictionary extensionDict = (DBDictionary)trans.GetObject(ent.ExtensionDictionary, OpenMode.ForRead); foreach (KeyValuePair <string, string> item in pairs) { String key = item.Key; String value = item.Value; Xrecord myXrecord; if (extensionDict.Contains(key)) { // Check to see if the entry we are going to add is already there. ObjectId entryId = extensionDict.GetAt(key); // Extract the Xrecord. Declare an Xrecord variable. myXrecord = default(Xrecord); extensionDict.UpgradeOpen(); // Instantiate the Xrecord variable myXrecord = (Xrecord)trans.GetObject(entryId, OpenMode.ForWrite); ResultBuffer data = new ResultBuffer(new TypedValue((int)DxfCode.Text, value)); myXrecord.Data = data; } else { // If the code gets to here then the data entry does not exist // upgrade the ExtensionDictionary created in step 5 to write extensionDict.UpgradeOpen(); // Create a new XRecord. myXrecord = new Xrecord(); // Create the resbuf list. ResultBuffer data = new ResultBuffer(new TypedValue((int)DxfCode.Text, value)); // Add the ResultBuffer to the Xrecord myXrecord.Data = data; // Create the entry in the ExtensionDictionary. extensionDict.SetAt(key, myXrecord); // Tell the transaction about the newly created Xrecord trans.AddNewlyCreatedDBObject(myXrecord, true); } } trans.Commit(); } catch (System.Exception ex) { // a problem occured, lets print it ed.WriteMessage("a problem occured because " + ex.Message); } finally { trans.Dispose(); } }
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(); } }
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); }
public static void ReadAll() { Editor ed = Application.DocumentManager.MdiActiveDocument.Editor; ed.WriteMessage("\n READ CALLED \n"); Database db = Application.DocumentManager.MdiActiveDocument.Database; using (DocumentLock docLock = Application.DocumentManager.MdiActiveDocument.LockDocument()) { using (Transaction tr = db.TransactionManager.StartTransaction()) { try { DBDictionary NOD = (DBDictionary)tr.GetObject(db.NamedObjectsDictionaryId, OpenMode.ForWrite); if (NOD.Contains(TableName)) { //ed.WriteMessage("Table found\n"); DBDictionary myDict = (DBDictionary)tr.GetObject(NOD.GetAt(TableName), OpenMode.ForWrite); if (myDict.Contains(PoleCounter)) { Xrecord xrec = (Xrecord)tr.GetObject(myDict.GetAt(PoleCounter), OpenMode.ForWrite); foreach (TypedValue tv in xrec.Data) { ed.WriteMessage("*** PoleCounter:{0}\n", tv.Value); Atend.Control.Common.Counters.PoleCounter = Convert.ToInt32(tv.Value); } } if (myDict.Contains(ConsolCounter)) { Xrecord xrec = (Xrecord)tr.GetObject(myDict.GetAt(ConsolCounter), OpenMode.ForWrite); foreach (TypedValue tv in xrec.Data) { ed.WriteMessage("*** ConsolCounter:{0}\n", tv.Value); Atend.Control.Common.Counters.ConsolCounter = Convert.ToInt32(tv.Value); } } if (myDict.Contains(ClampCounter)) { Xrecord xrec = (Xrecord)tr.GetObject(myDict.GetAt(ClampCounter), OpenMode.ForWrite); foreach (TypedValue tv in xrec.Data) { ed.WriteMessage("*** ClampCounter:{0}\n", tv.Value); Atend.Control.Common.Counters.ClampCounter = Convert.ToInt32(tv.Value); } } if (myDict.Contains(HeaderCounter)) { Xrecord xrec = (Xrecord)tr.GetObject(myDict.GetAt(HeaderCounter), OpenMode.ForWrite); foreach (TypedValue tv in xrec.Data) { ed.WriteMessage("*** HeaderCounter:{0}\n", tv.Value); Atend.Control.Common.Counters.HeadercableCounter = Convert.ToInt32(tv.Value); } } if (myDict.Contains(KablshoCounter)) { Xrecord xrec = (Xrecord)tr.GetObject(myDict.GetAt(KablshoCounter), OpenMode.ForWrite); foreach (TypedValue tv in xrec.Data) { ed.WriteMessage("*** KablshoCounter:{0}\n", tv.Value); Atend.Control.Common.Counters.KablshoCounter = Convert.ToInt32(tv.Value); } } } else { //ed.WriteMessage("Table not found\n"); //table was not exist NOD.UpgradeOpen(); DBDictionary MyDict = new DBDictionary(); NOD.SetAt(TableName, MyDict); tr.AddNewlyCreatedDBObject(MyDict, true); //ed.WriteMessage("found not dict\n"); //set its data here Xrecord Xrec = new Xrecord(); Atend.Control.Common.Counters.PoleCounter = 0; Xrec.Data = new ResultBuffer(new TypedValue((int)DxfCode.Int32, 0)); MyDict.SetAt(PoleCounter, Xrec); tr.AddNewlyCreatedDBObject(Xrec, true); Xrec = new Xrecord(); Atend.Control.Common.Counters.ConsolCounter = 0; Xrec.Data = new ResultBuffer(new TypedValue((int)DxfCode.Int32, 0)); MyDict.SetAt(ConsolCounter, Xrec); tr.AddNewlyCreatedDBObject(Xrec, true); Xrec = new Xrecord(); Atend.Control.Common.Counters.ClampCounter = 0; Xrec.Data = new ResultBuffer(new TypedValue((int)DxfCode.Int32, 0)); MyDict.SetAt(ClampCounter, Xrec); tr.AddNewlyCreatedDBObject(Xrec, true); Xrec = new Xrecord(); Atend.Control.Common.Counters.HeadercableCounter = 0; Xrec.Data = new ResultBuffer(new TypedValue((int)DxfCode.Int32, 0)); MyDict.SetAt(HeaderCounter, Xrec); tr.AddNewlyCreatedDBObject(Xrec, true); Xrec = new Xrecord(); Atend.Control.Common.Counters.KablshoCounter = 0; Xrec.Data = new ResultBuffer(new TypedValue((int)DxfCode.Int32, 0)); MyDict.SetAt(KablshoCounter, Xrec); tr.AddNewlyCreatedDBObject(Xrec, true); } } catch (System.Exception ex) { ed.WriteMessage("ERROR:{0}\n", ex.Message); } tr.Commit(); } } //ed.WriteMessage("PoleCounter:{0} \n", Atend.Control.Common.Counters.PoleCounter); //ed.WriteMessage("ConsolCounter:{0} \n", Atend.Control.Common.Counters.ConsolCounter); //ed.WriteMessage("ClampCounter:{0} \n", Atend.Control.Common.Counters.ClampCounter); //ed.WriteMessage("HeadercableCounter:{0} \n", Atend.Control.Common.Counters.HeadercableCounter); //ed.WriteMessage("KablshoCounter:{0} \n", Atend.Control.Common.Counters.KablshoCounter); }
public void addDataToNOD() { // get the editor object Editor ed = Application.DocumentManager.MdiActiveDocument.Editor; // pick entity to add data to! Transaction trans = ed.Document.Database.TransactionManager.StartTransaction(); try { // 26. Here we will add our data to the Named Objects Dictionary.(NOD) // Declare a variable as a DBDictionary. (name it nod). Instantiate it // by making it equal to the return of the GetObject method of the // Transaction created above. (trans). For the ObjectId argument use the // NamedObjectsDictionaryId property of the current Database: // (ed.Document.Database.NamedObjectsDictionaryId) The Editor (ed) was // instantiated above. Open it for read. DBDictionary nod = (DBDictionary)trans.GetObject(ed.Document.Database.NamedObjectsDictionaryId, OpenMode.ForRead); // 27. Check to see if the entry we are going to add to the NOD is // already there. Use the Contains property of the dictionary in an "if Else" // statement. // Note: put the closing curly brace and the else after step 33. Put the closing // curley brace for the else after step 39 if (nod.Contains("MyData")) { // 28. Declare an ObjectId variable named entryId. Instantiate it by making // it equal to the return of the GetAt method of the NOD (DBDictionary) // from step 26. For the EntryName agrument use "MyData" ObjectId entryId = nod.GetAt("MyData"); // 29. If we are here, then the Name Object Dictionary already has our data // Use the WriteMessage method of the editor. Use this for the Message argument // "\n" + "This entity already has data..." ed.WriteMessage("\n" + "This entity already has data..."); // 30. Get the the Xrecord from the NOD. Declare a variable as a new Xrecord Xrecord myXrecord = null; // 31. USe the Transaction (trans) and use the GetObject method to // get the the Xrecord from the NOD. For the ObjectId argument use the // ObjectId from step 28. Open the Xrecord for read myXrecord = (Xrecord)trans.GetObject(entryId, OpenMode.ForRead); // 32. Print out the values of the Xrecord to the command line. Use // a "foreach" statement. Use value for the element // name and the type is TypedValue. Use the Data property of the Xrecord from // step 31 for the group argument // Note: put the closing curly brace after step 33 foreach (TypedValue value in myXrecord.Data) { // 33. Use the WriteMessage method of the editor. Use this as the message: // "\n" + value.TypeCode.ToString() + " . " + value.Value.ToString() ed.WriteMessage("\n" + value.TypeCode.ToString() + " . " + value.Value.ToString()); } } else { // 34. Our data is not in the Named Objects Dictionary so need to add it // upgrade the status of the NOD variable from step 26 to write status nod.UpgradeOpen(); // 35. Declare a varable as a new Xrecord. Xrecord myXrecord = new Xrecord(); // 36. Create the resbuf list. Declare a ResultBuffer variable. Instantiate it // by creating a New ResultBuffer. For the ParamArray of TypeValue for the new // ResultBuffer use the following: // new TypedValue((int)DxfCode.Int16, 1), //new TypedValue((int)DxfCode.Text, "MyCompanyDefaultSettings"), //new TypedValue((int)DxfCode.Real, 51.9), //new TypedValue((int)DxfCode.Real, 100.0), //new TypedValue((int)DxfCode.Real, 320.6) ResultBuffer data = new ResultBuffer(new TypedValue((int)DxfCode.Int16, 1), new TypedValue((int)DxfCode.Text, "MyCompanyDefaultSettings"), new TypedValue((int)DxfCode.Real, 51.9), new TypedValue((int)DxfCode.Real, 100.0), new TypedValue((int)DxfCode.Real, 320.6)); // 37. Add the ResultBuffer to the Xrecord using the Data // property of the Xrecord. (make it equal the ResultBuffer // from step 36) myXrecord.Data = data; // 38. Create the entry in the ExtensionDictionary. Use the SetAt // method of the Named Objects Dictionary from step 26. For the SearchKey // argument use "MyData". For the DBObject argument use the Xrecord // created in step 35. nod.SetAt("MyData", myXrecord); // 39. Tell the transaction about the newly created Xrecord // using the AddNewlyCreatedDBObject of the Transaction (trans) trans.AddNewlyCreatedDBObject(myXrecord, true); } // End of LAB 5 // all ok, commit it trans.Commit(); } catch (Exception ex) { // a problem occurred, lets print it ed.WriteMessage("a problem occurred because " + ex.Message); } finally { // whatever happens we must dispose the transaction trans.Dispose(); } }
public static ObjectId CreateDivision(String division, String manager) { Database db = HostApplicationServices.WorkingDatabase; Transaction trans = db.TransactionManager.StartTransaction(); //Define a corporate level dictionary DBDictionary acmeDict; //First, get the NOD... using (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); }
public void InputMap() { string WolrdMapName = "大世界"; string layer = "Ground"; CurrentWorldMap = WolrdMapName; CurrentLayer = layer; //line1 = new Line(); //Point3d point1 = new Point3d(0, 0, 0); //Point3d point2 = new Point3d(100, 0, 0); //line1.StartPoint = point1; //line1.EndPoint = point2; //using (Transaction trans = db.TransactionManager.StartTransaction()) //{ // btr.AppendEntity(line1); // trans.AddNewlyCreatedDBObject(line1,true); // trans.Commit(); //} // Get the current database and start a transaction Database acCurDb; acCurDb = Application.DocumentManager.MdiActiveDocument.Database; using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction()) { // Define the name and image to use RasterImageDef acRasterDef; bool bRasterDefCreated = false; ObjectId acImgDefId; // Get the image dictionary ObjectId acImgDctID = RasterImageDef.GetImageDictionary(acCurDb); // Check to see if the dictionary does not exist, it not then create it if (acImgDctID.IsNull) { acImgDctID = RasterImageDef.CreateImageDictionary(acCurDb); } // Open the image dictionary DBDictionary acImgDict = acTrans.GetObject(acImgDctID, OpenMode.ForRead) as DBDictionary; ReadMapData(); //创建世界地图的边缘矩形 Document doc = Application.DocumentManager.MdiActiveDocument; Database db = doc.Database; BlockTable bt = acTrans.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable; BlockTableRecord btr = acTrans.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord; double worldWidth = AllMap[CurrentWorldMap].width; double worldHeight = AllMap[CurrentWorldMap].height; Point2d p1 = new Point2d(0, 0); Point2d p2 = new Point2d(worldWidth, 0); Point2d p3 = new Point2d(worldWidth, worldHeight); Point2d p4 = new Point2d(0, worldHeight); Autodesk.AutoCAD.DatabaseServices.Polyline RectPoly = new Autodesk.AutoCAD.DatabaseServices.Polyline(); RectPoly.AddVertexAt(0, p1, 0, 0, 0); RectPoly.AddVertexAt(1, p2, 0, 0, 0); RectPoly.AddVertexAt(2, p3, 0, 0, 0); RectPoly.AddVertexAt(3, p4, 0, 0, 0); RectPoly.Closed = true; WorldEdgeRect = btr.AppendEntity(RectPoly); acTrans.AddNewlyCreatedDBObject(RectPoly, true); //Line line1 = new Line() { StartPoint = new Point3d(0, 0, 0), EndPoint = new Point3d(worldWidth, 0, 0) }; //Line line2 = new Line() { StartPoint = new Point3d(0, worldWidth, 0), EndPoint = new Point3d(worldWidth, worldHeight, 0) }; //Line line3 = new Line() { StartPoint = new Point3d(worldWidth, worldHeight, 0), EndPoint = new Point3d(0, worldHeight, 0) }; //Line line4 = new Line() { StartPoint = new Point3d(0, worldHeight, 0), EndPoint = new Point3d(0, 0, 0) }; //btr.AppendEntity(line1); //btr.AppendEntity(line2); //btr.AppendEntity(line3); //btr.AppendEntity(line4); //acTrans.AddNewlyCreatedDBObject(line1, true); //acTrans.AddNewlyCreatedDBObject(line2, true); //acTrans.AddNewlyCreatedDBObject(line3, true); //acTrans.AddNewlyCreatedDBObject(line4, true); //Entity ent1 = (Entity)line1; //Entity ent2 = (Entity)line2; //Entity ent3 = (Entity)line3; //Entity ent4 = (Entity)line4; //Group group = new Group(); //group.Append(ent1.ObjectId); //group.Append(ent2.ObjectId); //group.Append(ent3.ObjectId); //group.Append(ent4.ObjectId); //DBDictionary groupdic = acTrans.GetObject(db.GroupDictionaryId, OpenMode.ForWrite) as DBDictionary; //group.Selectable = true; //group.Name = "mapEdge"; //groupdic.SetAt(group.Name, group); //acTrans.AddNewlyCreatedDBObject(group, true); //~创建世界地图的边缘矩形 foreach (var iter in AllMap[WolrdMapName].maps[layer]) { string strImgName = iter.MapName; string strFileName = mapDir + "\\" + iter.MapName + "\\" + layer + ".png"; if (acImgDict.Contains(strImgName)) { acImgDefId = acImgDict.GetAt(strImgName); acRasterDef = acTrans.GetObject(acImgDefId, OpenMode.ForWrite) as RasterImageDef; } else { // Create a raster image definition RasterImageDef acRasterDefNew = new RasterImageDef(); // Set the source for the image file acRasterDefNew.SourceFileName = strFileName; // Load the image into memory acRasterDefNew.Load(); // Add the image definition to the dictionary acImgDict.UpgradeOpen(); acImgDefId = acImgDict.SetAt(strImgName, acRasterDefNew); acTrans.AddNewlyCreatedDBObject(acRasterDefNew, true); acRasterDef = acRasterDefNew; bRasterDefCreated = true; } // Open the Block table for read BlockTable acBlkTbl; acBlkTbl = acTrans.GetObject(acCurDb.BlockTableId, OpenMode.ForRead) as BlockTable; // Open the Block table record Model space for write BlockTableRecord acBlkTblRec; acBlkTblRec = acTrans.GetObject(acBlkTbl[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord; // Create the new image and assign it the image definition using (RasterImage acRaster = new RasterImage()) { acRaster.ImageDefId = acImgDefId; //image = acRaster; // Use ImageWidth and ImageHeight to get the size of the image in pixels (1024 x 768). // Use ResolutionMMPerPixel to determine the number of millimeters in a pixel so you // can convert the size of the drawing into other units or millimeters based on the // drawing units used in the current drawing. // Define the width and height of the image Vector3d width; Vector3d height; // Check to see if the measurement is set to English (Imperial) or Metric units //if (acCurDb.Measurement == MeasurementValue.English) //{ //width = new Vector3d((acRasterDef.ResolutionMMPerPixel.X * acRaster.ImageWidth) / 25.4, 0, 0); //height = new Vector3d(0, (acRasterDef.ResolutionMMPerPixel.Y * acRaster.ImageHeight) / 25.4, 0); //} //else //{ if (iter.width < 0) { iter.width = acRaster.ImageWidth; } if (iter.height < 0) { iter.height = acRaster.ImageHeight; } if (iter.x < 0) { iter.x = 0; } if (iter.y < 0) { iter.y = 0; } width = new Vector3d(iter.width, 0, 0); height = new Vector3d(0, iter.height, 0); //} // Define the position for the image Point3d insPt = new Point3d(iter.x, iter.y, 0.0); // Define and assign a coordinate system for the image's orientation CoordinateSystem3d coordinateSystem = new CoordinateSystem3d(insPt, width, height); acRaster.Orientation = coordinateSystem; // Set the rotation angle for the image acRaster.Rotation = 0; // Add the new object to the block table record and the transaction iter.ID = acBlkTblRec.AppendEntity(acRaster); acTrans.AddNewlyCreatedDBObject(acRaster, true); // Connect the raster definition and image together so the definition // does not appear as "unreferenced" in the External References palette. RasterImage.EnableReactors(true); acRaster.AssociateRasterDef(acRasterDef); if (bRasterDefCreated) { acRasterDef.Dispose(); } } } // Save the new object to the database acTrans.Commit(); // Dispose of the transaction } }
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(); } }
private static RasterImage CreateRasterImage(string uri, double sz) { Document doc = Application.DocumentManager.MdiActiveDocument; Editor ed = doc.Editor; Database db = doc.Database; Transaction tr = db.TransactionManager.StartTransaction(); using (tr) { // Get the image dictionary's ID, if it already exists ObjectId dictId = RasterImageDef.GetImageDictionary(db); if (dictId.IsNull) // If it doesn't, create a new one { dictId = RasterImageDef.CreateImageDictionary(db); } // Open the image dictionary DBDictionary dict = (DBDictionary)tr.GetObject(dictId, OpenMode.ForRead); // Get a unique record name for our raster image definition int i = 0; string defName = APPLICATION_PREFIX + i.ToString(); while (dict.Contains(defName)) { i++; defName = APPLICATION_PREFIX + i.ToString(); } RasterImageDef rid = new RasterImageDef(); try { // Set its source image and load it rid.SourceFileName = uri; rid.Load(); } catch { ed.WriteMessage( "\nUnable to create image object. " + "Here is the URL to the image: {0}", uri ); System.Diagnostics.Process.Start(uri); return(null); } // Put the definition in the dictionary dict.UpgradeOpen(); ObjectId defId = dict.SetAt(defName, rid); // Let the transaction know about it tr.AddNewlyCreatedDBObject(rid, true); RasterImage ri = new RasterImage(); ri.ImageDefId = defId; // Resize ri.TransformBy(Matrix3d.Scaling(sz / 500.0, Point3d.Origin)); AppendEntityToCurrentSpace(ri); // Create a reactor between the RasterImage and the // RasterImageDef to avoid the "unreferenced" // warning in the XRef palette RasterImage.EnableReactors(true); ri.AssociateRasterDef(rid); tr.Commit(); return(ri); } }
private void InsertDownloadedImageToDocument(MapSource mapSource, AerialImageData imageData) { Editor ed = Application.DocumentManager.MdiActiveDocument.Editor; ed.WriteMessage("Image downloaded to: " + imageData.FileName + '\n'); Transaction tx = ed.Document.Database.TransactionManager.StartTransaction(); try { // Lock the document Application.DocumentManager.MdiActiveDocument.LockDocument(); // Get the document database Database dwg = Application.DocumentManager.MdiActiveDocument.Database; // Get the raster image dictionary id. // Create it if it's null. ObjectId imageDictId = RasterImageDef.GetImageDictionary(dwg); if (imageDictId.IsNull) { imageDictId = RasterImageDef.CreateImageDictionary(dwg); } // Open the image dictionary DBDictionary imageDict = tx.GetObject(imageDictId, OpenMode.ForWrite) as DBDictionary; // Get the image's name, i.e. Aerial for C:\Aerial.jpg string imageName = Path.GetFileName(imageData.FileName).Split('.')[0]; // Add the image to the dictionary, if it's not already present. RasterImageDef rasterImageDef; ObjectId imageDefId; bool rasterDefCreated = false; if (imageDict.Contains(imageName)) { // Get the image reference from the image dictionary. imageDefId = imageDict.GetAt(imageName); rasterImageDef = tx.GetObject(imageDefId, OpenMode.ForWrite) as RasterImageDef; } else { // Create the raster image definition RasterImageDef newImageDef = new RasterImageDef { SourceFileName = imageData.FileName }; // Load the image into the definition newImageDef.Load(); // Write the image to the image dictionary imageDict.UpgradeOpen(); imageDefId = imageDict.SetAt(imageName, newImageDef); // Notify the transaction of the change. tx.AddNewlyCreatedDBObject(newImageDef, true); rasterImageDef = newImageDef; rasterDefCreated = true; } // Open the block table to get the model space ID BlockTable bt = tx.GetObject(dwg.BlockTableId, OpenMode.ForRead) as BlockTable; // Open the block table record for the model space. BlockTableRecord btr = tx.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord; // Create the new image and assign it the image definition using (RasterImage image = new RasterImage()) { image.ImageDefId = imageDefId; // Get the scale for the image double width = DegreesToFeet(Math.Abs(imageData.SWCorner.lng - imageData.NECorner.lng)); double height = rasterImageDef.Size.Y * (width / rasterImageDef.Size.X); ed.WriteMessage($"Using {width} for width, and {height} for height.\n"); PromptKeywordOptions promptInsPtOpt = new PromptKeywordOptions("Select insert type [Origin/Real/Choose] <O> : ", "Origin Real Choose"); PromptResult promptInsPtOptRes = ed.GetKeywords(promptInsPtOpt); // Insert the image at the reference point Point3d?insertPt = null; if (promptInsPtOptRes.Status == PromptStatus.OK) { switch (promptInsPtOptRes.StringResult) { case "Real": insertPt = new Point3d(DegreesToFeet(imageData.SWCorner.lat), DegreesToFeet(imageData.SWCorner.lng), 0); break; case "Choose": PromptPointOptions insertPtOptions = new PromptPointOptions("Select insert point : "); PromptPointResult insertPtRes = ed.GetPoint(insertPtOptions); if (insertPtRes.Status == PromptStatus.OK) { insertPt = insertPtRes.Value; } break; } } if (insertPt == null) { insertPt = new Point3d(0, 0, 0); } // Create the coordinate system to define the width and height. // Otherwise, they will default to the image size in pixels. image.Orientation = new CoordinateSystem3d(insertPt.Value, new Vector3d(width, 0, 0), new Vector3d(0, height, 0)); // Set the rotation angle for the image. image.Rotation = 0; // Add the new object to the block table (must come before adding extension dict!) btr.AppendEntity(image); // Add the extension dictionary with associated image data. if (image.ExtensionDictionary.IsNull) { image.CreateExtensionDictionary(); } DBDictionary extDict = tx.GetObject(image.ExtensionDictionary, OpenMode.ForWrite) as DBDictionary; // Create the Xrecord and result buffer with TypedValue array Xrecord record = new Xrecord(); record.Data = new ResultBuffer(new TypedValue[] { new TypedValue((int)DxfCode.Real, imageData.Center.lat), new TypedValue((int)DxfCode.Real, imageData.Center.lng), new TypedValue((int)DxfCode.Real, imageData.NECorner.lat), new TypedValue((int)DxfCode.Real, imageData.NECorner.lng), new TypedValue((int)DxfCode.Real, imageData.SWCorner.lat), new TypedValue((int)DxfCode.Real, imageData.SWCorner.lng), new TypedValue((int)DxfCode.Int32, imageData.Zoom), new TypedValue((int)DxfCode.Int32, (int)imageData.MapType), new TypedValue((int)DxfCode.Int32, (int)mapSource), }); extDict.SetAt("ImageData", record); // Add the new objects to the transaction tx.AddNewlyCreatedDBObject(image, true); tx.AddNewlyCreatedDBObject(record, true); // Connect the raster definition and image together so the definition // does not appear as "unreferenced" in the External References palette RasterImage.EnableReactors(true); image.AssociateRasterDef(rasterImageDef); if (rasterDefCreated) { rasterImageDef.Dispose(); } } tx.Commit(); // TODO: Zoom to aerial } catch (Exception ex) { ed.WriteMessage("An error occurred inserting the image: " + ex.Message + '\n'); ed.WriteMessage("Please try again.\n"); } finally { tx.Dispose(); } }
public static void SetOutlineCount() { // Get the current document and database Document acDoc = Application.DocumentManager.MdiActiveDocument; Database acCurrDb = acDoc.Database; Editor acEditor = acDoc.Editor; using (Transaction acTrans = acCurrDb.TransactionManager.StartTransaction()) { try { // Get object id of the JPP_App_Config_Data dictionary DBDictionary nod = acTrans.GetObject(acCurrDb.NamedObjectsDictionaryId, OpenMode.ForWrite) as DBDictionary; ObjectId JPPAppConfigDataId = nod.GetAt(JPP_App_Config_Params.JPP_APP_CONFIG_DATA); if (JPPAppConfigDataId == null) { acEditor.WriteMessage("\nJPP App dictionary doesn't exist in this drawing. Please run the FF command."); return; } DBDictionary JPPAppConfigData = acTrans.GetObject(JPPAppConfigDataId, OpenMode.ForRead) as DBDictionary; ObjectId xrecId = JPPAppConfigData.GetAt(JPP_App_Config_Params.JPP_APP_NEXT_BLOCK_INDEX); Xrecord xrec = acTrans.GetObject(xrecId, OpenMode.ForRead) as Xrecord; TypedValue[] xrecData = xrec.Data.AsArray(); Int16 nextOutlineIndex = Convert.ToInt16(xrecData[0].Value); // Now iterate around all the outline blocks in the drawing to find the highest index. BlockTable acBlkTbl = acTrans.GetObject(acCurrDb.BlockTableId, OpenMode.ForRead) as BlockTable; Int16 maxOutlineIndex = 0; foreach (ObjectId acBlkTblRecId in acBlkTbl) { BlockTableRecord acBlkTblRec = acTrans.GetObject(acBlkTblRecId, OpenMode.ForRead) as BlockTableRecord; if (acBlkTblRec.Name.StartsWith(JPP_App_Config_Params.JPP_APP_NEW_BLOCK_PREFIX)) { string indexStr = acBlkTblRec.Name.Substring(JPP_App_Config_Params.JPP_APP_NEW_BLOCK_PREFIX.Length); Int16 index = Convert.ToInt16(indexStr); if (index > maxOutlineIndex) { maxOutlineIndex = index; } } } // Compare the values of the max outline index and the next outline index. If the // next outline index != max outline index + 1 then set the next outline index to // max outline index + 1 if (nextOutlineIndex != maxOutlineIndex + 1) { Xrecord newXrec = new Xrecord(); newXrec.Data = new ResultBuffer(new TypedValue((int)DxfCode.Int16, (maxOutlineIndex + 1))); JPPAppConfigData.UpgradeOpen(); JPPAppConfigData.SetAt(JPP_App_Config_Params.JPP_APP_NEXT_BLOCK_INDEX, newXrec); acTrans.AddNewlyCreatedDBObject(newXrec, true); acTrans.Commit(); Autodesk.AutoCAD.ApplicationServices.Application.ShowAlertDialog( "The outline count has been set to " + Convert.ToString(maxOutlineIndex + 1)); } else { acTrans.Dispose(); Autodesk.AutoCAD.ApplicationServices.Application.ShowAlertDialog("The outline count is correct."); } } catch (Autodesk.AutoCAD.Runtime.Exception acException) { Autodesk.AutoCAD.ApplicationServices.Application.ShowAlertDialog ("The following exception was caught: \n" + acException.Message + "\nError creating setting outline count!\n"); acTrans.Abort(); return; } } }