private void GetBlockLengths(ObjectId objectId) { double blockWidth = 0, blockHeight = 0; using (Transaction Tx = Active.Database.TransactionManager.StartTransaction()) { BlockReference bref = Tx.GetObject(objectId, OpenMode.ForWrite) as BlockReference; this.ScaleX = bref.ScaleFactors.X; Point3d blockPos3d = Autodesk.AutoCAD.Internal.Utils.UcsToDisplay(new Point3d(bref.Position.X, bref.Position.Y, 0), false); MinPointX = blockPos3d.X; MinPointY = blockPos3d.Y; BlockPosition = new Point2d(MinPointX, MinPointY); DynamicBlockReferencePropertyCollection props = bref.DynamicBlockReferencePropertyCollection; foreach (DynamicBlockReferenceProperty prop in props) { if (prop.PropertyName == "Ширина") { blockWidth = double.Parse(prop.Value.ToString(), System.Globalization.CultureInfo.InvariantCulture); } if (prop.PropertyName == "Высота") { blockHeight = double.Parse(prop.Value.ToString(), System.Globalization.CultureInfo.InvariantCulture); } if (prop.PropertyName == "Штамп") { StampViewName = prop.Value.ToString(); } } BlockDimensions = new Point2d(BlockPosition.X + blockWidth, BlockPosition.Y + blockHeight); Tx.Commit(); } }
protected void SetPropertyOnObject(string name, object value) { Transaction acTrans = _database.TransactionManager.TopTransaction; BlockReference reference = (BlockReference)acTrans.GetObject(BaseObject, OpenMode.ForWrite); if (reference.IsDynamicBlock) { DynamicBlockReferencePropertyCollection pc = reference.DynamicBlockReferencePropertyCollection; foreach (DynamicBlockReferenceProperty dynamicBlockReferenceProperty in pc) { if (dynamicBlockReferenceProperty.PropertyName == name) { dynamicBlockReferenceProperty.Value = value; return; } } foreach (ObjectId attId in reference.AttributeCollection) { AttributeReference attRef = (AttributeReference)acTrans.GetObject(attId, OpenMode.ForRead); if (attRef.Tag == name) { attRef.UpgradeOpen(); attRef.TextString = (string)value; return; } } throw new InvalidOperationException("Property not found"); } else { throw new NotImplementedException(); } }
public void GetBlockDimensions(ObjectId objectId) { double blockWidth = 0, blockHeidht = 0; using (Transaction Tx = Active.Database.TransactionManager.StartTransaction()) { BlockReference bref = Tx.GetObject(objectId, OpenMode.ForWrite) as BlockReference; DynamicBlockReferencePropertyCollection props = bref.DynamicBlockReferencePropertyCollection; foreach (DynamicBlockReferenceProperty prop in props) { object[] values = prop.GetAllowedValues(); if (prop.PropertyName == "Ширина") { this.Width = double.Parse(prop.Value.ToString(), System.Globalization.CultureInfo.InvariantCulture); Active.Editor.WriteMessage(blockWidth.ToString()); } if (prop.PropertyName == "Высота") { this.Height = double.Parse(prop.Value.ToString(), System.Globalization.CultureInfo.InvariantCulture); Active.Editor.WriteMessage("\n{0}", blockHeidht.ToString()); } } Tx.Commit(); } }
/// <summary> /// This updates the Dyanmic Blockreference with given Width and Height /// The initial parameters of Dynamic Blockrefence, Width =20.00 and Height =40.00 /// </summary> /// <param Editor="ed"></param> /// <param BlockReference="br"></param> /// <param String="name"></param> private static void UpdateDynamicProperties(BlockReference br, InputParams inputParams) { // Only continue is we have a valid dynamic block if (br != null && br.IsDynamicBlock) { // Get the dynamic block's property collection DynamicBlockReferencePropertyCollection pc = br.DynamicBlockReferencePropertyCollection; foreach (DynamicBlockReferenceProperty prop in pc) { switch (prop.PropertyName) { case "Width": prop.Value = inputParams.Width; break; case "Height": prop.Value = inputParams.Height; break; default: break; } } } }
public static void SetDynamicParameterValue(this BlockReference block, string parameterName, object parameterValue) { if (block.IsDynamicBlock) { DynamicBlockReferencePropertyCollection pc = block.DynamicBlockReferencePropertyCollection; DynamicBlockReferenceProperty prop = pc .Cast <DynamicBlockReferenceProperty>() .FirstOrDefault(p => p.PropertyName.Equals(parameterName, StringComparison.InvariantCulture)); if (prop != null) { if (prop.PropertyTypeCode == (short)DynamicPropertyTypes.Distance) { prop.Value = parameterValue; } else if (prop.PropertyTypeCode == (short)DynamicPropertyTypes.Visibility) { object val = prop.GetAllowedValues() .First(n => n.ToString() == parameterValue.ToString()); prop.Value = val; } } else { throw new ArgumentException("No parameter " + parameterName); } } }
private static string ReadDynamicPropertyValue(this BlockReference br, string propertyName) { DynamicBlockReferencePropertyCollection props = br.DynamicBlockReferencePropertyCollection; foreach (DynamicBlockReferenceProperty property in props) { //prdDbg($"Name: {property.PropertyName}, Units: {property.UnitsType}, Value: {property.Value}"); if (property.PropertyName == propertyName) { switch (property.UnitsType) { case DynamicBlockReferencePropertyUnitsType.NoUnits: return(property.Value.ToString()); case DynamicBlockReferencePropertyUnitsType.Angular: double angular = Convert.ToDouble(property.Value); return(angular.ToDegrees().ToString("0.##")); case DynamicBlockReferencePropertyUnitsType.Distance: double distance = Convert.ToDouble(property.Value); return(distance.ToString("0.##")); case DynamicBlockReferencePropertyUnitsType.Area: double area = Convert.ToDouble(property.Value); return(area.ToString("0.00")); default: return(""); } } } return(""); }
public static bool Contains(this DynamicBlockReferencePropertyCollection properties, string name) { Require.ParameterNotNull(properties, nameof(properties)); Require.StringNotEmpty(name, nameof(name)); return(properties.Cast <DynamicBlockReferenceProperty>() .Any(p => p.PropertyName == name)); }
private void Initialize(DynamicBlockReferencePropertyCollection pc) { if (pc == null) { throw new ArgumentNullException("pc"); } this._pc = pc; }
public static void LerTodosOsBlocosEBuscarOsAtributos() { Document documentoAtivo = Application.DocumentManager.MdiActiveDocument; Database database = documentoAtivo.Database; using (Transaction acTrans = database.TransactionManager.StartTransaction()) { BlockTable blockTable; blockTable = acTrans.GetObject(database.BlockTableId, OpenMode.ForRead) as BlockTable; try { _lista = new List <AtributosDoBloco>(); foreach (string nome in ConstantesTubulacao.TubulacaoNomeDosBlocos) { BlockTableRecord blockTableRecord; blockTableRecord = acTrans.GetObject(blockTable[nome], OpenMode.ForRead) as BlockTableRecord; foreach (ObjectId objId_loopVariable in blockTableRecord) { BlockReference blocoDinamico; blocoDinamico = (BlockReference)acTrans.GetObject(objId_loopVariable, OpenMode.ForRead) as BlockReference; DynamicBlockReferencePropertyCollection properties = blocoDinamico.DynamicBlockReferencePropertyCollection; AtributosDoBloco Atributo1 = new AtributosDoBloco(); for (int i = 0; i < properties.Count; i++) { DynamicBlockReferenceProperty property = properties[i]; if (property.PropertyName == "Distance1") { Atributo1.Distancia = property.Value.ToString(); } } Atributo1.X = blocoDinamico.Position.X; Atributo1.Y = blocoDinamico.Position.Y; Atributo1.nomeBloco = blocoDinamico.Name; Atributo1.Handle = blocoDinamico.Handle.ToString(); Atributo1.Angulo = blocoDinamico.Rotation; _lista.Add(Atributo1); } continue; } } catch (Exception e) { FinalizaTarefasAposExcecao("Ocorreu um erro ao ler os blocos do AutoCAD.", e); } acTrans.Commit(); } }
static public void SetDynamicBlkProperty() { Document doc = Application.DocumentManager.MdiActiveDocument; Database db = doc.Database; Editor ed = doc.Editor; PromptEntityOptions prEntOptions = new PromptEntityOptions("Выберите вставку динамического блока..."); PromptEntityResult prEntResult = ed.GetEntity(prEntOptions); if (prEntResult.Status != PromptStatus.OK) { ed.WriteMessage("Ошибка..."); return; } using (Transaction Tx = db.TransactionManager.StartTransaction()) { BlockReference bref = Tx.GetObject(prEntResult.ObjectId, OpenMode.ForWrite) as BlockReference; double blockWidth = 0; if (bref.IsDynamicBlock) { DynamicBlockReferencePropertyCollection props = bref.DynamicBlockReferencePropertyCollection; foreach (DynamicBlockReferenceProperty prop in props) { object[] values = prop.GetAllowedValues(); if (prop.PropertyName == "Штамп") { BlockTableRecord btr = (BlockTableRecord)Tx.GetObject(bref.BlockTableRecord, OpenMode.ForRead); btr.Dispose(); AttributeCollection attCol = bref.AttributeCollection; var attrDict = AttributeExtensions.GetAttributesValues(bref); if (prop.Value.ToString() == "Форма 3 ГОСТ Р 21.1101 - 2009") { blockWidth = double.Parse(prop.Value.ToString(), CultureInfo.InvariantCulture); } ed.WriteMessage(blockWidth.ToString()); } //if (prop.PropertyName == "Высота") //{ // blockHeidht = double.Parse(prop.Value.ToString(), System.Globalization.CultureInfo.InvariantCulture); // ed.WriteMessage("\n{0}", blockHeidht.ToString()); //} } } Tx.Commit(); } }
public static void SetValue(this DynamicBlockReferencePropertyCollection properties, string name, object value) { Require.ParameterNotNull(properties, nameof(properties)); Require.StringNotEmpty(name, nameof(name)); var property = properties.Cast <DynamicBlockReferenceProperty>() .FirstOrDefault(a => a.PropertyName == name); Require.ObjectNotNull(property, $"No {nameof(DynamicBlockReferenceProperty)} with name '{name}' found"); property.Value = value; }
private static DynamicBlockReferenceProperty GetDynamicPropertyByName(this BlockReference br, string name) { DynamicBlockReferencePropertyCollection pc = br.DynamicBlockReferencePropertyCollection; foreach (DynamicBlockReferenceProperty property in pc) { if (property.PropertyName == name) { return(property); } } return(null); }
public static object GetValue(this DynamicBlockReferencePropertyCollection properties, string name) { var property = properties.Cast <DynamicBlockReferenceProperty>() .FirstOrDefault(p => p.PropertyName == name); if (property == null) { throw Error.KeyNotFound(name); } else { return(property.Value); } }
public static void SetValue(this DynamicBlockReferencePropertyCollection properties, string name, object value) { var property = properties.Cast <DynamicBlockReferenceProperty>() .FirstOrDefault(a => a.PropertyName == name); if (property == null) { throw Error.KeyNotFound(name); } else { property.Value = value; } }
/// <summary> /// Текущее значение параметра видимости динамического блока /// </summary> /// <param name="block"></param> /// <returns>Текущее значение параметра видиомсти, /// если параметра видимости нет - пустая строка</returns> public static string GetCurrentVisibilityValue(this BlockReference block) { if (block.IsDynamicBlock) { DynamicBlockReferencePropertyCollection pc = block.DynamicBlockReferencePropertyCollection; foreach (DynamicBlockReferenceProperty property in pc) { if (property.PropertyTypeCode == 5) { return(property.Value.ToString()); } } } return(string.Empty); }
/// <summary> /// Получение возможный значений параметра видимости /// </summary> /// <param name="block"></param> /// <returns>Массив названий видимости. Если параметра видимости нет - null</returns> public static string[] GetVisibilityValues(this BlockReference block) { if (block.IsDynamicBlock) { DynamicBlockReferencePropertyCollection pc = block.DynamicBlockReferencePropertyCollection; foreach (DynamicBlockReferenceProperty property in pc) { if (property.PropertyTypeCode == 5) { return(property.GetAllowedValues().Select(n => n.ToString()).ToArray()); } } } return(null); }
private static string GetBlockAttributeValueByAttrName(BlockReference blkRef) { DynamicBlockReferencePropertyCollection props = blkRef.DynamicBlockReferencePropertyCollection; string blockStamp = ""; foreach (DynamicBlockReferenceProperty prop in props) { if (prop.PropertyName == "Штамп") { blockStamp = prop.Value.ToString(); } } return(blockStamp); }
public static object GetDynamicPropertyValue(this BlockReference block, string propertyname) { if (block.IsDynamicBlock) { DynamicBlockReferencePropertyCollection pc = block.DynamicBlockReferencePropertyCollection; foreach (DynamicBlockReferenceProperty property in pc) { if (property.PropertyName.Equals(propertyname, StringComparison.InvariantCulture)) { return(property.Value); } } } return(null); }
private void GetTopAndBottomPoint(BlockReference block, Transaction tr) { model = new AreaBorderModel(); model.handle = Goodies.ConvertHandleToString(block.Handle); model.position = new Point3dModel(block.Position.ToArray()); model.matrixTransform = new Matrix3dModel(block.BlockTransform.ToArray()); DynamicBlockReferencePropertyCollection dynBlockPropCol = block.DynamicBlockReferencePropertyCollection; foreach (DynamicBlockReferenceProperty dynProp in dynBlockPropCol) { if (dynProp.PropertyName.Equals(DBFixtureBeingUsedAreaName.X)) { model.X = (double)dynProp.Value; } else if (dynProp.PropertyName.Equals(DBFixtureBeingUsedAreaName.Y)) { model.Y = (double)dynProp.Value; } else if (dynProp.PropertyName.Equals("Origin")) { model.origin = new Point3dModel(((Point3d)dynProp.Value).ToArray()); } } foreach (ObjectId id in block.AttributeCollection) { AttributeReference aRef = (AttributeReference)tr.GetObject(id, OpenMode.ForRead); if (aRef.Tag == AreaBroderModelName.type) { model.type = aRef.TextString; } else if (aRef.Tag == AreaBroderModelName.alias) { model.alias = aRef.TextString; } } Point3d pointTop = new Point3d(model.origin.X, model.origin.Y, 0); //Use the regular X,Y coordinate, DO NOT use Game or Web coordinate Point3d pointBottom = new Point3d(model.origin.X + model.X, model.origin.Y - model.Y, 0); pointTop = pointTop.TransformBy(block.BlockTransform); pointBottom = pointBottom.TransformBy(block.BlockTransform); model.pointBottom = new Point3dModel(pointBottom.ToArray()); model.pointTop = new Point3dModel(pointTop.ToArray()); }
private static void DisplayDynBlockProperties(Editor ed, BlockReference br, string name) { // Only continue is we have a valid dynamic block if (br != null && br.IsDynamicBlock) { ed.WriteMessage("\nDynamic properties for \"{0}\"\n", name); // Get the dynamic block's property collection DynamicBlockReferencePropertyCollection pc = br.DynamicBlockReferencePropertyCollection; // Loop through, getting the info for each property foreach (DynamicBlockReferenceProperty prop in pc) { // Start with the property name, type and description ed.WriteMessage("\nProperty: \"{0}\" : {1}", prop.PropertyName, prop.UnitsType); if (prop.Description != "") { ed.WriteMessage("\n Description: {0}", prop.Description); } // Is it read-only? if (prop.ReadOnly) { ed.WriteMessage(" (Read Only)"); } // Get the allowed values, if it's constrained bool first = true; foreach (object value in prop.GetAllowedValues()) { ed.WriteMessage((first ? "\n Allowed values: [" : ", ")); ed.WriteMessage("\"{0}\"", value); first = false; } if (!first) { ed.WriteMessage("]"); } // And finally the current value ed.WriteMessage("\n Current value: \"{0}\"\n", prop.Value); } } }
protected void GetProperties() { Transaction acTrans = _database.TransactionManager.TopTransaction; BlockReference reference = (BlockReference)acTrans.GetObject(BaseObject, OpenMode.ForRead); if (reference.IsDynamicBlock) { DynamicBlockReferencePropertyCollection pc = reference.DynamicBlockReferencePropertyCollection; foreach (DynamicBlockReferenceProperty dynamicBlockReferenceProperty in pc) { if (_properties.ContainsKey(dynamicBlockReferenceProperty.PropertyName)) { _properties[dynamicBlockReferenceProperty.PropertyName] = dynamicBlockReferenceProperty.Value; } else { _properties.Add(dynamicBlockReferenceProperty.PropertyName, dynamicBlockReferenceProperty.Value); } } foreach (ObjectId attId in reference.AttributeCollection) { AttributeReference attRef = (AttributeReference)acTrans.GetObject(attId, OpenMode.ForRead); if (_properties.ContainsKey(attRef.Tag)) { _properties[attRef.Tag] = attRef.TextString; } else { _properties.Add(attRef.Tag, attRef.TextString); } } } else { throw new NotImplementedException(); } }
private void GetTopAndBottomPoint(BlockReference block) { model = new FixtureBeingUsedAreaModel(); model.handle = Goodies.ConvertHandleToString(block.Handle); model.position = new Point3dModel(block.Position.ToArray()); model.matrixTransform = new Matrix3dModel(block.BlockTransform.ToArray()); DynamicBlockReferencePropertyCollection dynBlockPropCol = block.DynamicBlockReferencePropertyCollection; foreach (DynamicBlockReferenceProperty dynProp in dynBlockPropCol) { if (dynProp.PropertyName.Equals(DBFixtureBeingUsedAreaName.X)) { model.X = (double)dynProp.Value; } else if (dynProp.PropertyName.Equals(DBFixtureBeingUsedAreaName.Y)) { model.Y = (double)dynProp.Value; } else if (dynProp.PropertyName.Equals("Origin")) { model.origin = new Point3dModel(((Point3d)dynProp.Value).ToArray()); } } Point3d pointTop = new Point3d(model.origin.X, model.origin.Y, 0); //Use the regular X,Y coordinate, DO NOT use Game or Web coordinate Point3d pointBottom = new Point3d(model.origin.X + model.X, model.origin.Y - model.Y, 0); pointTop = pointTop.TransformBy(block.BlockTransform); pointBottom = pointBottom.TransformBy(block.BlockTransform); model.pointBottom = new Point3dModel(pointBottom.ToArray()); model.pointTop = new Point3dModel(pointTop.ToArray()); }
public static void LerTodosOsBlocosEBuscarOsAtributos() { Document documentoAtivo = Application.DocumentManager.MdiActiveDocument; Database database = documentoAtivo.Database; Editor editor = documentoAtivo.Editor; using (Transaction acTrans = documentoAtivo.TransactionManager.StartTransaction()) { BlockTable blockTable; blockTable = acTrans.GetObject(database.BlockTableId, OpenMode.ForRead) as BlockTable; //TypedValue[] acTypValAr = new TypedValue[0]; // acTypValAr.SetValue(new TypedValue((int)DxfCode.Start, "BLOCK"),0); //SelectionFilter acSelFtr = new SelectionFilter(acTypValAr); PromptSelectionResult pmtSelRes = editor.GetSelection(); if (pmtSelRes.Status == PromptStatus.OK) { _lista = new List <AtributosDoBloco>(); foreach (ObjectId id in pmtSelRes.Value.GetObjectIds()) { try { AtributosDoBloco Atributo1 = new AtributosDoBloco(); foreach (string nome in ConstantesTubulacao.TubulacaoNomeDosBlocos) { BlockTableRecord blockTableRecord; blockTableRecord = acTrans.GetObject(blockTable[nome], OpenMode.ForRead) as BlockTableRecord; if (!blockTableRecord.IsDynamicBlock) { return; } try { if (blockTableRecord.IsDynamicBlock && blockTableRecord.Name.Equals(nome)) { BlockReference bloco = acTrans.GetObject(id, OpenMode.ForRead) as BlockReference; DynamicBlockReferencePropertyCollection properties = bloco.DynamicBlockReferencePropertyCollection; BlockTableRecord nomeRealBloco = null; nomeRealBloco = acTrans.GetObject(bloco.DynamicBlockTableRecord, OpenMode.ForRead) as BlockTableRecord; if (!_lista.Any(b => b.Handle.ToString() == Atributo1.Handle)) { for (int i = 0; i < properties.Count; i++) { DynamicBlockReferenceProperty property = properties[i]; if (property.PropertyName == "Distance1") { Atributo1.Distancia = property.Value.ToString(); _lista.Add(Atributo1); } Atributo1.X = bloco.Position.X; Atributo1.Y = bloco.Position.Y; Atributo1.NomeBloco = nomeRealBloco.Name; Atributo1.Handle = bloco.Handle.ToString(); Atributo1.Angulo = bloco.Rotation; _lista.Add(Atributo1); var lista = Atributo1.NomeBloco.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries); string diametro = lista.Where(p => p.Contains("TUBO FF DN ")).Any() ? lista.Where(p => p.Contains("TUBO FF DN ")).FirstOrDefault() : string.Empty; diametro = diametro.Replace("TUBO FF DN ", ""); Atributo1.Diametro = diametro; double distancia = Convert.ToDouble(Atributo1.Distancia); double dimensaoFinalX; double dimensaoFinalY; if (bloco.Rotation < 1.5708) { dimensaoFinalX = distancia * Math.Cos(bloco.Rotation); dimensaoFinalY = distancia * Math.Sin(bloco.Rotation); Atributo1.XTubo = bloco.Position.X + dimensaoFinalX; Atributo1.YTubo = bloco.Position.Y + dimensaoFinalY; _lista.Add(Atributo1); } else if (bloco.Rotation > 1.5708 && bloco.Rotation <= 3.14159265) { dimensaoFinalX = distancia * Math.Sin(3.14159265 - bloco.Rotation); dimensaoFinalY = distancia * Math.Cos(3.14159265 - bloco.Rotation); Atributo1.XTubo = bloco.Position.X - dimensaoFinalX; Atributo1.YTubo = bloco.Position.Y + dimensaoFinalY; _lista.Add(Atributo1); } else if (bloco.Rotation > 3.14159265 && bloco.Rotation <= 4.71239) { dimensaoFinalX = distancia * Math.Sin(4.71239 - bloco.Rotation); dimensaoFinalY = distancia * Math.Cos(4.71239 - bloco.Rotation); Atributo1.XTubo = bloco.Position.X - dimensaoFinalX; Atributo1.YTubo = bloco.Position.Y - dimensaoFinalY; _lista.Add(Atributo1); } else if (bloco.Rotation > 4.71239 && bloco.Rotation <= 6.28319) { dimensaoFinalX = distancia * Math.Sin(6.28319 - bloco.Rotation); dimensaoFinalY = distancia * Math.Cos(6.28319 - bloco.Rotation); Atributo1.XTubo = bloco.Position.X + dimensaoFinalX; Atributo1.YTubo = bloco.Position.Y - dimensaoFinalY; _lista.Add(Atributo1); } } } } } catch (Exception) { continue; } } } catch (Exception) { continue; } } } acTrans.Commit(); } }
public static bool Contains(this DynamicBlockReferencePropertyCollection properties, string name) { return(properties.Cast <DynamicBlockReferenceProperty>() .Any(p => p.PropertyName == name)); }
public static void LerTodosOsBlocosEBuscarOsAtributos() { Document documentoAtivo = Application.DocumentManager.MdiActiveDocument; Database database = documentoAtivo.Database; Editor editor = documentoAtivo.Editor; ObjectId idBTR = ObjectId.Null; using (Transaction acTrans = database.TransactionManager.StartTransaction()) { using (BlockTable acBlockTable = database.BlockTableId.GetObject(OpenMode.ForRead) as BlockTable) { BlockTable blockTable; blockTable = acTrans.GetObject(database.BlockTableId, OpenMode.ForRead) as BlockTable; try { _lista = new List <AtributosDoBloco>(); foreach (string nome in ConstantesTubulacao.TubulacaoNomeDosBlocos) { BlockTableRecord blockTableRecord; blockTableRecord = acTrans.GetObject(blockTable[nome], OpenMode.ForRead) as BlockTableRecord; BlockReference blocoRefDinamico; blocoRefDinamico = (BlockReference)acTrans.GetObject(blockTable[nome], OpenMode.ForRead) as BlockReference; BlockTableRecord blockTableRecordDynamic = acTrans.GetObject(blocoRefDinamico.DynamicBlockTableRecord, OpenMode.ForRead) as BlockTableRecord; foreach (ObjectId objId_loopVariable in blockTableRecord.GetBlockReferenceIds(true, true)) { if (blockTableRecordDynamic != null && !blockTableRecordDynamic.ExtensionDictionary.IsNull) { DBDictionary extDic = acTrans.GetObject(blockTableRecordDynamic.ExtensionDictionary, OpenMode.ForRead) as DBDictionary; if (extDic != null) { EvalGraph graph = acTrans.GetObject(extDic.GetAt("ACAD_ENHANCeditorBLOCK"), OpenMode.ForRead) as EvalGraph; int[] nodeIds = graph.GetAllNodes(); foreach (uint nodeId in nodeIds) { DBObject node = graph.GetNode(nodeId, OpenMode.ForRead, acTrans); if (!(node is BlockPropertiesTable)) { continue; } BlockPropertiesTable blockPropertiesTable = node as BlockPropertiesTable; int currentRow = SelectRowNumber(ref blockPropertiesTable); BlockPropertiesTableRow row = blockPropertiesTable.Rows[currentRow]; List <string> nameProps = new List <string>(); for (int i = 0; i < blockPropertiesTable.Columns.Count; i++) { nameProps.Add(blockPropertiesTable.Columns[i].Parameter.Name); } DynamicBlockReferencePropertyCollection dynPropsCol = blocoRefDinamico.DynamicBlockReferencePropertyCollection; foreach (DynamicBlockReferenceProperty dynProp in dynPropsCol) { int i = nameProps.FindIndex(delegate(string s) { return(s == dynProp.PropertyName); }); if (i >= 0 && i < nameProps.Count) { try { dynProp.Value = row[i].AsArray()[0].Value; } catch { editor.WriteMessage("\nCan not set to {0} value={1}", dynProp.PropertyName, row[i].AsArray()[0].Value); } //----------------------------------------------------------------------------------------------- //foreach (ObjectId objId_loopVariable in blocoRefDinamico.GetBlockReferenceIds(true, true)) AtributosDoBloco Atributo1 = new AtributosDoBloco(); Atributo1.X = blocoRefDinamico.Position.X; Atributo1.Y = blocoRefDinamico.Position.Y; Atributo1.Handle = blocoRefDinamico.Handle.ToString(); Atributo1.Angulo = blocoRefDinamico.Rotation; _lista.Add(Atributo1); } } } } } } continue; } } catch (Exception e) { FinalizaTarefasAposExcecao("Ocorreu um erro ao ler os blocos do AutoCAD.", e); } acTrans.Commit(); } } }
public void ImportEnvData() { Document doc = AcAp.DocumentManager.MdiActiveDocument; Database db = doc.Database; Editor ed = doc.Editor; // Local do arquivo de dados: O diretório do .dwg onde está sendo // executado o programa. string curDwgPath = AcAp.GetSystemVariable("DWGPREFIX").ToString(); // Cria um StreamReader para ler o arquivo 'ida.txt', que contém os // dados para inserir os blocos. var fileData = new StreamReader(curDwgPath + "\\ida.txt"); // Diretório dos arquivos '.dwg' dos blocos. Pois, caso o bloco // não exista no desenho atual, o programa irá procurar os blocos // em arquivos '.dwg' externos. String blkPath = curDwgPath; // Armazenará uma linha que será lida do 'ida.txt' string[] sFileLine; // Informações dos blocos, que serão lidos do 'ida.txt' string sBlkId; string sBlkName; Point3d ptBlkOrigin; double dbBlkRot; string sLayer; string sColor; ObjectId idBlkTblRec = ObjectId.Null; BlockTableRecord blkTblRec = null; string[] sBlkAtts; string[] oneAtt; string blkTag; string blkValue; Dictionary <string, string> dicBlkAtts = new Dictionary <string, string>(); using (var tr = db.TransactionManager.StartTransaction()) { BlockTable acBlkTbl = tr.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable; // O ModelSpace será usado para gravar em seu Extension Dictionary os Id's e os handles dos blocos. DBObject dbModelSpace = tr.GetObject(SymbolUtilityServices.GetBlockModelSpaceId(db), OpenMode.ForWrite); using (BlockTableRecord acBlkTblRec = (BlockTableRecord)tr.GetObject(acBlkTbl[BlockTableRecord.ModelSpace], OpenMode.ForRead)) { int contId = 0; while (!fileData.EndOfStream) { // sFileLine é uma array que lê uma linha do 'ida.txt' // tendo como separador de colunas ';' sFileLine = fileData.ReadLine().Split(';'); // Atribui os parâmetros de cada bloco que será inserido // baseado no 'ida.txt' sBlkId = Convert.ToString(contId); // O id não é declarado no 'ida.txt' pois este arquivo vem do matlab. sBlkName = sFileLine[0]; dbBlkRot = (Math.PI / 180) * Convert.ToDouble(sFileLine[1]); // Converte graus para radiano // Aqui é usado um Point3d pois é requisitado para criar um 'BlockReference' e não um Point2d. ptBlkOrigin = new Point3d(Convert.ToDouble(sFileLine[2]), Convert.ToDouble(sFileLine[3]), 0); sLayer = sFileLine[4]; sColor = sFileLine[5]; sBlkAtts = sFileLine[6].Split(new string[] { "//" }, StringSplitOptions.None); foreach (var sBlkAtt in sBlkAtts) { oneAtt = sBlkAtt.Split(new string[] { "::" }, StringSplitOptions.None); blkTag = oneAtt[0]; blkValue = oneAtt[1]; dicBlkAtts.Add(blkTag, blkValue); } // Se o bloco não existe no desenho atual if (!acBlkTbl.Has(sBlkName)) { try { using (var blkDb = new Database(false, true)) { // Lê o '.dwg' do bloco, baseado no diretório especificado. blkDb.ReadDwgFile(blkPath + "/" + sBlkName + ".dwg", FileOpenMode.OpenForReadAndAllShare, true, ""); // E então insere o bloco no banco de dados do desenho atual. // Mas ainda não está inserido no desenho. idBlkTblRec = db.Insert(sBlkName, blkDb, true); // Este método retorna o id do bloco. } } catch // Expressão para pegar erros. { } } else { idBlkTblRec = acBlkTbl[sBlkName]; } if (idBlkTblRec != ObjectId.Null) { blkTblRec = idBlkTblRec.GetObject(OpenMode.ForWrite) as BlockTableRecord; using (var trColor = db.TransactionManager.StartOpenCloseTransaction()) { // Altera a cor para "ByBlock" foreach (ObjectId oId in blkTblRec) { Entity ent = (Entity)trColor.GetObject(oId, OpenMode.ForWrite); ent.ColorIndex = 0; } trColor.Commit(); } // Aqui o bloco será adicionado ao desenho e serão gravados // seu id (identificação dada pelo programa atual, começando em 0 e incrementado 1 a 1) // pareado ao seu handle, para o uso dos outros comandos. using (BlockReference acBlkRef = new BlockReference(ptBlkOrigin, idBlkTblRec)) { BlockTableRecord acCurSpaceBlkTblRec; acCurSpaceBlkTblRec = tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite) as BlockTableRecord; acCurSpaceBlkTblRec.AppendEntity(acBlkRef); tr.AddNewlyCreatedDBObject(acBlkRef, true); acBlkRef.Rotation = dbBlkRot; acBlkRef.Layer = sLayer; acBlkRef.ColorIndex = Convert.ToInt32(sColor); // Início: Setar atributos do bloco *********************************************************** if (blkTblRec.HasAttributeDefinitions) { RXClass rxClass = RXClass.GetClass(typeof(AttributeDefinition)); foreach (ObjectId idAttDef in blkTblRec) { if (idAttDef.ObjectClass == rxClass) { DBObject obj = tr.GetObject(idAttDef, OpenMode.ForRead); AttributeDefinition ad = obj as AttributeDefinition; AttributeReference ar = new AttributeReference(); ar.SetAttributeFromBlock(ad, acBlkRef.BlockTransform); if (dicBlkAtts.ContainsKey(ar.Tag)) { ar.TextString = dicBlkAtts[ar.Tag]; } acBlkRef.AttributeCollection.AppendAttribute(ar); tr.AddNewlyCreatedDBObject(ar, true); } } // Setar propriedades dos blocos dinâmicos if (acBlkRef.IsDynamicBlock) { DynamicBlockReferencePropertyCollection pc = acBlkRef.DynamicBlockReferencePropertyCollection; foreach (DynamicBlockReferenceProperty prop in pc) { if (dicBlkAtts.ContainsKey(prop.PropertyName)) { // Propriedade de distância if (prop.PropertyTypeCode == 1) { prop.Value = Convert.ToDouble(dicBlkAtts[prop.PropertyName]); } // Propriedade visibilidade else if (prop.PropertyTypeCode == 5) { prop.Value = dicBlkAtts[prop.PropertyName]; } } } } } // Fim: Setar atributos do bloco ************************************************************ Entity eBlk = (Entity)tr.GetObject(acBlkRef.Id, OpenMode.ForRead); DBObject blkDb = (DBObject)tr.GetObject(acBlkRef.Id, OpenMode.ForRead); // Grava o id(dado pelo programa - base 0) e o handle do bloco // no Extension Dictionary do ModelSpace. RecOnXDict(dbModelSpace, sBlkId, DxfCode.Handle, eBlk.Handle, tr); // Grava o id do bloco em seu próprio Extension Dictionary, para fazer // uma 'busca reversa' no XDic do ModelSpace depois. RecOnXDict(blkDb, "id", DxfCode.XTextString, sBlkId, tr); } } contId++; dicBlkAtts.Clear(); } } fileData.Close(); tr.Commit(); } }
private void bw_ReadTitleBlocks_DoWork(object sender, DoWorkEventArgs e) { Transaction tr = db.TransactionManager.StartTransaction(); using (tr) { BlockTable bt = (BlockTable)tr.GetObject(db.BlockTableId, OpenMode.ForRead); BlockTableRecord btr = new BlockTableRecord(); try { btr = (BlockTableRecord)tr.GetObject(bt[TITLE_BLOCK_NAME], OpenMode.ForRead); } catch (Autodesk.AutoCAD.Runtime.Exception acadexc) { if (acadexc.ErrorStatus == Autodesk.AutoCAD.Runtime.ErrorStatus.KeyNotFound) { MessageBox.Show("Command was unable to find the Haskell ARCH D title block. Please verify the name of the block in AutoCAD and try again.", "Haskell ARCH D Not Found", MessageBoxButtons.OK, MessageBoxIcon.Error); tr.Commit(); } return; } ObjectIdCollection objIdCol = btr.GetBlockReferenceIds(true, false); ObjectIdCollection annobjIdCol = btr.GetAnonymousBlockIds(); //Finds all non-dynamic blocks #region FIND NONDYNAMIC foreach (ObjectId objId in objIdCol) { Title_Blocks.Add(new Title_Block(objId)); try { BlockReference br = (BlockReference)tr.GetObject(objId, OpenMode.ForRead); if (br != null) { //Loop through dynamic attributes/properties DynamicBlockReferencePropertyCollection pc = br.DynamicBlockReferencePropertyCollection; foreach (DynamicBlockReferenceProperty prop in pc) { if (prop.PropertyName.ToUpper().Equals("STAMP")) { Title_Blocks[Title_Blocks.Count - 1].Stamp = prop.Value.ToString(); } } //Loop through all attributes foreach (ObjectId arId in br.AttributeCollection) { DBObject obj = tr.GetObject(arId, OpenMode.ForRead); AttributeReference ar = (AttributeReference)obj; if (ar != null) { string attributeTag = ar.Tag.ToUpper(); if (attributeTag.Equals("SHEET_NUMBER")) { Title_Blocks[Title_Blocks.Count - 1].PageNumber = ar.TextString; } else if (ar.Tag.ToUpper().Equals("SHEET_TITLE")) { Title_Blocks[Title_Blocks.Count - 1].PageTitle = ar.TextString; } else if (attributeTag.Equals("DRAWNBY")) { Title_Blocks[Title_Blocks.Count - 1].DrawnBy = ar.TextString; } else if (attributeTag.Equals("CHECKEDBY")) { Title_Blocks[Title_Blocks.Count - 1].CheckedBy = ar.TextString; } else if (attributeTag.Equals("REV#")) { Title_Blocks[Title_Blocks.Count - 1].RevisionNumber = ar.TextString; } else { for (int i = 1; i <= 15; i++) { if (attributeTag.Equals(i.ToString())) { Title_Blocks[Title_Blocks.Count - 1].RevisionInfo[i, 1] = ar.TextString; } else if (attributeTag.Equals("ISSUE" + i.ToString() + "-TITLE")) { Title_Blocks[Title_Blocks.Count - 1].RevisionInfo[i, 2] = ar.TextString; } else if (attributeTag.Equals("ISSUE" + i.ToString() + "-DATE")) { Title_Blocks[Title_Blocks.Count - 1].RevisionInfo[i, 3] = ar.TextString; } } } } } } } catch { } } #endregion //Finds all dynamic blocks #region FIND DYNAMIC foreach (ObjectId id in annobjIdCol) { BlockTableRecord annbtr = (BlockTableRecord)tr.GetObject(id, OpenMode.ForRead); ObjectIdCollection blkRefIds = annbtr.GetBlockReferenceIds(true, false); foreach (ObjectId objId in blkRefIds) { Title_Blocks.Add(new Title_Block(objId)); try { BlockReference br = (BlockReference)tr.GetObject(objId, OpenMode.ForRead); if (br != null) { //Loop through dynamic attributes/properties DynamicBlockReferencePropertyCollection pc = br.DynamicBlockReferencePropertyCollection; foreach (DynamicBlockReferenceProperty prop in pc) { if (prop.PropertyName.ToUpper().Equals("STAMP")) { Title_Blocks[Title_Blocks.Count - 1].Stamp = prop.Value.ToString(); } } //Loop through all attributes foreach (ObjectId arId in br.AttributeCollection) { DBObject obj = tr.GetObject(arId, OpenMode.ForRead); AttributeReference ar = (AttributeReference)obj; if (ar != null) { string attributeTag = ar.Tag.ToUpper(); if (attributeTag.Equals("SHEET_NUMBER")) { Title_Blocks[Title_Blocks.Count - 1].PageNumber = ar.TextString; } else if (ar.Tag.ToUpper().Equals("SHEET_TITLE")) { Title_Blocks[Title_Blocks.Count - 1].PageTitle = ar.TextString; } else if (ar.Tag.ToUpper().Equals("PROJECTNUM")) { Title_Blocks[Title_Blocks.Count - 1].ProjectNumber = ar.TextString; } else if (attributeTag.Equals("DRAWNBY")) { Title_Blocks[Title_Blocks.Count - 1].DrawnBy = ar.TextString; } else if (attributeTag.Equals("CHECKEDBY")) { Title_Blocks[Title_Blocks.Count - 1].CheckedBy = ar.TextString; } else if (attributeTag.Equals("REV#")) { Title_Blocks[Title_Blocks.Count - 1].RevisionNumber = ar.TextString; } else { for (int i = 0; i < 15; i++) { if (attributeTag.Equals((i + 1).ToString())) { Title_Blocks[Title_Blocks.Count - 1].RevisionInfo[i, 0] = ar.TextString; break; } else if (attributeTag.Equals("ISSUE" + (i + 1).ToString() + "-TITLE")) { Title_Blocks[Title_Blocks.Count - 1].RevisionInfo[i, 1] = ar.TextString; break; } else if (attributeTag.Equals("ISSUE" + (i + 1).ToString() + "-DATE")) { Title_Blocks[Title_Blocks.Count - 1].RevisionInfo[i, 2] = ar.TextString; break; } } } } } } } catch { } } } #endregion tr.Commit(); } }
private void Write_To_TitleBlocks() { using (doc.LockDocument()) { Transaction tr = db.TransactionManager.StartTransaction(); using (tr) { foreach (Title_Block tb in Title_Blocks) { try { BlockReference br = (BlockReference)tr.GetObject(tb.BlockReferenceID, OpenMode.ForWrite); if (br != null) { //Loop through dynamic attributes/properties DynamicBlockReferencePropertyCollection pc = br.DynamicBlockReferencePropertyCollection; foreach (DynamicBlockReferenceProperty prop in pc) { if (prop.PropertyName.ToUpper().Equals("STAMP")) { if (!prop.ReadOnly) { prop.Value = tb.Stamp; } } } //Loop through all attributes foreach (ObjectId arId in br.AttributeCollection) { DBObject obj = tr.GetObject(arId, OpenMode.ForWrite); AttributeReference ar = (AttributeReference)obj; if (ar != null) { string attributeTag = ar.Tag.ToUpper(); if (attributeTag.Equals("SHEET_NUMBER")) { ar.TextString = tb.PageNumber; } else if (attributeTag.Equals("SHEET_TITLE")) { ar.TextString = tb.PageTitle; } else if (attributeTag.Equals("PROJECTNUM")) { ar.TextString = tb.ProjectNumber; } else if (attributeTag.Equals("DRAWNBY")) { ar.TextString = tb.DrawnBy; } else if (attributeTag.Equals("CHECKEDBY")) { ar.TextString = tb.CheckedBy; } else if (attributeTag.Equals("REV#")) { ar.TextString = tb.RevisionNumber; } else { for (int i = 0; i < 15; i++) { if (attributeTag.Equals((i + 1).ToString())) { if (tb.RevisionInfo[i, 0] == null) { ar.TextString = ""; } else { ar.TextString = tb.RevisionInfo[i, 0]; } break; } else if (attributeTag.Equals("ISSUE" + (i + 1).ToString() + "-TITLE")) { if (tb.RevisionInfo[i, 1] == null) { ar.TextString = ""; } else { ar.TextString = tb.RevisionInfo[i, 1]; } break; } else if (attributeTag.Equals("ISSUE" + (i + 1).ToString() + "-DATE")) { if (tb.RevisionInfo[i, 2] == null) { ar.TextString = ""; } else { ar.TextString = tb.RevisionInfo[i, 2]; } break; } } } } } } } catch { } } tr.Commit(); } } }
} // END ProcessDXFEntities // Note that a lot of checking has been eliminated by // util_ExcelReader.ValidateLayers & util_ExcelReader.ValidateBlocks BUT // you MUST call those methods before using InsertBlock! public static void InsertBlock( Point3d loc, string anno, string blockName, string dyn_val, string layer, string prop_name, double blkRotation) { Document doc = Application.DocumentManager.MdiActiveDocument; Database db = doc.Database; Editor ed = doc.Editor; using (Transaction tr = db.TransactionManager.StartTransaction()) { // Open BlockTable for Read BlockTable blkTbl = tr.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable; // Create a new ID for the new Block so we can access any Dynamic or // Attribute properties after creation and insertion into the drawing ObjectId blkRecId = ObjectId.Null; if (blkTbl.Has(blockName)) { // Use the correct BlockName from our Excel look-up tab (System.Data.DataTable) blkRecId = blkTbl[blockName]; } else { ed.WriteMessage("Please use INSERT or DESIGN CENTER (DC) to add this block " + blockName + " to your drawing.\n"); return; } if (blkRecId != ObjectId.Null) { // Get a reference to a Block Table Record for our new Block named in nTRIX.xlsx BlockTableRecord blkTblRec = tr.GetObject(blkRecId, OpenMode.ForWrite) as BlockTableRecord; using (BlockReference blkRef = new BlockReference(loc, blkTblRec.Id)) { // Open the [Model Space] BlockTable and get a BlockTableRecord acCurSpaceBlkTblRec = tr.GetObject(blkTbl[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord; // Assign the correct Layer blkRef.Layer = layer; blkRef.Rotation = blkRotation; // Append the new Block acCurSpaceBlkTblRec.AppendEntity(blkRef); // and insert it into the DWG's BlockTableRecord tr.AddNewlyCreatedDBObject(blkRef, true); // Set any Dynamic Blocks to display the correct symbol // (aka -> set the Property to the correct Dynamic_Value of nTRIX.xlsx // such as MH-VZ uses "Verizon" as the "OWNER" DynamicBlockReferenceProperty if (blkRef.IsDynamicBlock) { // Property Collection (DynamicBlockReferencePropertyCollection) is the // list of choices on a Dynamic Block that a Drafter can pick from DynamicBlockReferencePropertyCollection props = blkRef.DynamicBlockReferencePropertyCollection; // Initialize the count of Properties (aka Choices) available to the Drafter int propValues = 0; // Cycle through the list and find the one that matches the Dynamic_Value of nTRIX.xlsx foreach (DynamicBlockReferenceProperty prop in props) { // Use a zero based array to hold our values (Choice's numeric value) object[] values = prop.GetAllowedValues(); propValues = values.Length - 1; // Set property (Choice) to desired value (ie "Verizon" for MH-VZ) if (prop.PropertyName == prop_name && !prop.ReadOnly) { for (int i = 0; i < propValues; i++) { if (dyn_val == values[i].ToString()) { // Example: "Verizon" for MH-VZ prop.Value = values[i]; } } } } } // Parse and add any defined Block Attributes (For example: P-E_123 or TREE_6) if (blkTblRec.HasAttributeDefinitions) { // Split the ANNO from the Field Crew by the '_" character // to get the desired Block Attribute string value to use string[] attribVals = anno.Split('_'); // Intialize our Block Attributes counter in case this Block has Attributes // Notes: array.Split() removes the "_" and keeps the start. int numberAttributes = attribVals.Count(); // In case the Field Crew add too many "_"'s if (numberAttributes >= 4) { // Only use the first Splits. Example: PM2_123_124_125 // attribVals[0] = PM2 keep // attribVals[1] = 123 keep // attribVals[2] = 124 keep // attribVals[3] = 125 by setting numberAttributes = 3; // we ignore attribVals[3] = 125 } // In case the Field Crew misses the second attribute on: // PARKING METER - DOUBLE // JOINT-POLE-D // POLE2 if (blockName == "JOINT-POLE-D" || blockName == "POLE2" || blockName == "PARKING METER - DOUBLE") { if (numberAttributes == 2) { Array.Resize(ref attribVals, 3); if (blockName == "JOINT-POLE-D" || blockName == "POLE2") { attribVals[2] = "(E)NT"; numberAttributes = 3; } else { attribVals[2] = ""; numberAttributes = 3; } } } // Check to see if there are any Field Crew notes (_xxxx or _xxx_xxx) if (numberAttributes > 1) { // Track our Block Attribute(s) int currentAttribNR = 1; // Because the Block can have multiple types of Objects attached to it, // you need to find which Object is actually an AttributeDefinition... foreach (ObjectId acobjID in blkTblRec) { // Get a reference to our DBObject (AutoCAD Database Object) DBObject dbObj = tr.GetObject(acobjID, OpenMode.ForRead); // See if our DBObject is a Block Attribute (AttributeDefinition) if (dbObj.GetType() == typeof(AttributeDefinition)) { // (Cast) our DBObject to a Block Attribute (AttributeDefinition) AttributeDefinition acAtt = (AttributeDefinition)dbObj; // Make sure we are not trying to modify a Constant (READ ONLY) // Block Attribute (AttributeDefinition) if (!acAtt.Constant) { // Get a reference to our Block Attribute (AttributeDefinition)'s using (AttributeReference acAttRef = new AttributeReference()) { // Use the default orientation of the Block Attribute acAttRef.SetAttributeFromBlock(acAtt, blkRef.BlockTransform); // Use the default position/location of the Block Attribute acAttRef.Position = acAtt.Position.TransformBy(blkRef.BlockTransform); // Assign the Field Crew note (attribVals[#]) and increment counter if (currentAttribNR <= numberAttributes) { switch (blockName) { case "TREE W-ATTRIB": acAttRef.TextString = attribVals[currentAttribNR] + "\""; break; case "SOLE-OWNED-POLE-D": case "JOINT-POLE-D": case "POLE2": acAttRef.TextString = "P." + attribVals[currentAttribNR]; currentAttribNR = currentAttribNR + 1; break; default: acAttRef.TextString = attribVals[currentAttribNR]; currentAttribNR = currentAttribNR + 1; break; } } else { // Use the default Attribute acAttRef.TextString = acAtt.TextString; } // Commit our changes to the Block Reference and... blkRef.AttributeCollection.AppendAttribute(acAttRef); // ...add the new Attributes to the Block Reference tr.AddNewlyCreatedDBObject(acAttRef, true); } } } } } } } } tr.Commit(); } } // END InsertBlock
public static void LerTodosOsBlocosEBuscarOsAtributos() { Document documentoAtivo = Application.DocumentManager.MdiActiveDocument; Database database = documentoAtivo.Database; Editor editor = documentoAtivo.Editor; PromptSelectionResult pmtSelRes = editor.GetSelection(); using (Transaction acTrans = documentoAtivo.TransactionManager.StartTransaction()) { BlockTable blockTable; blockTable = acTrans.GetObject(database.BlockTableId, OpenMode.ForRead) as BlockTable; if (pmtSelRes.Status == PromptStatus.OK) { _lista = new List <AtributosDoBloco>(); _listaElevacao = new List <TextoElevacao>(); foreach (ObjectId id in pmtSelRes.Value.GetObjectIds()) { try { AtributosDoBloco Atributo1 = new AtributosDoBloco(); foreach (string nome in ConstantesTubulacao.TubulacaoNomeDosBlocos) { BlockTableRecord blockTableRecord; blockTableRecord = acTrans.GetObject(blockTable[nome], OpenMode.ForRead) as BlockTableRecord; if (!blockTableRecord.IsDynamicBlock) { return; } try { BlockReference bloco = null; bloco = acTrans.GetObject(id, OpenMode.ForRead) as BlockReference; BlockTableRecord nomeRealBloco = null; nomeRealBloco = acTrans.GetObject(bloco.DynamicBlockTableRecord, OpenMode.ForRead) as BlockTableRecord; DynamicBlockReferencePropertyCollection properties = bloco.DynamicBlockReferencePropertyCollection; if (blockTableRecord.IsDynamicBlock && blockTableRecord.Name == nome) { for (int i = 0; i < properties.Count; i++) { DynamicBlockReferenceProperty property = properties[i]; if (property.PropertyName == "Distance1") { Atributo1.Distancia = property.Value.ToString(); } Atributo1.X = bloco.Position.X; Atributo1.Y = bloco.Position.Y; Atributo1.NomeBloco = nomeRealBloco.Name; Atributo1.Handle = bloco.Handle.ToString(); Atributo1.Angulo = bloco.Rotation; var lista = Atributo1.NomeBloco.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries); if (lista.Where(c => c.Contains("TUBO FF DN ")).Any()) { string diametro = lista.Where(p => p.Contains("TUBO FF DN ")).Any() ? lista.Where(p => p.Contains("TUBO FF DN ")).FirstOrDefault() : string.Empty; diametro = diametro.Replace("TUBO FF DN ", ""); Atributo1.Diametro = diametro; } else if (lista.Where(c => c.Contains("TUBO CONC ARMADO DN")).Any()) { string diametro = lista.Where(p => p.Contains("TUBO CONC ARMADO DN")).Any() ? lista.Where(p => p.Contains("TUBO CONC ARMADO DN")).FirstOrDefault() : string.Empty; diametro = diametro.Replace("TUBO CONC ARMADO DN", ""); Atributo1.Diametro = diametro; } else if (lista.Where(c => c.Contains("TUBO PVC DN")).Any()) { string diametro = lista.Where(p => p.Contains("TUBO PVC DN ")).Any() ? lista.Where(p => p.Contains("TUBO PVC DN ")).FirstOrDefault() : string.Empty; diametro = diametro.Replace("TUBO PVC DN ", ""); Atributo1.Diametro = diametro; } double distancia = Convert.ToDouble(Atributo1.Distancia); double dimensaoFinalX; double dimensaoFinalY; if (bloco.Rotation < 1.5708) { dimensaoFinalX = distancia * Math.Cos(bloco.Rotation); dimensaoFinalY = distancia * Math.Sin(bloco.Rotation); Atributo1.XTubo = bloco.Position.X + dimensaoFinalX; Atributo1.YTubo = bloco.Position.Y + dimensaoFinalY; } else if (bloco.Rotation > 1.5708 && bloco.Rotation <= 3.14159265) { dimensaoFinalX = distancia * Math.Sin(3.14159265 - bloco.Rotation); dimensaoFinalY = distancia * Math.Cos(3.14159265 - bloco.Rotation); Atributo1.XTubo = bloco.Position.X - dimensaoFinalX; Atributo1.YTubo = bloco.Position.Y + dimensaoFinalY; } else if (bloco.Rotation > 3.14159265 && bloco.Rotation <= 4.71239) { dimensaoFinalX = distancia * Math.Sin(4.71239 - bloco.Rotation); dimensaoFinalY = distancia * Math.Cos(4.71239 - bloco.Rotation); Atributo1.XTubo = bloco.Position.X - dimensaoFinalX; Atributo1.YTubo = bloco.Position.Y - dimensaoFinalY; } else if (bloco.Rotation > 4.71239 && bloco.Rotation <= 6.28319) { dimensaoFinalX = distancia * Math.Sin(6.28319 - bloco.Rotation); dimensaoFinalY = distancia * Math.Cos(6.28319 - bloco.Rotation); Atributo1.XTubo = bloco.Position.X + dimensaoFinalX; Atributo1.YTubo = bloco.Position.Y - dimensaoFinalY; } TextoElevacao Elevacao1 = new TextoElevacao(); //---------------------------------------------------------------------------- Point3dCollection pntCol = new Point3dCollection { new Point3d(Atributo1.X - 5, Atributo1.Y + 5, 0), new Point3d(Atributo1.X + 5, Atributo1.Y + 5, 0), new Point3d(Atributo1.X + 5, Atributo1.Y - 5, 0), new Point3d(Atributo1.X - 5, Atributo1.Y - 5, 0) }; PromptSelectionResult pmtSelResPoint = editor.SelectCrossingPolygon(pntCol); if (pmtSelResPoint.Status == PromptStatus.OK) { MText itemSelecionado = null; double distanciaMinima = Double.MaxValue; foreach (ObjectId objId in pmtSelResPoint.Value.GetObjectIds()) { if (objId.ObjectClass.DxfName == "MTEXT") { var text = acTrans.GetObject(objId, OpenMode.ForWrite) as MText; if (text.Text.Contains("CF=")) { double distanciaTexto = Math.Sqrt(Math.Pow(text.Location.X - Atributo1.X, 2) + Math.Pow(text.Location.Y - Atributo1.Y, 2)); if (distanciaTexto < distanciaMinima) { distanciaMinima = distanciaTexto; itemSelecionado = text; } } } } if (itemSelecionado != null) { var listaTexto = itemSelecionado.Text.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries); string textoCA = listaTexto.Where(d => d.Contains("CF=")).Any() ? listaTexto.Where(p => p.Contains("CF=")).FirstOrDefault() : string.Empty; textoCA = textoCA.Replace("CF=", ""); Elevacao1.ElevacaoInicial = textoCA; Elevacao1.PosicaoX = itemSelecionado.Location.X; Elevacao1.PosicaoY = itemSelecionado.Location.Y; } else { editor.WriteMessage("\nAs Elevações não foram encontradas!"); } } //---------------------------------------------------------------------------------------------- Point3dCollection pntColElevacao = new Point3dCollection { new Point3d(Atributo1.XTubo - 5, Atributo1.YTubo + 5, 0), new Point3d(Atributo1.XTubo + 5, Atributo1.YTubo + 5, 0), new Point3d(Atributo1.XTubo + 5, Atributo1.YTubo - 5, 0), new Point3d(Atributo1.XTubo - 5, Atributo1.YTubo - 5, 0) }; PromptSelectionResult pmtSelResPoint2 = editor.SelectCrossingPolygon(pntColElevacao); if (pmtSelResPoint2.Status == PromptStatus.OK) { MText itemSelecionado2 = null; double distanciaMinima2 = Double.MaxValue; foreach (ObjectId objId2 in pmtSelResPoint2.Value.GetObjectIds()) { if (objId2.ObjectClass.DxfName == "MTEXT") { var text2 = acTrans.GetObject(objId2, OpenMode.ForWrite) as MText; if (text2.Text.Contains("CF=")) { double distanciaTexto2 = Math.Sqrt(Math.Pow(text2.Location.X - Atributo1.XTubo, 2) + Math.Pow(text2.Location.Y - Atributo1.YTubo, 2)); if (distanciaTexto2 < distanciaMinima2) { distanciaMinima2 = distanciaTexto2; itemSelecionado2 = text2; } } } } if (itemSelecionado2 != null) { var listaTexto2 = itemSelecionado2.Text.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries); string textoCA2 = listaTexto2.Where(d => d.Contains("CF=")).Any() ? listaTexto2.Where(p => p.Contains("CF=")).FirstOrDefault() : string.Empty; textoCA2 = textoCA2.Replace("CF=", ""); Elevacao1.ElevacaoFinal = textoCA2; Elevacao1.PosicaoX = itemSelecionado2.Location.X; Elevacao1.PosicaoY = itemSelecionado2.Location.Y; } else { editor.WriteMessage("\nAs Elevações não foram encontradas!"); } _listaElevacao.Add(Elevacao1); } _lista.Add(Atributo1); break; } } } catch (Exception) { continue; } } } catch (Exception) { continue; } } } acTrans.Commit(); } }