csharp 发表于 2014-5-7 05:31:07

AutoCAD .NET输出DBObject/Entity的详细接口信息

[ 本帖最后由 csharp 于 2014-5-7 19:46 编辑 ]\n\n[ 本帖最后由 csharp 于 2014-5-7 05:32 编辑 ]\n\nUsing C# to Export Detailed Information of AutoCAD .NET DBObject/Entity



Let us look at a cool AutoCAD .NET coding gadget in this post which can export all good properties of a selected AutoCAD Entity/DBObject to a CSV file, which can be opened in the Microsoft Excel or any other CSV supported tools for us to check the detailed information for each single property. The CSV file can be reused for some other more meaningful purposes as well for sure.

In the old days without the reflection technology, this is quite a nasty task. We generally had to cast the AutoCAD generic object/entity to each available good type and access to its properties. Many short points are with this approach. The two most prominent are not efficient at all likely hundreds of even thousands of line of code have to be made and not compatible with old or new object models so likely some properties are missing in one version but some others are not available in another.

With the wonderful reflection technology handy, especially the tool classes TypeDescriptor,
PropertyDescriptor and PropertyDescriptorCollection, which are introduced in the recent .NET Framework versions, all these problems have gone away completely. We can make the same work done more nicely and professionally in just about a dozen lines of code:

    void Dump2(DBObject obj)
    {
      string line = "Name, Value, Category, ComponentType, Description, DisplayName, IsLocalizable, IsReadOnly, PropertyType";
      using (StreamWriter sw = new StreamWriter(@"c:\temp\AcadObjectProperties.csv"))
      {
            sw.WriteLine(line);

            PropertyDescriptorCollection props = TypeDescriptor.GetProperties(obj);
            foreach (PropertyDescriptor prop in props)
            {
                object valueObj = null;
                string valueString = string.Empty;
                try
                {
                  valueObj = prop.GetValue(obj);
                  if (valueObj != null)
                  {
                        valueString = valueObj.ToString();
                        valueString = valueString.Replace(",", ";");
                        line = string.Format("{0}, {1}, {2}, {3}, {4}, {5}, {6}, {7}, {8}", prop.Name, valueString, prop.Category, prop.ComponentType.Name, prop.Description, prop.DisplayName, prop.IsLocalizable, prop.IsReadOnly, prop.PropertyType.Name);
                        sw.WriteLine(line);
                  }
                }
                catch (System.Exception ex)
                {
                  if (ex.InnerException is Autodesk.AutoCAD.Runtime.Exception &&
                        (ex.InnerException as Autodesk.AutoCAD.Runtime.Exception).ErrorStatus == ErrorStatus.NotApplicable)
                        continue;
                  else
                        throw;
                }
            }
      }
    }

As can be noticed, the NotApplicable or eNotApplicable case has also been taken care of in the succinct but cool coding gadget. For the sake of convenience, the command used to test it has been appended below:

    Database db = HostApplicationServices.WorkingDatabase;
    Editor ed = MgdAcApplication.DocumentManager.MdiActiveDocument.Editor;

   
    public void DumpEntityInfo2_Method()
    {
      try
      {
            using (Transaction tr = db.TransactionManager.StartTransaction())
            {
                //TODO: add your code below.   
                Debug.WriteLine("DumpEntityInfo2 ran.");
                ed.WriteMessage("DumpEntityInfo2 ran.\n");

                PromptEntityResult selRes = ed.GetEntity("Pick an entity:");
                if (selRes.Status == PromptStatus.OK)
                {
                  Entity ent = tr.GetObject(selRes.ObjectId, OpenMode.ForRead) as Entity;
                  Dump2(ent);
                }

                tr.Commit();
            }
      }
      catch (System.Exception ex)
      {
            ed.WriteMessage(ex.ToString());
      }
    }

If a circle is selected for example, the content of the output CSV may look like:

Name, Value, Category, ComponentType, Description, DisplayName, IsLocalizable, IsReadOnly, PropertyType
Diameter, 1.83653333040557, Geometry, Circle, , Diameter, False, False, Double
Circumference, 5.76963961887494, Geometry, Circle, , Circumference, False, False, Double
Normal, (0;0;1), Geometry, Circle, , Normal, False, False, Vector3d
Thickness, 0.01, General, Circle, , Thickness, False, False, Double
Radius, 0.918266665202785, Geometry, Circle, , Radius, False, False, Double
Center, (0.370300330077356;5.55497170118056;0), Geometry, Circle, , Center, False, False, Point3d
Area, 2.64903386612308, Geometry, Curve, , Area, False, True, Double
Spline, Autodesk.AutoCAD.DatabaseServices.Spline, Geometry, Curve, , Spline, False, True, Spline
EndPoint, (1.28856699528014;5.55497170118056;0), Geometry, Curve, , EndPoint, False, False, Point3d
StartPoint, (1.28856699528014;5.55497170118056;0), Geometry, Curve, , StartPoint, False, False, Point3d
EndParam, 6.28318530717959, Geometry, Curve, , EndParam, False, True, Double
StartParam, 0, Geometry, Curve, , StartParam, False, True, Double
IsPeriodic, True, Geometry, Curve, , IsPeriodic, False, True, Boolean
Closed, True, Geometry, Curve, , Closed, False, True, Boolean
EdgeStyleId, (0), 3D Visualization, Entity, , EdgeStyleId, False, False, ObjectId
FaceStyleId, (0), 3D Visualization, Entity, , FaceStyleId, False, False, ObjectId
VisualStyleId, (0), 3D Visualization, Entity, , VisualStyleId, False, False, ObjectId
ForceAnnoAllVisible, True, Misc, Entity, , ForceAnnoAllVisible, False, False, Boolean
BlockName, *Paper_Space, Misc, Entity, , BlockName, False, True, String
MaterialId, (8796087807488), 3D Visualization, Entity, , MaterialId, False, False, ObjectId
Material, Global, 3D Visualization, Entity, , Material, False, False, String
ReceiveShadows, True, 3D Visualization, Entity, , ReceiveShadows, False, False, Boolean
CastShadows, False, 3D Visualization, Entity, , CastShadows, False, False, Boolean
Hyperlinks, Autodesk.AutoCAD.DatabaseServices.HyperLinkCollection, General, Entity, , Hyperlinks, False, True, HyperLinkCollection
CloneMeForDragging, True, Misc, Entity, , CloneMeForDragging, False, True, Boolean
GeometricExtents, ((-0.547966345125429;4.63670502597777;-1E-08);(1.28856700528014;6.47323837638334;0.01000001)), Geometry, Entity, , GeometricExtents, False, True, Extents3d
Ecs, ((1;0;0;0);(0;1;0;0);(0;0;1;0);(0;0;0;1)), Misc, Entity, , Ecs, False, True, Matrix3d
IsPlanar, True, Geometry, Entity, , IsPlanar, False, True, Boolean
CollisionType, Solid, Geometry, Entity, , CollisionType, False, True, CollisionType
LineWeight, LineWeight005, General, Entity, , LineWeight, False, False, LineWeight
Visible, True, General, Entity, , Visible, False, False, Boolean
LinetypeScale, 0.02, General, Entity, , LinetypeScale, False, False, Double
LinetypeId, (8796087821072), General, Entity, , LinetypeId, False, False, ObjectId
Linetype, ACAD_ISO02W100, General, Entity, , Linetype, False, False, String
LayerId, (8796087820976), General, Entity, , LayerId, False, False, ObjectId
Layer, Layer1, General, Entity, , Layer, False, False, String
PlotStyleNameId, ((0)lotStyleNameByLayer), General, Entity, , PlotStyleNameId, False, False, PlotStyleDescriptor
PlotStyleName, Color_1, General, Entity, , PlotStyleName, False, False, String
Transparency, (33554559), General, Entity, , Transparency, False, False, Transparency
EntityColor, Autodesk.AutoCAD.Colors.EntityColor, General, Entity, , EntityColor, False, True, EntityColor
ColorIndex, 1, General, Entity, , ColorIndex, False, False, Int32
Color, red, General, Entity, , Color, False, False, Color
BlockId, (8796087806592), Misc, Entity, , BlockId, False, True, ObjectId
PaperOrientation, NotApplicable, Misc, DBObject, , PaperOrientation, False, True, PaperOrientationStates
Annotative, NotApplicable, Misc, DBObject, , Annotative, False, False, AnnotativeStates
HasFields, False, Misc, DBObject, , HasFields, False, True, Boolean
AcadObject, System.__ComObject, Misc, DBObject, , AcadObject, False, True, Object
ClassID, 8229fcda-0225-4ef2-960e-a93bcf521a2b, Misc, DBObject, , ClassID, False, True, Guid
ObjectBirthVersion, AC1012;Release0, Misc, DBObject, , ObjectBirthVersion, False, True, FullDwgVersion
HasSaveVersionOverride, False, Misc, DBObject, , HasSaveVersionOverride, False, False, Boolean
IsObjectIdsInFlux, False, Misc, DBObject, , IsObjectIdsInFlux, False, True, Boolean
IsAProxy, False, Misc, DBObject, , IsAProxy, False, True, Boolean
IsTransactionResident, True, Misc, DBObject, , IsTransactionResident, False, True, Boolean
IsReallyClosing, False, Misc, DBObject, , IsReallyClosing, False, True, Boolean
IsCancelling, False, Misc, DBObject, , IsCancelling, False, True, Boolean
IsUndoing, False, Misc, DBObject, , IsUndoing, False, True, Boolean
IsNotifying, False, Misc, DBObject, , IsNotifying, False, True, Boolean
IsNewObject, False, Misc, DBObject, , IsNewObject, False, True, Boolean
IsModifiedGraphics, False, Misc, DBObject, , IsModifiedGraphics, False, True, Boolean
IsModifiedXData, False, Misc, DBObject, , IsModifiedXData, False, True, Boolean
IsModified, False, Misc, DBObject, , IsModified, False, True, Boolean
IsNotifyEnabled, False, Misc, DBObject, , IsNotifyEnabled, False, True, Boolean
IsWriteEnabled, False, Misc, DBObject, , IsWriteEnabled, False, True, Boolean
IsReadEnabled, True, Misc, DBObject, , IsReadEnabled, False, True, Boolean
IsErased, False, Misc, DBObject, , IsErased, False, True, Boolean
IsEraseStatusToggled, False, Misc, DBObject, , IsEraseStatusToggled, False, True, Boolean
MergeStyle, Ignore, Misc, DBObject, , MergeStyle, False, False, DuplicateRecordCloning
ExtensionDictionary, (0), Misc, DBObject, , ExtensionDictionary, False, True, ObjectId
Drawable, Autodesk.AutoCAD.DatabaseServices.Circle, Misc, DBObject, , Drawable, False, True, Drawable
Database, Autodesk.AutoCAD.DatabaseServices.Database, Misc, DBObject, , Database, False, True, Database
Handle, 369, Misc, DBObject, , Handle, False, True, Handle
OwnerId, (8796087806592), Misc, DBObject, , OwnerId, False, False, ObjectId
ObjectId, (8796087820944), Misc, DBObject, , ObjectId, False, True, ObjectId
Id, (8796087820944), Misc, DBObject, , Id, False, True, ObjectId
IsPersistent, True, Misc, DBObject, , IsPersistent, False, True, Boolean
Bounds, ((-0.547966345125429;4.63670502597777;-1E-08);(1.28856700528014;6.47323837638334;0.01000001)), Misc, Drawable, , Bounds, False, True, Nullable`1
DrawableType, Geometry, Misc, Drawable, , DrawableType, False, True, DrawableType
AutoDelete, False, Misc, DisposableWrapper, , AutoDelete, False, True, Boolean
IsDisposed, False, Misc, DisposableWrapper, , IsDisposed, False, True, Boolean
UnmanagedObject, 710694656, Misc, DisposableWrapper, , UnmanagedObject, False, True, IntPtr

Some special properties may need to be tweaked a bit further or skipped at all. I would like to leave it as an exercise to readers who have the need!

csharp 发表于 2014-5-7 05:35:56

这个 Getpropertyvalue 比较全面了

csharp 发表于 2014-5-7 19:40:48

这样改成命令行输出,再加工后就是 Net 版的 GetpropertyValue 了

      void Dump2(DBObject obj)
      {
            Document doc = Application.DocumentManager.MdiActiveDocument;
            Editor ed = doc.Editor;
            Transaction tr = doc.TransactionManager.StartTransaction();
            using (tr )
            {
                PropertyDescriptorCollection props = TypeDescriptor.GetProperties(obj);
                foreach (PropertyDescriptor prop in props)
                {
                  object valueObj = null;
                  string valueString = string.Empty;
                  try
                  {

                        valueObj = prop.GetValue(obj);
                        if (valueObj != null)
                        {
                            valueString = valueObj.ToString();
                            valueString = valueString.Replace(",", ";");
                            ed.WriteMessage("{0} = {1}\n", prop.Name, valueString);
                        }
                  }
                  catch (System.Exception ex)
                  {

                        if (ex.InnerException is Autodesk.AutoCAD.Runtime.Exception &&
                            (ex.InnerException as Autodesk.AutoCAD.Runtime.Exception).ErrorStatus == ErrorStatus.NotApplicable)
                            continue;
                        else
                            throw;
                  }
                }
            }
      }

命令:DUMPENT
Pick an entity:
: UnitFactor = 1
BlockUnit = Millimeters
Name = A$C0E2C3778
AnonymousBlockTableRecord = (0)
DynamicBlockTableRecord = (2129671768)
IsDynamicBlock = False
DynamicBlockReferencePropertyCollection = Autodesk.AutoCAD.DatabaseServices.DynamicBlockReferencePropertyCollection
TreatAsBlockRefForExplode = False
AttributeCollection = Autodesk.AutoCAD.DatabaseServices.AttributeCollection
BlockTransform = ((1;0;0;3147.0126492974);(0;1;0;1741.26403207564);(0;0;1;0);(0;0;0;1))
Normal = (0;0;1)
Rotation = 0
ScaleFactors = (1;1;1)
Position = (3147.0126492974;1741.26403207564;0)
BlockTableRecord = (2129671768)
EdgeStyleId = (0)
FaceStyleId = (0)
VisualStyleId = (0)
ForceAnnoAllVisible = False
BlockName = *Model_Space
MaterialId = (2129665888)
Material = ByLayer
ReceiveShadows = True
CastShadows = True
Hyperlinks = Autodesk.AutoCAD.DatabaseServices.HyperLinkCollection
CloneMeForDragging = True
CompoundObjectTransform = ((1;0;0;3147.0126492974);(0;1;0;1741.26403207564);(0;0;1;0);(0;0;0;1))
GeometricExtents = ((3147.01264540362;1741.26403353986;-1E-08);(3443.85247018912;2038.10385832536;1E-08))
Ecs = ((1;0;0;0);(0;1;0;0);(0;0;1;0);(0;0;0;1))
IsPlanar = True
CollisionType = Solid
LineWeight = ByLayer
Visible = True
LinetypeScale = 1
LinetypeId = (2129665192)
Linetype = ByLayer
LayerId = (2129665152)
Layer = 0
PlotStyleNameId = ((0);PlotStyleNameByLayer)
PlotStyleName = ByLayer
Transparency = (0)
EntityColor = Autodesk.AutoCAD.Colors.EntityColor
ColorIndex = 256
Color = BYLAYER
BlockId = (2129665272)
PaperOrientation = False
Annotative = False
HasFields = False
AcadObject = System.__ComObject
ClassID = 1143d075-f1f5-4efc-a6fb-b18279042696
ObjectBirthVersion = AC1012;Release0
HasSaveVersionOverride = False
IsObjectIdsInFlux = False
IsAProxy = False
IsTransactionResident = True
IsReallyClosing = False
IsCancelling = False
IsUndoing = False
IsNotifying = False
IsNewObject = False
IsModifiedGraphics = False
IsModifiedXData = False
IsModified = False
IsNotifyEnabled = False
IsWriteEnabled = False
IsReadEnabled = True
IsErased = False
IsEraseStatusToggled = False
MergeStyle = Ignore
ExtensionDictionary = (0)
Drawable = Autodesk.AutoCAD.DatabaseServices.BlockReference
Database = Autodesk.AutoCAD.DatabaseServices.Database
Handle = 248
OwnerId = (2129665272)
ObjectId = (2129671808)
Id = (2129671808)
IsPersistent = True
Bounds = ((3147.01264540362;1741.26403353986;-1E-08);(3443.85247018912;2038.10385832536;1E-08))
DrawableType = Geometry
AutoDelete = False
IsDisposed = False
UnmanagedObject = 604201928

qq509103902 发表于 2016-12-7 11:11:35

啥也不说了,感谢楼主分享哇!

nihaogemen 发表于 2016-12-13 19:11:15

不懂
命令为 DUMPENT
可没有 这个函数啊
页: [1]
查看完整版本: AutoCAD .NET输出DBObject/Entity的详细接口信息