61
Selection sets / Re: Small Sample for selecting lines and reading coordinates
« on: October 12, 2012, 10:45:32 PM »
Glad I could help
Happy coding :)
Happy coding :)
This section allows you to view all posts made by this member. Note that you can only see posts made in areas you currently have access to.
//using System.IO;
private SelectionSet LineSelection(Editor ed)
{
// select lines on screen using filter
PromptSelectionOptions pso = new PromptSelectionOptions();
pso.MessageForRemoval = "\n Select lines only: ";
pso.MessageForAdding = "\nSelect lines: ";
pso.RejectObjectsOnLockedLayers = false;
TypedValue[] dxfcodes = new TypedValue[1] { new TypedValue(0, "LINE") };
SelectionFilter filter = new SelectionFilter(dxfcodes);
PromptSelectionResult psr = ed.GetSelection(pso, filter);
if (psr.Status != PromptStatus.OK)
return null;
return psr.Value;
}
[CommandMethod("LinesToFile", "ltf", CommandFlags.Modal | CommandFlags.UsePickSet)]
public void testLineSelection()
{
bool isOk = true;
Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
Database db = doc.Database;
Editor ed = doc.Editor;
List<Point3d[]> linedata = new List<Point3d[]>();
string txtname = (string)Autodesk.AutoCAD.ApplicationServices.Application.GetSystemVariable("dwgprefix");
string dwgname = (string)Autodesk.AutoCAD.ApplicationServices.Application.GetSystemVariable("dwgname");
dwgname = dwgname.Substring(0, dwgname.Length - 4) + ".csv";// <-- change on .txt if it's need
txtname = Path.Combine(txtname, dwgname);
try
{
using (Transaction tr = db.TransactionManager.StartTransaction())
{
SelectionSet sset = LineSelection(ed);
foreach (SelectedObject sobj in sset)
{
Line ln = tr.GetObject(sobj.ObjectId, OpenMode.ForRead) as Line;
if (ln != null)
{
Point3d p1 = ln.StartPoint;
Point3d p2 = ln.EndPoint;
Point3d[] pts = new Point3d[2];
pts[0] = p1;
pts[1] = p2;
linedata.Add(pts);
}
}
using (StreamWriter sw = new StreamWriter(txtname))
{
foreach (Point3d[] lnItem in linedata)
{
string txtline = string.Format("{0:f6}\t{1:f6}\t{2:f6}\t{3:f6}\t{4:f6}\t{5:f6}", lnItem[0].X, lnItem[0].Y, lnItem[0].Z, lnItem[1].X, lnItem[1].Y, lnItem[1].Z);
sw.WriteLine(txtline);
}
sw.Flush();
sw.Close();
}
tr.Commit();
}
}
catch (System.Exception ex)
{
isOk = false;
ed.WriteMessage(ex.Message + "\n" + ex.StackTrace);
}
finally
{
if (isOk)
{
ed.WriteMessage("\nProgram ended up with success\nSee record in:\n{0}", txtname);
}
else
{
ed.WriteMessage("\nProgram failed");
}
}
} // using System.Linq;
#region "Selection block by attribute tag"
// get the real block name. //
public static string EffectiveName(Transaction tr, BlockReference bref)
{
BlockTableRecord btr = null;
if ((bref.IsDynamicBlock)
| (bref.Name.StartsWith("*U", StringComparison.InvariantCultureIgnoreCase)))
{
btr = tr.GetObject(bref.DynamicBlockTableRecord, OpenMode.ForRead) as BlockTableRecord;
}
else
{
btr = tr.GetObject(bref.BlockTableRecord, OpenMode.ForRead) as BlockTableRecord;
}
return btr.Name;
}
[CommandMethod("SelectByAttributeValue", "byval", CommandFlags.Modal)]
public void GetSelectionByAtt()
{
Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
Database db = doc.Database;
Editor ed = doc.Editor;
string m_str = string.Empty;
PromptStringOptions psto = new PromptStringOptions("\nEnter the tag to find (case-nonsensitive): ");
// to disable the blank space in user input
psto.AllowSpaces = false;
PromptResult pstr = ed.GetString(psto);
if (pstr.Status != PromptStatus.OK) return;
m_str = pstr.StringResult.ToUpper();
List<object[]> blockdata = new List<object[]>();
PromptSelectionOptions pso = new PromptSelectionOptions();
pso.MessageForRemoval = "\nFailed to select a blocks!";
pso.MessageForAdding = "\nPlease select a blocks: ";
// build filter to select all attributed blocks
SelectionFilter filter =
new SelectionFilter(
new TypedValue[] { new TypedValue(0, "insert"),
new TypedValue(66, 1) }
);
// perform block selection
PromptSelectionResult sres = ed.GetSelection(pso, filter);// might be SelectAll instead
if (sres.Status != PromptStatus.OK) return;
try
{
SelectionSet sset = sres.Value;
using (Transaction tr = db.TransactionManager.StartTransaction())
{
foreach (SelectedObject sobj in sset)
{
Entity ent = tr.GetObject(sobj.ObjectId, OpenMode.ForRead, false) as Entity;
BlockReference bref = ent as BlockReference;
AttributeCollection attribs = bref.AttributeCollection;
foreach (ObjectId attid in attribs)
{
AttributeReference attref = tr.GetObject(attid, OpenMode.ForRead, false) as AttributeReference;
if (attref.Tag == m_str)
{
object[] datum = new object[] { EffectiveName(tr, bref), attref.Tag, attref.TextString };
// add block info to the list
blockdata.Add(datum);
}
}
}
// display total result
//foreach (object[] item in blockdata)
// ed.WriteMessage("\n{0}\t{1}\t{2}", item[0], item[1],item[2]);
var grps = from blk in blockdata
group blk by new
{
Name =blk.ElementAt(0), Tag =blk.ElementAt(1),AttValue=blk.ElementAt(2)
}
into grp
select new
{
BlockName=grp.First().ElementAt(0),
Tag=grp.First().ElementAt(1),
AttValue=grp.First().ElementAt(2),
Count= grp.Count()
};
// display subtotals
foreach (var grp in grps)
{
ed.WriteMessage("\n[ Block Name: {0} |Tag: {1} | Value: {2} | Count: {3} ]\n",
grp.BlockName,
grp.Tag,
grp.AttValue,
grp.Count
);
}
tr.Commit();
}
}
catch (System.Exception ex)
{
Autodesk.AutoCAD.ApplicationServices.Application.ShowAlertDialog(ex.Message + "\n" + ex.StackTrace);
}
finally
{
}
}
#endregion // using System.Linq;
#region "Selection block by attribute tag"
// get the real block name. //
public static string EffectiveName(Transaction tr, BlockReference bref)
{
BlockTableRecord btr = null;
if ((bref.IsDynamicBlock)
| (bref.Name.StartsWith("*U", StringComparison.InvariantCultureIgnoreCase)))
{
btr = tr.GetObject(bref.DynamicBlockTableRecord, OpenMode.ForRead) as BlockTableRecord;
}
else
{
btr = tr.GetObject(bref.BlockTableRecord, OpenMode.ForRead) as BlockTableRecord;
}
return btr.Name;
}
[CommandMethod("SelectByAttribute","byatt", CommandFlags.Modal)]
public void GetSelectionByAtt()
{
Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
Database db = doc.Database;
Editor ed = doc.Editor;
string m_str = string.Empty;
PromptStringOptions psto= new PromptStringOptions("\nEnter the tag to find (case-nonsensitive): ");
// to disable the blank space in user input
psto.AllowSpaces=false;
PromptResult pstr= ed.GetString(psto);
if (pstr.Status!= PromptStatus.OK) return;
m_str= pstr.StringResult.ToUpper();
List<object[]> blockdata = new List<object[]>();
PromptSelectionOptions pso = new PromptSelectionOptions();
pso.MessageForRemoval = "\nFailed to select a blocks!";
pso.MessageForAdding = "\nPlease select a blocks: ";
// build filter to select all attributed blocks
SelectionFilter filter =
new SelectionFilter(
new TypedValue[] { new TypedValue(0, "insert"),
new TypedValue(66, 1) }
);
// perform block selection
PromptSelectionResult sres = ed.GetSelection(pso, filter);// might be SelectAll instead
if (sres.Status != PromptStatus.OK) return;
try
{
SelectionSet sset = sres.Value;
using (Transaction tr = db.TransactionManager.StartTransaction())
{
foreach (SelectedObject sobj in sset)
{
Entity ent = tr.GetObject(sobj.ObjectId,OpenMode.ForRead, false) as Entity;
BlockReference bref = ent as BlockReference;
AttributeCollection attribs = bref.AttributeCollection;
foreach ( ObjectId attid in attribs)
{
AttributeReference attref= tr.GetObject(attid, OpenMode.ForRead,false) as AttributeReference;
if (attref.Tag==m_str)
{
object[] datum = new object[]{EffectiveName(tr, bref), attref.Tag,attref.TextString};
// add block info to the list
blockdata.Add(datum);
}
}
}
// display total result
//foreach (object[] item in blockdata)
// ed.WriteMessage("\n{0}\t{1}\t{2}", item[0], item[1],item[2]);
// group items by name and attribute tag
var grps = from s in blockdata
group s by s[0] into grp
select new
{
BlockName = grp.Key,
Tag = grp.First().ElementAt(1),
AttValue = grp.First().ElementAt(2),
Count= grp.Count()
};
// display subtotals
foreach (var grp in grps)
{
ed.WriteMessage("\n[ Block Name: {0} |Tag: {1} | Value: {2} | Count: {3} ]\n",
grp.BlockName,
grp.Tag,
grp.AttValue,
grp.Count
);
}
tr.Commit();
}
}
catch (System.Exception ex)
{
Autodesk.AutoCAD.ApplicationServices.Application.ShowAlertDialog(ex.Message + "\n" + ex.StackTrace);
}
finally
{
}
}
#endregion #region "Add prefix and suffix to the text or mtext multiply"
[CommandMethod("PSUF")]
public static void UpdateMultipleTexts()
{
Database db = HostApplicationServices.WorkingDatabase;
Editor ed = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor;
Transaction tr = db.TransactionManager.StartTransaction();
string pref = GetstringDflt(ed, "Enter a Prefix: ", "A-");
string suff = GetstringDflt(ed, "Enter a Suffix: ", "-B");
using (tr)
{
try
{
Entity ent;
PromptEntityResult per;
ObjectId id;
do
{
PromptEntityOptions peo = new PromptEntityOptions("\nSelect Text >>");
peo.SetRejectMessage("\nMust be selected a Text or Mtext only!");
peo.AddAllowedClass(typeof(DBText),false);
peo.AddAllowedClass(typeof(MText),false);
per = ed.GetEntity(peo);
if (per.Status != PromptStatus.OK)
{
break;
}
id = per.ObjectId;
ent = id.GetObject(OpenMode.ForRead) as Entity;
ed.WriteMessage("\nObject Selected:\t{0}", ent.GetRXClass().DxfName);
if ((!(ent is DBText)) && (!(ent is MText)))
{
ed.WriteMessage("\nNot a Text or MText");
continue;
}
DBText txt= ent as DBText;
if (txt!= null)
{
txt.UpgradeOpen();
string text = txt.TextString;
txt.TextString = pref + text+ suff;
txt.DowngradeOpen();
}
MText mtxt = ent as MText;
if (mtxt != null)
{
mtxt.UpgradeOpen();
string text = mtxt.Contents;
mtxt.Contents = pref + text + suff;
mtxt.DowngradeOpen();
}
db.TransactionManager.QueueForGraphicsFlush();
}
while (per.Status == PromptStatus.OK);
tr.Commit();
}
catch (Autodesk.AutoCAD.Runtime.Exception ex)
{
ed.WriteMessage("\n" + ex.StackTrace + "\n" + ex.Message);
}
}
}
#region "Helpers"
public static string GetstringDflt(Editor ed, string msg, string dflt)
{
string answer = string.Empty;
PromptStringOptions pso = new PromptStringOptions("\n" + msg);
if (dflt != string.Empty)
{
pso.DefaultValue = dflt;
}
pso.AllowSpaces = true;
PromptResult pr = ed.GetString(pso);
if (pr.Status == PromptStatus.OK)
{
answer = pr.StringResult;
}
return answer;
}
#endregion
#endregion // based on C++ code by Virupaksha Aithal from this page:
//http://adndevblog.typepad.com/autocad/2012/08/create-3d-solid-by-extruding-a-polyline.html
[CommandMethod("extt")]
public void CreateExtrude()
{
Autodesk.AutoCAD.ApplicationServices.Application.SetSystemVariable("delobj", 1);
Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
Database db = doc.Database;
Editor ed = doc.Editor;
PromptSelectionOptions pso = new PromptSelectionOptions();
pso.SingleOnly = true;
pso.SinglePickInSpace = true;
pso.MessageForAdding = "\nPlease select a polyline: ";
pso.MessageForRemoval = "Failed to select a polyline";
pso.PrepareOptionalDetails = true;
SelectionFilter filter =
new SelectionFilter(
new TypedValue[] { new TypedValue(0, "lwpolyline"),new TypedValue(70, 1) });
//select the polyline
PromptSelectionResult sres = ed.GetSelection(pso,filter);
if (sres.Status != PromptStatus.OK) return;
using (Transaction tr = doc.TransactionManager.StartTransaction())
{
//get the boundary curves of the polyline
ObjectId idPoly = sres.Value[0].ObjectId;
Entity pEntity = tr.GetObject(idPoly, OpenMode.ForRead) as Entity;
Polyline pPoly = pEntity as Polyline; ;
if (pPoly == null) return;
DBObjectCollection lines = new DBObjectCollection();
pPoly.Explode(lines);
// Create a region from the set of lines.
DBObjectCollection regions = new DBObjectCollection();
regions = Region.CreateFromCurves(lines);
if (regions.Count == 0)
{
ed.WriteMessage("\nFailed to create region\n");
return;
}
Region pRegion = (Region)regions[0];
// Extrude the region to create a solid.
Solid3d pSolid = new Solid3d();
pSolid.RecordHistory = true;
pSolid.Extrude(pRegion, 10.0, 0.0);
ObjectId savedExtrusionId = ObjectId.Null;
ObjectId modelId;
modelId = SymbolUtilityServices.GetBlockModelSpaceId(db);
BlockTableRecord btr = tr.GetObject(modelId, OpenMode.ForWrite) as BlockTableRecord;
savedExtrusionId = btr.AppendEntity(pSolid);
tr.AddNewlyCreatedDBObject(pSolid,true);
if (!pPoly.IsWriteEnabled) pPoly.UpgradeOpen();
pPoly.Erase();
tr.Commit();
}
} public class BlockUtils
{
public ObjectIdCollection ids = new ObjectIdCollection();
public void curdb_ObjectAppended(object sender, ObjectEventArgs e)
{
//add the object id
ids.Add(e.DBObject.ObjectId);
}
[CommandMethod("reins")]
public void ReinsertBlock()
{
Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
Database db = doc.Database;
Editor ed = doc.Editor;
try
{
using (Transaction tr = db.TransactionManager.StartTransaction())
{
BlockTableRecord m_ctab = (BlockTableRecord)tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite);
BlockTable bt = (BlockTable)tr.GetObject(db.BlockTableId, OpenMode.ForRead, false, true);
PromptStringOptions psto = new PromptStringOptions("\nEnter the new block name: ");
psto.AllowSpaces = true;
PromptResult stres;
stres = ed.GetString(psto);
if (stres.Status != PromptStatus.OK)
return;
try
{
// Validate the provided block name
SymbolUtilityServices.ValidateSymbolName(stres.StringResult, false);
}
catch
{
ed.WriteMessage("\n\"{0}\"n is an invalid name, try another one.", stres.StringResult);
return;
}
string blockname = stres.StringResult;
if (bt.Has(blockname))
{
Autodesk.AutoCAD.Runtime.ErrorStatus es = ErrorStatus.DuplicateRecordName;
ed.WriteMessage("\n{0}\n{1}\n", es.ToString(), "Block already exist, try another name");
return;
}
PromptEntityOptions peo = new PromptEntityOptions("\nSelect block: ");
peo.SetRejectMessage("\nYou have to select BlockReference only!");
peo.AllowNone = false;
peo.AllowObjectOnLockedLayer = true;
peo.AddAllowedClass(typeof(BlockReference), false);
PromptEntityResult per = ed.GetEntity(peo);
if (per.Status != PromptStatus.OK) return;
ObjectId objId = per.ObjectId;
if (!objId.ObjectClass.IsDerivedFrom(RXClass.GetClass(typeof(BlockReference))))
{
ed.WriteMessage( "\nYou didn't select a BlockReference, please try again...\n");
return;
}
DBObject blkobj = (DBObject)tr.GetObject(objId, OpenMode.ForRead, false);
BlockReference bref = blkobj as BlockReference;
if (bref == null) return;
BlockTableRecord btrec = null;
btrec = tr.GetObject(bref.BlockTableRecord, OpenMode.ForRead) as BlockTableRecord;
DBObjectCollection explobjs = new DBObjectCollection();
ids.Clear();
// Add event
db.ObjectAppended += new ObjectEventHandler(curdb_ObjectAppended);
bref.ExplodeToOwnerSpace();
// Remove event
db.ObjectAppended -= new ObjectEventHandler(curdb_ObjectAppended);
ObjectIdCollection newids = new ObjectIdCollection();
// Create BlockTableRecord
Matrix3d ucs2wcs = ed.CurrentUserCoordinateSystem;
Matrix3d wcs2ucs = ucs2wcs.Inverse();
// Add BlockTableRecord to Database
BlockTableRecord newbtr = new BlockTableRecord();
newbtr.Origin = btrec.Origin;
newbtr.Name = blockname;
newbtr.Units = bref.BlockUnit;
newbtr.Annotative = btrec.Annotative;
bt.UpgradeOpen();
ObjectId newblkid = bt.Add(newbtr);
tr.AddNewlyCreatedDBObject(newbtr, true);
// Pick displacement point, use pan and zoom to find an empty area for copy of the block
PromptPointOptions ppo = new PromptPointOptions("\nPick a displacement point: ");
ppo.BasePoint = bref.Position;
ppo.UseBasePoint = true;
ppo.UseDashedLine = true;
PromptPointResult pres = ed.GetPoint(ppo);
if (pres.Status != PromptStatus.OK) return;
Point3d movept = pres.Value;
//create vector for displacement
Vector3d vectrans = new Vector3d();
vectrans = movept.GetAsVector().Subtract(bref.Position.GetAsVector());
Matrix3d mat = Matrix3d.Displacement(vectrans);
foreach (ObjectId id in ids)
{
Entity ent = tr.GetObject(id, OpenMode.ForWrite) as Entity;
ent.TransformBy(mat);
tr.TransactionManager.QueueForGraphicsFlush();
}
PromptEntityOptions pxo = new PromptEntityOptions("\nSelect entity to remove from block: ");
pxo.AllowNone = false;
pxo.AllowObjectOnLockedLayer = true;
PromptEntityResult pxr = ed.GetEntity(pxo);
if (pxr.Status != PromptStatus.OK) return;
ObjectId exId = pxr.ObjectId;
ids.Remove(exId);
Entity exnt = (Entity)tr.GetObject(exId, OpenMode.ForWrite);
exnt.Erase();
exnt.Dispose();
newbtr.Origin = movept;
newbtr.AssumeOwnershipOf(ids);
tr.TransactionManager.QueueForGraphicsFlush();
if (btrec.HasAttributeDefinitions)
{
// Transform objects now in block from WCS to UCS
// and collect attributes
System.Collections.Generic.List<AttributeDefinition> attdefs =
new System.Collections.Generic.List<AttributeDefinition>();
foreach (ObjectId oid in newbtr)
{
Entity ent = (Entity)tr.GetObject(oid, OpenMode.ForWrite);
ent.TransformBy(wcs2ucs);
AttributeDefinition ad = ent as AttributeDefinition;
if (ad != null && !ad.Constant) attdefs.Add(ad);
}
// Create BlockReference
using (BlockReference newbref = new BlockReference(Point3d.Origin, bt[blockname]))
{
newbref.TransformBy(ucs2wcs * Matrix3d.Displacement(movept.GetAsVector()));
ObjectContextCollection occ = db.ObjectContextManager.GetContextCollection("ACDB_ANNOTATIONSCALES");
if (occ.HasContext(db.Cannoscale.Name))
Autodesk.AutoCAD.Internal.ObjectContexts.AddContext(
newbref, occ.GetContext(db.Cannoscale.Name));
// Add BlockReference to current space
m_ctab.AppendEntity(newbref);
tr.AddNewlyCreatedDBObject(newbref, true);
// Add attributes to BlockReference, if any
foreach (AttributeDefinition ad in attdefs)
using (AttributeReference attref = new AttributeReference())
{
attref.SetAttributeFromBlock(ad, newbref.BlockTransform);
if (ad.IsMTextAttributeDefinition)
attref.UpdateMTextAttribute();
attref.AdjustAlignment(db);
newbref.AttributeCollection.AppendAttribute(attref);
tr.AddNewlyCreatedDBObject(attref, true);
}
}
}
doc.TransactionManager.FlushGraphics();
tr.TransactionManager.QueueForGraphicsFlush();
tr.Commit();
}
}
catch (Autodesk.AutoCAD.Runtime.Exception ex)
{
Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor.WriteMessage
(ex.Message + "\n" + ex.StackTrace);
}
finally
{
}
}
} [CommandMethod("dellt")]
public void DelLayout()
{
// put desired layout name:
string laytName = "D-Size Layout";// may have any layout name belongs to current drawing
LayoutManager laytmgr = LayoutManager.Current;
try
{
laytmgr.DeleteLayout(laytName);
Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor.Regen();
}
catch (Autodesk.AutoCAD.Runtime.Exception ex)
{
Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor.WriteMessage
(ex.Message + "\n" + ex.StackTrace);
}
} // move attributes to the new positions
// run command ATTSYNC manually to display result
// right after the command is finished
[CommandMethod("DAR")]
static public void MoveAttributeReferences()
{
Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
Database db = doc.Database;
Editor ed = doc.Editor;
// Select a block reference
PromptEntityOptions peo = new PromptEntityOptions("\nSelect a block reference:");
peo.SetRejectMessage("\nMust be block reference...");
peo.AddAllowedClass(typeof(BlockReference), true);
PromptEntityResult per = ed.GetEntity(peo);
if (per.Status != PromptStatus.OK)
return;
// Select attribute reference
PromptNestedEntityOptions pno = new PromptNestedEntityOptions("\nSelect an attribute ");
PromptNestedEntityResult nres = ed.GetNestedEntity(pno);
if (nres.Status != PromptStatus.OK)
{
ed.WriteMessage("\nAttribute nentsel failed");
return;
}
Point3d spickPt = nres.PickedPoint;
ed.WriteMessage("\nPicked point is {0}", spickPt);
ObjectId sselId = nres.ObjectId;
List<ObjectId> enIds = new List<ObjectId>(nres.GetContainers());
// Reverse the "containers" list
// Now append the selected entity
enIds.Add(sselId);
enIds.Reverse();
// Retrieve the sub-entity path for this entity
SubentityId subent = new SubentityId(SubentityType.Null, 0);
FullSubentityPath path = new FullSubentityPath(enIds.ToArray(), subent);
// Open the outermost container, relying on the open
// transaction...
Transaction tr = db.TransactionManager.StartTransaction();
using (tr)
{
// This time we just open the block reference
BlockReference br = (BlockReference)tr.GetObject(per.ObjectId, OpenMode.ForRead);
// If the block reference has attribute references...
if (br.AttributeCollection.Count == 0) return;
BlockTableRecord owner;
owner = (BlockTableRecord)tr.GetObject(br.BlockTableRecord, OpenMode.ForRead);
if (br.IsDynamicBlock)
{
owner = (BlockTableRecord)tr.GetObject(br.DynamicBlockTableRecord, OpenMode.ForRead);
}
owner.UpgradeOpen();
Entity attent = tr.GetObject(enIds[0], OpenMode.ForRead, false) as Entity;
AttributeReference attref = attent as AttributeReference;
Point3d pt = attref.Position;
PromptPointOptions ppo = new PromptPointOptions("\nSpecify the new attribute position: ");
ppo.BasePoint=pt;
ppo.UseBasePoint = true;
ppo.UseDashedLine = true;
PromptPointResult pres = ed.GetPoint(ppo);
if (pres.Status != PromptStatus.OK) return;
Point3d dp = pres.Value;
Vector3d vec = pt.GetVectorTo(dp);
Matrix3d mat = Matrix3d.Displacement(vec);
foreach (ObjectId id in owner)
{
if (id.ObjectClass.IsDerivedFrom(RXClass.GetClass(typeof(AttributeDefinition))))
{
AttributeDefinition attdef = (AttributeDefinition)tr.GetObject(id, OpenMode.ForRead);
attdef.UpgradeOpen();
// move attribute
attdef.TransformBy(mat);
attdef.DowngradeOpen();
//attdef.Erase();// debug only, commented
}
}
owner.DowngradeOpen();
tr.Commit();
}
} [CommandMethod("copyseg")]
public void copySegment()
{
Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
Editor ed = doc.Editor;
Database db = doc.Database;
PromptEntityOptions peo = new PromptEntityOptions("\nSelect the segment to copy: ");
peo.SetRejectMessage("\nYou have to select polyline only!");
peo.AllowNone = false;
peo.AllowObjectOnLockedLayer = false;
peo.AddAllowedClass(typeof(Polyline), true);
PromptEntityResult per = ed.GetEntity(peo);
if (per.Status == PromptStatus.OK)
{
ObjectId objId = per.ObjectId;
try
{
using (Transaction tr = db.TransactionManager.StartTransaction())
{
Polyline pline = tr.GetObject(objId, OpenMode.ForRead, false) as Polyline;
if (pline != null)
{
BlockTableRecord btr = tr.GetObject(db.CurrentSpaceId,OpenMode.ForWrite, false) as BlockTableRecord;
Point3d pickPt = pline.GetClosestPointTo((Point3d)per.PickedPoint, false);
double param = pline.GetParameterAtPoint(pickPt);
int index = (int)param;
double swid= pline.GetStartWidthAt(index);
double ewid = pline.GetEndWidthAt(index);
SegmentType stype= pline.GetSegmentType(index);
if (stype == SegmentType.Line)
{
LineSegment2d lineseg= pline.GetLineSegment2dAt(index);
Polyline spoly = new Polyline();
Point2d sp = lineseg.StartPoint;
Point2d ep = lineseg.EndPoint;
spoly.AddVertexAt(0, sp, 0, swid, ewid);
spoly.AddVertexAt(1, ep,0,swid,ewid);
spoly.ColorIndex = 1;
btr.AppendEntity(spoly);
tr.AddNewlyCreatedDBObject(spoly, true);
}
if (stype == SegmentType.Arc)
{
CircularArc2d arcseg = pline.GetArcSegment2dAt(index);
Polyline spoly = new Polyline();
Point2d sp = arcseg.StartPoint;
Point2d ep = arcseg.EndPoint;
double boo = pline.GetBulgeAt(index);
spoly.AddVertexAt(0, sp, boo, swid, ewid);
spoly.AddVertexAt(1, ep, boo, swid, ewid);
spoly.ColorIndex = 2;
btr.AppendEntity(spoly);
tr.AddNewlyCreatedDBObject(spoly, true);
}
}
tr.Commit();
}
}
catch (System.Exception ex)
{
ed.WriteMessage("\nError: {0}\nTrace: {1}" , ex.Message , ex.StackTrace);
}
}
} <CommandMethod("copyseg")> _
Public Sub copySegment()
Dim doc As Document = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument
Dim ed As Editor = doc.Editor
Dim db As Database = doc.Database
Dim peo As New PromptEntityOptions(vbLf & "Select the segment to copy: ")
peo.SetRejectMessage(vbLf & "You have to select polyline only!")
peo.AllowNone = False
peo.AllowObjectOnLockedLayer = False
peo.AddAllowedClass(GetType(Polyline), True)
Dim per As PromptEntityResult = ed.GetEntity(peo)
If per.Status = PromptStatus.OK Then
Dim objId As ObjectId = per.ObjectId
Try
Using tr As Transaction = db.TransactionManager.StartTransaction()
Dim pline As Polyline = TryCast(tr.GetObject(objId, OpenMode.ForRead, False), Polyline)
If pline IsNot Nothing Then
Dim btr As BlockTableRecord = TryCast(tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite, False), BlockTableRecord)
Dim pickPt As Point3d = pline.GetClosestPointTo(per.PickedPoint, False)
Dim param As Double = pline.GetParameterAtPoint(pickPt)
Dim index As Integer = CInt(Math.Truncate(param))
Dim swid As Double = pline.GetStartWidthAt(index)
Dim ewid As Double = pline.GetEndWidthAt(index)
Dim stype As SegmentType = pline.GetSegmentType(index)
If stype = SegmentType.Line Then
Dim lineseg As LineSegment2d = pline.GetLineSegment2dAt(index)
Dim spoly As New Polyline()
Dim sp As Point2d = lineseg.StartPoint
Dim ep As Point2d = lineseg.EndPoint
spoly.AddVertexAt(0, sp, 0, swid, ewid)
spoly.AddVertexAt(1, ep, 0, swid, ewid)
spoly.ColorIndex = 1
btr.AppendEntity(spoly)
tr.AddNewlyCreatedDBObject(spoly, True)
End If
If stype = SegmentType.Arc Then
Dim arcseg As CircularArc2d = pline.GetArcSegment2dAt(index)
Dim spoly As New Polyline()
Dim sp As Point2d = arcseg.StartPoint
Dim ep As Point2d = arcseg.EndPoint
Dim boo As Double = pline.GetBulgeAt(index)
spoly.AddVertexAt(0, sp, boo, swid, ewid)
spoly.AddVertexAt(1, ep, boo, swid, ewid)
spoly.ColorIndex = 2
btr.AppendEntity(spoly)
tr.AddNewlyCreatedDBObject(spoly, True)
End If
End If
tr.Commit()
End Using
Catch ex As System.Exception
ed.WriteMessage(vbLf & "Error: {0}" & vbLf & "Trace: {1}", ex.Message, ex.StackTrace)
End Try
End If
End Sub
// tested on AutoCAD 2010
[CommandMethod("ResetDimValues", "rdv", CommandFlags.Modal | CommandFlags.Redraw)]
public void ResetDims()
{
Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
Editor ed = doc.Editor;
Database db = doc.Database;
TypedValue[] values = new TypedValue[] { new TypedValue(0, "DIMENSION") };
SelectionFilter filter = new SelectionFilter(values);
PromptSelectionOptions opts = new PromptSelectionOptions();
opts.MessageForRemoval = "\nMust be a type of Dimension!";
opts.MessageForAdding = "\nSelect dimensions to reset : ";
opts.PrepareOptionalDetails = false;
opts.SingleOnly = false;
opts.SinglePickInSpace = false;
opts.AllowDuplicates = true;
PromptSelectionResult result = ed.GetSelection(opts, filter);
if (result.Status != PromptStatus.OK) return;
try
{
using (Transaction tr = db.TransactionManager.StartTransaction())
{
SelectionSet sset = result.Value;
foreach (SelectedObject selobj in sset)
{
DBObject obj = tr.GetObject(selobj.ObjectId, OpenMode.ForWrite, false) as DBObject;
Dimension dim = obj as Dimension;
if (dim != null)
{
dim.DimensionText = "<>";
}
}
tr.Commit();
}
}
catch (System.Exception ex)
{
ed.WriteMessage("\nProblem updating dimensions.\n");
ed.WriteMessage(ex.Message);
}
} // tested on AutoCAD 2010
[CommandMethod("CopyTextToLeader", "ttl", CommandFlags.Redraw)]
public void TextToMleader()
{
Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
Editor ed = doc.Editor;
Database db = doc.Database;
// save current DIMBLK variable
string dblk = Autodesk.AutoCAD.ApplicationServices.Application.GetSystemVariable("DIMBLK").ToString();
try
{
PromptEntityOptions peo =
new PromptEntityOptions("\nSelect Text / MText: ");
peo.SetRejectMessage("\nMust be select type of Text or MText.");
peo.AddAllowedClass(typeof(DBText), false);
peo.AddAllowedClass(typeof(MText), false);
PromptEntityResult per = ed.GetEntity(peo);
if (per.Status != PromptStatus.OK) return;
ObjectId txtId = per.ObjectId;
PromptPointOptions opt = new PromptPointOptions("\nSpecify leader arrowhead location: ");
PromptPointResult res = ed.GetPoint(opt);
if (res.Status != PromptStatus.OK) return;
Point3d pt = res.Value;
using (Transaction tr = db.TransactionManager.StartTransaction())
{
BlockTable bt = (BlockTable)tr.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable;
BlockTableRecord btr = (BlockTableRecord)tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite) as BlockTableRecord;
ObjectId blkid = ObjectId.Null;
DBObject obj = (DBObject)tr.GetObject(txtId, OpenMode.ForWrite) as DBObject;
ed.WriteMessage("\nType\t{0}\n", obj.GetRXClass().DxfName);
DBText txtobj = null;
MText mtxtobj = null;
Point3d tp = new Point3d();
if (obj.GetRXClass().DxfName == "TEXT")
{
txtobj = obj as DBText;
if (txtobj == null) return;
tp = txtobj.Position;
}
if (obj.GetRXClass().DxfName == "MTEXT")
{
mtxtobj = obj as MText;
if (mtxtobj == null) return;
tp = mtxtobj.Location;
}
Leader leader = new Leader();
// Create the MText annotation
MText copymtx = new MText();
if (mtxtobj != null)
{
copymtx = mtxtobj.Clone() as MText;
}
if (txtobj != null)
{
copymtx = new MText();
copymtx.Location = txtobj.Position;
copymtx.Contents = txtobj.TextString;
}
// Add the new object to current space and the transaction
btr.AppendEntity(copymtx);
tr.AddNewlyCreatedDBObject(copymtx, true);
if (txtobj != null)
{
leader.TextStyleId = txtobj.TextStyleId;
}
if (mtxtobj != null)
{
leader.TextStyleId = mtxtobj.TextStyleId;
}
// set arrow head block to DOT
if (!bt.Has("_DOT"))
{
Autodesk.AutoCAD.ApplicationServices.Application.SetSystemVariable("DIMBLK", "_DOT");
}
leader.HasArrowHead = true;
leader.Dimldrblk = bt["_DOT"];
leader.Dimasz = db.Dimtxt * 0.2;
leader.AppendVertex(pt);
leader.AppendVertex(tp);
btr.AppendEntity(leader);
tr.AddNewlyCreatedDBObject(leader, true);
// attach the annotation after the leader object is added
leader.Annotation = copymtx.ObjectId;
// evaluate leader
leader.EvaluateLeader();
// erase prototypes
if (mtxtobj != null) mtxtobj.Erase();
if (txtobj != null) txtobj.Erase();
tr.Commit();
}
}
catch (System.Exception ex)
{
ed.WriteMessage("\nError: {0}\nTrace: {1}", ex.Message, ex.StackTrace);
}
finally
{
// reset DIMBLK
if (dblk != "")
{
Autodesk.AutoCAD.ApplicationServices.Application.SetSystemVariable("DIMBLK", dblk);
}
else
{
Autodesk.AutoCAD.ApplicationServices.Application.SetSystemVariable("DIMBLK", ".");
}
}
} //tested on AutoCAD 2010
[CommandMethod("AddVertexToMLeader", "mlv", CommandFlags.Redraw)]
public void AddMleaderVx()
{
Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
Editor ed = doc.Editor;
Database db = doc.Database;
try
{
PromptEntityOptions peo =
new PromptEntityOptions("\nSelect mleader: ");
peo.SetRejectMessage("\nMust be select type of MLeader.");
peo.AddAllowedClass(typeof(MLeader), false);
PromptEntityResult per = ed.GetEntity(peo);
if (per.Status != PromptStatus.OK) return;
ObjectId txtId = per.ObjectId;
PromptPointOptions opt = new PromptPointOptions("\nSpecify new vertex location: ");
PromptPointResult res = ed.GetPoint(opt);
if (res.Status != PromptStatus.OK) return;
Point3d vp = res.Value;
using (Transaction tr = db.TransactionManager.StartTransaction())
{
BlockTableRecord btr = (BlockTableRecord)tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite) as BlockTableRecord;
DBObject obj = (DBObject)tr.GetObject(txtId, OpenMode.ForWrite) as DBObject;
MLeader leader = obj as MLeader;
int ld = leader.AddLeader();
int ln = leader.AddLeaderLine(ld);
leader.AddFirstVertex(ln, vp);
leader.AddLastVertex(ln, leader.TextLocation);
tr.Commit();
}
}
catch (System.Exception ex)
{
ed.WriteMessage("\nError: {0}\nTrace: {1}", ex.Message, ex.StackTrace);
}
finally
{
}
} // tested on AutoCAD 2010
[CommandMethod("TextToLeader", "ttm", CommandFlags.Redraw)]
public void TextToMleader()
{
Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
Editor ed = doc.Editor;
Database db = doc.Database;
// save current DIMBLK variable
string dblk = Autodesk.AutoCAD.ApplicationServices.Application.GetSystemVariable("DIMBLK").ToString();
try
{
PromptEntityOptions peo =
new PromptEntityOptions("\nSelect Text / MText: ");
peo.SetRejectMessage("\nMust be select type of Text or MText.");
peo.AddAllowedClass(typeof(DBText), false);
peo.AddAllowedClass(typeof(MText), false);
PromptEntityResult per = ed.GetEntity(peo);
if (per.Status != PromptStatus.OK) return;
ObjectId txtId = per.ObjectId;
PromptPointOptions opt = new PromptPointOptions("\nSpecify mleader arrowhead location: ");
PromptPointResult res = ed.GetPoint(opt);
if (res.Status != PromptStatus.OK) return;
Point3d pt = res.Value;
using (Transaction tr = db.TransactionManager.StartTransaction())
{
BlockTable bt = (BlockTable)tr.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable;
BlockTableRecord btr = (BlockTableRecord)tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite) as BlockTableRecord;
ObjectId blkid = ObjectId.Null;
DBObject obj = (DBObject)tr.GetObject(txtId, OpenMode.ForWrite) as DBObject;
ed.WriteMessage("\nType\t{0}\n", obj.GetRXClass().DxfName);
DBText txtobj = null;
MText mtxtobj = null;
Point3d tp = new Point3d();
if (obj.GetRXClass().DxfName == "TEXT")
{
txtobj = obj as DBText;
if (txtobj == null) return;
tp = txtobj.Position;
}
if (obj.GetRXClass().DxfName == "MTEXT")
{
mtxtobj = obj as MText;
if (mtxtobj == null) return;
tp = mtxtobj.Location;
}
MLeader leader = new MLeader();
leader.ContentType = ContentType.MTextContent;
MText annomtx = new MText();
if (mtxtobj != null)
{
leader.MText = mtxtobj;
leader.TextHeight = mtxtobj.TextHeight;
}
if (txtobj != null)
{
annomtx = new MText();
annomtx.Location = txtobj.Position;
annomtx.Contents = txtobj.TextString;
leader.MText = annomtx;
leader.TextHeight = txtobj.Height;
}
// set arrow head block to DOT
if (!bt.Has("_DOT"))
{
Autodesk.AutoCAD.ApplicationServices.Application.SetSystemVariable("DIMBLK", "_DOT");
}
leader.ArrowSymbolId = bt["_DOT"];
leader.ArrowSize = leader.TextHeight * 0.2;
leader.DoglegLength = leader.TextHeight * 0.25;
leader.LeaderLineType = LeaderType.StraightLeader;
int ld = leader.AddLeader();
int ln = leader.AddLeaderLine(ld);
leader.AddFirstVertex(ln, pt);
leader.AddLastVertex(ln, tp);
btr.AppendEntity(leader);
tr.AddNewlyCreatedDBObject(leader, true);
// erase prototypes
if (mtxtobj != null) mtxtobj.Erase();
if (txtobj != null) txtobj.Erase();
tr.Commit();
}
}
catch (System.Exception ex)
{
ed.WriteMessage("\nError: {0}\nTrace: {1}", ex.Message, ex.StackTrace);
}
finally
{
// reset DIMBLK
if (dblk != "")
{
Autodesk.AutoCAD.ApplicationServices.Application.SetSystemVariable("DIMBLK", dblk);
}
else
{
Autodesk.AutoCAD.ApplicationServices.Application.SetSystemVariable("DIMBLK", ".");
}
}
}