protected AttributeReference AddAttrToBlockRef(BlockReference blRef, ObjectId idAttrDef, string textString) { using (var attrDef = idAttrDef.GetObject(OpenMode.ForRead, false, true) as AttributeDefinition) { var attrRef = new AttributeReference(); attrRef.SetAttributeFromBlock(attrDef, blRef.BlockTransform); attrRef.TextString = textString; blRef.AttributeCollection.AppendAttribute(attrRef); t.AddNewlyCreatedDBObject(attrRef, true); return attrRef; } }
public Handle InsertBlock(Transaction trans, string blockName, Point3d origin, double scale, double rotationDegrees, string layerName) { BlockTable bt = trans.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable; LayerTable lt = trans.GetObject(db.LayerTableId, OpenMode.ForRead) as LayerTable; if (!bt.Has(blockName)) { BlockDefinitionCreator bdc = new BlockDefinitionCreator(); bdc.CreateBlock(blockName); } if (!lt.Has(layerName)) { throw new ArgumentException("Layer doesn't exists."); } ObjectId btObjectId = bt[blockName]; if (btObjectId != ObjectId.Null) { BlockReference blockRef = new BlockReference(origin, btObjectId); blockRef.Rotation = rotationDegrees * Math.PI / 180; blockRef.TransformBy(Matrix3d.Scaling(scale, origin)); blockRef.Layer = layerName; BlockTableRecord currentSpaceId = trans.GetObject(db.CurrentSpaceId, OpenMode.ForWrite) as BlockTableRecord; currentSpaceId.AppendEntity(blockRef); trans.AddNewlyCreatedDBObject(blockRef, true); BlockTableRecord btr = trans.GetObject(btObjectId, OpenMode.ForRead) as BlockTableRecord; if (btr.HasAttributeDefinitions) { foreach (ObjectId atId in btr) { Entity ent = trans.GetObject(atId, OpenMode.ForRead) as Entity; if (ent is AttributeDefinition) { AttributeDefinition atd = ent as AttributeDefinition; AttributeReference atr = new AttributeReference(); atr.SetAttributeFromBlock(atd, blockRef.BlockTransform); blockRef.AttributeCollection.AppendAttribute(atr); trans.AddNewlyCreatedDBObject(atr, true); } } } return blockRef.ObjectId.Handle; } else { return new Handle(); } }
public long MapPosition(long pos) { if (_attribute.IsNonResident) { return ((IMappedBuffer)_attribute.RawBuffer).MapPosition(pos); } else { AttributeReference attrRef = new AttributeReference(_file.MftReference, _attribute.PrimaryRecord.AttributeId); ResidentAttributeRecord attrRecord = (ResidentAttributeRecord)_file.GetAttribute(attrRef).PrimaryRecord; long attrStart = _file.GetAttributeOffset(attrRef); long mftPos = attrStart + attrRecord.DataOffset + pos; return _file.Context.GetFileByIndex(MasterFileTable.MftIndex).GetAttribute(AttributeType.Data, null).OffsetToAbsolutePos(mftPos); } }
public bool ReplaceExtent(AttributeReference oldRef, AttributeReference newRef, AttributeRecord record) { if (!_extents.Remove(oldRef)) { return false; } else { if (oldRef.Equals(Reference) || _extents.Count == 0) { _record = record; _containingFile = newRef.File; } _extents.Add(newRef, record); return true; } }
/// <summary> /// Добавление атрибутов к вставке блока /// </summary> public static void AddAttributes(BlockReference blRef, BlockTableRecord btrBl, Transaction t) { foreach (ObjectId idEnt in btrBl) { if (idEnt.ObjectClass.Name == "AcDbAttributeDefinition") { var atrDef = t.GetObject(idEnt, OpenMode.ForRead) as AttributeDefinition; if (!atrDef.Constant) { using (var atrRef = new AttributeReference()) { atrRef.SetAttributeFromBlock(atrDef, blRef.BlockTransform); //atrRef.TextString = atrDef.TextString; blRef.AttributeCollection.AppendAttribute(atrRef); t.AddNewlyCreatedDBObject(atrRef, true); } } } } }
private AttributeReference addAttrToBlockCross(BlockReference blRefCross, string num) { if (blRefCross == null) { return null; } AttributeReference attrRefCross = null; if (!panelBase.Service.Env.IdAttrDefCross.IsNull) { using (var attrDefCross = panelBase.Service.Env.IdAttrDefCross.GetObject(OpenMode.ForRead, false, true) as AttributeDefinition) { attrRefCross = new AttributeReference(); attrRefCross.SetAttributeFromBlock(attrDefCross, blRefCross.BlockTransform); attrRefCross.TextString = num; blRefCross.AttributeCollection.AppendAttribute(attrRefCross); t.AddNewlyCreatedDBObject(attrRefCross, true); } } return attrRefCross; }
public static void DrawVolumesTableInBlock(decimal[] decVolumesArray/*, Point3d tablePosition */) { if (decVolumesArray == null) { AcVolShowForm(); return; } string tableLayerName = "acVlm_Таблицы объемов"; CreateLayer(tableLayerName, true, false); string tableAttributeLayerName = "acVlm_Invisible Layers"; CreateLayer(tableAttributeLayerName, false, true); Document acDoc = Application.DocumentManager.MdiActiveDocument; //Текущий документ. //Editor acDocEd = acDoc.Editor; // Editor текущего документа. Database acDocDb = acDoc.Database; // Database текущего документа. using (acDoc.LockDocument()) // блокировка документа { // начинаем транзакцию using (Transaction acTrans = acDocDb.TransactionManager.StartTransaction()) { //*** // ШАГ 0 - запрос ПК поперечника и его распознание //*** double doublePk = ParcePk(SelectPk("Укажите ПК поперечного профиля:")); if (doublePk < 0) { MessageBox.Show("Пикет не распознан или выбор пикета отменен!\nТаблица объемов не будет привязана к пикету и не будет учитываться при экспорте объемов в Excel.", myCommands.msgBoxCaption_acVolume, MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } //*** //ШАГ 1 - создаем таблицу и заполняем ее //*** Table objTable = new Table(); int tableColNumber = 3; int tableRowNumber = _form.listBoxLayers.Items.Count + 1;// количество слоев +1 строка на заголовок таблицы objTable.SetSize(tableRowNumber, tableColNumber); Point3d tablePosition = GetUserPoint("Укажите точку вставки таблицы:"); if (tablePosition == new Point3d(2147483647, 2147483647, 2147483647)) { acTrans.Abort(); AcVolShowForm(); return; } objTable.Position = tablePosition; //создаем массив значений для таблицы включая заголовки. string[,] strTableArray = new string[tableRowNumber, tableColNumber]; //Записываем в массив заголовки strTableArray[0, 0] = "Наименование"; strTableArray[0, 1] = "Ед.Изм."; strTableArray[0, 2] = "Значение"; //Записываем в массив Имя объема, Ед.Изм и значение объема и так для каждого объема из лист бокса for (int rowNumber = 1; rowNumber < tableRowNumber; rowNumber++) { strTableArray[rowNumber, 0] = (string)_form.listBoxLayers.Items[rowNumber - 1]; strTableArray[rowNumber, 1] = (string)_form.listBoxLayersUnits.Items[rowNumber - 1]; strTableArray[rowNumber, 2] = Convert.ToString(Math.Round(decVolumesArray[rowNumber - 1], 2), CultureInfo.InvariantCulture); } // Заполняем таблицу значениями из массива String[,] strTableArray for (int rowNumber = 0; rowNumber < tableRowNumber; rowNumber++) { for (int colNumber = 0; colNumber < tableColNumber; colNumber++) { objTable.Cells[rowNumber, colNumber].TextHeight = 2.5; switch (colNumber) { case 0: objTable.Columns[colNumber].Width = 60; break; case 1: objTable.Columns[colNumber].Width = 15; break; case 2: objTable.Columns[colNumber].Width = 20; break; } objTable.Rows[rowNumber].Height = 8; if (colNumber == 0 & rowNumber > 0) { objTable.Cells[rowNumber, colNumber].Alignment = CellAlignment.MiddleLeft; } else { objTable.Cells[rowNumber, colNumber].Alignment = CellAlignment.MiddleCenter; } objTable.Cells[rowNumber, colNumber].SetValue(strTableArray[rowNumber, colNumber], ParseOption.ParseOptionNone); } } // задаем слой таблице objTable.Layer = tableLayerName; //*** // если ПК распознан, то создаем блок, помещаем таблицу в блок и присваиваем атрибут "ПК" //*** if (doublePk >= 0) { string pk = Convert.ToString(doublePk, CultureInfo.InvariantCulture); // имя создаваемого блока string objTableBlockName = "acVlm_" + Convert.ToString((DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds, CultureInfo.InvariantCulture); // открываем таблицу блоков на чтение BlockTable blockTable = (BlockTable)acTrans.GetObject(acDocDb.BlockTableId, OpenMode.ForRead); // вначале проверяем, нет ли в таблице блока с таким именем // если есть - выводим сообщение об ошибке и заканчиваем выполнение команды if (blockTable.Has(objTableBlockName)) { MessageBox.Show("A block with the name \"" + objTableBlockName + "\" already exists.", myCommands.msgBoxCaption_acVolume, MessageBoxButtons.OK, MessageBoxIcon.Error); return; } // создаем новое определение блока, задаем ему имя BlockTableRecord objBtr = new BlockTableRecord { Name = objTableBlockName }; blockTable.UpgradeOpen(); //переоткрываем blockTable на запись. // добавляем созданное определение блока в таблицу блоков и в транзакцию, // запоминаем ID созданного определения блока (оно пригодится чуть позже) ObjectId objBtrId = blockTable.Add(objBtr); acTrans.AddNewlyCreatedDBObject(objBtr, true); //добавляем таблицу в блок и в транзацию objBtr.AppendEntity(objTable); acTrans.AddNewlyCreatedDBObject(objTable, true); // создаем определение аттрибута AttributeDefinition objAttribute = new AttributeDefinition { Position = new Point3d(0, 0, 0), Tag = "ПК", Layer = tableAttributeLayerName }; // добавляем атрибут в блок и в транзакцию objBtr.AppendEntity(objAttribute); acTrans.AddNewlyCreatedDBObject(objAttribute, true); //*** // добавляем вхождение созданного блока на чертеж //*** var acBtr = acTrans.GetObject(acDocDb.CurrentSpaceId, OpenMode.ForWrite) as BlockTableRecord; // создаем новое вхождение блока, используя ранее сохраненный ID определения блока BlockReference objBlockReference = new BlockReference(Point3d.Origin, objBtrId) { Layer = tableLayerName }; // добавляем созданное вхождение блока на пространство чертежа и в транзакцию if (acBtr != null) acBtr.AppendEntity(objBlockReference); acTrans.AddNewlyCreatedDBObject(objBlockReference, true); // задаем значение аттрибута AttributeReference objAttributeReference = new AttributeReference(); objAttributeReference.SetAttributeFromBlock(objAttribute, objBlockReference.BlockTransform); objAttributeReference.TextString = pk; objAttributeReference.Layer = tableAttributeLayerName; objBlockReference.AttributeCollection.AppendAttribute(objAttributeReference); acTrans.AddNewlyCreatedDBObject(objAttributeReference, true); } //*** // если ПК _НЕ_распознан, то помещаем таблицу на чертеж без создания блока с выводом предупреждения //*** else { var acBtr = acTrans.GetObject(acDocDb.CurrentSpaceId, OpenMode.ForWrite) as BlockTableRecord; if (acBtr != null) acBtr.AppendEntity(objTable); acTrans.AddNewlyCreatedDBObject(objTable, true); } // фиксируем транзакцию acTrans.Commit(); AcVolShowForm(); } } }
public void ListAttributes() { var ed = Application.DocumentManager.MdiActiveDocument.Editor; var doc = Application.DocumentManager.MdiActiveDocument; try { var acDB = doc.Database; using (var trans = acDB.TransactionManager.StartTransaction()) { DBDictionary layoutPages = (DBDictionary)trans.GetObject(acDB.LayoutDictionaryId, OpenMode.ForRead); // Handle Corner Record meta data dictionary extracted from Properties and Content Dictionary <String, object> cornerRecordForms = new Dictionary <string, object>(); CivilDB.CogoPointCollection cogoPointsColl = CivilDB.CogoPointCollection.GetCogoPoints(doc.Database); var cogoPointCollected = CogoPointJson.geolocationCapture(cogoPointsColl); List <string> layoutNamesList = new List <string>(); foreach (DBDictionaryEntry layoutPage in layoutPages) { var crFormItems = layoutPage.Value.GetObject(OpenMode.ForRead) as Layout; var isModelSpace = crFormItems.ModelType; ObjectIdCollection textObjCollection = new ObjectIdCollection(); Dictionary <String, String> crAttributes = new Dictionary <String, String>(); if (isModelSpace != true) { BlockTableRecord blkTblRec = trans.GetObject(crFormItems.BlockTableRecordId, OpenMode.ForRead) as BlockTableRecord; layoutNamesList.Add(crFormItems.LayoutName.Trim().ToString().ToLower().Replace(" ", "")); foreach (ObjectId blkId in blkTblRec) { textObjCollection.Add(blkId); var blkRef = trans.GetObject(blkId, OpenMode.ForRead) as BlockReference; if (blkRef != null && blkRef.IsDynamicBlock) { //ed.WriteMessage("\nBlock: " + blkRef.Name); //btr.Dispose(); AttributeCollection attCol = blkRef.AttributeCollection; foreach (ObjectId attId in attCol) { AttributeReference attRef = (AttributeReference)trans.GetObject(attId, OpenMode.ForRead); //ed.WriteMessage("\nAttribute Tag: {0} \nAttribute String: {1}", attRef.Tag.ToString(), attRef.TextString.ToString()); if (attRef.Tag.ToString() == "CITY_NAME") { crAttributes.Add("CRCity_c", attRef.TextString.ToString()); } else if (attRef.Tag.ToString() == "LEGAL_DESCRIPTION") { crAttributes.Add("Corner_Type_c", "Lot"); crAttributes.Add("Legal_Description_c", attRef.TextString.ToString()); } } } } // Build Final JSON File with LayoutName and Attributes cornerRecordForms.Add(crFormItems.LayoutName.Trim().ToString().ToLower().Replace(" ", ""), crAttributes); } } // Checks to see whether the points from the cogo point collection exist within // the layout by searching for the correct collection key and layout name List <string> cogoPointCollectedCheck = cogoPointCollected.Keys.ToList(); List <bool> boolCheckResults = new List <bool>(); IEnumerable <string> cogoPointNameCheck = layoutNamesList.Except(cogoPointCollectedCheck); List <string> cogoPointNameCheckResults = cogoPointNameCheck.ToList(); var layoutNameChecker = new Regex("^(\\s*cr\\s*\\d\\d*)$"); if (!cogoPointNameCheckResults.Where(f => layoutNameChecker.IsMatch(f)).ToList().Any()) { boolCheckResults.Add(true); } else { foreach (string cogoPointNameResultItem in cogoPointNameCheckResults) { Match layoutNameMatch = Regex.Match(cogoPointNameResultItem, "^(\\s*cr\\s*\\d\\d*)$", RegexOptions.IgnoreCase); if (layoutNameMatch.Success) { string layoutNameX = layoutNameMatch.Value; ed.WriteMessage("\nLayout Named {0} does not have an associated cogo point", layoutNameX); } } boolCheckResults.Add(false); } IEnumerable <string> layoutNameCheck = cogoPointCollectedCheck.Except(layoutNamesList); List <string> layoutNameCheckResults = layoutNameCheck.ToList(); var cogoNameChecker = new Regex("^(\\s*cr\\s*\\d\\d*)$"); // If the layout name has any value other than CR == PASS // If CR point exists and does not match then throw an error for user to fix if (!layoutNameCheckResults.Where(f => cogoNameChecker.IsMatch(f)).ToList().Any()) { boolCheckResults.Add(true); } else // Found a CR point that DID NOT match a layout name { foreach (string layoutNameCheckResultItem in layoutNameCheckResults) { Match cogoNameMatch = Regex.Match(layoutNameCheckResultItem, "^(\\s*cr\\s*\\d\\d*)$", RegexOptions.IgnoreCase); if (cogoNameMatch.Success) { string cogoNameX = cogoNameMatch.Value; ed.WriteMessage("\nCorner Record point named {0} does not have an associated Layout", cogoNameX); } } boolCheckResults.Add(false); } // Output JSON file to BIN folder // IF there are two true booleans in the list then add the data to the corresponding keys (cr1 => cr1) if ((boolCheckResults.Count(v => v == true)) == 2) { foreach (string cornerRecordFormKey in cornerRecordForms.Keys) { if (cogoPointCollected.ContainsKey(cornerRecordFormKey)) { //ed.WriteMessage("WORKS FOR {0}", cornerRecordFormKey); var cogoFinal = (Dictionary <string, string>)cornerRecordForms[cornerRecordFormKey]; //var cogoFinalType = ((Dictionary<string, string>)cogoPointCollected[cornerRecordFormKey])["Corner_Type_c"]; var cogoFinalLong = ((Dictionary <string, object>)cogoPointCollected[cornerRecordFormKey]) ["Geolocation_Longitude_s"]; var cogoFinalLat = ((Dictionary <string, object>)cogoPointCollected[cornerRecordFormKey]) ["Geolocation_Latitude_s"]; //cogoFinal.Add("Corner_Type_c", cogoFinalType); cogoFinal.Add("Geolocation_Longitude_s", cogoFinalLong.ToString()); cogoFinal.Add("Geolocation_Latitude_s", cogoFinalLat.ToString()); } } using (var writer = File.CreateText("CornerRecordForms.json")) { string strResultJson = JsonConvert.SerializeObject(cornerRecordForms, Formatting.Indented); writer.WriteLine(strResultJson); } } trans.Commit(); } } catch (Autodesk.AutoCAD.Runtime.Exception ex) { ed.WriteMessage(("Exception: " + ex.Message)); } }
internal void RemoveAttributeExtent(AttributeReference extentRef) { FileRecord fileRec = _context.Mft.GetRecord(extentRef.File); if (fileRec != null) { fileRec.RemoveAttribute(extentRef.AttributeId); } if (fileRec.Attributes.Count == 0) { _context.Mft.RemoveRecord(extentRef.File); } }
/// <summary> /// Retreive all text data from dwg file and store them in CADModels /// @CreatBridgeForRevit2018 /// </summary> public static List <CADTextModel> GetCADText(string dwgPath) { List <CADTextModel> listCADModels = new List <CADTextModel>(); using (new Services()) { using (Database database = new Database(false, false)) { database.ReadDwgFile(dwgPath, FileShare.Read, true, ""); using (var trans = database.TransactionManager.StartTransaction()) { using (BlockTable table = (BlockTable)database.BlockTableId.GetObject(OpenMode.ForRead)) { using (SymbolTableEnumerator enumerator = table.GetEnumerator()) { StringBuilder sb = new StringBuilder(); while (enumerator.MoveNext()) { using (BlockTableRecord record = (BlockTableRecord)enumerator.Current.GetObject(OpenMode.ForRead)) { foreach (ObjectId id in record) { Entity entity = (Entity)id.GetObject(OpenMode.ForRead, false, false); CADTextModel model = new CADTextModel(); switch (entity.GetRXClass().Name) { case "AcDbText": DBText text = (DBText)entity; model.Location = ConverCADPointToRevitPoint(text.Position); model.Text = text.TextString; Debug.Print(model.Text); model.Angel = text.Rotation; model.Layer = text.Layer; listCADModels.Add(model); break; case "AcDbMText": MText mText = (MText)entity; model.Location = ConverCADPointToRevitPoint(mText.Location); model.Text = mText.Text; model.Angel = mText.Rotation; model.Layer = mText.Layer; listCADModels.Add(model); break; case "AcDbBlockReference": BlockReference br = (BlockReference)entity; AttributeCollection attcol = br.AttributeCollection; foreach (ObjectId attId in attcol) { AttributeReference attRef = (AttributeReference)trans.GetObject(attId, OpenMode.ForRead); if (IsLabel(attRef.TextString)) { model.Text = attRef.TextString; model.Location = ConverCADPointToRevitPoint(br.Position); model.Angel = br.Rotation; model.Layer = br.Layer; listCADModels.Add(model); } } break; } } } } } } } } } return(listCADModels); }
private void FindReplaceItem(Transaction tr, ObjectId id) { try { foreach (FindReplaceOptions item in options) { string replacedText = string.Empty; if (frText && id.ObjectClass.IsDerivedFrom(RXObject.GetClass(typeof(DBText)))) { // Single line text DBText text = (DBText)tr.GetObject(id, OpenMode.ForRead); if (GetReplacedText(item.Find, item.Replace, text.TextString, out replacedText)) { text.UpgradeOpen(); text.TextString = replacedText; } } else if (frText && id.ObjectClass.IsDerivedFrom(RXObject.GetClass(typeof(MText)))) { // Multiline text MText mtext = (MText)tr.GetObject(id, OpenMode.ForRead); if (GetReplacedText(item.Find, item.Replace, mtext.Contents, out replacedText)) { mtext.UpgradeOpen(); mtext.Contents = replacedText; } } else if (frDimension && id.ObjectClass.IsDerivedFrom(RXObject.GetClass(typeof(Dimension)))) { // Dimension text Dimension dimension = (Dimension)tr.GetObject(id, OpenMode.ForRead); if (GetReplacedText(item.Find, item.Replace, dimension.DimensionText, out replacedText)) { dimension.UpgradeOpen(); dimension.DimensionText = replacedText; } } else if (frLeader && id.ObjectClass.IsDerivedFrom(RXObject.GetClass(typeof(MLeader)))) { // Multileader MLeader leader = (MLeader)tr.GetObject(id, OpenMode.ForRead); if (leader.ContentType == ContentType.MTextContent) { if (GetReplacedText(item.Find, item.Replace, leader.MText.Contents, out replacedText)) { leader.UpgradeOpen(); leader.MText.Contents = replacedText; } } } else if (frAttribute && id.ObjectClass.IsDerivedFrom(RXObject.GetClass(typeof(BlockReference)))) { // Block attributes BlockReference blockRef = (BlockReference)tr.GetObject(id, OpenMode.ForRead); foreach (ObjectId attid in blockRef.AttributeCollection) { AttributeReference attRef = (AttributeReference)tr.GetObject(attid, OpenMode.ForRead); if (GetReplacedText(item.Find, item.Replace, attRef.TextString, out replacedText)) { attRef.UpgradeOpen(); attRef.TextString = replacedText; } } } else if (frTable && id.ObjectClass.IsDerivedFrom(RXObject.GetClass(typeof(Table)))) { // Table text Table table = (Table)tr.GetObject(id, OpenMode.ForWrite); for (int i = 0; i < table.Rows.Count; i++) { for (int j = 0; j < table.Columns.Count; j++) { if (GetReplacedText(item.Find, item.Replace, table.Cells[i, j].TextString, out replacedText)) { table.Cells[i, j].TextString = replacedText; } } } } } } catch (System.Exception ex) { OnError(ex); } }
internal long GetAttributeOffset(AttributeReference attrRef) { long recordOffset = _mft.GetRecordOffset(attrRef.File); FileRecord frs = GetFileRecord(attrRef.File); return recordOffset + frs.GetAttributeOffset(attrRef.AttributeId); }
//private bool checkBlockRefs(BlockTableRecord btrFrame, Transaction t) //{ // bool res = false; // var ms = t.GetObject(SymbolUtilityServices.GetBlockModelSpaceId(_db), OpenMode.ForRead) as BlockTableRecord; // foreach (ObjectId idEnt in ms) // { // if (idEnt.ObjectClass.Name == "AcDbBlockReference") // { // var blRef = t.GetObject(idEnt, OpenMode.ForRead, false, true) as BlockReference; // if (blRef.GetEffectiveName().Equals(_blFrameName, StringComparison.OrdinalIgnoreCase)) // { // // считывание атрибутов // var atrCol = blRef.AttributeCollection; // _attrs = new Dictionary<string, string>(); // foreach (ObjectId idAtrRef in atrCol) // { // var atrRef = t.GetObject(idAtrRef, OpenMode.ForRead, false, true) as AttributeReference; // string key = atrRef.Tag.ToUpper(); // if (!_attrs.ContainsKey(key)) // { // _attrs.Add(key, atrRef.TextString); // } // } // res = true; // } // } // } // return res; //} //private bool checkBtrFrame(BlockTableRecord btrFrame, Transaction t) //{ // bool res = false; // if (btrFrame.HasAttributeDefinitions) // { // Dictionary<string, string> attrsChecks = new Dictionary<string, string>(); // foreach (ObjectId idEnt in btrFrame) // { // if (idEnt.ObjectClass.Name == "AcDbAttributeDefinition") // { // var atrDef = t.GetObject(idEnt, OpenMode.ForRead, false, true) as AttributeDefinition; // switch (atrDef.Tag.ToUpper()) // { // case "ВИД": // attrsChecks.Add("ВИД", atrDef.TextString); // break; // case "НАИМЕНОВАНИЕ": // attrsChecks.Add("НАИМЕНОВАНИЕ", atrDef.TextString); // break; // case "ЛИСТ": // attrsChecks.Add("ЛИСТ", atrDef.TextString); // break; // default: // break; // } // } // } // if (attrsChecks.Count == 3) // { // res = true; // } // } // return res; //} private void updateBlRefFrame(BlockReference blRef, BlockTableRecord btrFrame, Transaction t, bool insertDescription) { // Обновление вхождения блока рамки if (!IsOk) return; // Удаление атрибутов foreach (ObjectId idAtrRef in blRef.AttributeCollection) { var atrRef = t.GetObject(idAtrRef, OpenMode.ForWrite, false, true) as AttributeReference; atrRef.Erase(true); } blRef.UpgradeOpen(); foreach (ObjectId idEnt in btrFrame) { if (idEnt.ObjectClass.Name == "AcDbAttributeDefinition") { var atrDef = t.GetObject(idEnt, OpenMode.ForRead, false, true) as AttributeDefinition; if (!atrDef.Constant) { if (!insertDescription && atrDef.Tag.Equals("ПРИМЕЧАНИЕ", StringComparison.OrdinalIgnoreCase)) { continue; } using (var atrRef = new AttributeReference()) { atrRef.SetAttributeFromBlock(atrDef, blRef.BlockTransform); string key = atrDef.Tag.ToUpper(); if (_attrs.ContainsKey(key)) { atrRef.TextString = _attrs[key]; } else { atrRef.TextString = atrDef.TextString; } blRef.AttributeCollection.AppendAttribute(atrRef); t.AddNewlyCreatedDBObject(atrRef, true); } } } } }
public void Generate() { Database acCurDb; acCurDb = Application.DocumentManager.MdiActiveDocument.Database; ObjectContextCollection occ = acCurDb.ObjectContextManager.GetContextCollection("ACDB_ANNOTATIONSCALES"); Transaction acTrans = acCurDb.TransactionManager.TopTransaction; //Centre line Curve c = acTrans.GetObject(ObjectId, OpenMode.ForRead) as Curve; //Offset it LayerTable acLyrTbl = acTrans.GetObject(acCurDb.LayerTableId, OpenMode.ForRead) as LayerTable; ObjectId current = acCurDb.Clayer; acCurDb.Clayer = acLyrTbl[Utilities.FoundationLayer]; // Open the Block table for read BlockTable acBlkTbl = acTrans.GetObject(acCurDb.BlockTableId, OpenMode.ForRead) as BlockTable; // Open the Block table record Model space for write BlockTableRecord acBlkTblRec = acTrans.GetObject(acBlkTbl[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord; DBObjectCollection offsets = c.GetOffsetCurves(FoundationWidth / 2); DBObjectCollection offsets2 = c.GetOffsetCurves(-(FoundationWidth / 2)); foreach (Entity e in offsets) { acBlkTblRec.AppendEntity(e); acTrans.AddNewlyCreatedDBObject(e, true); e.LayerId = acCurDb.Clayer; PositiveFoundationId = e.ObjectId; } foreach (Entity e in offsets2) { acBlkTblRec.AppendEntity(e); acTrans.AddNewlyCreatedDBObject(e, true); e.LayerId = acCurDb.Clayer; NegativeFoundationId = e.ObjectId; } acCurDb.Clayer = current; //Tag it acCurDb.Clayer = acLyrTbl[Utilities.FoundationTextLayer]; //Add foundation tag Matrix3d curUCSMatrix = Application.DocumentManager.MdiActiveDocument.Editor.CurrentUserCoordinateSystem; CoordinateSystem3d curUCS = curUCSMatrix.CoordinateSystem3d; //Get lable point Point3d labelPoint3d = c.GetPointAtDist(c.GetDistanceAtParameter(c.EndParam) / 2); Point3d labelPoint = new Point3d(labelPoint3d.X, labelPoint3d.Y, 0); BlockTableRecord blockDef = acBlkTbl["FormationTag"].GetObject(OpenMode.ForRead) as BlockTableRecord; // Insert the block into the current space using (BlockReference acBlkRef = new BlockReference(labelPoint, acBlkTbl["FormationTag"])) { //Calculate Line Angle double y = c.EndPoint.Y - c.StartPoint.Y; double x = c.EndPoint.X - c.StartPoint.X; double angle = Math.Atan(Math.Abs(y) / Math.Abs(x)); if (angle >= Math.PI / 4) { acBlkRef.TransformBy(Matrix3d.Rotation(0, curUCS.Zaxis, labelPoint)); } else { acBlkRef.TransformBy(Matrix3d.Rotation(Math.PI / 2, curUCS.Zaxis, labelPoint)); } acBlkRef.AddContext(occ.GetContext("10:1")); acBlkTblRec = acTrans.GetObject(acCurDb.CurrentSpaceId, OpenMode.ForWrite) as BlockTableRecord; acBlkTblRec.AppendEntity(acBlkRef); acTrans.AddNewlyCreatedDBObject(acBlkRef, true); // AttributeDefinitions foreach (ObjectId id in blockDef) { DBObject obj = id.GetObject(OpenMode.ForRead); AttributeDefinition attDef = obj as AttributeDefinition; if ((attDef != null) && (!attDef.Constant)) { //This is a non-constant AttributeDefinition //Create a new AttributeReference using (AttributeReference attRef = new AttributeReference()) { attRef.SetAttributeFromBlock(attDef, acBlkRef.BlockTransform); attRef.TextString = Parent.FormationLevel.ToString("F3"); //Add the AttributeReference to the BlockReference acBlkRef.AttributeCollection.AppendAttribute(attRef); acTrans.AddNewlyCreatedDBObject(attRef, true); } } } FormationTagId = acBlkRef.ObjectId; } acCurDb.Clayer = current; }
public void Update() { Document acDoc = Application.DocumentManager.MdiActiveDocument; Database acCurDb = acDoc.Database; Transaction tr = acCurDb.TransactionManager.TopTransaction; //Centre line Curve c = tr.GetObject(ObjectId, OpenMode.ForRead) as Curve; //Delete existing NegativeFoundationId.GetObject(OpenMode.ForWrite, true).Erase(); PositiveFoundationId.GetObject(OpenMode.ForWrite, true).Erase(); //Offset it LayerTable acLyrTbl = tr.GetObject(acCurDb.LayerTableId, OpenMode.ForRead) as LayerTable; ObjectId current = acCurDb.Clayer; acCurDb.Clayer = acLyrTbl[Utilities.FoundationLayer]; // Open the Block table for read BlockTable acBlkTbl = tr.GetObject(acCurDb.BlockTableId, OpenMode.ForRead) as BlockTable; // Open the Block table record Model space for write BlockTableRecord acBlkTblRec = tr.GetObject(acBlkTbl[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord; DBObjectCollection offsets = c.GetOffsetCurves(FoundationWidth / 2); DBObjectCollection offsets2 = c.GetOffsetCurves(-(FoundationWidth / 2)); foreach (Entity e in offsets) { acBlkTblRec.AppendEntity(e); tr.AddNewlyCreatedDBObject(e, true); e.LayerId = acCurDb.Clayer; PositiveFoundationId = e.ObjectId; } foreach (Entity e in offsets2) { acBlkTblRec.AppendEntity(e); tr.AddNewlyCreatedDBObject(e, true); e.LayerId = acCurDb.Clayer; NegativeFoundationId = e.ObjectId; } acCurDb.Clayer = current; //Update formation tag if (FormationTagId != null) { BlockReference acBlkRef = tr.GetObject(FormationTagId, OpenMode.ForRead) as BlockReference; //Set value AttributeCollection attCol = acBlkRef.AttributeCollection; foreach (ObjectId attId in attCol) { AttributeReference att = tr.GetObject(attId, OpenMode.ForRead) as AttributeReference; if (att.Tag == "LEVEL") { att.UpgradeOpen(); att.TextString = Parent.FormationLevel.ToString("F3"); } } } }
public void RunCommand() { NumberFormatInfo provider = new NumberFormatInfo(); provider.NumberDecimalSeparator = "."; provider.NumberGroupSeparator = ","; provider.NumberGroupSizes = new int[] { 3 }; Document adoc = Application.DocumentManager.MdiActiveDocument; if (adoc == null) { return; } Database db = adoc.Database; Editor ed = adoc.Editor; PromptFileNameResult sourceFileName; sourceFileName = ed.GetFileNameForOpen("\nEnter the name of the coordinates file to be imported:"); string[] lines = File.ReadAllLines(sourceFileName.StringResult); using (db) { using (Transaction tr = db.TransactionManager.StartTransaction()) { //BlockTableRecord btr = (BlockTableRecord)tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite); string blockName = "piket"; BlockTable bt = (BlockTable)db.BlockTableId.GetObject(OpenMode.ForRead); BlockTableRecord blockDef = (BlockTableRecord)bt[blockName].GetObject(OpenMode.ForRead); BlockTableRecord ms = (BlockTableRecord)bt[BlockTableRecord.ModelSpace].GetObject(OpenMode.ForWrite); string[] coord; foreach (string s in lines) { coord = s.Split(','); double coordX = Convert.ToDouble(coord[0], provider); double coordY = Convert.ToDouble(coord[1], provider); double coordZ = 0.0; string prim = coord[2]; Point3d point = new Point3d(coordX, coordY, coordZ); using (BlockReference blockRef = new BlockReference(point, blockDef.ObjectId)) { ms.AppendEntity(blockRef); tr.AddNewlyCreatedDBObject(blockRef, true); foreach (ObjectId id in blockDef) { DBObject obj = id.GetObject(OpenMode.ForRead); AttributeDefinition attDef = obj as AttributeDefinition; if ((attDef != null) && (!attDef.Constant)) { using (AttributeReference attRef = new AttributeReference()) { attRef.SetAttributeFromBlock(attDef, blockRef.BlockTransform); attRef.TextString = prim; blockRef.AttributeCollection.AppendAttribute(attRef); tr.AddNewlyCreatedDBObject(attRef, true); } } } } //DBPoint point = new DBPoint(new Point3d(coordX, coordY, coordZ)); //btr.AppendEntity(point); //tr.AddNewlyCreatedDBObject(point, true); //ed.WriteMessage("\n" + coordX); //ed.WriteMessage("\n" + coordY); //ed.WriteMessage("\n" + coordZ); //ed.WriteMessage("\n" + prim); } //btr.Dispose(); tr.Commit(); } } //Database db = adoc.Database; }
public static void AppendAttributeTest() { Document doc = AcAp.DocumentManager.MdiActiveDocument; Editor ed = doc.Editor; Database db = doc.Database; try { using (doc.LockDocument()) { using (Transaction tr = db.TransactionManager.StartTransaction()) { BlockTable bt = tr.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable; BlockTableRecord currSp = tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite) as BlockTableRecord; PromptNestedEntityOptions pno = new PromptNestedEntityOptions("\nSelect source attribute to append new attribute below this one >>"); PromptNestedEntityResult nres = ed.GetNestedEntity(pno); if (nres.Status != PromptStatus.OK) { return; } ObjectId id = nres.ObjectId; Entity ent = (Entity)tr.GetObject(id, OpenMode.ForRead); Point3d pnt = nres.PickedPoint; ObjectId owId = ent.OwnerId; AttributeReference attref = null; if (id.ObjectClass.IsDerivedFrom(RXClass.GetClass(typeof(AttributeReference)))) { attref = tr.GetObject(id, OpenMode.ForWrite) as AttributeReference; } BlockTableRecord btr = null; BlockReference bref = null; if (owId.ObjectClass.IsDerivedFrom(RXClass.GetClass(typeof(BlockReference)))) { bref = tr.GetObject(owId, OpenMode.ForWrite) as BlockReference; if (bref.IsDynamicBlock) { btr = tr.GetObject(bref.DynamicBlockTableRecord, OpenMode.ForRead) as BlockTableRecord; } else { btr = tr.GetObject(bref.BlockTableRecord, OpenMode.ForRead) as BlockTableRecord; } } Point3d insPt = attref.Position.TransformBy(bref.BlockTransform); btr.UpgradeOpen(); ObjectIdCollection bids = new ObjectIdCollection(); AttributeDefinition def = null; foreach (ObjectId defid in btr) { if (defid.ObjectClass.IsDerivedFrom(RXClass.GetClass(typeof(AttributeDefinition)))) { def = tr.GetObject(defid, OpenMode.ForRead) as AttributeDefinition; if (def.Tag == attref.Tag) { def.UpgradeOpen(); bids.Add(defid); break; } } } IdMapping map = new IdMapping(); db.DeepCloneObjects(bids, btr.ObjectId, map, true); ObjectIdCollection coll = new ObjectIdCollection(); AttributeDefinition attDef = null; foreach (IdPair pair in map) { if (pair.IsPrimary) { Entity oent = (Entity)tr.GetObject(pair.Value, OpenMode.ForWrite); if (oent != null) { if (pair.Value.ObjectClass.IsDerivedFrom(RXClass.GetClass(typeof(AttributeDefinition)))) { attDef = oent as AttributeDefinition; attDef.UpgradeOpen(); attDef.SetPropertiesFrom(def as Entity); // add other properties from source attribute definition to suit here: attDef.Justify = def.Justify; attDef.Position = btr.Origin.Add( new Vector3d(attDef.Position.X, attDef.Position.Y - attDef.Height * 1.25, attDef.Position.Z)).TransformBy(Matrix3d.Identity ); attDef.Tag = "NEW_TAG"; attDef.TextString = "New Prompt"; attDef.TextString = "New Textstring"; coll.Add(oent.ObjectId); } } } } btr.AssumeOwnershipOf(coll); btr.DowngradeOpen(); attDef.Dispose();//optional bref.RecordGraphicsModified(true); tr.TransactionManager.QueueForGraphicsFlush(); doc.TransactionManager.FlushGraphics();//optional ed.UpdateScreen(); tr.Commit(); } } } catch (System.Exception ex) { ed.WriteMessage(ex.Message + "\n" + ex.StackTrace); } finally { AcAp.ShowAlertDialog("Call command \"ATTSYNC\" manually"); } }
/// <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> /// 用于在AutoCAD图形中插入带属性的块参照 /// </summary> /// <param name="spaceId">块参照要加入的模型空间或图纸空间的Id</param> /// <param name="layer">块参照要加入的图层名</param> /// <param name="blockName">块参照所属的块名</param> /// <param name="position">块参照的插入点</param> /// <param name="scale">块参照的缩放比例</param> /// <param name="rotateAngle">块参照的旋转角度</param> /// <param name="attNameValues">属性的名称和取值</param> /// <returns></returns> public static ObjectId InsertBlockReference(this ObjectId spaceId, string layer, string blockName, Point3d position, Scale3d scale, double rotateAngle, Dictionary <string, string> attNameValues) { //获取数据库对象 Database db = spaceId.Database; //以读的方式打开块表 BlockTable bt = (BlockTable)db.BlockTableId.GetObject(OpenMode.ForRead); //如果没有blockName表示的块,则程序返回 if (!bt.Has(blockName)) { return(ObjectId.Null); } //以写的方式打开空间(模型空间或图纸空间) BlockTableRecord space = (BlockTableRecord)spaceId.GetObject(OpenMode.ForWrite); //获取块表记录的Id ObjectId btrId = bt[blockName]; //打开块表记录 BlockTableRecord btr = (BlockTableRecord)btrId.GetObject(OpenMode.ForRead); //创建一个块参照并设置插入点 BlockReference br = new BlockReference(position, bt[blockName]); //设置块参照的缩放比例 br.ScaleFactors = scale; //设置块参照的图层 br.Layer = layer; //设置块参照的旋转角度 br.Rotation = rotateAngle; //将块参照添加到模型空间 space.AppendEntity(br); //判断块表记录是否包含属性定义 if (btr.HasAttributeDefinitions) { //遍历属性定义 foreach (ObjectId id in btr) { //检查是否是属性定义 AttributeDefinition attDef = id.GetObject(OpenMode.ForRead) as AttributeDefinition; if (attDef != null) { //创建一个新的属性对象 AttributeReference attribute = new AttributeReference(); //从属性定义获得属性对象的对象特征 attribute.SetAttributeFromBlock(attDef, br.BlockTransform); //设置属性对象的其它特征 attribute.Position = attDef.Position.TransformBy(br.BlockTransform); attribute.Rotation = attDef.Rotation; attribute.AdjustAlignment(db); //判断是否包含指定的属性名称 if (attNameValues.ContainsKey(attDef.Tag.ToUpper())) { //设置属性值 attribute.TextString = attNameValues[attDef.Tag.ToUpper()].ToString(); } //向块参照添加属性对象 br.AttributeCollection.AppendAttribute(attribute); db.TransactionManager.AddNewlyCreatedDBObject(attribute, true); } } } db.TransactionManager.AddNewlyCreatedDBObject(br, true); //返回添加的块参照的Id return(br.ObjectId); }
public int UPDATEATTRIBUTESINBLOCK( ObjectId btrId, string blockName, string attbName, string attbValue ) { // Will return the number of attributes modified int changedCount = 0; Document doc = Application.DocumentManager.MdiActiveDocument; Database db = doc.Database; Editor ed = doc.Editor; Transaction tr = doc.TransactionManager.StartTransaction(); using (tr) { BlockTableRecord btr = (BlockTableRecord)tr.GetObject( btrId, OpenMode.ForRead ); // Test each entity in the container... foreach (ObjectId entId in btr) { Entity ent = tr.GetObject(entId, OpenMode.ForRead) as Entity; if (ent != null) { BlockReference br = ent as BlockReference; if (br != null) { BlockTableRecord bd = (BlockTableRecord)tr.GetObject( br.BlockTableRecord, OpenMode.ForRead ); // ... to see whether it's a block with // the name we're after if (bd.Name.ToUpper() == blockName) { // Check each of the attributes... foreach ( ObjectId arId in br.AttributeCollection ) { DBObject obj = tr.GetObject( arId, OpenMode.ForRead ); AttributeReference ar = obj as AttributeReference; if (ar != null) { // ... to see whether it has // the tag we're after if (ar.Tag.ToUpper() == attbName) { // If so, update the value // and increment the counter ar.UpgradeOpen(); ar.TextString = attbValue; ar.DowngradeOpen(); changedCount++; } } } } // Recurse for nested blocks changedCount += UPDATEATTRIBUTESINBLOCK( br.BlockTableRecord, blockName, attbName, attbValue ); } } } tr.Commit(); } return(changedCount); }
public void MakeCoordGrid() { if (!CheckLicense.Check()) { return; } Autodesk.AutoCAD.ApplicationServices.Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument; Autodesk.AutoCAD.DatabaseServices.Database db = doc.Database; ObjectId textStyleId = ObjectId.Null; using (Transaction tr = db.TransactionManager.StartTransaction()) using (TextStyleTable tt = (TextStyleTable)tr.GetObject(db.TextStyleTableId, OpenMode.ForRead)) { if (tt.Has(TextStyleName)) { textStyleId = tt[TextStyleName]; } tr.Commit(); } ObjectId textLayerId = AcadUtility.AcadEntity.GetOrCreateLayer(db, TextLayerName, Color.FromColorIndex(ColorMethod.ByAci, 1)); ObjectId lineLayerId = AcadUtility.AcadEntity.GetOrCreateLayer(db, LineLayerName, Color.FromColorIndex(ColorMethod.ByAci, 3)); ObjectId blockId = GetOrCreateBlock(db, BlockName, textLayerId, lineLayerId, textStyleId); Matrix3d ucs2wcs = AcadUtility.AcadGraphics.UcsToWcs; Matrix3d wcs2ucs = AcadUtility.AcadGraphics.WcsToUcs; // Pick polyline PromptPointResult ptRes = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor.GetPoint("\nKöşe noktası: "); if (PolylineJig.Jig(ptRes.Value, out Point3dCollection points)) { int xmin = int.MaxValue; int xmax = int.MinValue; int ymin = int.MaxValue; int ymax = int.MinValue; for (int i = 0; i < 4; i++) { Point3d pt = points[i]; xmin = Math.Min(xmin, (int)pt.X); xmax = Math.Max(xmax, (int)pt.X); ymin = Math.Min(ymin, (int)pt.Y); ymax = Math.Max(ymax, (int)pt.Y); } // Interval PromptIntegerOptions intOpts = new PromptIntegerOptions("\nAralık: "); intOpts.AllowNegative = false; intOpts.AllowZero = false; intOpts.AllowNone = false; intOpts.DefaultValue = Properties.Settings.Default.Command_COORDGRID_Interval; intOpts.UseDefaultValue = true; PromptIntegerResult intRes = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor.GetInteger(intOpts); if (intRes.Status == PromptStatus.OK) { Interval = intRes.Value; } else { return; } // Round limits to multiples of the interval xmin = (int)Math.Floor((double)xmin / Interval) * Interval; xmax = (int)Math.Ceiling((double)xmax / Interval) * Interval; ymin = (int)Math.Floor((double)ymin / Interval) * Interval; ymax = (int)Math.Ceiling((double)ymax / Interval) * Interval; // Text height PromptDoubleOptions thOpts = new PromptDoubleOptions("\nYazı yüksekliği: "); thOpts.AllowNegative = false; thOpts.AllowZero = false; thOpts.AllowNone = false; thOpts.DefaultValue = Properties.Settings.Default.Command_COORDGRID_TextHeight; thOpts.UseDefaultValue = true; PromptDoubleResult thRes = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor.GetDouble(thOpts); if (thRes.Status == PromptStatus.OK) { TextHeight = thRes.Value; } else { return; } // Save settings Properties.Settings.Default.Command_COORDGRID_TextHeight = TextHeight; Properties.Settings.Default.Command_COORDGRID_Interval = Interval; Properties.Settings.Default.Save(); // Print grid NumberFormatInfo nfi = (NumberFormatInfo)CultureInfo.InvariantCulture.NumberFormat.Clone(); nfi.NumberGroupSeparator = " "; nfi.NumberDecimalDigits = 0; using (Transaction tr = db.TransactionManager.StartTransaction()) using (BlockTable bt = (BlockTable)tr.GetObject(db.BlockTableId, OpenMode.ForRead)) using (BlockTableRecord btr = (BlockTableRecord)tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite)) { BlockTableRecord blockDef = (BlockTableRecord)tr.GetObject(blockId, OpenMode.ForRead); for (int x = xmin; x <= xmax; x += Interval) { for (int y = ymin; y <= ymax; y += Interval) { Point3d v = new Point3d(x, y, 0); if (!PolylineContains(points, v)) { continue; } BlockReference blockRef = AcadUtility.AcadEntity.CreateBlockReference(db, blockId, v, TextHeight, 0); btr.AppendEntity(blockRef); tr.AddNewlyCreatedDBObject(blockRef, true); // Set attributes foreach (ObjectId id in blockDef) { AttributeDefinition attDef = tr.GetObject(id, OpenMode.ForRead) as AttributeDefinition; if (attDef != null) { using (AttributeReference attRef = new AttributeReference()) { attRef.SetDatabaseDefaults(db); attRef.SetAttributeFromBlock(attDef, blockRef.BlockTransform); blockRef.AttributeCollection.AppendAttribute(attRef); tr.AddNewlyCreatedDBObject(attRef, true); attRef.TextString = attDef.Tag == "X" ? x.ToString("n", nfi) : y.ToString("n", nfi); attRef.AdjustAlignment(db); } } } } } tr.Commit(); } } }
/// <summary> /// Gets an attribute by reference. /// </summary> /// <param name="attrRef">Reference to the attribute.</param> /// <returns>The attribute.</returns> internal NtfsAttribute GetAttribute(AttributeReference attrRef) { foreach (var attr in _attributes) { if (attr.Reference.Equals(attrRef)) { return attr; } } return null; }
private static void ReplaceBlock(BlockReference element, BlockTable blockTable, BlockTableRecord modelSpace) { // If entity is a TRP####(mapit) block replace it with a mavat(M####) block. if ((Regex.IsMatch(element.Name, "TRP."))) { Dictionary <string, string> attDic = new Dictionary <string, string>(); foreach (ObjectId oid in element.AttributeCollection) { AttributeReference ar = (AttributeReference)oid.GetObject(OpenMode.ForRead); if (ar.Tag == "HIGHTM") { attDic.Add("HEIGHT", ar.TextString); } else { attDic.Add(ar.Tag, ar.TextString); } } if (!trpToMavat.Keys.Contains(element.Name)) { QuaryConvertTable(element.Name, blockTable); } using (Transaction trans = dataBase.TransactionManager.StartTransaction()) { try { // btr = BlockTableRecord for mavat block in database. BlockTableRecord btr = (BlockTableRecord)blockTable[trpToMavat[element.Name]].GetObject(OpenMode.ForRead); // Append mavat block to drawing. using (BlockReference br = new BlockReference(element.Position, btr.ObjectId)) { modelSpace.UpgradeOpen(); modelSpace.AppendEntity(br); element.UpgradeOpen(); element.Erase(); // Add all attributes to new mavat block. foreach (ObjectId id in btr) { var v = id.GetObject(OpenMode.ForRead); if (v.GetType() == typeof(AttributeDefinition)) { using (AttributeReference attRef = new AttributeReference()) { attRef.SetAttributeFromBlock((AttributeDefinition)v, br.BlockTransform); attRef.TextString = attDic[attRef.Tag]; br.AttributeCollection.AppendAttribute(attRef); trans.AddNewlyCreatedDBObject(attRef, true); } } } trans.AddNewlyCreatedDBObject(br, true); } trans.Commit(); } catch (KeyNotFoundException e) { doc.Editor.WriteMessage($"{element.Name} does not exists in trpToMavat dictionary.\n"); } } } }
public string CHECKATTRIBUTEVALUE( string blockName, string attbName ) { Document doc = Application.DocumentManager.MdiActiveDocument; Editor ed = doc.Editor; Database db = doc.Database; doc.LockDocument(); string attributeValue = ""; // Get the IDs of the spaces we want to process // and simply call a function to process each ObjectId psId; Transaction tr1 = db.TransactionManager.StartTransaction(); using (tr1) { BlockTable bt = (BlockTable)tr1.GetObject( db.BlockTableId, OpenMode.ForRead ); psId = bt[BlockTableRecord.PaperSpace]; // Not needed, but quicker than aborting tr1.Commit(); } // Will return the value of the named attribute. Transaction tr2 = doc.TransactionManager.StartTransaction(); using (tr2) { BlockTableRecord btr = (BlockTableRecord)tr2.GetObject( psId, OpenMode.ForRead ); // Test each entity in the container... foreach (ObjectId entId in btr) { Entity ent = tr2.GetObject(entId, OpenMode.ForRead) as Entity; if (ent != null) { //////////attributeValue = "1"; BlockReference br = ent as BlockReference; if (br != null) { ////////////attributeValue = "2"; BlockTableRecord bd = (BlockTableRecord)tr2.GetObject( br.BlockTableRecord, OpenMode.ForRead ); // ... to see whether it's a block with // the name we're after ////////////attributeValue = bd.Name.ToUpper() + " = " + blockName; if (bd.Name.ToUpper() == blockName) { // Check each of the attributes... foreach (ObjectId arId in br.AttributeCollection) { DBObject obj = tr2.GetObject(arId, OpenMode.ForRead); AttributeReference ar = obj as AttributeReference; if (ar != null) { //attributeValue = ar.Tag.ToUpper() + " = " + attbName; // ... to see whether it has // the tag we're after if (ar.Tag.ToUpper() == attbName) { ////////////attributeValue = "5"; // If so, update the value // and increment the counter ar.UpgradeOpen(); attributeValue = ar.TextString; ar.DowngradeOpen(); } } } } } } } tr2.Commit(); } return(attributeValue); }
protected bool Equals(AttributeReference other) { return(string.Equals(Text, other.Text)); }
public void DrawGroupLeader() { Editor ed = dwg.Editor; PromptEntityOptions prmtEntityOpts = new PromptEntityOptions("Укажите линию"); prmtEntityOpts.AllowNone = false; prmtEntityOpts.SetRejectMessage("Должна быть линия или полилиния!"); prmtEntityOpts.AddAllowedClass(typeof(Line), true); prmtEntityOpts.AddAllowedClass(typeof(Polyline), true); PromptEntityResult entRes = ed.GetEntity(prmtEntityOpts); if (entRes.Status!= PromptStatus.OK) { return; } using (Transaction tr = CurrentDatabase.TransactionManager.StartTransaction()) { GroupsInformation groupEntities = new GroupsInformation(tr, CurrentDatabase); List<string> groupList = groupEntities.GetGroupsOfObject(entRes.ObjectId); if (groupList == null) { ed.WriteMessage("За указанным объектом не значится никаких групп!"); return; } PromptPointOptions pointOpts = new PromptPointOptions("\nУкажите точку вставки блока: "); PromptPointResult pointRes = ed.GetPoint(pointOpts); if (pointRes.Status!= PromptStatus.OK) { return; } BlockTable bt = (BlockTable)CurrentDatabase.BlockTableId.GetObject(OpenMode.ForRead); BlockTableRecord btrSpace = (BlockTableRecord)CurrentDatabase.CurrentSpaceId .GetObject(OpenMode.ForWrite); if (!bt.Has("group_vinoska")) { ed.WriteMessage("\nВ файле не определён блок выноски!!"); return; } BlockTableRecord gleaderBtr = (BlockTableRecord)bt["group_vinoska"].GetObject(OpenMode.ForRead); BlockReference gleader = new BlockReference(pointRes.Value, gleaderBtr.ObjectId); btrSpace.AppendEntity(gleader); tr.AddNewlyCreatedDBObject(gleader, true); //Если блок аннотативный - добавляем в таблицу аннотативных масштабов блока текущий масштаб ObjectContextManager ocm = CurrentDatabase.ObjectContextManager; ObjectContextCollection occ = ocm.GetContextCollection("ACDB_ANNOTATIONSCALES"); if (gleaderBtr.Annotative == AnnotativeStates.True) { ObjectContexts.AddContext(gleader, occ.CurrentContext); } gleader.SetDatabaseDefaults(); if (gleaderBtr.HasAttributeDefinitions) { var attDefs = gleaderBtr.Cast<ObjectId>() .Where(n => n.ObjectClass.Name == "AcDbAttributeDefinition") .Select(n => (AttributeDefinition)n.GetObject(OpenMode.ForRead)); foreach (AttributeDefinition attdef in attDefs) { AttributeReference attref = new AttributeReference(); attref.SetAttributeFromBlock(attdef, gleader.BlockTransform); gleader.AttributeCollection.AppendAttribute(attref); tr.AddNewlyCreatedDBObject(attref, true); if (gleaderBtr.Annotative == AnnotativeStates.True) { ObjectContexts.AddContext(attref, occ.CurrentContext); } int attCount = int.Parse(attref.Tag.Remove(0,10)); if (attCount<=groupList.Count) { attref.TextString = groupList[attCount-1]; } } } if (gleaderBtr.IsDynamicBlock) { DynamicBlockReferencePropertyCollection dynBRefColl = gleader.DynamicBlockReferencePropertyCollection; foreach (DynamicBlockReferenceProperty prop in dynBRefColl) { if (prop.PropertyName == "Lookup1") { prop.Value = prop.GetAllowedValues()[groupList.Count-1]; } } } tr.Commit(); } }
//[CommandMethod("BJ")] public static void BlockJigCmd(Double finalCalcText) { Document doc = Application.DocumentManager.MdiActiveDocument; Database db = doc.Database; Editor ed = doc.Editor; //Set the block Name to use. string pr = "TagHgr"; Transaction tr = doc.TransactionManager.StartTransaction(); using (tr) { BlockTable bt = (BlockTable)tr.GetObject( db.BlockTableId, OpenMode.ForRead ); if (!bt.Has(pr)) { ed.WriteMessage( "\nBlock \"" + pr + "\" not found."); return; } BlockTableRecord space = (BlockTableRecord)tr.GetObject( db.CurrentSpaceId, OpenMode.ForWrite ); BlockTableRecord btr = (BlockTableRecord)tr.GetObject( bt[pr], OpenMode.ForRead); // Block needs to be inserted to current space before // being able to append attribute to it BlockReference br = new BlockReference(new Point3d(), btr.ObjectId); space.AppendEntity(br); tr.AddNewlyCreatedDBObject(br, true); Dictionary<ObjectId, AttInfo> attInfo = new Dictionary<ObjectId, AttInfo>(); if (btr.HasAttributeDefinitions) { foreach (ObjectId id in btr) { DBObject obj = tr.GetObject(id, OpenMode.ForRead); AttributeDefinition ad = obj as AttributeDefinition; if (ad != null && !ad.Constant) { AttributeReference ar = new AttributeReference(); ar.SetAttributeFromBlock(ad, br.BlockTransform); ar.Position = ad.Position.TransformBy(br.BlockTransform); if (ad.Justify != AttachmentPoint.BaseLeft) { ar.AlignmentPoint = ad.AlignmentPoint.TransformBy(br.BlockTransform); } if (ar.IsMTextAttribute) { ar.UpdateMTextAttribute(); } //ar.TextString = ad.TextString; ar.TextString = PopulateAttributes(ad.Tag, finalCalcText.ToString()); ObjectId arId = br.AttributeCollection.AppendAttribute(ar); tr.AddNewlyCreatedDBObject(ar, true); // Initialize our dictionary with the ObjectId of // the attribute reference + attribute definition info attInfo.Add( arId, new AttInfo( ad.Position, ad.AlignmentPoint, ad.Justify != AttachmentPoint.BaseLeft ) ); } } } // Run the jig BlockJig myJig = new BlockJig(tr, br, attInfo); if (myJig.Run() != PromptStatus.OK) return; // Commit changes if user accepted, otherwise discard tr.Commit(); } }
private void file_open_handler(object sender, EventArgs e) { if (DialogResult.OK == openFileDialog.ShowDialog(this)) { if (lm != null) { lm.LayoutSwitched -= new Teigha.DatabaseServices.LayoutEventHandler(reinitGraphDevice); HostApplicationServices.WorkingDatabase = null; lm = null; } bool bLoaded = true; database = new Database(false, false); if (openFileDialog.FilterIndex == 1) { try { database.ReadDwgFile(openFileDialog.FileName, FileOpenMode.OpenForReadAndAllShare, false, ""); //现在进入数据库并获得数据库的块表引用 Transaction trans = database.TransactionManager.StartTransaction(); BlockTable bt = (BlockTable)trans.GetObject(database.BlockTableId, OpenMode.ForRead, false, true); //从块表的模型空间特性中获得块表记录,块表记录对象包含DWG文件数据库实体 BlockTableRecord btr = (BlockTableRecord)trans.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForRead, false, true); foreach (ObjectId btrId in btr) { DBObject entBlock = (DBObject)trans.GetObject(btrId, OpenMode.ForRead, false, true); String dxfName = entBlock.GetRXClass().DxfName; if (entBlock.GetRXClass().DxfName.ToUpper() == "INSERT") { BlockReference bRef = (BlockReference)entBlock; if (bRef.AttributeCollection.Count != 0) { System.Collections.IEnumerator bRefEnum = bRef.AttributeCollection.GetEnumerator(); while (bRefEnum.MoveNext()) { ObjectId aId = (ObjectId)bRefEnum.Current;//这一句极其关键 AttributeReference aRef = (AttributeReference)trans.GetObject(aId, OpenMode.ForRead, false, true); string sss = aRef.TextString; //this.textBox1.Text = aRef.TextString;//此语句即获得属性单行文本,请自行在此语句前添加 属性单行文本 赋于的变量 } } } if (entBlock.GetRXClass().DxfName.ToUpper() == "MTEXT") { MText bRef = (MText)entBlock; string sd = bRef.Text; } if (entBlock.GetRXClass().DxfName.ToUpper() == "LINE") { Line bRef = (Line)entBlock; ObjectId oid = bRef.Id; } } trans.Commit(); //提交事务处理 btr.Dispose(); bt.Dispose(); } catch (System.Exception ex) { MessageBox.Show(ex.Message); bLoaded = false; } } else if (openFileDialog.FilterIndex == 2) { try { database.DxfIn(openFileDialog.FileName, ""); } catch (System.Exception ex) { MessageBox.Show(ex.Message); bLoaded = false; } } if (bLoaded) { HostApplicationServices.WorkingDatabase = database; lm = LayoutManager.Current; lm.LayoutSwitched += new Teigha.DatabaseServices.LayoutEventHandler(reinitGraphDevice); String str = HostApplicationServices.Current.FontMapFileName; //menuStrip. exportToolStripMenuItem.Enabled = true; zoomToExtentsToolStripMenuItem.Enabled = true; zoomWindowToolStripMenuItem.Enabled = true; setAvtiveLayoutToolStripMenuItem.Enabled = true; fileDependencyToolStripMenuItem.Enabled = true; panel1.Enabled = true; pageSetupToolStripMenuItem.Enabled = true; printPreviewToolStripMenuItem.Enabled = true; printToolStripMenuItem.Enabled = true; this.Text = String.Format("OdViewExMgd - [{0}]", openFileDialog.SafeFileName); initializeGraphics(); Invalidate(); } } }
public static void CheckAttribute(string drawingFullName, string blockName, string tag, ref List <StringCollection> excelData, ref StringCollection logFileContents, int existcolor, int notesistcolor, bool checdigut, bool delimiterISpoint) { Document doc = null; bool document_is_open = false; #region проверяваме дали документа е отворен foreach (Document dd in Application.DocumentManager) { if (dd.Name == drawingFullName) { document_is_open = true; doc = dd; Application.DocumentManager.MdiActiveDocument = doc; break; } } if (!document_is_open) { //doc = Application.DocumentManager.Open(drawingFullName, false); doc = new UtilityClass().ReadDocument(drawingFullName); } #endregion bool existBLOCKREF = false; String LOGSTRING = ""; using (DocumentLock DocLock = doc.LockDocument()) { Database db = doc.Database; using (Transaction acTrans = db.TransactionManager.StartTransaction()) { BlockTable bt = (BlockTable)acTrans.GetObject(db.BlockTableId, OpenMode.ForRead); foreach (ObjectId blockId in bt) { BlockTableRecord btr = (BlockTableRecord)acTrans.GetObject(blockId, OpenMode.ForRead); if (btr.IsLayout || btr.IsAnonymous) { continue; } if (btr.Name == blockName) { ObjectIdCollection coll = GetBlockReferenceIds(blockId); //--------------------------------------------------- List <List <Pair <string, ObjectId> > > pre = GetRefLayout(ref coll, ref db); int NN = 0; foreach (List <Pair <string, ObjectId> > jjo in pre) { foreach (Pair <string, ObjectId> rts in jjo) { // MessageBox.Show(NN.ToString()+"\n"+rts.First); } NN++; } //----------------------------------------------------- if (coll.Count > 0) { existBLOCKREF = true; } //foreach (ObjectId obid in coll) string temp = ""; String LOGS = ""; String LOGS1 = ""; String LOGS2 = ""; foreach (List <Pair <string, ObjectId> > list in pre) { if (list[0].First != "-1") { temp = "Layer: " + list[0].First + "- Attribute content is\r\n"; } else { //temp = "Layer: - Attribute content is\r\n"; continue; } foreach (Pair <string, ObjectId> PA in list) { BlockReference brf = acTrans.GetObject(PA.Second, OpenMode.ForWrite) as BlockReference; bool existATTR = false; for (int i = 0; i < brf.AttributeCollection.Count; i++) { AttributeReference AttRef = (AttributeReference) acTrans.GetObject(brf.AttributeCollection[i], OpenMode.ForWrite); if (AttRef.Tag.ToString() == tag) { existATTR = true; if (((AttributeReference)AttRef).TextString.Length > 0) { if (checdigut) { bool digit = true; string sr = ((AttributeReference)AttRef).TextString; char ch = delimiterISpoint ? '.' : ','; if (sr.IndexOf(ch) == sr.LastIndexOf(ch)) { foreach (char c in sr) { if (!Char.IsDigit(c) && (c != ch)) { digit = false; } } } else { digit = false; } if (!digit) { LOGS2 += "\"" + ((AttributeReference)AttRef).TextString + "\" in BlockReference Position" + brf.Position.ToString() + " not a Number.\r\n"; } } if (excelData != null) { Pair <int, int> pa = SearchStrigInEXcelData( ((AttributeReference)AttRef).TextString, ref excelData); if ((pa.First < 0) || (pa.Second < 0)) { ((AttributeReference)AttRef).ColorIndex = notesistcolor; LOGS1 += "\"" + ((AttributeReference)AttRef).TextString + "\" in BlockReference Position" + brf.Position.ToString() + "is not found in the Excel file\r\n"; } else { ((AttributeReference)AttRef).ColorIndex = existcolor; } } } else { LOGS += "TAG is Empty in BlockReference Position" + brf.Position.ToString() + "\r\n"; } break; } } if (!existATTR) { LOGS += "TAG Missin in BlockReference Position " + brf.Position.ToString() + "\r\n"; } } if (LOGS.Length > 0) { LOGSTRING += temp + LOGS; } if (!(LOGS.Length > 0)) { if (LOGS1.Length > 0) { LOGSTRING += temp + LOGS1; } } else { if (LOGS1.Length > 0) { LOGSTRING += LOGS1; } } if (!(LOGS.Length > 0) && !(LOGS1.Length > 0)) { if (LOGS2.Length > 0) { LOGSTRING += temp + LOGS2; } } else { if (LOGS2.Length > 0) { LOGSTRING += LOGS2; } } LOGS = string.Empty; LOGS1 = string.Empty; LOGS2 = string.Empty; } } } acTrans.Commit(); } } if (!existBLOCKREF) { LOGSTRING = "In File " /* + DrawingFullName + */ + " missing BlockReference !\r\n"; } if (LOGSTRING.Length > 0) { LOGSTRING = drawingFullName + ":\r\n" + LOGSTRING; } if (LOGSTRING.Length > 0) { logFileContents.Add(LOGSTRING); } try { if (!document_is_open) { //doc.CloseAndSave(drawingFullName); new UtilityClass().CloseActiveDocument(true); } else { doc.SendStringToExecute("_qsave ", false, false, false); } } catch { // Why is that? } }
public virtual void VisitAttributeReference(AttributeReference attributeReference) { DefaultVisit(attributeReference); }
private void ChangeAttributeTag(AttributeReference attribute, double newHeight) { attribute.TextString = GetCrrectHeightFormat(newHeight); }
public AttributeRefDetail(AttributeReference attr) { Tag = attr.Tag; Text = attr.TextString; IdAtrRef = attr.Id; }
private void btnSelectBlock_Click(object sender, EventArgs e) { try { _AcAp.DocumentCollection dm = _AcAp.Application.DocumentManager; _AcAp.Document doc = dm.MdiActiveDocument; Editor ed = doc.Editor; #if NEWSETFOCUS _AcAp.Application.DocumentManager.MdiActiveDocument.Window.Focus(); #else Autodesk.AutoCAD.Internal.Utils.SetFocusToDwgView(); // previous 2014 AutoCAD - Versions #endif PromptEntityResult per = ed.GetEntity("\nRaumblock wählen: "); //DocumentLock loc = dm.MdiActiveDocument.LockDocument(); //using (loc) //{ //} if (per.Status == PromptStatus.OK) { Transaction tr = doc.TransactionManager.StartTransaction(); using (tr) { DBObject obj = tr.GetObject(per.ObjectId, OpenMode.ForRead); BlockReference br = obj as BlockReference; if (br == null) { return; } txtBlockname.Text = Plan2Ext.Globs.GetBlockname(br, tr); tr.Commit(); } per = ed.GetNestedEntity("\nFlächen-Attribut wählen: "); if (per.Status == PromptStatus.OK) { tr = doc.TransactionManager.StartTransaction(); using (tr) { DBObject obj = tr.GetObject(per.ObjectId, OpenMode.ForRead); AttributeReference ar = obj as AttributeReference; if (ar == null) { return; } txtAttribute.Text = ar.Tag; tr.Commit(); } } txtPeriAtt.Text = ""; per = ed.GetNestedEntity("\nUmfang-Attribut wählen: "); if (per.Status == PromptStatus.OK) { tr = doc.TransactionManager.StartTransaction(); using (tr) { DBObject obj = tr.GetObject(per.ObjectId, OpenMode.ForRead); AttributeReference ar = obj as AttributeReference; if (ar == null) { return; } txtPeriAtt.Text = ar.Tag; tr.Commit(); } } } } catch (Exception ex) { _AcAp.Application.ShowAlertDialog(ex.Message); } }
private void addCheekViewBlock(bool doTrans, Matrix3d trans, double xPosView, bool isLeft) { // Добавление блока вида. // Если блока нет, то выход. if (panelBase.Service.Env.IdBtrView.IsNull) { return; } Point3d ptBlView = new Point3d(xPosView, 860, 0); if (doTrans) { ptBlView = ptBlView.TransformBy(trans); } BlockReference blRefView = CreateBlRefInBtrDim(ptBlView, panelBase.Service.Env.IdBtrView, Settings.Default.SheetScale); if (blRefView == null) { return; } // атрибут Вида if (!panelBase.Service.Env.IdAttrDefView.IsNull) { using (var attrDefView = panelBase.Service.Env.IdAttrDefView.GetObject(OpenMode.ForRead, false, true) as AttributeDefinition) { var attrRefView = new AttributeReference(); attrRefView.SetAttributeFromBlock(attrDefView, blRefView.BlockTransform); attrRefView.TextString = "А"; blRefView.AttributeCollection.AppendAttribute(attrRefView); t.AddNewlyCreatedDBObject(attrRefView, true); if ((!isLeft || doTrans) && !(!isLeft && doTrans)) { attrRefView.TransformBy(Matrix3d.Mirroring( new Line3d(attrRefView.AlignmentPoint, new Point3d(attrRefView.AlignmentPoint.X, 0, 0)))); } } } if ((!isLeft || doTrans) && !(!isLeft && doTrans)) { blRefView.TransformBy(Matrix3d.Mirroring(new Line3d(ptBlView, new Point3d(ptBlView.X, 0, 0)))); } }
//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; } }
public void RemoveExtentCacheSafe(AttributeReference reference) { _extents.Remove(reference); }
static public void Plan2CalcFlaSelVolAtts() { try { if (Plan2Ext.Flaeche.TheCalcAreaPalette == null) { return; } Document doc = Application.DocumentManager.MdiActiveDocument; log.DebugFormat("Dokumentname: {0}.", doc.Name); if (doc == null) { return; } using (DocumentLock m_doclock = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.LockDocument()) { DocumentCollection dm = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager; if (doc == null) { return; } Editor ed = doc.Editor; #if NEWSETFOCUS Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Window.Focus(); #else Autodesk.AutoCAD.Internal.Utils.SetFocusToDwgView(); // previous 2014 AutoCAD - Versions #endif PromptEntityResult per = ed.GetNestedEntity("\nHöhenattribut wählen: "); if (per.Status == PromptStatus.OK) { using (Transaction tr = doc.TransactionManager.StartTransaction()) { DBObject obj = tr.GetObject(per.ObjectId, OpenMode.ForRead); AttributeReference ar = obj as AttributeReference; if (ar == null) { return; } Plan2Ext.Flaeche.TheCalcAreaPalette.SetHeightAttribut(ar.Tag); tr.Commit(); } } per = ed.GetNestedEntity("\nVolumsattribut wählen: "); if (per.Status == PromptStatus.OK) { using (Transaction tr = doc.TransactionManager.StartTransaction()) { DBObject obj = tr.GetObject(per.ObjectId, OpenMode.ForRead); AttributeReference ar = obj as AttributeReference; if (ar == null) { return; } Plan2Ext.Flaeche.TheCalcAreaPalette.SetVolAttribut(ar.Tag); tr.Commit(); } } } } catch (System.Exception ex) { Application.ShowAlertDialog(string.Format(CultureInfo.CurrentCulture, "Fehler in Plan2CalcFlaSelVolAtts aufgetreten! {0}", ex.Message)); } }
private void rotateHorCross(BlockReference blRefCross, AttributeReference attrRef) { blRefCross.Rotation = 90d.ToRadians(); }
public FixtureUnit(BlockReference bRef, Transaction tr) { model = new FixtureUnitModel(); model.position = new Point3dModel(bRef.Position.ToArray()); model.matrixTransform = new Matrix3dModel(bRef.BlockTransform.ToArray()); model.blockName = Goodies.GetDynamicName(bRef); model.fuS = FixtureUnitBlock.GetFixtureUnitStatus(model.blockName); Point3d v, m, r1; foreach (DynamicBlockReferenceProperty prop in bRef.DynamicBlockReferencePropertyCollection) { if (prop.PropertyName == FixtureUnitModelName.A1) { model.A1 = (double)prop.Value; } else if (prop.PropertyName == FixtureUnitModelName.A2) { model.A2 = (double)prop.Value; } else if (prop.PropertyName == FixtureUnitModelName.A3) { model.A3 = (double)prop.Value; } else if (prop.PropertyName == FixtureUnitModelName.D1) { model.D1 = (double)prop.Value; } else if (prop.PropertyName == FixtureUnitModelName.Y2) { model.Y2 = (double)prop.Value; } else if (prop.PropertyName == FixtureUnitModelName.X2) { model.X2 = (double)prop.Value; } else if (prop.PropertyName == FixtureUnitModelName.X2_2) { model.X2_2 = (double)prop.Value; } else if (prop.PropertyName == FixtureUnitModelName.V) { v = (Point3d)prop.Value; model.V = new Point3dModel(v.X, v.Y, v.Z); } else if (prop.PropertyName == FixtureUnitModelName.M) { m = (Point3d)prop.Value; model.M = new Point3dModel(m.X, m.Y, m.Z); } else if (prop.PropertyName == FixtureUnitModelName.R1) { r1 = (Point3d)prop.Value; model.R1 = new Point3dModel(r1.X, r1.Y, r1.Z); } } foreach (ObjectId id in bRef.AttributeCollection) { AttributeReference attRef = (AttributeReference)tr.GetObject(id, OpenMode.ForRead); if (attRef.Tag == FixtureUnitModelName.CWSFU) { model.CWSFU = Convert.ToDouble(attRef.TextString); } else if (attRef.Tag == FixtureUnitModelName.WSFU) { model.WSFU = Convert.ToDouble(attRef.TextString); } else if (attRef.Tag == FixtureUnitModelName.HWSFU) { model.HWSFU = Convert.ToDouble(attRef.TextString); } else if (attRef.Tag == FixtureUnitModelName.VENT_DIA) { model.VENT_DIA = Convert.ToDouble(attRef.TextString); } else if (attRef.Tag == FixtureUnitModelName.WASTE_DIA) { model.WASTE_DIA = Convert.ToDouble(attRef.TextString); } else if (attRef.Tag == FixtureUnitModelName.STORM_DIA) { model.STORM_DIA = Convert.ToDouble(attRef.TextString); } else if (attRef.Tag == FixtureUnitModelName.DFU) { model.DFU = Convert.ToDouble(attRef.TextString); } else if (attRef.Tag == FixtureUnitModelName.HW_DIA) { model.HW_DIA = Convert.ToDouble(attRef.TextString); } else if (attRef.Tag == FixtureUnitModelName.CW_DIA) { model.CW_DIA = Convert.ToDouble(attRef.TextString); } else if (attRef.Tag == FixtureUnitModelName.INDEX) { model.INDEX = Convert.ToDouble(attRef.TextString); } else if (attRef.Tag == FixtureUnitModelName.TAG) { throw new Exception("Check This Out."); } } }
static public void BlockJigCmd() { var doc = Application.DocumentManager.MdiActiveDocument; var db = doc.Database; var ed = doc.Editor; var pso = new PromptStringOptions("\nEnter block name: "); var pr = ed.GetString(pso); if (pr.Status != PromptStatus.OK) { return; } using (var tr = doc.TransactionManager.StartTransaction()) { var bt = (BlockTable)tr.GetObject( db.BlockTableId, OpenMode.ForRead ); if (!bt.Has(pr.StringResult)) { ed.WriteMessage( "\nBlock \"" + pr.StringResult + "\" not found."); return; } var ms = (BlockTableRecord)tr.GetObject( db.CurrentSpaceId, OpenMode.ForWrite ); var btr = (BlockTableRecord)tr.GetObject( bt[pr.StringResult], OpenMode.ForRead ); // Block needs to be inserted to current space before // being able to append attribute to it var br = new BlockReference(new Point3d(), btr.ObjectId); br.TransformBy(ed.CurrentUserCoordinateSystem); ms.AppendEntity(br); tr.AddNewlyCreatedDBObject(br, true); if (btr.Annotative == AnnotativeStates.True) { var ocm = db.ObjectContextManager; var occ = ocm.GetContextCollection(annoScalesDict); br.AddContext(occ.CurrentContext); } else { br.ScaleFactors = new Scale3d(br.UnitFactor); } // Instantiate our map between attribute references // and their definitions var atts = new Dictionary <ObjectId, ObjectId>(); if (btr.HasAttributeDefinitions) { foreach (ObjectId id in btr) { var obj = tr.GetObject(id, OpenMode.ForRead); var ad = obj as AttributeDefinition; if (ad != null && !ad.Constant) { var ar = new AttributeReference(); // Set the initial positional information ar.SetAttributeFromBlock(ad, br.BlockTransform); ar.TextString = ad.TextString; // Add the attribute to the block reference // and transaction var arId = br.AttributeCollection.AppendAttribute(ar); tr.AddNewlyCreatedDBObject(ar, true); // Initialize our dictionary with the ObjectIds of // the attribute reference & definition atts.Add(arId, ad.ObjectId); } } } // Run the jig var jig = new BlockJig( ed.CurrentUserCoordinateSystem, tr, br, atts ); if (jig.Run() != PromptStatus.OK) { return; } // Commit changes if user accepted, otherwise discard tr.Commit(); } }
// 获取实体信息 public void GetEntitiesInfo(ArrayList entities, Transaction trans, BlockTableRecord btr, int numSample, Document doc, Editor ed) { ArrayList uuid = new ArrayList(); ArrayList geom = new ArrayList(); // 坐标点集合 ArrayList colorList = new ArrayList(); // 颜色集合 ArrayList type = new ArrayList(); // 类型集合 ArrayList layerName = new ArrayList(); ArrayList tableName = new ArrayList(); // 表名 System.Data.DataTable attributeList = new System.Data.DataTable(); // 属性集合 ArrayList attributeIndexList = new ArrayList(); //属性索引集合 ArrayList tuliList = new ArrayList(); //图例集合 string projectId = ""; //项目ID string chartName = ""; //表名称 ArrayList kgGuide = new ArrayList(); //控规引导 string srid = ""; //地理坐标系统编号 ArrayList parentId = new ArrayList(); //配套设施所在地块集合 ArrayList textContent = new ArrayList(); // 文字内容(GIS端展示) ArrayList blockContent = new ArrayList(); // 块内容(GIS端展示) Dictionary <string, string> result = new Dictionary <string, string>(); // 汇总 // 遍历所有实体 foreach (object entity in entities) { ArrayList singlePositionList = new ArrayList(); // 单个实体坐标点集合 //取得边界数 int loopNum = 1; if (entity is Hatch) { loopNum = (entity as Hatch).NumberOfLoops; type.Add("polygon"); } Point3dCollection col_point3d = new Point3dCollection(); BulgeVertexCollection col_ver = new BulgeVertexCollection(); Curve2dCollection col_cur2d = new Curve2dCollection(); for (int i = 0; i < loopNum; i++) { col_point3d.Clear(); HatchLoop hatLoop = null; if (entity is Hatch) { try { hatLoop = (entity as Hatch).GetLoopAt(i); } catch (System.Exception) { continue; } //如果HatchLoop为PolyLine if (hatLoop.IsPolyline) { col_ver = hatLoop.Polyline; foreach (BulgeVertex vertex in col_ver) { col_point3d.Add(new Point3d(vertex.Vertex.X, vertex.Vertex.Y, 0)); } } } // 如果实体为Polyline if (entity is Polyline) { // 类型 type.Add("polyline"); Polyline polyline = (Polyline)entity; int vn = polyline.NumberOfVertices; for (int w = 0; w < vn; w++) { Point2d pt = polyline.GetPoint2dAt(w); col_point3d.Add(new Point3d(pt.X, pt.Y, 0)); } } //// 如果实体为Curve //if (entity is Curve) //{ // col_cur2d = hatLoop.Curves; // foreach (Curve2d item in col_cur2d) // { // Point2d[] M_point2d = item.GetSamplePoints(numSample); // foreach (Point2d pt in M_point2d) // { // if (!col_point3d.Contains(new Point3d(pt.X, pt.Y, 0))) // col_point3d.Add(new Point3d(pt.X, pt.Y, 0)); // } // } //} // 如果实体为Point2d if (entity is DBPoint) { type.Add("point"); DBPoint entity3 = (DBPoint)entity; col_point3d.Add(new Point3d(entity3.Position.X, entity3.Position.Y, 0)); } // 如果实体为Point if (entity is Point3d) { type.Add("point"); Point3d entity3 = (Point3d)entity; col_point3d.Add(entity3); } // 如果实体为文字 if (entity is MText) { type.Add("text"); col_point3d.Add(new Point3d((entity as MText).Location.X, (entity as MText).Location.Y, 0)); } // 如果实体为文字 if (entity is DBText) { type.Add("text"); col_point3d.Add(new Point3d((entity as DBText).Position.X, (entity as DBText).Position.Y, 0)); } // 块参照 if (entity is BlockReference) { type.Add("block"); col_point3d.Add(new Point3d((entity as BlockReference).Position.X, (entity as BlockReference).Position.Y, 0)); } double[] pointPositionList = new double[2]; //单个点的坐标点集合 // 经纬度转换 foreach (Point3d point in col_point3d) { pointPositionList = new double[2] { Transform(point)[0], Transform(point)[1] }; singlePositionList.Add(pointPositionList); } // 经纬度转换结束 } // 单个实体几何坐标数量循环结束 // UUID Entity entityLayer = (Entity)entity; Guid guid = new Guid(); guid = Guid.NewGuid(); string str = guid.ToString(); uuid.Add(str); // 坐标 geom.Add(singlePositionList); // 颜色 if (entity is Point3d) { colorList.Add(""); // 图层名 layerName.Add("无"); } else { LayerTableRecord ltr = (LayerTableRecord)trans.GetObject(entityLayer.LayerId, OpenMode.ForRead); string color; color = entityLayer.ColorIndex == 256 ? MethodCommand.GetLayerColorByID(entityLayer.LayerId) : ColorTranslator.ToHtml(entityLayer.Color.ColorValue); colorList.Add(color); // 图层名 layerName.Add(ltr.Name); } // 表名 tableName.Add("a"); // 属性索引 // 获取每个闭合多段线对应的个体编号和用地代号 ArrayList tagList = new ArrayList(); PromptSelectionResult psrss = ed.SelectCrossingPolygon(col_point3d); // 获取闭合区域内实体方法 if (psrss.Status == PromptStatus.OK) { tagList.Clear(); SelectionSet SS = psrss.Value; ObjectId[] idArray = SS.GetObjectIds(); // 如果读取的块参照数量大于1,取中心点在闭合多段线的块参照 if (idArray.Length > 1) { for (int i = 0; i < idArray.Length; i++) { Entity ent1 = (Entity)idArray[i].GetObject(OpenMode.ForRead); if (ent1 is BlockReference) { BlockReference ent2 = (BlockReference)ent1; if (IsInPolygon(ent2.Position, col_point3d)) { foreach (ObjectId rt in ((BlockReference)ent1).AttributeCollection) { DBObject dbObj = trans.GetObject(rt, OpenMode.ForRead) as DBObject; AttributeReference acAttRef = dbObj as AttributeReference; tagList.Add(acAttRef.TextString); //MessageBox.Show("Tag: " + acAttRef.Tag + "\n" + // "Value: " + acAttRef.TextString + "\n"); } } } } } // 如果读取的块参照数量等于1,取中心点在闭合多段线的块参照 else { for (int i = 0; i < idArray.Length; i++) { Entity ent1 = (Entity)idArray[i].GetObject(OpenMode.ForRead); if (ent1 is BlockReference) { foreach (ObjectId rt in ((BlockReference)ent1).AttributeCollection) { DBObject dbObj = trans.GetObject(rt, OpenMode.ForRead) as DBObject; AttributeReference acAttRef = dbObj as AttributeReference; tagList.Add(acAttRef.TextString); } } } } } // 如果地块编码属性只有两个属性值,attributeIndexList,如果少于2个或者多于2个都视为异常,添加空。 if (tagList.Count == 2) { attributeIndexList.Add(tagList[0] + "_" + tagList[1]); } else { attributeIndexList.Add(""); } // 属性 readAttributeList attributeListObj = new readAttributeList(); attributeList = attributeListObj.AttributeList(); // 配套设施所属的地块UUID // 获取块参照的属性值 ArrayList blockAttribute = new ArrayList(); // 是否是地块编码本身 string isBlockNum = ""; // 如果这个块标注是幼儿园、公厕等,找对对应的地块编号或UUID if (entity is BlockReference) { // 清除原有内容 blockAttribute.Clear(); // 如果entity有两个属性值,可以判断这是一个地块编码 if (((BlockReference)entity).AttributeCollection.Count == 2) { isBlockNum = "Block"; } // 获取地块界限图层上的所有实体 ArrayList polylineEntities = new ArrayList(); // 找出地块界限里的所有闭合多段线,并判断当前块标注实体是否在某一个闭合多段线内,如果在,找出该闭合多段线内的块参照个体编号 TypedValue[] tvs = new TypedValue[1] { new TypedValue( (int)DxfCode.LayerName, "地块界限" ) }; SelectionFilter sf = new SelectionFilter(tvs); PromptSelectionResult psr = ed.SelectAll(sf); if (psr.Status == PromptStatus.OK) { SelectionSet SS = psr.Value; ObjectId[] idArray = SS.GetObjectIds(); //MessageBox.Show(idArray.Length.ToString()); Point3dCollection polylinePoint3d = new Point3dCollection(); for (int j = 0; j < idArray.Length; j++) { // 清除原有内容 polylinePoint3d.Clear(); Entity ent1 = trans.GetObject(idArray[j], OpenMode.ForWrite) as Entity; if (ent1 is Polyline && (ent1 as Polyline).Closed) { Polyline polyline = (Polyline)ent1; int vn = polyline.NumberOfVertices; for (int w = 0; w < vn; w++) { Point2d pt = polyline.GetPoint2dAt(w); polylinePoint3d.Add(new Point3d(pt.X, pt.Y, 0)); } // 获取闭合多段线(地块)内的所有实体 PromptSelectionResult psrss2 = ed.SelectCrossingPolygon(polylinePoint3d); if (psrss2.Status == PromptStatus.OK) { SelectionSet SS2 = psrss2.Value; ObjectId[] idArray2 = SS2.GetObjectIds(); // 如果读取的块参照数量大于1,且包含当前实体,找出当前块参照所在的闭合多段线 if (idArray2.Length > 1) { for (int i = 0; i < idArray2.Length; i++) { Entity ent2 = (Entity)idArray2[i].GetObject(OpenMode.ForRead); // 判断是否是配套设施开始 if (ent2 is BlockReference && (ent2 as BlockReference).Position.X == (entity as BlockReference).Position.X) { for (int k = 0; k < idArray2.Length; k++) { Entity ent3 = (Entity)idArray2[k].GetObject(OpenMode.ForRead); if (ent3 is BlockReference) { // 判断块参照中心点是否在闭合多段线内,只读取中心点在闭合多段线内的块参照 if (IsInPolygon((ent3 as BlockReference).Position, polylinePoint3d)) { foreach (ObjectId rt in ((BlockReference)ent3).AttributeCollection) { DBObject dbObj = trans.GetObject(rt, OpenMode.ForRead) as DBObject; AttributeReference acAttRef = dbObj as AttributeReference; blockAttribute.Add(acAttRef.TextString); } } } } } // 判断是否是配套设施结束 } } } // 获取闭合多段线(地块)内的所有实体结束 } } } } // 如果这个块标注是幼儿园、公厕等,找对对应的地块编号或UUID 结束 // 如果地块编码属性只有两个属性值,而且不是地块编码块参照,添加到parentId,如果少于2个或者多于2个都视为异常,添加空。 if (blockAttribute.Count == 2 && isBlockNum != "Block") { parentId.Add(blockAttribute[0] + "_" + blockAttribute[1]); } else { parentId.Add(""); } // 文字内容(GIS端展示) if (entity is DBText) { textContent.Add((entity as DBText).TextString); } else if (entity is MText) { textContent.Add((entity as MText).Text); } else if (entity is BlockReference) { List <string> singleBlockContent = new List <string>(); string text = ""; if ((entity as BlockReference).AttributeCollection.Count > 0) { foreach (ObjectId rt in ((BlockReference)entity).AttributeCollection) { DBObject dbObj = trans.GetObject(rt, OpenMode.ForRead) as DBObject; AttributeReference acAttRef = dbObj as AttributeReference; text = text + acAttRef.TextString + "//"; } text = text.Substring(0, text.Length - 2); } textContent.Add(text); } else { textContent.Add(""); } // 块内容(GIS端展示) if (entity is BlockReference) { List <string> singleBlockContent = new List <string>(); string text = "//"; foreach (ObjectId rt in ((BlockReference)entity).AttributeCollection) { DBObject dbObj = trans.GetObject(rt, OpenMode.ForRead) as DBObject; AttributeReference acAttRef = dbObj as AttributeReference; text = acAttRef.TextString + text; //singleBlockContent.Add(acAttRef.TextString); } blockContent.Add(text); //blockContent.Add(singleBlockContent); } else { blockContent.Add(""); } } // 所有的实体循环结束 // 图例 readAttributeList attributeListObj3 = new readAttributeList(); //tuliList.Add(attributeListObj3.TuliList()); tuliList.Add(""); // 项目名 //string projectIdBaseAddress = "http://172.18.84.70:8081/PDD/pdd/individual-manage!findAllProject.action"; //var projectIdHttp = (HttpWebRequest)WebRequest.Create(new Uri(projectIdBaseAddress)); //var response = projectIdHttp.GetResponse(); //var stream = response.GetResponseStream(); //var sr = new StreamReader(stream, Encoding.UTF8); //var content = sr.ReadToEnd(); //MessageBox.Show(content); projectId = "D3DEC178-2C05-C5F1-F6D3-45729EB9436A"; // 图表名或者叫文件名 chartName = Path.GetFileName(ed.Document.Name); // 控规引导 readAttributeList attributeListObj2 = new readAttributeList(); kgGuide = attributeListObj2.KgGuide(); //地理坐标系统编号 srid = "4326"; // 发文字信息 RegulatoryPost.FenTuZe.FenTuZe.SendData(result, uuid, geom, colorList, type, layerName, tableName, attributeIndexList, attributeList, tuliList, projectId, chartName, kgGuide, srid, parentId, textContent, blockContent); }
// 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 AttributeInfo([NotNull] AttributeReference atrRef) { Tag = atrRef.Tag; Text = atrRef.TextString; IdAtr = atrRef.Id; }
internal void RemoveAttributeExtent(AttributeReference extentRef) { FileRecord fileRec = GetFileRecord(extentRef.File); if (fileRec != null) { fileRec.RemoveAttribute(extentRef.AttributeId); // Remove empty non-primary MFT records if (fileRec.Attributes.Count == 0 && fileRec.BaseFile.Value != 0) { RemoveFileRecord(extentRef.File); } } }
public static bool Is([NotNull] this AttributeReference attr, string tag) { return(string.Equals(attr.Tag, tag, StringComparison.CurrentCultureIgnoreCase)); }
internal void MakeAttributeNonResident(AttributeReference attrRef, int maxData) { NtfsAttribute attr = GetAttribute(attrRef); if (attr.IsNonResident) { throw new InvalidOperationException("Attribute is already non-resident"); } ushort id = _records[0].CreateNonResidentAttribute(attr.Type, attr.Name, attr.Flags); AttributeRecord newAttrRecord = _records[0].GetAttribute(id); IBuffer attrBuffer = attr.GetDataBuffer(); byte[] tempData = Utilities.ReadFully(attrBuffer, 0, (int)Math.Min(maxData, attrBuffer.Capacity)); RemoveAttributeExtents(attr); attr.SetExtent(_records[0].Reference, newAttrRecord); attr.GetDataBuffer().Write(0, tempData, 0, tempData.Length); UpdateAttributeList(); }
public void AddAnEnt(List <BlockReferencePlacement> t) { // get the editor object so we can carry out some input Editor ed = Application.DocumentManager.MdiActiveDocument.Editor; // if ok // enter the name of the block string blockName = "RebarAtt"; Database dwg = ed.Document.Database; Transaction trans = (Transaction)dwg.TransactionManager.StartTransaction(); try { BlockTableRecord newBlockDef = new BlockTableRecord(); newBlockDef.Name = blockName; BlockTable blockTable = (BlockTable)trans.GetObject(dwg.BlockTableId, OpenMode.ForRead); if ((blockTable.Has(blockName) == false)) { blockTable.UpgradeOpen(); blockTable.Add(newBlockDef); trans.AddNewlyCreatedDBObject(newBlockDef, true); //Define a new block Circle circle1 = new Circle(); circle1.Center = new Point3d(0, 0, 0); circle1.Radius = 1000; newBlockDef.AppendEntity(circle1); AttributeDefinition att1 = new AttributeDefinition(); att1.Tag = "No"; att1.Position = new Point3d(-1000, 0, 0); AttributeDefinition att2 = new AttributeDefinition(); att2.Tag = "Diameter"; att2.Position = new Point3d(0, 0, 0); AttributeDefinition att3 = new AttributeDefinition(); att3.Tag = "Spacing"; att3.Position = new Point3d(1000, 0, 0); AttributeDefinition att4 = new AttributeDefinition(); att4.Tag = "Length"; att4.Position = new Point3d(0, 1000, 0); AttributeDefinition att5 = new AttributeDefinition(); att5.Tag = "Distance"; att5.Position = new Point3d(0, -1000, 0); newBlockDef.AppendEntity(att1); newBlockDef.AppendEntity(att2); newBlockDef.AppendEntity(att3); newBlockDef.AppendEntity(att4); newBlockDef.AppendEntity(att5); trans.AddNewlyCreatedDBObject(circle1, true); trans.AddNewlyCreatedDBObject(att1, true); trans.AddNewlyCreatedDBObject(att2, true); trans.AddNewlyCreatedDBObject(att3, true); trans.AddNewlyCreatedDBObject(att4, true); trans.AddNewlyCreatedDBObject(att5, true); //Declare a BlockReference to place in current Space of Autocad BlockReference blockRef = new BlockReference(t[0].xyz, newBlockDef.ObjectId); BlockTableRecord curSpace = (BlockTableRecord)trans.GetObject(dwg.CurrentSpaceId, OpenMode.ForWrite); //Append Block Reference to this space curSpace.AppendEntity(blockRef); trans.AddNewlyCreatedDBObject(blockRef, true); //BlockTableRecord, get the blockname to read its Attribute Definition BlockTableRecord blockDef = blockTable[blockName].GetObject(OpenMode.ForRead) as BlockTableRecord; foreach (ObjectId id in blockDef) { AttributeDefinition attributeDefinition = id.GetObject(OpenMode.ForRead) as AttributeDefinition; if ((attributeDefinition != null) && (!attributeDefinition.Constant)) { switch (attributeDefinition.Tag) { case "No": using (AttributeReference attRef = new AttributeReference()) { attRef.SetAttributeFromBlock(attributeDefinition, blockRef.BlockTransform); attRef.TextString = t[0].numberofsteels; //Add the AttributeReference to the BlockReference blockRef.AttributeCollection.AppendAttribute(attRef); trans.AddNewlyCreatedDBObject(attRef, true); } break; case "Diameter": using (AttributeReference attRef = new AttributeReference()) { attRef.SetAttributeFromBlock(attributeDefinition, blockRef.BlockTransform); attRef.TextString = t[0].diameter; //Add the AttributeReference to the BlockReference blockRef.AttributeCollection.AppendAttribute(attRef); trans.AddNewlyCreatedDBObject(attRef, true); } break; case "Spacing": using (AttributeReference attRef = new AttributeReference()) { attRef.SetAttributeFromBlock(attributeDefinition, blockRef.BlockTransform); attRef.TextString = t[0].spacing; //Add the AttributeReference to the BlockReference blockRef.AttributeCollection.AppendAttribute(attRef); trans.AddNewlyCreatedDBObject(attRef, true); } break; case "Length": using (AttributeReference attRef = new AttributeReference()) { attRef.SetAttributeFromBlock(attributeDefinition, blockRef.BlockTransform); attRef.TextString = t[0].length.ToString(); //Add the AttributeReference to the BlockReference blockRef.AttributeCollection.AppendAttribute(attRef); trans.AddNewlyCreatedDBObject(attRef, true); } break; case "Distance": using (AttributeReference attRef = new AttributeReference()) { attRef.SetAttributeFromBlock(attributeDefinition, blockRef.BlockTransform); attRef.TextString = t[0].distance.ToString(); //Add the AttributeReference to the BlockReference blockRef.AttributeCollection.AppendAttribute(attRef); trans.AddNewlyCreatedDBObject(attRef, true); } break; } } } // 34. If the code makes it here then all is ok. Commit the transaction by calling // the Commit method trans.Commit(); } else { BlockTableRecord blockDef = blockTable[blockName].GetObject(OpenMode.ForRead) as BlockTableRecord; //Declare a BlockReference to place in current Space of Autocad BlockReference blockRef = new BlockReference(t[0].xyz, blockDef.ObjectId); BlockTableRecord curSpace = (BlockTableRecord)trans.GetObject(dwg.CurrentSpaceId, OpenMode.ForWrite); //Append Block Reference to this space curSpace.AppendEntity(blockRef); trans.AddNewlyCreatedDBObject(blockRef, true); //BlockTableRecord, get the blockname to read its Attribute Definition foreach (ObjectId id in blockDef) { AttributeDefinition attributeDefinition = id.GetObject(OpenMode.ForRead) as AttributeDefinition; if ((attributeDefinition != null) && (!attributeDefinition.Constant)) { switch (attributeDefinition.Tag) { case "No": using (AttributeReference attRef = new AttributeReference()) { attRef.SetAttributeFromBlock(attributeDefinition, blockRef.BlockTransform); attRef.TextString = t[0].numberofsteels; //Add the AttributeReference to the BlockReference blockRef.AttributeCollection.AppendAttribute(attRef); trans.AddNewlyCreatedDBObject(attRef, true); } break; case "Diameter": using (AttributeReference attRef = new AttributeReference()) { attRef.SetAttributeFromBlock(attributeDefinition, blockRef.BlockTransform); attRef.TextString = t[0].diameter; //Add the AttributeReference to the BlockReference blockRef.AttributeCollection.AppendAttribute(attRef); trans.AddNewlyCreatedDBObject(attRef, true); } break; case "Spacing": using (AttributeReference attRef = new AttributeReference()) { attRef.SetAttributeFromBlock(attributeDefinition, blockRef.BlockTransform); attRef.TextString = t[0].spacing; //Add the AttributeReference to the BlockReference blockRef.AttributeCollection.AppendAttribute(attRef); trans.AddNewlyCreatedDBObject(attRef, true); } break; case "Length": using (AttributeReference attRef = new AttributeReference()) { attRef.SetAttributeFromBlock(attributeDefinition, blockRef.BlockTransform); attRef.TextString = t[0].length.ToString(); //Add the AttributeReference to the BlockReference blockRef.AttributeCollection.AppendAttribute(attRef); trans.AddNewlyCreatedDBObject(attRef, true); } break; case "Distance": using (AttributeReference attRef = new AttributeReference()) { attRef.SetAttributeFromBlock(attributeDefinition, blockRef.BlockTransform); attRef.TextString = t[0].distance.ToString(); //Add the AttributeReference to the BlockReference blockRef.AttributeCollection.AppendAttribute(attRef); trans.AddNewlyCreatedDBObject(attRef, true); } break; } } } // 34. If the code makes it here then all is ok. Commit the transaction by calling // the Commit method trans.Commit(); } } catch (Autodesk.AutoCAD.Runtime.Exception ex) { ed.WriteMessage("Chon dung hoac it hon 6 Block thoi nha! " + ex.Message); } finally { trans.Dispose(); } }
private void MoveAttribute(FileRecord record, AttributeRecord attrRec, FileRecord targetRecord) { AttributeReference oldRef = new AttributeReference(record.Reference, attrRec.AttributeId); record.RemoveAttribute(attrRec.AttributeId); targetRecord.AddAttribute(attrRec); AttributeReference newRef = new AttributeReference(targetRecord.Reference, attrRec.AttributeId); foreach (var attr in _attributes) { attr.ReplaceExtent(oldRef, newRef, attrRec); } UpdateAttributeList(); }
//SELECIONAR UMA REGIÃO DO PROJETO PARA LEVANTAR O QUANTITATIVO public List <Elemento> SelecionarBlocos() { List <double> contagem = new List <double>(); int Id = 0; Document acDoc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument; Database acCurDb = acDoc.Database; Editor acDocEd = acDoc.Editor; List <string> listaDeAtributos = new List <string>(); //COMEÇAR UMA TRANSAÇÃO using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction()) { //CRIAR UM ARRAY COM O(S) TIPO(S) DE OBJETO(S) A SER(EM) FILTRADO(S) TypedValue[] acTypValAr = new TypedValue[1]; //acTypValAr.SetValue(new TypedValue((int)DxfCode.Start, "CIRCLE"), 0); acTypValAr.SetValue(new TypedValue((int)DxfCode.Start, "INSERT"), 0); //CRIAR O FILTRO COM O ARRAY DECLARADO ACIMA SelectionFilter acSelFtr = new SelectionFilter(acTypValAr); //É PEDIDO AO USUÁRIO SELECIONAR UMA REGIÃO DO DESENHO PromptSelectionResult acSSPrompt = acDocEd.GetSelection(acSelFtr); string tipo = ""; string id = ""; string nome = ""; string quant = "0"; //CASO ELE SELECIONE UMA REGIÃO if (acSSPrompt.Status == PromptStatus.OK) { SelectionSet acSSet = acSSPrompt.Value; //PERCORRE OS OBJETOS DO CONJUNTO DE SELEÇÃO foreach (SelectedObject acSSObj in acSSet) { Elemento elemento = new Elemento(); //VERIFICAR SE O OBJETO SELECIONADO EXISTE if (acSSObj != null) { // Open the selected object for write Entity acEnt = acTrans.GetObject(acSSObj.ObjectId, OpenMode.ForRead) as Entity; contagem.Add(10); if (acEnt.GetType() == typeof(BlockReference)) { Id++; id = Convert.ToString(Id); BlockReference blRef = acEnt as BlockReference; nome = blRef.Name; elemento.Nome = nome; AttributeCollection atributos = blRef.AttributeCollection; int qtde = atributos.Count; //----->>>>>>>>>> quantidade de atributos no bloco //MessageBox.Show(qtde.ToString(), "Contagem de blocos", MessageBoxButtons.OK, MessageBoxIcon.Information); if (qtde > 0) { foreach (ObjectId AttId in atributos) { AttributeReference attref = (AttributeReference)acTrans.GetObject(AttId, OpenMode.ForRead); if (attref != null) { listaDeAtributos.Add(attref.TextString); //MessageBox.Show(attref.TextString, "Contagem de blocos", MessageBoxButtons.OK, MessageBoxIcon.Information); elemento.Especificacao = attref.TextString; } } //elemento.Especificacao = MontaEspecificacaoBloco(listaDeAtributos); } if (qtde <= 0) { elemento.Especificacao = "Peça sem atributo associado"; } elemento.Tipo = "bloco"; elemento.Quantificacao = quant; elemento.ID = id; //tipo = RetornaTipoElemento(nome); //MessageBox.Show("Nome do bloco: " + nome, "Contagem de blocos", MessageBoxButtons.OK, MessageBoxIcon.Information); //Now you can open BlockTableRecord: //BlockTableRecord acBlkTblRec = acTrans.GetObject(blRef.BlockTableRecord, OpenMode.ForRead) as BlockTableRecord; //foreach (ObjectId eid in acBlkTblRec) //{ // DBObject obj = (Entity)acTrans.GetObject(eid, OpenMode.ForRead); // // if (obj is AttributeDefinition) // { // AttributeDefinition atdef = obj as AttributeDefinition; // if (atdef.Constant) // { // Id++; // id = Convert.ToString(Id); // especificacao = atdef.Tag; // elemento.ID = id; // elemento.Especificacao = especificacao; // elemento.Quantificacao = quant; // MessageBox.Show(atdef.Tag, "Contagem de blocos", MessageBoxButtons.OK, MessageBoxIcon.Information); // MessageBox.Show(atdef.TextString, "Contagem de blocos", MessageBoxButtons.OK, MessageBoxIcon.Information); // } // } // //} //acBlkTblRec.Dispose(); //AttributeCollection attCol = blRef.AttributeCollection; //foreach (ObjectId attId in attCol) //{ // AttributeReference attRef = (AttributeReference)acTrans.GetObject(attId, OpenMode.ForRead); // string str = ("\n Attribute Tag: " + attRef.Tag + "\n Attribute String: " + attRef.TextString); // MessageBox.Show(str, "Contagem de blocos", MessageBoxButtons.OK, MessageBoxIcon.Information); //} } } if (elemento.Nome != "") { listaElementos.Add(elemento); } } //SALVAR O OBJETO NO BANCO DE DADOS acTrans.Commit(); } //int qtd = contagem.Count(); //MessageBox.Show("Número de blocos selecionados: " + qtd.ToString(), "Contagem de blocos", MessageBoxButtons.OK, MessageBoxIcon.Information); // Dispose of the transaction } return(listaElementos); }