public static void Together() { Document doc = Application.DocumentManager.MdiActiveDocument; Database db = doc.Database; Editor ed = doc.Editor; // Выбор блоков if(IdBlRefs == null) { IdBlRefs = ed.SelectBlRefs("\nВыбор блоков:").ToArray(); } // Точка соединения всех блоков (точка вставки). var ptInsert = ed.GetPointWCS("\nТочка вставки:"); using (var t = db.TransactionManager.StartTransaction()) { var cs = db.CurrentSpaceId.GetObject(OpenMode.ForWrite) as BlockTableRecord; foreach (var idBlRef in IdBlRefs) { var blRef = idBlRef.GetObject(OpenMode.ForRead, false, true) as BlockReference; if (blRef == null) continue; if (blRef.Name.StartsWith(Settings.Default.BlockPlaneMountingPrefixName)) { // вставка нового вхождения этого блока var blRefNew = new BlockReference(ptInsert, blRef.BlockTableRecord); cs.AppendEntity(blRefNew); t.AddNewlyCreatedDBObject(blRefNew, true); } } t.Commit(); } IdBlRefs = null; }
/// <summary> /// Attaches the specified Xref to the current space in the current drawing. /// </summary> /// <param name="path">Path to the drawing file to attach as an Xref.</param> /// <param name="pos">Position of Xref in WCS coordinates.</param> /// <param name="name">Optional name for the Xref.</param> /// <param name="idBtrXref">Блок внешней ссылки - BlockTableRecord</param> /// <returns>Whether the attach operation succeeded.</returns> public static bool XrefAttachAndInsert(this Database db, string path, Point3d pos, out ObjectId idBtrXref, out ObjectId idBlRefXref, string name = null) { idBtrXref = ObjectId.Null; idBlRefXref = ObjectId.Null; var ret = false; if (!File.Exists(path)) return ret; if (String.IsNullOrEmpty(name)) name = Path.GetFileNameWithoutExtension(path); using (var t = db.TransactionManager.StartOpenCloseTransaction()) { idBtrXref = db.AttachXref(path, name); if (idBtrXref.IsValid) { var ms = (BlockTableRecord)t.GetObject(SymbolUtilityServices.GetBlockModelSpaceId(db), OpenMode.ForWrite); var br = new BlockReference(pos, idBtrXref); idBlRefXref = ms.AppendEntity(br); t.AddNewlyCreatedDBObject(br, true); ret = true; } t.Commit(); } return ret; }
/// <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>返回块参照的Id</returns> public static ObjectId InsertBlockReference(this ObjectId spaceId, string layer, string blockName, Point3d position, Scale3d scale, double rotateAngle) { DocumentLock docLock = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.LockDocument(); ObjectId blockRefId; Database db = spaceId.Database; BlockTable bt = (BlockTable)db.BlockTableId.GetObject(OpenMode.ForRead); if (!bt.Has(blockName)) return ObjectId.Null; BlockTableRecord space = (BlockTableRecord)spaceId.GetObject(OpenMode.ForWrite); BlockReference br = new BlockReference(position, bt[blockName]); br.ScaleFactors = scale; br.Layer = layer; br.Rotation = rotateAngle; ObjectId btrId = bt[blockName]; BlockTableRecord record = (BlockTableRecord)btrId.GetObject(OpenMode.ForRead); if (record.Annotative == AnnotativeStates.True) { ObjectContextCollection contextCollection = db.ObjectContextManager.GetContextCollection("ACDB_ANNOTATIONSCALES"); ObjectContexts.AddContext(br, contextCollection.GetContext("1:1")); } blockRefId = space.AppendEntity(br); db.TransactionManager.AddNewlyCreatedDBObject(br, true); space.DowngradeOpen(); docLock.Dispose(); return blockRefId; }
// public Movil(ref ObjectId line, ref ObjectId mobile, double minSeparation, double maxSeparation, bool loopTravel) { this.line = line; this.mobile = mobile; this.dPromMin = minSeparation; this.dPromMax = maxSeparation; this.loopTravel = loopTravel; this.goal = false; this.ruta = Lab3.DBMan.OpenEnity(line) as Polyline; this.bloque = Lab3.DBMan.OpenEnity(mobile) as BlockReference; this.bloqueCentro = new Point3d((bloque.GeometricExtents.MinPoint.X + bloque.GeometricExtents.MaxPoint.X) / 2, (bloque.GeometricExtents.MinPoint.Y + bloque.GeometricExtents.MaxPoint.Y) / 2, 0); this.numeroSegmentos = this.ruta.NumberOfVertices - 1; this.segmentoActualIndex = 0; this.segmentoActual = this.ruta.GetLineSegment2dAt(segmentoActualIndex); Lab3.DBMan.UpdateBlockPosition(new Point3d(this.segmentoActual.StartPoint.X, this.segmentoActual.StartPoint.Y, 0), mobile); // AttributeManager attribute = new AttributeManager(mobile); attribute.SetAttribute("Velocity", this.velocity+" [Kms/hr]"); // this.pointActualCurve = 0; this.velocityScale = 0.00001f; this.velocity = this.UpdateDireccion(); Lab3.DBMan.UpdateBlockRotation(new Vector2d(this.velocity.X, this.velocity.Y).Angle, this.mobile); }
public void CreateEmployee() { Database db = HostApplicationServices.WorkingDatabase; Editor ed = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor; // The try/finally idiom is another approach for using, commiting // and disposing of transactions. This technique is demonstrated once here. // However, the 'Using' approach will be used from here on. Transaction trans = db.TransactionManager.StartTransaction(); try { BlockTable bt = (BlockTable)(trans.GetObject(db.BlockTableId, OpenMode.ForWrite)); BlockTableRecord btr = (BlockTableRecord)trans.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite); //Create the block reference...use the return from CreateEmployeeDefinition directly! BlockReference br = new BlockReference(new Point3d(10, 10, 0), CreateEmployeeDefinition()); btr.AppendEntity(br); //Add the reference to ModelSpace trans.AddNewlyCreatedDBObject(br, true); //Let the transaction know about it trans.Commit(); // Commit is always required to indicate success. } catch (System.Exception ex) { // The calling, top-level method (such as this) should be used // to report errors that occur even in called methods. ed.WriteMessage("Error Creating Employee Block: " + ex.Message); } finally { trans.Dispose(); // Manual cleanup necessary in this transaction model } }
public static List<Zone> GetZones(BlockReference blref) { List<Zone> zones = new List<Zone>(); Database db = HostApplicationServices.WorkingDatabase; using (var t = db.TransactionManager.StartTransaction () ) { foreach (ObjectId id in blref.AttributeCollection) { var attRef = t.GetObject(id, OpenMode.ForRead) as AttributeReference; // Если тег атрибута начинается с з, то это номер зоны, значение атрибута это тип цвета if (attRef.Tag.StartsWith ("з") ) { Zone zone = new Zone(); zone.Name = attRef.Tag.Substring(1); zone.TypeColor = attRef.TextString; TileColor.AddTypeColor(zone.TypeColor); zones.Add(zone); } } t.Commit(); } return zones; }
public BlockInfo(BlockReference blRef, string blName) { IdBtr = blRef.DynamicBlockTableRecord; BlName = blName; AttrsDef = AttributeInfo.GetAttrDefs(IdBtr); AttrsRef = AttributeInfo.GetAttrRefs(blRef); }
public FacadeFrontBlock(BlockReference blRef) { Position = blRef.Position; BlName = blRef.GetEffectiveName(); IdBlRef = blRef.Id; Extents = blRef.GeometricExtentsСlean(); RectangleRTree = new Rectangle(Extents.MinPoint.X, Extents.MinPoint.Y, Extents.MaxPoint.X, Extents.MaxPoint.Y, 0, 0); }
public Toilet(BlockReference blRef) { _idBlRef = blRef.Id; _position = blRef.Position; getAttrs(blRef); getDynParams(blRef); checkParams(blRef); }
public PanelBlRefExport(BlockReference blRef, PanelBtrExport panelBtrExport) { IdBlRefAkr = blRef.Id; Position = blRef.Position; PanelBtrExport = panelBtrExport; Transform = blRef.BlockTransform; Extents = blRef.GeometricExtents; }
private void checkParams(BlockReference blRef) { bool hasErr = false; string errMsg = string.Format( "Ошибки в блоке {0}: ", Options.Instance.BlockSupplementName); // Длина и ширина if (_owner == EnumConstructionType.Baseboard || _owner == EnumConstructionType.Carnice) { // Присваиваем длину - макисальное значение из двух значений, она должна быть больше 0 _lenght = _lenght > _width ? _lenght : _width; if (_lenght <=0) { errMsg += "Длина не определена. "; hasErr = true; } } else if (_owner == EnumConstructionType.Ceil || _owner == EnumConstructionType.Deck || _owner == EnumConstructionType.Wall) { // Обе величины не должны быть равны 0 if (_lenght <= 0) { errMsg += "Длина не определена. "; hasErr = true; } if (_width <= 0) { errMsg += "Ширина не определена. "; hasErr = true; } } // Действие if (_operation == EnumOperation.Undefined) { errMsg += "Действие не определено (может быть + - +-). "; hasErr = true; } // Принадлежность (Стена, Потлок, Пол, Карниз, Плинтус) if (_owner == EnumConstructionType.Undefined) { errMsg += "Не определена принадлежность добавки (Пол, Потолок, Карниз, Стена или Плинтус). "; hasErr = true; } // Материал if (string.IsNullOrEmpty(_material)) { errMsg += "Материал не определен. "; hasErr = true; } if (hasErr) { Inspector.AddError(errMsg, blRef, System.Drawing.SystemIcons.Error); } }
public Supplement(BlockReference blRef) { _idBlRef = blRef.Id; _material = ""; // Поумолчанию = "" - материал берется с принадлежности добавки (стена, пол, потолок, плинтус, карниз). _position = blRef.Position; getAttrs(blRef); getDynParams(blRef); checkParams(blRef); }
private double _lenght; // Длина #endregion Fields #region Constructors public Aperture(BlockReference blRef) { _idBlRef = blRef.Id; //_extents = blRef.GeometricExtents; // Определение длины из динамического параметра Расстояние _lenght = getLenght(blRef); // Определение высоты _height = getHeight(blRef); _area = _lenght * _height; }
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 Number(BlockReference blRef, string blName) { IdBlRef = blRef.Id; BlName = BlName; Position = blRef.Position; var attrs = AttributeInfo.GetAttrRefs(blRef); AtrNum = attrs.Find(a => a.Tag.Equals(Options.Instance.AttrRoomNumber, StringComparison.OrdinalIgnoreCase)); if (AtrNum != null) { int num; Num = int.TryParse(AtrNum.Text, out num) ? num : 0; } }
public WallElement(BlockReference blRefElem, Module module, string blName, List<Parameter> parameters, string category) : base(blRefElem, module, blName, parameters, category) { ExtentsClean = blRefElem.GeometricExtentsСlean(); Contour = getWallContour(blRefElem); if (Contour != null) { Contour = (Polyline)Contour.Clone(); //Contour.UpgradeOpen(); Contour.TransformBy(blRefElem.BlockTransform); //Contour.DowngradeOpen(); } }
public static WindowTranslator GetAkrBlWinTranslator(BlockReference blRefWindow) { WindowTranslator res = null; foreach (DynamicBlockReferenceProperty prop in blRefWindow.DynamicBlockReferencePropertyCollection) { if (prop.PropertyName.Equals(Settings.Default.BlockWindowVisibilityName, StringComparison.OrdinalIgnoreCase)) { string markNew = getNewMarkAkrWin(prop.Value.ToString()); res = new WindowTranslator(Settings.Default.BlockWindowName, markNew); break; } } return res; }
public Semaforo(ref ObjectId id, int indexList, int changeStateLimit, int changeStateLimitPrecaution, ref ObjectId idI) { this.id = id; this.idIndicator = idI; this.block = Lab3.DBMan.OpenEnity(id) as BlockReference; this.blockIndicator = Lab3.DBMan.OpenEnity(idIndicator) as BlockReference; this.indexList = indexList; this.state = EstadoSemaforo.alto; this.changeStateLimit = changeStateLimit; this.changeStateLimitPrecaution = changeStateLimitPrecaution; this.count = 0; Lab3.DBMan.UpdateBlockPosition( new Point3d(this.block.Position.X, this.block.Position.Y, this.block.Position.Z+100f), this.idIndicator); this.UpdateColor(); }
public void CreateBtrPanelFromBase(int i, string[] marks) { // Тест создания определения блока панели по описанию в xml базе. PanelBase panelBase; string testFile = @"c:\temp\test\АКР\Base\Tests\CreateBlockPanelTest\TestCreatePanels.dwg"; //File.Copy(@"c:\Autodesk\AutoCAD\Pik\Settings\Template\АР\АР.dwt", testFile, true); using (var db = new Database(false, true)) { db.ReadDwgFile(testFile, FileOpenMode.OpenForReadAndAllShare, false, ""); db.CloseInput(true); using (AcadLib.WorkingDatabaseSwitcher dbSwitcher = new AcadLib.WorkingDatabaseSwitcher(db)) { baseService.ClearPanelsAkrFromDrawing(db); baseService.InitToCreationPanels(db); Point3d pt = Point3d.Origin; List<ObjectId> idsBtrPanels = new List<ObjectId>(); // Создание определениц блоков панелей foreach (var mark in marks) { Panel panelXml = baseService.GetPanelXml(mark); panelBase = new PanelBase(panelXml, baseService); panelBase.CreateBlock(); if (!panelBase.IdBtrPanel.IsNull) { idsBtrPanels.Add(panelBase.IdBtrPanel); } } // Вставка вхождениц блоков панелей в модель using (var t = db.TransactionManager.StartTransaction()) { foreach (var idBtrPanel in idsBtrPanels) { var blRefPanel = new BlockReference(pt, idBtrPanel); var ms = db.CurrentSpaceId.GetObject(OpenMode.ForWrite) as BlockTableRecord; ms.AppendEntity(blRefPanel); t.AddNewlyCreatedDBObject(blRefPanel, true); pt = new Point3d(0, pt.Y + 10000, 0); } t.Commit(); } } db.SaveAs(testFile, DwgVersion.Current); } }
public static Aperture GetAperture(BlockReference blRefAperture) { string layerKey = blRefAperture.Layer.ToUpper(); Aperture aperture = null; if (layerKey.Equals (Options.Instance.LayerApertureDoor.ToUpper()) ) { aperture = new DoorAperture(blRefAperture); } else if (layerKey.Equals(Options.Instance.LayerApertureWindow.ToUpper())) { aperture = new WindowAperture(blRefAperture); } return aperture; }
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(); } }
private string GetTileZone(BlockReference blRefTile) { foreach (ObjectId idAtr in blRefTile.AttributeCollection) { var atrRef = idAtr.GetObject(OpenMode.ForRead) as AttributeReference; string textAtr = atrRef.TextString; string tagAtr = atrRef.Tag; atrRef.Close(); if (tagAtr == "ЗОНА") { return textAtr; } } return ""; }
public static string GetEffectiveBlockName(BlockReference blref) { string res = string.Empty; if (blref.IsDynamicBlock) { var btr =blref.DynamicBlockTableRecord.GetObject(OpenMode.ForRead) as BlockTableRecord; res = btr.Name; btr.Close(); } else { res = blref.Name; } return res; }
public WindowRedefine(bool isAkrBlWin, BlockReference blRefWinOld, WindowTranslator translatorW) { IdBlRef = blRefWinOld.Id; TranslatorW = translatorW; IdBtrOwner = blRefWinOld.OwnerId; if (isAkrBlWin) { Position = blRefWinOld.Position; } else { var extOldWind = blRefWinOld.GeometricExtentsСlean(); Position = extOldWind.MinPoint; } }
private int getHeight(BlockReference blRef) { int height = 0; foreach (ObjectId idAtrRef in blRef.AttributeCollection) { using (var atrRef = idAtrRef.GetObject( OpenMode.ForRead)as AttributeReference ) { string tag = atrRef.Tag.ToUpper(); if (tag.Equals (Options.Instance.ApertureBlAttrTagHeight.ToUpper())) { int.TryParse(atrRef.TextString, out height); break; } } } return height; }
private Polyline getWallContour(BlockReference blRefElem) { var btr = blRefElem.BlockTableRecord.GetObject(OpenMode.ForRead) as BlockTableRecord; Polyline resVal = null; double maxArea = 0; foreach (var idEnt in btr) { var pl = idEnt.GetObject(OpenMode.ForRead, false, true) as Polyline; if (pl == null || !pl.Visible || pl.Area ==0) continue; if (pl.Area>maxArea) { maxArea = pl.Area; resVal = pl; } } return resVal; }
public FloorArchitect(BlockReference blRefArPlan, BaseService service) { Service = service; IdBlRef = blRefArPlan.Id; IdBtr = blRefArPlan.BlockTableRecord; BlName = blRefArPlan.Name; // определение параметров плана и окон try { definePlanNumberAndSection(blRefArPlan); } catch (Exception ex) { Inspector.AddError($"Ошибка при определении параметров арх.плана {BlName}.", blRefArPlan, icon: System.Drawing.SystemIcons.Error); } // определение окон в плане Windows = defineWindows(blRefArPlan); }
public ColorArea(BlockReference blRef) { EntInfo = new EntityInfo(blRef); Pos = new Point3d(blRef.Position.X - UtilsCopyColorArea.Base.X, blRef.Position.Y - UtilsCopyColorArea.Base.Y, 0); foreach (DynamicBlockReferenceProperty prop in blRef.DynamicBlockReferencePropertyCollection) { if (prop.PropertyName.Equals(Settings.Default.BlockColorAreaDynPropLength, StringComparison.OrdinalIgnoreCase )) { Length = (double)prop.Value; } else if(prop.PropertyName.Equals(Settings.Default.BlockColorAreaDynPropHeight, StringComparison.OrdinalIgnoreCase)) { Height = (double)prop.Value; } } }
/// <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 RotateBlockJig(BlockReference BlockRef) : base(BlockRef) { this.BlockRef = BlockRef; this.UcsRot = BlockRef.Rotation; }
public void ProcessBlock() { double insPnt_X = 0d; double insPnt_Y = 0d; Document bDwg = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument; Autodesk.AutoCAD.DatabaseServices.TransactionManager bTransMan = bDwg.TransactionManager; Editor ed = bDwg.Editor; string path = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory); string[] familyFiles = Directory.GetFiles(path + "\\fixtures", "*.dwg", SearchOption.TopDirectoryOnly); ed.WriteMessage("\nUsing directory {0}", path + "\\fixtures"); try { DocumentCollection acDocMgr = Application.DocumentManager; foreach (string familyFile in familyFiles) { string equipmentNumber = Path.GetFileNameWithoutExtension(familyFile); Document doc = acDocMgr.Open(familyFile, false); if (doc != null) { doc.LockDocument(); ed.WriteMessage("\nProcessing {0}", equipmentNumber); ExplodeBlockByNameCommand(ed, doc, equipmentNumber); doc.CloseAndSave(familyFile); doc.Dispose(); } else { ed.WriteMessage("\nCould not open {0}", equipmentNumber); } using (bDwg.LockDocument()) using (Transaction bTrans = bTransMan.StartTransaction()) { Database blkDb = new Database(false, true); blkDb.ReadDwgFile(familyFile, System.IO.FileShare.Read, true, ""); //Reading block source file string name = Path.GetFileNameWithoutExtension(familyFile); ObjectId oid = bDwg.Database.Insert(name, blkDb, true); using (BlockReference acBlkRef = new BlockReference(new Point3d(insPnt_X, insPnt_Y, 0), oid)) { BlockTableRecord acCurSpaceBlkTblRec; acCurSpaceBlkTblRec = bTrans.GetObject(bDwg.Database.CurrentSpaceId, OpenMode.ForWrite) as BlockTableRecord; acCurSpaceBlkTblRec.AppendEntity(acBlkRef); bTrans.AddNewlyCreatedDBObject(acBlkRef, true); } bTrans.Commit(); } insPnt_X += 240d; if (insPnt_X > 2400) { insPnt_X = 0; insPnt_Y += 240d; } } } catch (System.Exception err) { ed.WriteMessage("\nSomething went wrong in main process."); File.AppendAllText(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory) + "\\error_main.log", err.ToString()); } finally { } }
private bool BlockToDatabase(BlockReference block, Transaction tr) { try { Dictionary <string, AttributeReference> attribs = GetBlockAttributes(block, tr); if (String.IsNullOrEmpty(attribs["DRAWING-NUMBER"].TextString)) { PromptResult pr1 = _ed.GetString("Drawing Number:"); attribs["DRAWING-NUMBER"].TextString = pr1.StringResult; } if (String.IsNullOrEmpty(attribs["SHEET"].TextString)) { PromptResult pr1 = _ed.GetString("Sheet Number:"); attribs["SHEET"].TextString = pr1.StringResult; } if (String.IsNullOrEmpty(attribs["DRAWING-NUMBER"].TextString) || String.IsNullOrEmpty(attribs["SHEET"].TextString)) { _ed.WriteMessage("No drawing/sheet number forthcoming, returning.\n"); return(false); } DrawingsDataContext dc = DBCommon.NewDC; Drawing drawing = GetDrawing(dc, attribs["DRAWING-NUMBER"].TextString, attribs["SHEET"].TextString); if (drawing == null) { drawing = new Drawing(); dc.Drawings.InsertOnSubmit(drawing); } foreach (var kvp in attribs) { if (DrawingHelper.AttributeExists(kvp.Key)) //only save the desired attributes { drawing.SetAttribute(kvp.Key, kvp.Value.TextString); } } drawing.SheetSize = GetSheetSizeFromBlock(block, tr); //TODO: check this if (_db.Filename.EndsWith("sv$", StringComparison.OrdinalIgnoreCase)) { _ed.WriteMessage("File has not been saved since autosave, filename not put into the database.\n"); } else { drawing.FileName = _db.Filename; //drawing.Filename = _db.OriginalFileName; } //If we're putting this in via the CAD, then it must be electronic drawing.Electronic = true; dc.SubmitChanges(); if (drawing.Category == DrawingCategory.Undefined) { _ed.WriteMessage("WARNING: Drawing Category is undefined!\n"); } if (drawing.Status == DrawingStatus.Undefined) { _ed.WriteMessage("WARNING: Drawing Status is undefined!\n"); } _ed.WriteMessage("Data successfully written to the database from block " + block.Name + "\n"); return(true); } catch (Exception ex) { _ed.WriteMessage(ex.Message); return(false); } }
public void Merge() { Document doc = Application.DocumentManager.MdiActiveDocument; Editor ed = doc.Editor; LayoutManager lm = LayoutManager.Current; lm.CurrentLayout = "Layout1"; Database db = doc.Database; string dwgName = Path.GetFileNameWithoutExtension(doc.Name); string folderPath = Path.GetDirectoryName(doc.Name); List<SheetObject> sheetObjects = Helpers.SheetsObjectsFromCSV(folderPath, dwgName); using (Transaction transCreateLayers = db.TransactionManager.StartTransaction()) { foreach (SheetObject sheetObject in sheetObjects) { string layerName = $"0-{sheetObject.xrefName}"; Helpers.CreateLayer(db, transCreateLayers, layerName); ed.WriteMessage("======================== Layer created: " + layerName + "\n"); LayerTable layerTable = transCreateLayers.GetObject(db.LayerTableId, OpenMode.ForRead) as LayerTable; ObjectId layer = new ObjectId(); foreach (ObjectId layerId in layerTable) { LayerTableRecord currentLayer = transCreateLayers.GetObject(layerId, OpenMode.ForWrite) as LayerTableRecord; if (currentLayer.Name == layerName) { layer = layerId; } } //Load Xref #region string PathName = $"{folderPath}\\{sheetObject.xrefName}"; ObjectId acXrefId = db.AttachXref(PathName, sheetObject.xrefName); if (!acXrefId.IsNull) { // Attach the DWG reference to the model space Point3d insPt = new Point3d(0, 0, 0); using (BlockReference blockRef = new BlockReference(insPt, acXrefId)) { blockRef.SetLayerId(layer, true); BlockTable blocktable = transCreateLayers.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable; BlockTableRecord modelSpace = transCreateLayers.GetObject(blocktable[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord; modelSpace.AppendEntity(blockRef); transCreateLayers.AddNewlyCreatedDBObject(blockRef, true); } ed.WriteMessage("======================== xref loaded\n"); } #endregion } transCreateLayers.Commit(); } //get document name ed.WriteMessage("\n======================== Dwg Name: " + doc.Name + "\n"); //objects to delete List<ObjectId[]> viewportContentList = new List<ObjectId[]>(); foreach (SheetObject sheetObject in sheetObjects) { string layerName = $"0-{sheetObject.xrefName}"; using (Transaction trans = db.TransactionManager.StartTransaction()) { ed.WriteMessage("======================== Xref(s): " + sheetObject.xrefName + "\n"); XYZ currentVpCentre = sheetObject.viewportCentre; Point3d revitViewportCentre = new Point3d(currentVpCentre.x, currentVpCentre.y, 0); XYZ _revitViewCentreWCS = sheetObject.viewCentre; Point3d revitViewCentreWCS = new Point3d(_revitViewCentreWCS.x, _revitViewCentreWCS.y, 0); double degrees = Helpers.DegToRad(sheetObject.angleToNorth); double vpWidht = sheetObject.viewportWidth; double vpHeight = sheetObject.viewportHeight; lm.CurrentLayout = "Layout1"; string currentLo = lm.CurrentLayout; DBDictionary LayoutDict = trans.GetObject(db.LayoutDictionaryId, OpenMode.ForRead) as DBDictionary; Layout CurrentLo = trans.GetObject((ObjectId)LayoutDict[currentLo], OpenMode.ForRead) as Layout; Viewport matchingViewport = null; List<ObjectId> layerToFreeze = new List<ObjectId>(); //LayerTable layerTable = trans.GetObject(db.LayerTableId, OpenMode.ForRead) as LayerTable; //foreach (ObjectId layerId in layerTable) //{ // LayerTableRecord currentLayer = trans.GetObject(layerId, OpenMode.ForWrite) as LayerTableRecord; // if (currentLayer.Name != layerName) // { // layerToFreeze.Add(layerId); // } //} #region Find the equivalent Revit viewport foreach (ObjectId ID in CurrentLo.GetViewports()) { Viewport VP = trans.GetObject(ID, OpenMode.ForWrite) as Viewport; if (VP != null && CurrentLo.GetViewports().Count == 2 && VP.CenterPoint.X > 20) //by default the Layout is a viewport too...https://forums.autodesk.com/t5/net/layouts-and-viewports/td-p/3128748 { matchingViewport = VP; ed.WriteMessage("======================== Single Viewport on sheet\n"); } if (VP != null && VP.CenterPoint.DistanceTo(revitViewportCentre) < 100) //Should use the closest viewport, not a fixed distance { matchingViewport = VP; ed.WriteMessage("======================== Multiple Viewports on sheet\n"); } else { VP.FreezeLayersInViewport(layerToFreeze.GetEnumerator()); } } ed.WriteMessage("======================== Viewport Name: " + matchingViewport.BlockName + "\n"); ed.WriteMessage("======================== Viewport Center: " + matchingViewport.CenterPoint + "\n"); #endregion #region Delete Viewport Content Point3dCollection vpCorners = GetViewportBoundary(matchingViewport); Matrix3d mt = PaperToModel(matchingViewport); Point3dCollection vpCornersInModel = TransformPaperSpacePointToModelSpace(vpCorners, mt); try { ObjectId[] viewportContent = SelectEntitisInModelSpaceByViewport(doc, vpCornersInModel); viewportContentList.Add(viewportContent); ed.WriteMessage("======================== Viewport objects: " + viewportContent.Length.ToString() + "\n"); } catch (System.Exception ex) { ed.WriteMessage("======================== Error: " + ex.Message + "\n"); } #endregion //Recenter Viewport #region Helpers.UpdateViewport(matchingViewport, revitViewportCentre, revitViewCentreWCS, degrees, vpWidht, vpHeight); ed.WriteMessage("======================== Viewport updated \n"); #endregion trans.Commit(); }//close transaction }//close loop through sheet objects using (Transaction transDeleteObjects = db.TransactionManager.StartTransaction()) { foreach (ObjectId[] itemList in viewportContentList) { if (itemList != null) { foreach (ObjectId item in itemList) { Entity e = (Entity)transDeleteObjects.GetObject(item, OpenMode.ForWrite); //ed.WriteMessage(item.GetType().Name); e.Erase(); } ed.WriteMessage("======================== Viewport content deleted\n"); } else { ed.WriteMessage("======================== viewport content is null!\n"); } } transDeleteObjects.Commit(); } ed.WriteMessage("Switch to Model layout \n"); lm.CurrentLayout = "Model"; //ed.WriteMessage("======================== Run Set by layer\n"); //ed.Command("-setbylayer", "all"," ","y","y"); ed.WriteMessage("======================== Run Audit\n"); ed.Command("audit", "y"); ed.WriteMessage("======================== Run Purge \n"); ed.Command("-purge", "all", " ", "n"); lm.CurrentLayout = "Layout1"; ed.Command("_.zoom", "_extents"); ed.Command("_.zoom", "_scale", "0.9"); ed.WriteMessage("Save file \n"); db.SaveAs(doc.Name, true, DwgVersion.Current, doc.Database.SecurityParameters); ed.WriteMessage("done"); }
public void ShowPick() { Document doc = Application.DocumentManager.MdiActiveDocument; Database db = doc.Database; Editor editor = doc.Editor; try { using (Transaction trans = db.TransactionManager.StartTransaction()) { // 获取PickFirst选择集 PromptSelectionResult psr = editor.SelectImplied(); // 如果提示状态OK,说明启动命令前选择了对象; if (psr.Status != PromptStatus.OK) { editor.WriteMessage("没有选中对象\n"); return; } SelectionSet sset = psr.Value; editor.WriteMessage("选中{0:d}对象,第一个类型为{1:s}\n", sset.Count, sset[0].ObjectId.ObjectClass.DxfName); StringBuilder sb = new StringBuilder(); foreach (SelectedObject so in sset) { if (so.ObjectId.ObjectClass.DxfName == "TEXT") { DBText text = (DBText)so.ObjectId.GetObject(OpenMode.ForRead); sb.AppendLine(text.TextString); string s = string.Format("( {0:f1}, {1:f1} ) ( {2:f1}, {3:f1} )", text.GeometricExtents.MinPoint.X, text.GeometricExtents.MinPoint.Y, text.GeometricExtents.MaxPoint.X, text.GeometricExtents.MaxPoint.Y ); sb.AppendLine(s); //sb.Append(text.Position.ToString()); } else if (so.ObjectId.ObjectClass.DxfName == "MTEXT") { MText text = (MText)so.ObjectId.GetObject(OpenMode.ForRead); sb.AppendLine(text.Contents); sb.AppendLine(text.Text); string s = string.Format("( {0:f1}, {1:f1} ) ( {2:f1}, {3:f1} )", text.GeometricExtents.MinPoint.X, text.GeometricExtents.MinPoint.Y, text.GeometricExtents.MaxPoint.X, text.GeometricExtents.MaxPoint.Y ); sb.AppendLine(s); //sb.Append(text.Location.ToString()); } else if (so.ObjectId.ObjectClass.DxfName == "LINE") { Line line = (Line)so.ObjectId.GetObject(OpenMode.ForRead); sb.Append(line.StartPoint.ToString()); sb.Append(line.EndPoint.ToString()); } else if (so.ObjectId.ObjectClass.DxfName == "LWPOLYLINE") { Polyline pLine = (Polyline)so.ObjectId.GetObject(OpenMode.ForRead); for (int i = 0; i < pLine.NumberOfVertices; i++) { sb.Append(pLine.GetPoint2dAt(i).ToString()); } } else if (so.ObjectId.ObjectClass.DxfName == "INSERT") { Entity entity = (Entity)so.ObjectId.GetObject(OpenMode.ForWrite); if (entity is BlockReference) { BlockReference br = entity as BlockReference; sb.Append(br.Name); } } } editor.WriteMessage(sb.ToString()); trans.Commit(); } } catch (System.Exception e) { editor.WriteMessage(e.ToString()); } }
public static List <AttributeDefinition> GetAttributes(BlockReference br, Transaction trans) { BlockTableRecord btr = (BlockTableRecord)trans.GetObject(br.BlockTableRecord, OpenMode.ForRead); return(GetAttributes(btr, trans)); }
public static ObjectId AddBlockRefToModelSpace(ObjectId blockTableRecordId, List <string> attrTextValues, Point3d location, Matrix3d matrix, Transaction trans, bool commit) { // Add a block reference to the model space BlockTableRecord ms = Tools.GetAcadBlockTableRecordModelSpace(trans, OpenMode.ForWrite); BlockTableRecord btr = (BlockTableRecord)trans.GetObject(blockTableRecordId, OpenMode.ForRead); BlockReference br = new BlockReference(location, blockTableRecordId); br.TransformBy(matrix); ObjectContextManager ocm = btr.Database.ObjectContextManager; ObjectContextCollection occ = ocm.GetContextCollection("ACDB_ANNOTATIONSCALES"); if (btr.Annotative == AnnotativeStates.True) { br.AddContext(occ.CurrentContext); } //br.RecordGraphicsModified(true); ObjectId brId = ms.AppendEntity(br); trans.AddNewlyCreatedDBObject(br, true); // Add attributes from the block table record List <AttributeDefinition> attributes = GetAttributes(btr, trans); int i = 0; foreach (AttributeDefinition acAtt in attributes) { if (!acAtt.Constant) { using (AttributeReference acAttRef = new AttributeReference()) { //acAttRef.RecordGraphicsModified(true); acAttRef.SetAttributeFromBlock(acAtt, br.BlockTransform); //acAttRef.Position = acAtt.Position.TransformBy(br.BlockTransform); if (attrTextValues != null) { acAttRef.TextString = attrTextValues[i++]; } else { acAttRef.TextString = acAtt.TextString; } //if (acAtt.Annotative == AnnotativeStates.True) //acAttRef.AddContext(occ.CurrentContext); br.AttributeCollection.AppendAttribute(acAttRef); trans.AddNewlyCreatedDBObject(acAttRef, true); } } // Change the attribute definition to be displayed as backwards //acAtt.UpgradeOpen(); //acAtt.IsMirroredInX = true; //acAtt.IsMirroredInY = false; } br.RecordGraphicsModified(true); if (commit) { trans.Commit(); } return(brId); }
/// <summary> /// /// * Insert Drawing As Block - DWG or DXF * /// the source drawig should be drawn as number of /// separate entites with or without attributes /// /// </summary> /// <param name="destinationDocument"></param> /// <param name="sourceDrawing"></param> /// <param name="insertionPoint"></param> /// <param name="transforMatrix"> </param> /// <exception cref="NotImplementedException">Not implemented for DXFs</exception> /// <returns>ObjectID of the Block Def that was imported.</returns> private void ReplaceBlockRefWithDWG(Document destinationDocument, string sourceDrawing, Point3d insertionPoint, Matrix3d transforMatrix) { Point3d oldPoint = insertionPoint.TransformBy(transforMatrix.Inverse()); insertionPoint = new Point3d(0, 0, 0); Database destinationDb = destinationDocument.Database; Editor ed = destinationDocument.Editor; string blockname = sourceDrawing.Remove(0, sourceDrawing.LastIndexOf("\\", StringComparison.Ordinal) + 1); blockname = blockname.Substring(0, blockname.Length - 4); // remove the extension using (destinationDocument.LockDocument()) { using (var inMemoryDb = new Database(false, true)) { if (sourceDrawing.LastIndexOf(".dwg", StringComparison.Ordinal) > 0) { inMemoryDb.ReadDwgFile(sourceDrawing, FileShare.ReadWrite, true, ""); } else if (sourceDrawing.LastIndexOf(".dxf", StringComparison.Ordinal) > 0) { throw new NotImplementedException("DXFs not suppported"); //inMemoryDb.DxfIn(string filename, string logFilename); } using (var transaction = destinationDocument.TransactionManager.StartTransaction()) { var destinationDatabaseBlockTable = (BlockTable)transaction.GetObject(destinationDb.BlockTableId, OpenMode.ForRead); ObjectId sourceBlockObjectId; if (destinationDatabaseBlockTable.Has(blockname)) { ed.WriteMessage("Block " + blockname + " already exists.\n Attempting to create block reference..."); var destinationDatabaseCurrentSpace = (BlockTableRecord)destinationDb.CurrentSpaceId.GetObject(OpenMode.ForWrite); var destinationDatabaseBlockDefinition = (BlockTableRecord) transaction.GetObject(destinationDatabaseBlockTable[blockname], OpenMode.ForRead); sourceBlockObjectId = destinationDatabaseBlockDefinition.ObjectId; // Create a block reference to the existing block definition using (var blockReference = new BlockReference(insertionPoint, sourceBlockObjectId)) { //Matrix3d Mat = Matrix3d.Identity; Vector3d mov = new Vector3d(oldPoint.X, oldPoint.Y, oldPoint.Z); mov = mov.TransformBy(transforMatrix); blockReference.TransformBy(transforMatrix); blockReference.TransformBy(Matrix3d.Displacement(mov)); blockReference.ScaleFactors = new Scale3d(1, 1, 1); destinationDatabaseCurrentSpace.AppendEntity(blockReference); transaction.AddNewlyCreatedDBObject(blockReference, true); ed.Regen(); transaction.Commit(); // At this point the Bref has become a DBObject and can be disposed } return; } // There is not such block definition, so we are inserting/creating new one sourceBlockObjectId = destinationDb.Insert(blockname, inMemoryDb, true); #region Create Block Ref from the already imported Block Def // We continue here the creation of the new block reference of the already imported block definition var sourceDatabaseCurrentSpace = (BlockTableRecord)destinationDb.CurrentSpaceId.GetObject(OpenMode.ForWrite); using (var blockReference = new BlockReference(insertionPoint, sourceBlockObjectId)) { blockReference.ScaleFactors = new Scale3d(1, 1, 1); sourceDatabaseCurrentSpace.AppendEntity(blockReference); transaction.AddNewlyCreatedDBObject(blockReference, true); var blockTableRecord = (BlockTableRecord)blockReference.BlockTableRecord.GetObject(OpenMode.ForRead); var atcoll = blockReference.AttributeCollection; foreach (ObjectId subid in blockTableRecord) { var entity = (Entity)subid.GetObject(OpenMode.ForRead); var attributeDefinition = entity as AttributeDefinition; if (attributeDefinition == null) { continue; } var attributeReference = new AttributeReference(); attributeReference.SetPropertiesFrom(attributeDefinition); attributeReference.Visible = attributeDefinition.Visible; attributeReference.SetAttributeFromBlock(attributeDefinition, blockReference.BlockTransform); attributeReference.HorizontalMode = attributeDefinition.HorizontalMode; attributeReference.VerticalMode = attributeDefinition.VerticalMode; attributeReference.Rotation = attributeDefinition.Rotation; attributeReference.Position = attributeDefinition.Position + insertionPoint.GetAsVector(); attributeReference.Tag = attributeDefinition.Tag; attributeReference.FieldLength = attributeDefinition.FieldLength; attributeReference.TextString = attributeDefinition.TextString; attributeReference.AdjustAlignment(destinationDb); atcoll.AppendAttribute(attributeReference); transaction.AddNewlyCreatedDBObject(attributeReference, true); } var mov = new Vector3d(oldPoint.X, oldPoint.Y, oldPoint.Z); mov = mov.TransformBy(transforMatrix); blockReference.TransformBy(transforMatrix); blockReference.TransformBy(Matrix3d.Displacement(mov)); transaction.Commit(); } #endregion ed.Regen(); } } } }
/// <summary> /// Синхронизация вхождений блоков с их определением /// via http://sites.google.com/site/bushmansnetlaboratory/moi-zametki/attsynch /// </summary> /// <param name="btr">Запись таблицы блоков, принятая за определение блока</param> /// <param name="directOnly">Следует ли искать только на верхнем уровне, или же нужно /// анализировать и вложенные вхождения, т.е. следует ли рекурсивно обрабатывать блок в блоке: /// true - только верхний; false - рекурсивно проверять вложенные блоки.</param> /// <param name="removeSuperfluous"> /// Следует ли во вхождениях блока удалять лишние атрибуты (те, которых нет в определении блока).</param> /// <param name="setAttDefValues"> /// Следует ли всем атрибутам, во вхождениях блока, назначить текущим значением значение по умолчанию.</param> public static void AttSync(this BlockTableRecord btr, bool directOnly, bool removeSuperfluous, bool setAttDefValues) { Database db = btr.Database; // using (Bushman.AutoCAD.DatabaseServices.WorkingDatabaseSwitcher wdb = new Bushman.AutoCAD.DatabaseServices.WorkingDatabaseSwitcher(db)) { using (Transaction t = db.TransactionManager.StartTransaction()) { BlockTable bt = (BlockTable)t.GetObject(db.BlockTableId, OpenMode.ForRead); //Получаем все определения атрибутов из определения блока IEnumerable <AttributeDefinition> attdefs = btr.Cast <ObjectId>() .Where(n => n.ObjectClass.Name == "AcDbAttributeDefinition") .Select(n => (AttributeDefinition)t.GetObject(n, OpenMode.ForRead)) .Where(n => !n.Constant);//Исключаем константные атрибуты, т.к. для них AttributeReference не создаются. //В цикле перебираем все вхождения искомого определения блока foreach (ObjectId brId in btr.GetBlockReferenceIds(directOnly, false)) { BlockReference br = (BlockReference)t.GetObject(brId, OpenMode.ForWrite); //Проверяем имена на соответствие. В том случае, если вхождение блока "A" вложено в определение блока "B", //то вхождения блока "B" тоже попадут в выборку. Нам нужно их исключить из набора обрабатываемых объектов //- именно поэтому проверяем имена. if (br.Name != btr.Name) { continue; } //Получаем все атрибуты вхождения блока IEnumerable <AttributeReference> attrefs = br.AttributeCollection.Cast <ObjectId>() .Select(n => (AttributeReference)t.GetObject(n, OpenMode.ForWrite)); //Тэги существующих определений атрибутов IEnumerable <string> dtags = attdefs.Select(n => n.Tag); //Тэги существующих атрибутов во вхождении IEnumerable <string> rtags = attrefs.Select(n => n.Tag); //Если требуется - удаляем те атрибуты, для которых нет определения //в составе определения блока if (removeSuperfluous) { foreach (AttributeReference attref in attrefs.Where(n => rtags .Except(dtags).Contains(n.Tag))) { attref.Erase(true); } } //Свойства существующих атрибутов синхронизируем со свойствами их определений foreach (AttributeReference attref in attrefs.Where(n => dtags .Join(rtags, a => a, b => b, (a, b) => a).Contains(n.Tag))) { AttributeDefinition ad = attdefs.First(n => n.Tag == attref.Tag); //Метод SetAttributeFromBlock, используемый нами далее в коде, сбрасывает //текущее значение многострочного атрибута. Поэтому запоминаем это значение, //чтобы восстановить его сразу после вызова SetAttributeFromBlock. string value = attref.TextString; attref.SetAttributeFromBlock(ad, br.BlockTransform); //Восстанавливаем значение атрибута attref.TextString = value; if (attref.IsMTextAttribute) { } //Если требуется - устанавливаем для атрибута значение по умолчанию if (setAttDefValues) { attref.TextString = ad.TextString; } attref.AdjustAlignment(db); } //Если во вхождении блока отсутствуют нужные атрибуты - создаём их IEnumerable <AttributeDefinition> attdefsNew = attdefs.Where(n => dtags .Except(rtags).Contains(n.Tag)); foreach (AttributeDefinition ad in attdefsNew) { AttributeReference attref = new AttributeReference(); attref.SetAttributeFromBlock(ad, br.BlockTransform); attref.AdjustAlignment(db); br.AttributeCollection.AppendAttribute(attref); t.AddNewlyCreatedDBObject(attref, true); } } btr.UpdateAnonymousBlocks(); t.Commit(); } //Если это динамический блок if (btr.IsDynamicBlock) { using (Transaction t = db.TransactionManager.StartTransaction()) { foreach (ObjectId id in btr.GetAnonymousBlockIds()) { BlockTableRecord _btr = (BlockTableRecord)t.GetObject(id, OpenMode.ForWrite); //Получаем все определения атрибутов из оригинального определения блока IEnumerable <AttributeDefinition> attdefs = btr.Cast <ObjectId>() .Where(n => n.ObjectClass.Name == "AcDbAttributeDefinition") .Select(n => (AttributeDefinition)t.GetObject(n, OpenMode.ForRead)); //Получаем все определения атрибутов из определения анонимного блока IEnumerable <AttributeDefinition> attdefs2 = _btr.Cast <ObjectId>() .Where(n => n.ObjectClass.Name == "AcDbAttributeDefinition") .Select(n => (AttributeDefinition)t.GetObject(n, OpenMode.ForWrite)); //Определения атрибутов анонимных блоков следует синхронизировать //с определениями атрибутов основного блока //Тэги существующих определений атрибутов IEnumerable <string> dtags = attdefs.Select(n => n.Tag); IEnumerable <string> dtags2 = attdefs2.Select(n => n.Tag); //1. Удаляем лишние foreach (AttributeDefinition attdef in attdefs2.Where(n => !dtags.Contains(n.Tag))) { attdef.Erase(true); } //2. Синхронизируем существующие foreach (AttributeDefinition attdef in attdefs.Where(n => dtags .Join(dtags2, a => a, b => b, (a, b) => a).Contains(n.Tag))) { AttributeDefinition ad = attdefs2.First(n => n.Tag == attdef.Tag); ad.Position = attdef.Position; #if ACAD2009 ad.TextStyle = attdef.TextStyle; #else ad.TextStyleId = attdef.TextStyleId; #endif //Если требуется - устанавливаем для атрибута значение по умолчанию if (setAttDefValues) { ad.TextString = attdef.TextString; } ad.Tag = attdef.Tag; ad.Prompt = attdef.Prompt; ad.LayerId = attdef.LayerId; ad.Rotation = attdef.Rotation; ad.LinetypeId = attdef.LinetypeId; ad.LineWeight = attdef.LineWeight; ad.LinetypeScale = attdef.LinetypeScale; ad.Annotative = attdef.Annotative; ad.Color = attdef.Color; ad.Height = attdef.Height; ad.HorizontalMode = attdef.HorizontalMode; ad.Invisible = attdef.Invisible; ad.IsMirroredInX = attdef.IsMirroredInX; ad.IsMirroredInY = attdef.IsMirroredInY; ad.Justify = attdef.Justify; ad.LockPositionInBlock = attdef.LockPositionInBlock; ad.MaterialId = attdef.MaterialId; ad.Oblique = attdef.Oblique; ad.Thickness = attdef.Thickness; ad.Transparency = attdef.Transparency; ad.VerticalMode = attdef.VerticalMode; ad.Visible = attdef.Visible; ad.WidthFactor = attdef.WidthFactor; ad.CastShadows = attdef.CastShadows; ad.Constant = attdef.Constant; ad.FieldLength = attdef.FieldLength; ad.ForceAnnoAllVisible = attdef.ForceAnnoAllVisible; ad.Preset = attdef.Preset; ad.Prompt = attdef.Prompt; ad.Verifiable = attdef.Verifiable; ad.AdjustAlignment(db); } //3. Добавляем недостающие foreach (AttributeDefinition attdef in attdefs.Where(n => !dtags2.Contains(n.Tag))) { AttributeDefinition ad = new AttributeDefinition(); ad.SetDatabaseDefaults(); ad.Position = attdef.Position; #if ACAD2009 ad.TextStyle = attdef.TextStyle; #else ad.TextStyleId = attdef.TextStyleId; #endif ad.TextString = attdef.TextString; ad.Tag = attdef.Tag; ad.Prompt = attdef.Prompt; ad.LayerId = attdef.LayerId; ad.Rotation = attdef.Rotation; ad.LinetypeId = attdef.LinetypeId; ad.LineWeight = attdef.LineWeight; ad.LinetypeScale = attdef.LinetypeScale; ad.Annotative = attdef.Annotative; ad.Color = attdef.Color; ad.Height = attdef.Height; ad.HorizontalMode = attdef.HorizontalMode; ad.Invisible = attdef.Invisible; ad.IsMirroredInX = attdef.IsMirroredInX; ad.IsMirroredInY = attdef.IsMirroredInY; ad.Justify = attdef.Justify; ad.LockPositionInBlock = attdef.LockPositionInBlock; ad.MaterialId = attdef.MaterialId; ad.Oblique = attdef.Oblique; ad.Thickness = attdef.Thickness; ad.Transparency = attdef.Transparency; ad.VerticalMode = attdef.VerticalMode; ad.Visible = attdef.Visible; ad.WidthFactor = attdef.WidthFactor; ad.CastShadows = attdef.CastShadows; ad.Constant = attdef.Constant; ad.FieldLength = attdef.FieldLength; ad.ForceAnnoAllVisible = attdef.ForceAnnoAllVisible; ad.Preset = attdef.Preset; ad.Prompt = attdef.Prompt; ad.Verifiable = attdef.Verifiable; _btr.AppendEntity(ad); t.AddNewlyCreatedDBObject(ad, true); ad.AdjustAlignment(db); } //Синхронизируем все вхождения данного анонимного определения блока _btr.AttSync(directOnly, removeSuperfluous, setAttDefValues); } //Обновляем геометрию определений анонимных блоков, полученных на основе //этого динамического блока btr.UpdateAnonymousBlocks(); t.Commit(); } } // } }
public WallOpeningBlock(BlockReference blRef, string blName) : base(blRef, blName) { }
editExistCalloutsByDatumAdj(SelectionSet SS, double dblAdj) { BlockReference BR = null; string strElev = string.Empty; double dblElev = 0.0; try { using (Transaction tr = BaseObjs.startTransactionDb()) { ObjectId[] objIDs = SS.GetObjectIds(); foreach (ObjectId objID in objIDs) { BR = (BlockReference)tr.GetObject(objID, OpenMode.ForWrite); if (BR != null) { AttributeCollection AC = BR.AttributeCollection; foreach (ObjectId arID in AC) { AttributeReference AR = (AttributeReference)tr.GetObject(arID, OpenMode.ForWrite); string strAttVal = AR.TextString.ToString(); if (strAttVal != string.Empty) { if (strAttVal.StartsWith("(")) { if (strAttVal.Contains(" ") == true) { string[] strFields = Txt.splitFields(strAttVal, ' '); if (strFields[0] != string.Empty) { string strVal = strFields[0]; strElev = strVal.Substring(1, strVal.Length - 1); Boolean boolDbl = double.TryParse(strElev, out dblElev); if (boolDbl == true) { dblElev = dblElev + dblAdj; strElev = dblElev.ToString(); strAttVal = string.Format("({0} {1}", strElev, strFields[1]); AR.TextString = strAttVal; BR.Color = Autodesk.AutoCAD.Colors.Color.FromRgb(255, 200, 200); } } } else { strElev = strAttVal.Substring(1, strAttVal.Length - 2); Boolean boolDbl = double.TryParse(strElev, out dblElev); if (boolDbl == true) { dblElev = dblElev + dblAdj; strElev = dblElev.ToString(); strAttVal = string.Format("({0})", strElev); AR.TextString = strAttVal; BR.Color = Autodesk.AutoCAD.Colors.Color.FromRgb(255, 200, 200); } } } } } } } tr.Commit(); } //end using tr } catch (System.Exception ex) { BaseObjs.writeDebug(ex.Message + " Mod.cs: line: 337"); } }
public override void Run(string filename, Database db) { if (blockNames.Count == 0) { return; } using (Transaction tr = db.TransactionManager.StartTransaction()) { try { ObjectIdCollection blockIDs = new ObjectIdCollection(); if (applyToAllBlockDefinitons) { // Apply to all block definitions BlockTable blockTable = (BlockTable)tr.GetObject(db.BlockTableId, OpenMode.ForRead); foreach (ObjectId id in blockTable) { if (id == SymbolUtilityServices.GetBlockModelSpaceId(db)) { continue; } BlockTableRecord block = (BlockTableRecord)tr.GetObject(id, OpenMode.ForRead); if (block.IsLayout) { continue; } blockIDs.Add(id); } } else { // Model space (or entire drawing) if (applyModel) { blockIDs.Add(SymbolUtilityServices.GetBlockModelSpaceId(db)); } // Layouts (or entire drawing) if (applyLayouts) { DBDictionary layoutDict = (DBDictionary)tr.GetObject(db.LayoutDictionaryId, OpenMode.ForRead); foreach (DBDictionaryEntry entry in layoutDict) { if (entry.Key.ToUpperInvariant() != "MODEL") { Layout layout = (Layout)tr.GetObject(entry.Value, OpenMode.ForRead); blockIDs.Add(layout.BlockTableRecordId); } } } } foreach (ObjectId spaceId in blockIDs) { // Open the block space BlockTableRecord btr = (BlockTableRecord)tr.GetObject(spaceId, OpenMode.ForRead); foreach (ObjectId id in btr) { if (id.ObjectClass.IsDerivedFrom(RXObject.GetClass(typeof(BlockReference)))) { BlockReference bref = (BlockReference)tr.GetObject(id, OpenMode.ForRead); bool canDelete = false; foreach (string name in blockNames) { if (string.Compare(name, bref.Name, StringComparison.OrdinalIgnoreCase) == 0) { canDelete = true; } } if (canDelete) { bref.UpgradeOpen(); bref.Erase(true); } } } } } catch (System.Exception ex) { OnError(ex); } tr.Commit(); } }
public abstract void SetAttributeValue(BlockReference blockReference);
private static void GetAllXRefFullPaths(string[] files, List <string> usedXRefFullPaths) { foreach (var fileName in files) { Database db = new Database(false, true); using (db) { db.ReadDwgFile(fileName, System.IO.FileShare.Read, allowCPConversion: false, password: ""); using (Transaction tr = db.TransactionManager.StartTransaction()) { BlockTable bt = (BlockTable)tr.GetObject(db.BlockTableId, OpenMode.ForRead); foreach (var id in bt) { BlockTableRecord btr = (BlockTableRecord)tr.GetObject(id, OpenMode.ForRead); if (btr.IsLayout) { foreach (var oid in btr) { var ent = tr.GetObject(oid, OpenMode.ForRead); BlockReference bref = ent as BlockReference; if (bref != null) { if (bref.BlockTableRecord == default(ObjectId)) { try { log.WarnFormat(CultureInfo.CurrentCulture, "Block in '{0}' hat keinen Blocktable-Record. Handle = {1}", bref.BlockName, bref.Handle); } catch (System.Exception ex) { log.Error(ex.Message, ex); } } else { var bd = (BlockTableRecord)tr.GetObject(bref.BlockTableRecord, OpenMode.ForRead); if (bd.IsFromExternalReference) { string xpath = bd.PathName; string completePath = string.Empty; if (!System.IO.Path.IsPathRooted(xpath)) { // relativer pfad string cpath = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(fileName), xpath); completePath = System.IO.Path.GetFullPath(cpath); } else { // absoluter pfad completePath = System.IO.Path.GetFullPath(xpath); } completePath = completePath.ToUpperInvariant(); if (!usedXRefFullPaths.Contains(completePath)) { usedXRefFullPaths.Add(completePath); } } } } } } } tr.Commit(); } } } }
public static bool IsScaleEquals([NotNull] this BlockReference blref, int scale) { return(blref.ScaleFactors.IsEqualTo(new Scale3d(scale), tolerance)); }
private bool GetHeightFromVermBlocks(ref double height) { _AcAp.DocumentCollection dm = _AcAp.Application.DocumentManager; _AcAp.Document doc = dm.MdiActiveDocument; Editor ed = doc.Editor; #if NEWSETFOCUS doc.Window.Focus(); #else Autodesk.AutoCAD.Internal.Utils.SetFocusToDwgView(); // previous 2014 AutoCAD - Versions #endif PromptEntityResult per = ed.GetEntity("\nErsten Vermessungsblock wählen: "); //DocumentLock loc = dm.MdiActiveDocument.LockDocument(); //using (loc) //{ //} bool blockFound = false; double height1 = 0.0; double height2 = 0.0; 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(false); } if (br.Name == "GEOINOVA") { blockFound = true; height1 = br.Position.Z; br.Highlight(); } if (blockFound) { blockFound = false; per = ed.GetEntity("\nZweiten Vermessungsblock wählen: "); if (per.Status == PromptStatus.OK) { obj = tr.GetObject(per.ObjectId, OpenMode.ForRead); BlockReference br2 = obj as BlockReference; if (br2 == null) { return(false); } if (br2.Name == "GEOINOVA") { blockFound = true; height2 = br2.Position.Z; } } if (blockFound) { height = Math.Abs(height1 - height2); } br.Unhighlight(); } tr.Commit(); } if (!blockFound) { return(false); } return(true); } return(false); }
public InsertBlockJig(BlockReference BlockRef) : base(BlockRef) { this.BlockRef = BlockRef; this.Position = BlockRef.Position; }
private static void placementAparts(Database db) { using (var t = db.TransactionManager.StartTransaction()) { ObjectId idTextStylePik = db.GetTextStylePIK(); var bt = db.BlockTableId.GetObject(OpenMode.ForRead) as BlockTable; var ms = bt[BlockTableRecord.ModelSpace].GetObject(OpenMode.ForWrite) as BlockTableRecord; int countAparts; var btrApartGroups = getGroupedAparts(bt, out countAparts); Point3d pt = Point3d.Origin; Point3d ptCenterPlace; using (var progress = new ProgressMeter()) { progress.SetLimit(countAparts); progress.Start("Расстановка квартир..."); foreach (var btrApartGroup in btrApartGroups) { progress.MeterProgress(); foreach (var idBtrApart in btrApartGroup) { var curPlaceWidth = placeWidth; var blRefApart = new BlockReference(pt, idBtrApart); blRefApart.SetDatabaseDefaults(db); var extApart = blRefApart.GeometricExtents; var lenApart = extApart.MaxPoint.X - extApart.MinPoint.X; if (lenApart > placeWidth) { curPlaceWidth = lenApart + 1000; } ptCenterPlace = new Point3d(pt.X + curPlaceWidth * 0.5, pt.Y - placeHeight * 0.5, 0); var ptBlCenter = extApart.Center(); // Перемещение блока в центр прямоугольной области Matrix3d displace = Matrix3d.Displacement(ptCenterPlace - ptBlCenter); blRefApart.TransformBy(displace); ms.AppendEntity(blRefApart); t.AddNewlyCreatedDBObject(blRefApart, true); // Подпись квартиры DBText text = new DBText(); text.SetDatabaseDefaults(); text.TextStyleId = idTextStylePik; text.Height = 900; text.TextString = getApartName(blRefApart.Name); text.Position = new Point3d(pt.X + 300, pt.Y + 300, 0); ms.AppendEntity(text); t.AddNewlyCreatedDBObject(text, true); // Прямоугольник расположения квартиры Polyline pl = new Polyline(4); pl.AddVertexAt(0, pt.Convert2d(), 0, 0, 0); pl.AddVertexAt(1, new Point2d(pt.X + curPlaceWidth, pt.Y), 0, 0, 0); pl.AddVertexAt(2, new Point2d(pt.X + curPlaceWidth, pt.Y - placeHeight), 0, 0, 0); pl.AddVertexAt(3, new Point2d(pt.X, pt.Y - placeHeight), 0, 0, 0); pl.Closed = true; pl.SetDatabaseDefaults(); ms.AppendEntity(pl); t.AddNewlyCreatedDBObject(pl, true); pt = new Point3d(pt.X + curPlaceWidth, pt.Y, 0); } pt = new Point3d(0, pt.Y - placeHeight - 8000, 0); } progress.Stop(); } t.Commit(); } }
public static ObjectId AppendBlockItem(Point3d insertPointWcs, ObjectId blockTableRecordId, Dictionary <string, string> attrTextValues) { ObjectId resBlockId = ObjectId.Null; Tools.StartTransaction(() => { Transaction trans = Tools.GetTopTransaction(); // Add a block reference to the model space BlockTableRecord ms = Tools.GetAcadBlockTableRecordModelSpace(OpenMode.ForWrite); BlockTableRecord btr = blockTableRecordId.GetObjectForRead <BlockTableRecord>(); BlockReference br = new BlockReference(insertPointWcs, blockTableRecordId); br.SetDatabaseDefaults(); ObjectContextManager ocm = btr.Database.ObjectContextManager; ObjectContextCollection occ = ocm.GetContextCollection("ACDB_ANNOTATIONSCALES"); if (btr.Annotative == AnnotativeStates.True) { br.AddContext(occ.CurrentContext); } resBlockId = ms.AppendEntity(br); trans.AddNewlyCreatedDBObject(br, true); // Add attributes from the block table record List <AttributeDefinition> attributes = GetAttributes(btr, trans); foreach (AttributeDefinition acAtt in attributes) { acAtt.UpgradeOpen(); acAtt.AdjustAlignment(br.Database); // acAtt.RecordGraphicsModified(true); // if (!acAtt.Constant) { using (AttributeReference acAttRef = new AttributeReference()) { acAttRef.SetAttributeFromBlock(acAtt, br.BlockTransform); if (attrTextValues != null) { if (attrTextValues.ContainsKey(acAtt.Tag)) { acAttRef.TextString = attrTextValues[acAtt.Tag]; } else { acAttRef.TextString = acAtt.TextString; } } else { acAttRef.TextString = acAtt.TextString; } acAttRef.AdjustAlignment(br.Database); // acAttRef.RecordGraphicsModified(true); // br.AttributeCollection.AppendAttribute(acAttRef); trans.AddNewlyCreatedDBObject(acAttRef, true); } } } br.RecordGraphicsModified(true); }); return(resBlockId); }
//这是转换操作函数 private void convertToText(PromptSelectionResult SelResult) { //初始化转换计数 int count = 0; //获取选择集所有实体的ID ObjectId[] ObIDs = SelResult.Value.GetObjectIds(); //启动事务进行实体操作 using (Transaction trans = db.TransactionManager.StartTransaction()) { //加一个try进行异常处理 try { //遍历选择集中的所有实体 foreach (ObjectId ObID in ObIDs) { //依据实体ID获取实体对象 //为加快系统处理速度,OpenMode使用ForRead,轮到需要的实体时再用UpgradeOpen()改为ForWrite DBObject ent = trans.GetObject(ObID, OpenMode.ForRead) as DBObject; //属性块的情况麻烦些,单独拎出来 if (ent != null) { if (ent.GetType().Name == "BlockReference") { BlockReference blk = ent as BlockReference; //判断是否是动态块 if (blk.IsDynamicBlock) { AttributeCollection ac = blk.AttributeCollection; foreach (ObjectId arID in ac) { AttributeReference ar = arID.GetObject(OpenMode.ForWrite) as AttributeReference; if (ar.HasFields) { ar.ConvertFieldToText(); count++; } } } } if (ent.HasFields) { //获取实体的类型进行判断 switch (ent.GetType().Name) { //单行文字 case "DBText": { DBText Dt = (DBText)ent; //改为ForWrite Dt.UpgradeOpen(); //利用DBText的ConvertFieldToText()方法转换 //注:该方法用在不含有字段的文字时会报错 Dt.ConvertFieldToText(); count++; break; } //多行文字 case "MText": { MText Dt = (MText)ent; Dt.UpgradeOpen(); Dt.ConvertFieldToText(); count++; break; } } } } } //提交事务保存 trans.Commit(); } catch (Autodesk.AutoCAD.Runtime.Exception Ex) { ed.WriteMessage("\n出错了!" + Ex.ToString()); } finally { //关闭事务 trans.Dispose(); } } ed.WriteMessage("\n完成转换" + count + "个字段"); }
/// <summary> /// Блок - по имени и ссылке на вхождение блока /// Заполняются параметры блока. и граница Bounds /// </summary> public BlockBase([NotNull] BlockReference blRef, string blName) { BlName = blName; Update(blRef); }
public Extents3d GetExtents3dFromInsertPointOfBlockReferenceAndTwoVectorsWithScale(BlockReference acBlkRef, Vector3d[] acVec3dOrgArr, Scale3d acScl3dOrg) { Point3d acPtIns = acBlkRef.Position; //Application.ShowAlertDialog(acPtIns.ToString()); //Application.ShowAlertDialog(acScl3dOrg.X.ToString()); //Application.ShowAlertDialog("Insert Point: \n" + acPtIns.ToString() + "\nScale: \n" + acBlkRef.ScaleFactors.X.ToString() + "\nVector 0: \n" + acVec3dOrgArr[0].ToString()); Point3d acPt1 = new Point3d(acPtIns.X + acVec3dOrgArr[0].X * acBlkRef.ScaleFactors.X / acScl3dOrg.X, acPtIns.Y + acVec3dOrgArr[0].Y * acBlkRef.ScaleFactors.Y / acScl3dOrg.Y, 0); Point3d acPt2 = new Point3d(acPtIns.X + acVec3dOrgArr[1].X * acBlkRef.ScaleFactors.X / acScl3dOrg.X, acPtIns.Y + acVec3dOrgArr[1].Y * acBlkRef.ScaleFactors.Y / acScl3dOrg.Y, 0); Extents3d acExt3d = new Extents3d(acPt1, acPt2); //Application.ShowAlertDialog(acExt3d.ToString()); return(acExt3d); }
public void ReplaceBlockReferenceWithBlockTableRecord(DocumentCollection acDocMgr, Document acDoc, Transaction acTrans, BlockTableRecord acBlkTblRecSpc, BlockReference acBlkRefRemoved, BlockTableRecord acBklTblRecReplaced, int[] acAttRefIndexCol) { BlockTableRecord acBlkTblRecReplacedClone; BlockTable acBlkTbl = (BlockTable)acTrans.GetObject(acDoc.Database.BlockTableId, OpenMode.ForRead); //BlockTableRecord acBlkTblRecReplacedClone = (BlockTableRecord)acBklTblRecReplaced.Clone(); if (!acBlkTbl.IsWriteEnabled) { acBlkTbl.UpgradeOpen(); } if (!acBlkTbl.Has(acBklTblRecReplaced.Name)) { //acBlkTbl.Add(acBlkTblRecReplacedClone); acTrans.AddNewlyCreatedDBObject(acBlkTblRecReplacedClone, true); InsertBlock(acDocMgr, acDoc, acBklTblRecReplaced); } acBlkTblRecReplacedClone = (BlockTableRecord)acTrans.GetObject(acBlkTbl[acBklTblRecReplaced.Name], OpenMode.ForRead); //Application.ShowAlertDialog("Start"); //BlockTableRecord acBlkTblRecRemoved =(BlockTableRecord) acTrans.GetObject(acBlkRefRemoved.BlockTableRecord, OpenMode.ForRead); Extents3d acExtRemoved = acBlkRefRemoved.GeometricExtents; //Extents3d extents = br.GeometricExtents; //Vector3d acVec3d = acBlkTblRecRemoved.Origin.GetVectorTo(acExtRemoved.MinPoint); //Application.ShowAlertDialog("-2"); double acLenRemoved = Math.Abs(acExtRemoved.MinPoint.Y - acExtRemoved.MaxPoint.Y); //Application.ShowAlertDialog(acLenRemoved.ToString()); //Application.ShowAlertDialog("-3"); BlockReference acBlkRefReplacedIns = new BlockReference(new Point3d(0, 0, 0), acBlkTblRecReplacedClone.Id); //Application.ShowAlertDialog("-4"); Extents3d acExtReplaced = acBlkRefReplacedIns.GeometricExtents; //acVec3d = acBklTblRecReplaced.Origin.GetVectorTo(acExtReplaced.MinPoint); double acLenReplaced = Math.Abs(acExtReplaced.MinPoint.Y - acExtReplaced.MaxPoint.Y); //Application.ShowAlertDialog(acLenReplaced.ToString()); //Point3d acPtBot = new Point3d(acBlkRefRemoved.Position.X + acVec3d.X* acBlkRefRemoved.ScaleFactors.X, acBlkRefRemoved.Position.Y + acVec3d.Y* acBlkRefRemoved.ScaleFactors.Y, 0); Point3d acPtBot = acExtRemoved.MinPoint; Point3d acPtPos = new Point3d(acPtBot.X - acExtReplaced.MinPoint.X, acPtBot.Y - acExtReplaced.MinPoint.Y, 0); //Application.ShowAlertDialog("-5"); string[] acAttRefValCol = GetAttributeReferenceValueCollection(acTrans, acBlkRefRemoved); /* * for (int j = 0; j < acAttRefValCol.Length; j++) * { * Application.ShowAlertDialog(acAttRefValCol[j]); * Application.ShowAlertDialog(acAttRefIndexCol[j].ToString()); * } */ //Application.ShowAlertDialog("-6"); BlockReference acBlkRefReplaced = new BlockReference(acPtPos, acBlkTblRecReplacedClone.Id); //Application.ShowAlertDialog("-7"); if (!acBlkTblRecSpc.IsWriteEnabled) { acBlkTblRecSpc.UpgradeOpen(); } //Application.ShowAlertDialog("1"); acBlkTblRecSpc.AppendEntity(acBlkRefReplaced); acTrans.AddNewlyCreatedDBObject(acBlkRefReplaced, true); if (!acBlkRefRemoved.IsWriteEnabled) { acBlkRefRemoved.UpgradeOpen(); } acBlkRefRemoved.Erase(true); //Application.ShowAlertDialog("2"); int i = 0; foreach (ObjectId acObjId in acBlkTblRecReplacedClone) { //Application.ShowAlertDialog("Index \n"+i.ToString()); DBObject acDbObj = acTrans.GetObject(acObjId, OpenMode.ForRead); if (acDbObj is AttributeDefinition) { //Application.ShowAlertDialog("3"); AttributeDefinition acAttDef = (AttributeDefinition)acDbObj; if (!acAttDef.Constant) { using (AttributeReference acAttRef = new AttributeReference()) { if (!acBlkTblRecReplacedClone.IsWriteEnabled) { acBlkTblRecReplacedClone.UpgradeOpen(); } if (!acBlkRefReplaced.IsWriteEnabled) { acBlkRefReplaced.UpgradeOpen(); } //Application.ShowAlertDialog("4"); acAttRef.SetAttributeFromBlock(acAttDef, acBlkRefReplaced.BlockTransform); acAttRef.Position = acAttDef.Position.TransformBy(acBlkRefReplaced.BlockTransform); //Application.ShowAlertDialog("5"); if (i < acAttRefIndexCol.Length) { if (acAttRefIndexCol[i] < acAttRefIndexCol.Length) { acAttRef.TextString = acAttRefValCol[acAttRefIndexCol[i]]; } else { acAttRef.TextString = acAttDef.TextString; } } else { acAttRef.TextString = acAttDef.TextString; } Application.ShowAlertDialog(acAttRef.TextString); //Application.ShowAlertDialog("6"); acBlkRefReplaced.AttributeCollection.AppendAttribute(acAttRef); acTrans.AddNewlyCreatedDBObject(acAttRef, true); //Application.ShowAlertDialog("7"); i++; //Application.ShowAlertDialog("Index \n"+i.ToString()); } } } } //Application.ShowAlertDialog("8"); //double acScl = acLenRemoved / acLenReplaced * ((double)acBlkRefRemoved.ScaleFactors.Y); //acScl = acLenRemoved / acLenReplaced; //Application.ShowAlertDialog(acScl.ToString()); //double acSCL1 = 1; acBlkRefReplaced.TransformBy(Matrix3d.Scaling(acLenRemoved / acLenReplaced /*acBlkRefRemoved.ScaleFactors.X*/, acPtBot)); //tBlkRef.TransformBy(Matrix3d.Scaling(acScale, tBlkRef.Position)); //Application.ShowAlertDialog("Finish"); }
private bool SelectZuRaumIdEntities(bool ignoreFirstCancel) { _HKBlocks.Clear(); _VermPunkte.Clear(); _RaumPolygons.Clear(); //LayerOnAndThaw(new List<string> { _HoePrOptions.PolygonLayer, "X_FH_SYMB", "X_SPKT_SYMB", "X_GH_SYMB", "X_DR_SYMB", FEHLER_LINE_LAYER }); LayerOnAndThawRegex(new List <string> { "^" + _HoePrOptions.PolygonLayer + "$", "^X", "^" + FEHLER_LINE_LAYER + "$" }); var ed = _AcAp.Application.DocumentManager.MdiActiveDocument.Editor; SelectionFilter filter = new SelectionFilter(new TypedValue[] { new TypedValue((int)DxfCode.Operator, "<OR"), new TypedValue((int)DxfCode.Operator, "<AND"), new TypedValue((int)DxfCode.Start, "INSERT"), new TypedValue((int)DxfCode.BlockName, _HoePrOptions.HKBlockname), new TypedValue((int)DxfCode.Operator, "AND>"), // zusätzlicher höhenkotenblock new TypedValue((int)DxfCode.Operator, "<AND"), new TypedValue((int)DxfCode.Start, "INSERT"), new TypedValue((int)DxfCode.BlockName, HOEHENKOTEN_BLOCK_2), new TypedValue((int)DxfCode.Operator, "AND>"), new TypedValue((int)DxfCode.Operator, "<AND"), new TypedValue((int)DxfCode.Start, "INSERT"), new TypedValue((int)DxfCode.BlockName, "GEOINOVA"), new TypedValue((int)DxfCode.Operator, "<OR"), new TypedValue((int)DxfCode.LayerName, "X_FH_SYMB"), new TypedValue((int)DxfCode.LayerName, "X_SPKT_SYMB"), new TypedValue((int)DxfCode.LayerName, "X_GH_SYMB"), new TypedValue((int)DxfCode.LayerName, "X_DR_SYMB"), new TypedValue((int)DxfCode.Operator, "OR>"), new TypedValue((int)DxfCode.Operator, "AND>"), new TypedValue((int)DxfCode.Operator, "<AND"), new TypedValue((int)DxfCode.Start, "*POLYLINE"), new TypedValue((int)DxfCode.LayerName, _HoePrOptions.PolygonLayer), new TypedValue((int)DxfCode.Operator, "AND>"), new TypedValue((int)DxfCode.Operator, "OR>"), }); PromptSelectionResult res = ed.GetSelection(filter); if (res.Status == PromptStatus.Cancel && ignoreFirstCancel) { res = ed.GetSelection(filter); } if (res.Status != PromptStatus.OK) { return(false); } List <ObjectId> allEntities = null; #if BRX_APP SelectionSet ss = res.Value; #else using (SelectionSet ss = res.Value) #endif { allEntities = ss.GetObjectIds().ToList(); } if (allEntities == null || allEntities.Count == 0) { return(false); } bool someMarkedAsOk = false; using (Transaction myT = _TransMan.StartTransaction()) { foreach (var oid in allEntities) { Entity ent = _TransMan.GetObject(oid, OpenMode.ForRead) as Entity; if (ent == null) { continue; } BlockReference blockRef = ent as BlockReference; if (blockRef != null) { var bd = (BlockTableRecord)_TransMan.GetObject(blockRef.BlockTableRecord, OpenMode.ForRead); if ( (string.Compare(_HoePrOptions.HKBlockname, blockRef.Name, StringComparison.OrdinalIgnoreCase) == 0) || (string.Compare(HOEHENKOTEN_BLOCK_2, blockRef.Name, StringComparison.OrdinalIgnoreCase) == 0) ) { //HKBlocks if (!MarkedAsOk(oid)) { _HKBlocks.Add(oid); } else { Plan2Ext.Globs.Stern(blockRef.Position, 1.0, 32, color: 3, highLighted: false); someMarkedAsOk = true; } } else { _VermPunkte.Add(oid); } } else { //Polylines if (string.Compare(_HoePrOptions.PolygonLayer, ent.Layer, StringComparison.OrdinalIgnoreCase) == 0) { _RaumPolygons.Add(oid); } } } myT.Commit(); } if (someMarkedAsOk) { log.Warn("Einige Blöcke wurden ignoriert, da sie als OK markiert wurden."); } if (_HKBlocks.Count == 0) { log.Warn("Es wurden keine Höhenkoten gefunden!"); } else { log.InfoFormat(CultureInfo.CurrentCulture, "Anzahl der Höhenkoten: {0}", _HKBlocks.Count); } if (_VermPunkte.Count == 0) { log.Warn("Es wurden keine passenden Vermessungspunkte gefunden!"); } else { log.InfoFormat(CultureInfo.CurrentCulture, "Anzahl der Vermessungspunkte: {0}", _VermPunkte.Count); } if (_RaumPolygons.Count == 0) { string msg = "Es wurden keine Raumpolylinien gewählt!"; log.Warn(msg); _AcAp.Application.ShowAlertDialog(msg); } else { log.InfoFormat(CultureInfo.CurrentCulture, "Anzahl der Raumpolylinien: {0}", _RaumPolygons.Count); } if (_HKBlocks.Count > 0 && _VermPunkte.Count > 0 && _RaumPolygons.Count > 0) { return(true); } else { return(false); } }
public static void InterpolatePoint() { Document doc = acadApp.DocumentManager.MdiActiveDocument; Database db = doc.Database; Editor ed = doc.Editor; PromptEntityOptions peoXref = new PromptEntityOptions("\nSelect Grading Xref.") { AllowObjectOnLockedLayer = true, AllowNone = false }; PromptEntityOptions peoPolyLine1 = new PromptEntityOptions("\nSelect polyline 1."); PromptEntityOptions peoPolyLine2 = new PromptEntityOptions("\nSelect polyline 2."); PromptPointOptions ppo = new PromptPointOptions("\nSelect Point of intrest."); PromptPointResult ppr = ed.GetPoint(ppo); if (ppr.Status == PromptStatus.OK) { Transaction tr = doc.TransactionManager.StartTransaction(); using (tr) { try { Point3d pt = ppr.Value; BlockTable bt = (BlockTable)tr.GetObject(db.BlockTableId, OpenMode.ForRead); PromptEntityResult perXref = ed.GetEntity(peoXref); if (perXref.Status == PromptStatus.OK) { BlockReference xrefRef = (BlockReference)tr.GetObject(perXref.ObjectId, OpenMode.ForRead); if (xrefRef != null) { // If so, we check whether the block table record to which it refers is actually from an XRef ObjectId xrefId = xrefRef.BlockTableRecord; BlockTableRecord xrefBTR = (BlockTableRecord)tr.GetObject(xrefId, OpenMode.ForRead); if (xrefBTR != null) { if (xrefBTR.IsFromExternalReference) { // If so, then we prigrammatically select the object underneath the pick-point already used PromptNestedEntityOptions pneo = new PromptNestedEntityOptions("") { NonInteractivePickPoint = perXref.PickedPoint, UseNonInteractivePickPoint = true }; PromptNestedEntityResult pner = ed.GetNestedEntity(pneo); if (pner.Status == PromptStatus.OK) { try { ObjectId selId = pner.ObjectId; // Let's look at this programmatically-selected object, to see what it is DBObject obj = tr.GetObject(selId, OpenMode.ForRead); // If it's a polyline vertex, we need to go one level up to the polyline itself if (obj is PolylineVertex3d || obj is Vertex2d) { selId = obj.OwnerId; } // We don't want to do anything at all for textual stuff, let's also make sure we are // dealing with an entity (should always be the case) if (obj is MText || obj is DBText || !(obj is Entity)) { return; } // Now let's get the name of the layer, to use later Entity ent = (Entity)obj; LayerTableRecord ltr = (LayerTableRecord)tr.GetObject(ent.LayerId, OpenMode.ForRead); ed.WriteMessage("\nObject Selected is {0} on layer {1} in xref {2}.", selId.GetType(), ltr.Name, xrefBTR.Name); } catch { // A number of innocuous things could go wrong // so let's not worry about the details // In the worst case we are simply not trying // to replace the entity, so OFFSET will just // reject the selected Xref } } } } } } } catch { ed.WriteMessage("\nFailed in xrefSelect"); } //BlockTableRecord ms = (BlockTableRecord)tr.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite); } tr.Commit(); } else { ed.WriteMessage("Failed to find point of intrest."); } }
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("\nAttribut 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(); } } } } catch (Exception ex) { _AcAp.Application.ShowAlertDialog(ex.Message); } }
updateExistCallouts(SelectionSet SS) { ResultBuffer RB = null; BlockReference BR = null; CogoPoint cogoPnt = null; string strAppName = string.Empty; string strElev = string.Empty; try { using (Transaction tr = BaseObjs.startTransactionDb()) { ObjectId[] objIDs = SS.GetObjectIds(); foreach (ObjectId objID in objIDs) { cogoPnt = (CogoPoint)tr.GetObject(objID, OpenMode.ForRead); strElev = cogoPnt.Location.Z.ToString("#,###.00"); RB = cogoPnt.GetXDataForApplication("lblPnts"); if (RB != null) { strAppName = "lblPnts"; } else { RB = cogoPnt.GetXDataForApplication("lblPntsPT"); strAppName = "lblPntsPT"; } if (RB != null) { try { foreach (TypedValue TV in RB) { if (TV.TypeCode.ToString() == "1005") { try { string strHandle = TV.Value.ToString(); ObjectId brID = Misc.getObjectIdFromHandle(strHandle); Autodesk.AutoCAD.DatabaseServices.DBObject dbObj = tr.GetObject(brID, OpenMode.ForRead); BR = (BlockReference)dbObj; if (BR != null) { AttributeCollection AC = BR.AttributeCollection; foreach (ObjectId arID in AC) { AttributeReference AR = (AttributeReference)tr.GetObject(arID, OpenMode.ForWrite); string strAttVal = AR.TextString.ToString(); if (strAttVal != string.Empty) { string[] strFields = Txt.splitFields(strAttVal, ' '); if (strFields[0] != string.Empty) { string strVal = strFields[0]; if (strVal.StartsWith("(")) { string strChr = strVal[1].ToString(); int num; Boolean isNum = strChr.isInteger(out num); if (isNum == true) { strAttVal = string.Format("({0} {1}", strElev, strFields[1]); AR.TextString = strAttVal; } } } } } } } catch (System.Exception ex) { BaseObjs.writeDebug(ex.Message + " Mod.cs: line: 1091"); } } } } catch (System.Exception ex) { BaseObjs.writeDebug(ex.Message + " Mod.cs: line: 1098"); } } } tr.Commit(); } //end using tr } catch (System.Exception ex) { BaseObjs.writeDebug(ex.Message + " Mod.cs: line: 1108"); } } //end updateDesignCallout
static public void Plan2HoePrSelHkBlockAndAtt() { try { if (!OpenHoePrPalette()) { return; } var opts = Globs.TheHoePrOptions; Document doc = Application.DocumentManager.MdiActiveDocument; using (DocumentLock m_doclock = doc.LockDocument()) { DocumentCollection dm = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager; if (doc == null) { return; } Editor ed = doc.Editor; #if NEWSETFOCUS doc.Window.Focus(); #else Autodesk.AutoCAD.Internal.Utils.SetFocusToDwgView(); // previous 2014 AutoCAD - Versions #endif PromptNestedEntityResult per = ed.GetNestedEntity("\nHöhenkotenblock wählen: "); if (per.Status == PromptStatus.OK) { using (var tr = doc.TransactionManager.StartTransaction()) { DBObject obj = tr.GetObject(per.ObjectId, OpenMode.ForRead); BlockReference br = obj as BlockReference; if (br == null) { br = Plan2Ext.Globs.GetBlockFromItsSubentity(tr, per); if (br == null) { return; } } opts.SetHKBlockname(br.Name); tr.Commit(); } per = ed.GetNestedEntity("\nHöhen-Attribut wählen: "); if (per.Status != PromptStatus.OK) { return; } using (var tr = doc.TransactionManager.StartTransaction()) { DBObject obj = tr.GetObject(per.ObjectId, OpenMode.ForRead); AttributeReference ar = obj as AttributeReference; if (ar == null) { return; } opts.SetHoehenAtt(ar.Tag); tr.Commit(); } } } } catch (System.Exception ex) { Application.ShowAlertDialog(string.Format(CultureInfo.CurrentCulture, "Fehler in Plan2HoePrSelHkBlockAndAtt aufgetreten! {0}", ex.Message)); } }
public static bool IsScaleEquals1([NotNull] this BlockReference blref) { return(blref.ScaleFactors.IsEqualTo(scale1, tolerance)); }
public ApertureBase(BlockReference blRef, string blName) : base(blRef, blName) { }