// 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 ObjectId CreateEmployee(string name, string division, double salary, Point3d position) { var db = HostApplicationServices.WorkingDatabase; var blkId = CreateBlkDefinition(); ObjectId idIns = ObjectId.Null; using (var trans = db.TransactionManager.StartTransaction()) { var ins = new BlockReference(position, blkId); var curBtr = trans.GetObject(db.CurrentSpaceId, OpenMode.ForWrite) as BlockTableRecord; idIns = curBtr.AppendEntity(ins); trans.AddNewlyCreatedDBObject(ins, true); var empBlk = trans.GetObject(blkId, OpenMode.ForRead) as BlockTableRecord; foreach (var id in empBlk) { if (trans.GetObject(id, OpenMode.ForRead, false) is AttributeDefinition attDef) { var attRef = new AttributeReference(); attRef.SetPropertiesFrom(attDef); attRef.Position = position; attRef.Height = attDef.Height; attRef.Rotation = attDef.Rotation; attRef.Tag = attDef.Tag; attRef.TextString = name; attRef.HorizontalMode = attDef.HorizontalMode; attRef.VerticalMode = attDef.VerticalMode; attRef.AlignmentPoint = position; attRef.AdjustAlignment(db); ins.AttributeCollection.AppendAttribute(attRef); trans.AddNewlyCreatedDBObject(attRef, true); } } ins.CreateExtensionDictionary(); var extDict = trans.GetObject(ins.ExtensionDictionary, OpenMode.ForWrite) as DBDictionary; var data = new ResultBuffer( new TypedValue((int)DxfCode.Text, name), new TypedValue((int)DxfCode.Real, salary), new TypedValue((int)DxfCode.Text, division)); CreateXRecWithData(trans, extDict, "EmploeeInfo", data); trans.Commit(); } return(idIns); }
/// <summary> /// Inserts a block in the drawing. /// </summary> /// <param name="name">Name of the block to insert.</param> /// <param name="insertionPoint">Point where the block will be inserted.</param> /// <param name="attributes"></param> /// <returns></returns> public static BlockReference InsertBlockReference(string name, Point3d insertionPoint, string[] attributes, Transaction transaction) { BlockReference block = InsertBlockReference(name, insertionPoint, transaction); Database database = HostApplicationServices.WorkingDatabase; BlockTable blockTable = (BlockTable)transaction.GetObject(database.BlockTableId, OpenMode.ForRead); BlockTableRecord blockTableRecord = (BlockTableRecord)transaction.GetObject(blockTable[name], OpenMode.ForRead); AttributeReference attribute; AttributeDefinition attributeDefinition; int attributeIndex = 0; Entity entity; foreach (ObjectId id in blockTableRecord) { entity = (Entity)transaction.GetObject(id, OpenMode.ForWrite, false, true); if (entity.GetType() == typeof(AttributeDefinition)) { attributeDefinition = (AttributeDefinition)entity; attribute = new AttributeReference(); attribute.SetPropertiesFrom(attributeDefinition); attribute.Position = new Point3d(attributeDefinition.Position.X + block.Position.X, attributeDefinition.Position.Y + block.Position.Y, attribute.Position.Z + block.Position.Z); attribute.Height = attributeDefinition.Height; attribute.Rotation = attributeDefinition.Rotation; attribute.Tag = attributeDefinition.Tag; attribute.TextString = attributes[attributeIndex]; attributeIndex++; block.AttributeCollection.AppendAttribute(attribute); transaction.AddNewlyCreatedDBObject(attribute, true); } } return(block); }
/// <summary> /// /// * Insert Drawing As Block - DWG or DXF * /// the source drawig should be drawn as number of /// separate entites with or without attributes /// /// </summary> /// <param name="destinationDocument"></param> /// <param name="sourceDrawing"></param> /// <param name="insertionPoint"></param> /// <param name="transforMatrix"> </param> /// <exception cref="NotImplementedException">Not implemented for DXFs</exception> /// <returns>ObjectID of the Block Def that was imported.</returns> private void ReplaceBlockRefWithDWG(Document destinationDocument, string sourceDrawing, Point3d insertionPoint, Matrix3d transforMatrix) { Point3d oldPoint = insertionPoint.TransformBy(transforMatrix.Inverse()); insertionPoint = new Point3d(0, 0, 0); Database destinationDb = destinationDocument.Database; Editor ed = destinationDocument.Editor; string blockname = sourceDrawing.Remove(0, sourceDrawing.LastIndexOf("\\", StringComparison.Ordinal) + 1); blockname = blockname.Substring(0, blockname.Length - 4); // remove the extension using (destinationDocument.LockDocument()) { using (var inMemoryDb = new Database(false, true)) { if (sourceDrawing.LastIndexOf(".dwg", StringComparison.Ordinal) > 0) { inMemoryDb.ReadDwgFile(sourceDrawing, FileShare.ReadWrite, true, ""); } else if (sourceDrawing.LastIndexOf(".dxf", StringComparison.Ordinal) > 0) { throw new NotImplementedException("DXFs not suppported"); //inMemoryDb.DxfIn(string filename, string logFilename); } using (var transaction = destinationDocument.TransactionManager.StartTransaction()) { var destinationDatabaseBlockTable = (BlockTable) transaction.GetObject(destinationDb.BlockTableId, OpenMode.ForRead); ObjectId sourceBlockObjectId; if (destinationDatabaseBlockTable.Has(blockname)) { ed.WriteMessage("Block " + blockname + " already exists.\n Attempting to create block reference..."); var destinationDatabaseCurrentSpace = (BlockTableRecord) destinationDb.CurrentSpaceId.GetObject(OpenMode.ForWrite); var destinationDatabaseBlockDefinition = (BlockTableRecord) transaction.GetObject(destinationDatabaseBlockTable[blockname], OpenMode.ForRead); sourceBlockObjectId = destinationDatabaseBlockDefinition.ObjectId; // Create a block reference to the existing block definition using (var blockReference = new BlockReference(insertionPoint, sourceBlockObjectId)) { //Matrix3d Mat = Matrix3d.Identity; Vector3d mov = new Vector3d(oldPoint.X, oldPoint.Y, oldPoint.Z); mov = mov.TransformBy(transforMatrix); blockReference.TransformBy(transforMatrix); blockReference.TransformBy(Matrix3d.Displacement(mov)); blockReference.ScaleFactors = new Scale3d(1, 1, 1); destinationDatabaseCurrentSpace.AppendEntity(blockReference); transaction.AddNewlyCreatedDBObject(blockReference, true); ed.Regen(); transaction.Commit(); // At this point the Bref has become a DBObject and can be disposed } return; } // There is not such block definition, so we are inserting/creating new one sourceBlockObjectId = destinationDb.Insert(blockname, inMemoryDb, true); #region Create Block Ref from the already imported Block Def // We continue here the creation of the new block reference of the already imported block definition var sourceDatabaseCurrentSpace = (BlockTableRecord) destinationDb.CurrentSpaceId.GetObject(OpenMode.ForWrite); using (var blockReference = new BlockReference(insertionPoint, sourceBlockObjectId)) { blockReference.ScaleFactors = new Scale3d(1, 1, 1); sourceDatabaseCurrentSpace.AppendEntity(blockReference); transaction.AddNewlyCreatedDBObject(blockReference, true); var blockTableRecord = (BlockTableRecord) blockReference.BlockTableRecord.GetObject(OpenMode.ForRead); var atcoll = blockReference.AttributeCollection; foreach (ObjectId subid in blockTableRecord) { var entity = (Entity) subid.GetObject(OpenMode.ForRead); var attributeDefinition = entity as AttributeDefinition; if (attributeDefinition == null) { continue; } var attributeReference = new AttributeReference(); attributeReference.SetPropertiesFrom(attributeDefinition); attributeReference.Visible = attributeDefinition.Visible; attributeReference.SetAttributeFromBlock(attributeDefinition, blockReference.BlockTransform); attributeReference.HorizontalMode = attributeDefinition.HorizontalMode; attributeReference.VerticalMode = attributeDefinition.VerticalMode; attributeReference.Rotation = attributeDefinition.Rotation; attributeReference.Position = attributeDefinition.Position + insertionPoint.GetAsVector(); attributeReference.Tag = attributeDefinition.Tag; attributeReference.FieldLength = attributeDefinition.FieldLength; attributeReference.TextString = attributeDefinition.TextString; attributeReference.AdjustAlignment(destinationDb); atcoll.AppendAttribute(attributeReference); transaction.AddNewlyCreatedDBObject(attributeReference, true); } var mov = new Vector3d(oldPoint.X, oldPoint.Y, oldPoint.Z); mov = mov.TransformBy(transforMatrix); blockReference.TransformBy(transforMatrix); blockReference.TransformBy(Matrix3d.Displacement(mov)); transaction.Commit(); } #endregion ed.Regen(); } } } }
//This function creates a new BlockReference to the "EmployeeBlock" object, //and adds it to ModelSpace. public static ObjectId CreateEmployee(String name, String division, Double salary, Point3d pos) { 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(pos, CreateEmployeeDefinition()); // create a new attribute reference 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.GetType().FullName.Equals("Autodesk.AutoCAD.DatabaseServices.AttributeDefinition")) //We use .NET//s 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; } } btr.AppendEntity(br); //Add the reference to ModelSpace //Add the attribute reference to the block reference br.AttributeCollection.AppendAttribute(attRef); //let the transaction know trans.AddNewlyCreatedDBObject(attRef, true); 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, 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); trans.Commit(); //return the objectId of the employee block reference return(br.ObjectId); } finally { trans.Dispose(); } }
// 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 void Draw(string block, string Basislayer) { Database db = HostApplicationServices.WorkingDatabase; _AcDb.TransactionManager myTm = db.TransactionManager; Transaction myT = db.TransactionManager.StartTransaction(); Editor ed = Application.DocumentManager.MdiActiveDocument.Editor; ObjectContextManager conTextManager = db.ObjectContextManager; Dictionary <string, Point3d> _attPos = new Dictionary <string, Point3d>(); List <AttributeDefinition> _attDef = new List <AttributeDefinition>(); MyLayer objLayer = MyLayer.Instance; //objLayer.CheckLayer(Basislayer, true); try { using (DocumentLock dl = Application.DocumentManager.MdiActiveDocument.LockDocument()) { //Block in Zeichnung einfügen BlockTable bt = (BlockTable)myT.GetObject(db.BlockTableId, OpenMode.ForRead); BlockTableRecord btr = (BlockTableRecord)myT.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite); BlockTableRecord btrDef = (BlockTableRecord)myT.GetObject(bt[block], OpenMode.ForRead); //Attribute aus Blockdefinition übernehmen if (btrDef.HasAttributeDefinitions) { foreach (ObjectId id in btrDef) { DBObject obj = myT.GetObject(id, OpenMode.ForRead); try { AttributeDefinition ad = (AttributeDefinition)obj; if (ad != null) { _attPos.Add(ad.Tag, ad.Position); _attDef.Add(ad); } } catch { try { Entity ent = (Entity)obj; //Layer = ent.Layer; } catch { } } } } BlockReference blkRef = new BlockReference(_Pos3d, bt[block]) { ScaleFactors = new Scale3d(db.Cannoscale.Scale), Layer = Basislayer }; btr.AppendEntity(blkRef); //XData schreiben RegAppTable acRegAppTbl; acRegAppTbl = (RegAppTable)myT.GetObject(db.RegAppTableId, OpenMode.ForRead); if (!acRegAppTbl.Has(Global.Instance.AppName)) { using (RegAppTableRecord acRegAppTblRec = new RegAppTableRecord()) { acRegAppTblRec.Name = Global.Instance.AppName; acRegAppTbl.UpgradeOpen(); acRegAppTbl.Add(acRegAppTblRec); myT.AddNewlyCreatedDBObject(acRegAppTblRec, true); } } using (ResultBuffer rb = new ResultBuffer()) { rb.Add(new TypedValue((int)DxfCode.ExtendedDataRegAppName, Global.Instance.AppName)); rb.Add(new TypedValue((int)DxfCode.ExtendedDataWorldXCoordinate, _Pos3d)); if (_HöheOrg != null) { rb.Add(new TypedValue((int)DxfCode.ExtendedDataAsciiString, _HöheOrg)); } blkRef.XData = rb; rb.Dispose(); } myT.AddNewlyCreatedDBObject(blkRef, true); //Attribute befüllen if (_attPos != null) { string[] lsBasislayer = Basislayer.Split('-'); string Stammlayer = lsBasislayer[lsBasislayer.Length - 2]; for (int i = 0; i < _attPos.Count; i++) { AttributeReference _attRef = new AttributeReference(); _attRef.SetDatabaseDefaults(); _attRef.SetAttributeFromBlock(_attDef[i], Matrix3d.Identity); _attRef.SetPropertiesFrom(_attDef[i]); Point3d ptBase = new Point3d(blkRef.Position.X + _attRef.Position.X, blkRef.Position.Y + _attRef.Position.Y, blkRef.Position.Z + _attRef.Position.Z); _attRef.Position = ptBase; string attLayer = String.Empty; KeyValuePair <string, Point3d> keyValuePair = _attPos.ElementAt(i); switch (keyValuePair.Key) { case "number": _attRef.TextString = _PNum; _attRef.Layer = Stammlayer + Global.Instance.LayNummer; break; case "height": if (_HöheOrg != null) { _attRef.TextString = _HöheOrg; _attRef.Layer = Stammlayer + Global.Instance.LayHöhe; } break; case "date": _attRef.Layer = Stammlayer + "-Datum"; _attRef.Layer = Stammlayer + Global.Instance.LayDatum; break; case "code": _attRef.Layer = Stammlayer + "-Code"; _attRef.Layer = Stammlayer + Global.Instance.LayCode; break; case "owner": _attRef.Layer = Stammlayer + "-Hersteller"; break; default: break; } blkRef.AttributeCollection.AppendAttribute(_attRef); myT.AddNewlyCreatedDBObject(_attRef, true); } blkRef.Dispose(); } } } //Block aus Prototypzeichnung holen catch { } finally { myT.Commit(); myT.Dispose(); } }
public void draw(string block, string Basislayer) { Database db = HostApplicationServices.WorkingDatabase; Autodesk.AutoCAD.DatabaseServices.TransactionManager myTm = db.TransactionManager; Transaction myT = db.TransactionManager.StartTransaction(); Editor ed = Application.DocumentManager.MdiActiveDocument.Editor; ObjectContextManager conTextManager = db.ObjectContextManager; Dictionary <string, Point3d> _attPos = new Dictionary <string, Point3d>(); List <AttributeDefinition> _attDef = new List <AttributeDefinition>(); MyLayer objLayer = MyLayer.Instance; objLayer.CheckLayer(Basislayer, true); try { using (DocumentLock dl = Application.DocumentManager.MdiActiveDocument.LockDocument()) { //Block in Zeichnung einfügen Prototyp.Instance.Blockname = block; if (Prototyp.Instance.OK) { BlockTable bt = (BlockTable)myT.GetObject(db.BlockTableId, OpenMode.ForRead); BlockTableRecord btr = (BlockTableRecord)myT.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite); BlockTableRecord btrDef = (BlockTableRecord)myT.GetObject(bt[block], OpenMode.ForRead); //Attribute übernehmen if (btrDef.HasAttributeDefinitions) { foreach (ObjectId id in btrDef) { DBObject obj = myT.GetObject(id, OpenMode.ForRead); try { AttributeDefinition ad = (AttributeDefinition)obj; if (ad != null) { _attPos.Add(ad.Tag, ad.Position); _attDef.Add(ad); } } catch { try { Entity ent = (Entity)obj; //Layer = ent.Layer; } catch { } } } } BlockReference blkRef = new BlockReference(_Pos3d, bt[block]); blkRef.ScaleFactors = new Scale3d(db.Cannoscale.Scale); blkRef.Layer = Basislayer; btr.AppendEntity(blkRef); myT.AddNewlyCreatedDBObject(blkRef, true);; //Attribute befüllen if (_attPos != null) { for (int i = 0; i < _attPos.Count; i++) { AttributeReference _attRef = new AttributeReference(); _attRef.SetDatabaseDefaults(); _attRef.SetAttributeFromBlock(_attDef[i], Matrix3d.Identity); _attRef.SetPropertiesFrom(_attDef[i]); Point3d ptBase = new Point3d(blkRef.Position.X + _attRef.Position.X, blkRef.Position.Y + _attRef.Position.Y, blkRef.Position.Z + _attRef.Position.Z); _attRef.Position = ptBase; string Stammlayer = Basislayer.Substring(0, Basislayer.Length - 2); string attLayer = String.Empty; KeyValuePair <string, Point3d> keyValuePair = _attPos.ElementAt(i); switch (keyValuePair.Key) { case "number": _attRef.TextString = _PNum; break; case "height": if (_Höhe.HasValue) { _attRef.TextString = _Höhe.Value.ToString(); } break; default: break; } blkRef.AttributeCollection.AppendAttribute(_attRef); myT.AddNewlyCreatedDBObject(_attRef, true); } } } } } //Block aus Prototypzeichnung holen catch (Autodesk.AutoCAD.Runtime.Exception e) { } finally { myT.Commit(); myT.Dispose(); } }
/// <summary> /// Creates BlockReference from the block with the given name. /// Throws ArgumentException if block with such a name does not exist. /// </summary> /// <param name="blockName"></param> /// <param name="insertionPoint"></param> /// <param name="space">The model space or some of the paper spaces</param> /// <param name="blockTable">The block table of the associated drawing in the helper.</param> /// <returns>The BlockReference of the block</returns> private BlockReference CreateBlockReference(string blockName, UnitsValue sourceBlockMeasurementUnits, Point3d insertionPoint, BlockTableRecord space, BlockTable blockTable) { Matrix3d ucs = _ed.CurrentUserCoordinateSystem; BlockReference newBlockReference; //All open objects opened during a transaction are closed at the end of the transaction. using (Transaction transaction = _db.TransactionManager.StartTransaction()) { blockTable.UpgradeOpen(); // If the DWG already contains this block definition we will create a block reference and not a copy of the same definition if (!blockTable.Has(blockName)) { _logger.Error(MethodBase.GetCurrentMethod().DeclaringType.FullName + "." + MethodBase.GetCurrentMethod().Name + " : Block with name '" + blockName + "' does not exist."); transaction.Abort(); throw new ArgumentException("Block with name '" + blockName + "' does not exist."); } BlockTableRecord sourceBlockTableRecord = (BlockTableRecord)transaction.GetObject(blockTable[blockName], OpenMode.ForRead); newBlockReference = new BlockReference(insertionPoint, sourceBlockTableRecord.ObjectId); var converter = new MeasurementUnitsConverter(); var scaleFactor = converter.GetScaleRatio(sourceBlockMeasurementUnits, blockTable.Database.Insunits); _ed.CurrentUserCoordinateSystem = Matrix3d.Identity; newBlockReference.TransformBy(ucs); _ed.CurrentUserCoordinateSystem = ucs; newBlockReference.ScaleFactors = new Scale3d(scaleFactor); space.UpgradeOpen(); space.AppendEntity(newBlockReference); transaction.AddNewlyCreatedDBObject(newBlockReference, true); AttributeCollection atcoll = newBlockReference.AttributeCollection; foreach (ObjectId subid in sourceBlockTableRecord) { var entity = (Entity)subid.GetObject(OpenMode.ForRead); var attributeDefinition = entity as AttributeDefinition; if (attributeDefinition != null) { var attributeReference = new AttributeReference(); attributeReference.SetPropertiesFrom(attributeDefinition); attributeReference.Visible = attributeDefinition.Visible; attributeReference.SetAttributeFromBlock(attributeDefinition, newBlockReference.BlockTransform); attributeReference.HorizontalMode = attributeDefinition.HorizontalMode; attributeReference.VerticalMode = attributeDefinition.VerticalMode; attributeReference.Rotation = attributeDefinition.Rotation; attributeReference.Position = attributeDefinition.Position + insertionPoint.GetAsVector(); attributeReference.Tag = attributeDefinition.Tag; attributeReference.FieldLength = attributeDefinition.FieldLength; attributeReference.TextString = attributeDefinition.TextString; attributeReference.AdjustAlignment(_db); atcoll.AppendAttribute(attributeReference); transaction.AddNewlyCreatedDBObject(attributeReference, true); } } transaction.Commit(); } _ed.Regen(); return(newBlockReference); }
public ObjectId ImportDynamicBlockAndFillItsProperties(string dynamicBlockPath, Point3d basePoint, Hashtable dynamicBlockProperties, Hashtable dynamicBlockAttributes) { var resultingObjectId = new ObjectId(); var blockname = dynamicBlockPath.Remove(0, dynamicBlockPath.LastIndexOf("\\", StringComparison.Ordinal) + 1); blockname = blockname.Remove(blockname.LastIndexOf(".dwg", StringComparison.Ordinal)); using (_doc.LockDocument()) { using (var inMemoryDb = new Database(false, true)) { inMemoryDb.ReadDwgFile(dynamicBlockPath, System.IO.FileShare.Read, true, ""); using (var transaction = _doc.TransactionManager.StartTransaction()) { var blockTable = (BlockTable)transaction.GetObject(_db.BlockTableId, OpenMode.ForRead); AttributeCollection atcoll; if (blockTable.Has(blockname)) { var currentSpace = (BlockTableRecord)_db.CurrentSpaceId.GetObject(OpenMode.ForWrite); var newDynamicBlockDefinition = (BlockTableRecord)transaction.GetObject(blockTable[blockname], OpenMode.ForRead); // Create a block reference to the existing block definition var newBlockReference = new BlockReference(basePoint, newDynamicBlockDefinition.ObjectId); newBlockReference.TransformBy(Matrix3d.Identity); newBlockReference.ScaleFactors = new Scale3d(1, 1, 1); currentSpace.AppendEntity(newBlockReference); transaction.AddNewlyCreatedDBObject(newBlockReference, true); resultingObjectId = newBlockReference.ObjectId; using (var pc = newBlockReference.DynamicBlockReferencePropertyCollection) { foreach (DynamicBlockReferenceProperty prop in pc) { if (dynamicBlockProperties.ContainsKey(prop.PropertyName)) { prop.Value = dynamicBlockProperties[prop.PropertyName]; } } } var bref3 = (BlockReference)transaction.GetObject(newBlockReference.ObjectId, OpenMode.ForWrite); atcoll = bref3.AttributeCollection; foreach (var subid in newDynamicBlockDefinition) { var ent = (Entity)subid.GetObject(OpenMode.ForRead); var attDef = ent as AttributeDefinition; if (attDef == null) { continue; } var attRef = new AttributeReference(); attRef.SetPropertiesFrom(attDef); attRef.SetAttributeFromBlock(attDef, newBlockReference.BlockTransform); attRef.AdjustAlignment(_db); attRef.TextString = dynamicBlockAttributes.ContainsKey(attRef.Tag) ? dynamicBlockAttributes[attRef.Tag].ToString() : attDef.TextString; atcoll.AppendAttribute(attRef); transaction.AddNewlyCreatedDBObject(attRef, true); } transaction.Commit(); _ed.Regen(); return(resultingObjectId); } // There is not such block definition, so we are inserting/creating new one var sourceBlockId = _db.Insert(blockname, inMemoryDb, false); // We continue the creation of the new block definition of the sourceDWG var btrec = (BlockTableRecord)sourceBlockId.GetObject(OpenMode.ForRead); btrec.UpgradeOpen(); btrec.Name = blockname; btrec.DowngradeOpen(); var currentSpaceBlockTableRecord = (BlockTableRecord)_db.CurrentSpaceId.GetObject(OpenMode.ForWrite); // We have created the block definition up there, and now we create the block reference to this block definition var bref = new BlockReference(basePoint, sourceBlockId); currentSpaceBlockTableRecord.AppendEntity(bref); transaction.AddNewlyCreatedDBObject(bref, true); if (bref.IsDynamicBlock) { resultingObjectId = bref.ObjectId; using (var pc = bref.DynamicBlockReferencePropertyCollection) { try { foreach (DynamicBlockReferenceProperty prop in pc) { if (dynamicBlockProperties.ContainsKey(prop.PropertyName)) { prop.Value = dynamicBlockProperties[prop.PropertyName]; } } } catch (Exception exception) { _logger.Error("Error applying dynamic block properties.", exception); throw; } } } // Copy the attributes var btAttRec = (BlockTableRecord)bref.BlockTableRecord.GetObject(OpenMode.ForWrite); var bref2 = (BlockReference)transaction.GetObject(bref.ObjectId, OpenMode.ForWrite); atcoll = bref2.AttributeCollection; foreach (var subid in btAttRec) { var ent = (Entity)subid.GetObject(OpenMode.ForRead); var attDef = ent as AttributeDefinition; if (attDef == null) { continue; } var attRef = new AttributeReference(); attRef.SetPropertiesFrom(attDef); attRef.SetAttributeFromBlock(attDef, bref.BlockTransform); attRef.AdjustAlignment(_db); attRef.TextString = dynamicBlockAttributes.ContainsKey(attRef.Tag) ? dynamicBlockAttributes[attRef.Tag].ToString() : attDef.TextString; atcoll.AppendAttribute(attRef); transaction.AddNewlyCreatedDBObject(attRef, true); } transaction.Commit(); } _ed.Regen(); } } return(resultingObjectId); }
addBlockRef(string strName, Point3d pnt3dIns, double dblRotation, List <string> attValues) { Database db = BaseObjs._db; Editor ed = BaseObjs._editor; BlockTableRecord btrx = null; BlockReference br = null; try { using (Transaction tr = BaseObjs.startTransactionDb()) { BlockTable bt = (BlockTable)db.BlockTableId.GetObject(OpenMode.ForRead); if (!bt.Has(strName)) { btrx = addBtr(strName); } else { btrx = (BlockTableRecord)bt[strName].GetObject(OpenMode.ForRead); } //---> debug only foreach (ObjectId idObj in btrx) { Entity ent = (Entity)idObj.GetObject(OpenMode.ForRead); AttributeDefinition ad = ent as AttributeDefinition; if (ad != null) { ed.WriteMessage(string.Format("\n{0}", ad.Tag)); } }//<--- debug only //BlockTableRecord Btr = (BlockTableRecord)DB.CurrentSpaceId.GetObject(OpenMode.ForWrite); btrx.UpgradeOpen(); using (btrx) { br = new BlockReference(pnt3dIns, btrx.ObjectId); using (br) { Matrix3d ucsMatrix = ed.CurrentUserCoordinateSystem; CoordinateSystem3d ucs = ucsMatrix.CoordinateSystem3d; Matrix3d mat3d = new Matrix3d(); mat3d = Matrix3d.Rotation(dblRotation, ucs.Zaxis, pnt3dIns); br.TransformBy(mat3d); br.ScaleFactors = new Scale3d(1, 1, 1); btrx.AppendEntity(br); tr.AddNewlyCreatedDBObject(br, true); BlockTableRecord btratt = (BlockTableRecord)br.BlockTableRecord.GetObject(OpenMode.ForRead); using (btratt) { Autodesk.AutoCAD.DatabaseServices.AttributeCollection ATTcol = br.AttributeCollection; foreach (ObjectId subid in btratt) { Entity ent = (Entity)subid.GetObject(OpenMode.ForRead); AttributeDefinition ad = ent as AttributeDefinition; if (ad != null) { AttributeReference ar = new AttributeReference(); ar.SetPropertiesFrom(ad); ar.SetAttributeFromBlock(ad, br.BlockTransform); ar.Visible = ad.Visible; ar.HorizontalMode = ad.HorizontalMode; ar.VerticalMode = ad.VerticalMode; ar.Rotation = ad.Rotation; ar.TextStyleId = ad.TextStyleId; ar.Position = ad.Position + pnt3dIns.GetAsVector(); ar.Tag = ad.Tag; ar.FieldLength = ad.FieldLength; ar.AdjustAlignment(db); //if (ar.Tag == "TOPTXT") // ar.TextString = strTop; //if (ar.Tag == "MIDTXT") // ar.TextString = strMid; //if (ar.Tag == "BOTTXT") // ar.TextString = strBot; ar.Position = ad.Position.TransformBy(br.BlockTransform); ATTcol.AppendAttribute(ar); tr.AddNewlyCreatedDBObject(ar, true); } } } br.DowngradeOpen(); } btrx.DowngradeOpen(); } tr.Commit(); } } catch (System.Exception ex) { BaseObjs.writeDebug(ex.Message + " Blocks.cs: line: 194"); } return(br); }
addBlockRef(string strName, string strTopNum, string strTopTxt, string strBotNum, string strBotTxt, Point3d pnt3dIns, double dblRotation) { Database DB = BaseObjs._db; Editor ED = BaseObjs._editor; ObjectId blkID = ObjectId.Null; BlockTableRecord Btrx = null; using (Transaction tr = BaseObjs.startTransactionDb()) { BlockTable BT = (BlockTable)DB.BlockTableId.GetObject(OpenMode.ForRead); if (!BT.Has(strName)) { blkID = insBlockRef(@"R:\Tset\Block\", "GradeTag.dwg"); Btrx = (BlockTableRecord)blkID.GetObject(OpenMode.ForRead); Btrx.UpgradeOpen(); Btrx.Name = "GradeTag"; Btrx.DowngradeOpen(); } else { Btrx = (BlockTableRecord)BT[strName].GetObject(OpenMode.ForRead); } //---> debug only foreach (ObjectId objID in Btrx) { Entity ENT = (Entity)objID.GetObject(OpenMode.ForRead); AttributeDefinition AD = ENT as AttributeDefinition; if (AD != null) { ED.WriteMessage(string.Format("\n{0}", AD.Tag)); } }//<--- debug only BlockTableRecord Btr = (BlockTableRecord)DB.CurrentSpaceId.GetObject(OpenMode.ForWrite); using (Btr) { BlockReference BR = new BlockReference(pnt3dIns, Btrx.ObjectId); using (BR) { Matrix3d UCSMatrix = ED.CurrentUserCoordinateSystem; CoordinateSystem3d UCS = UCSMatrix.CoordinateSystem3d; Matrix3d MAT3d = new Matrix3d(); MAT3d = Matrix3d.Rotation(dblRotation, UCS.Zaxis, pnt3dIns); BR.TransformBy(MAT3d); BR.ScaleFactors = new Scale3d(1, 1, 1); Btr.AppendEntity(BR); tr.AddNewlyCreatedDBObject(BR, true); BlockTableRecord Btratt = (BlockTableRecord)BR.BlockTableRecord.GetObject(OpenMode.ForRead); using (Btratt) { Autodesk.AutoCAD.DatabaseServices.AttributeCollection ATTcol = BR.AttributeCollection; foreach (ObjectId subID in Btratt) { Entity ENT = (Entity)subID.GetObject(OpenMode.ForRead); AttributeDefinition AD = ENT as AttributeDefinition; if (AD != null) { AttributeReference AR = new AttributeReference(); AR.SetPropertiesFrom(AD); AR.SetAttributeFromBlock(AD, BR.BlockTransform); AR.Visible = AD.Visible; AR.HorizontalMode = AD.HorizontalMode; AR.VerticalMode = AD.VerticalMode; AR.Rotation = AD.Rotation; AR.TextStyleId = AD.TextStyleId; AR.Position = AD.Position + pnt3dIns.GetAsVector(); AR.Tag = AD.Tag; AR.FieldLength = AD.FieldLength; AR.AdjustAlignment(DB); if (AR.Tag == "TOPNUM") { AR.TextString = strTopNum; } if (AR.Tag == "TOPTXT") { AR.TextString = strTopTxt; } if (AR.Tag == "BOTNUM") { AR.TextString = strBotNum; } if (AR.Tag == "BOTTXT") { AR.TextString = strBotTxt; } AR.Position = AD.Position.TransformBy(BR.BlockTransform); ATTcol.AppendAttribute(AR); tr.AddNewlyCreatedDBObject(AR, true); } // end if } //end foreach } BR.DowngradeOpen(); } Btr.DowngradeOpen(); } // BT.DowngradeOpen (); tr.Commit(); } return(true); }
//This function creates a new BlockReference to the "EmployeeBlock" object, //and adds it to ModelSpace. public static ObjectId CreateEmployee(String name, String division, Double salary, Point3d pos) { 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()); // create a new attribute reference 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.GetType().FullName.Equals("Autodesk.AutoCAD.DatabaseServices.AttributeDefinition")) //We use .NET//s 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; } } btr.AppendEntity(br); //Add the reference to ModelSpace //Add the attribute reference to the block reference br.AttributeCollection.AppendAttribute(attRef); //let the transaction know trans.AddNewlyCreatedDBObject(attRef, true); 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, 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); trans.Commit(); //return the objectId of the employee block reference return br.ObjectId; } }
/// <summary> /// Inserts a block in the drawing. /// </summary> /// <param name="name">Name of the block to insert.</param> /// <param name="insertionPoint">Point where the block will be inserted.</param> /// <param name="attributes"></param> /// <returns></returns> public static BlockReference InsertBlockReference(string name, Point3d insertionPoint, string[] attributes, Transaction transaction) { BlockReference block = InsertBlockReference(name, insertionPoint, transaction); Database database = HostApplicationServices.WorkingDatabase; BlockTable blockTable = (BlockTable)transaction.GetObject(database.BlockTableId, OpenMode.ForRead); BlockTableRecord blockTableRecord = (BlockTableRecord)transaction.GetObject(blockTable[name], OpenMode.ForRead); AttributeReference attribute; AttributeDefinition attributeDefinition; int attributeIndex = 0; Entity entity; foreach (ObjectId id in blockTableRecord) { entity = (Entity)transaction.GetObject(id, OpenMode.ForWrite, false, true); if (entity.GetType() == typeof(AttributeDefinition)) { attributeDefinition = (AttributeDefinition)entity; attribute = new AttributeReference(); attribute.SetPropertiesFrom(attributeDefinition); attribute.Position = new Point3d(attributeDefinition.Position.X + block.Position.X, attributeDefinition.Position.Y + block.Position.Y, attribute.Position.Z + block.Position.Z); attribute.Height = attributeDefinition.Height; attribute.Rotation = attributeDefinition.Rotation; attribute.Tag = attributeDefinition.Tag; attribute.TextString = attributes[attributeIndex]; attributeIndex++; block.AttributeCollection.AppendAttribute(attribute); transaction.AddNewlyCreatedDBObject(attribute, true); } } return block; }