000

Index Labels

Drawing Custom Properties - Make It Configurable

.
Drawing custom properties can be used as a container to store per-drawing data, which is persisted with drawing file.

Drawing custom properties can be accessed for read/write via COM API since AutoCAD 2002. AutoCAD ObjectARX .NET API provides DatabaseSummaryInfo structure and DatabaseSummaryBuilder class to deal with drawing custom properties.

In this post, I attempt to put together some code that makes the process of attaching custom process configurable. That is, using the code presented here, one can easily configure what custom properties he/she wants to attach to drawing (property name, data type).

Firstly, here is the first part of code that defines 2 classes: CustomProperty and CustomProperties:

Code Snippet
  1. using System;
  2. using System.Collections.Generic;
  3.  
  4. namespace DwgCustomProps
  5. {
  6.     public enum CustomPropertyValueType
  7.     {
  8.         Integer=0,
  9.         RealNumber=1,
  10.         Text=2,
  11.         Date=3,
  12.         Time=4,
  13.         DateAndTime=5,
  14.         YesNo=6,
  15.     }
  16.  
  17.     public class CustomProperty
  18.     {
  19.         public string Name { set; get; }
  20.         public CustomPropertyValueType ValueType { set; get; }
  21.         public string FormatString { set; get; }
  22.         public object Value { set; get; }
  23.  
  24.         public CustomProperty()
  25.         {
  26.             Name = "";
  27.             FormatString = "";
  28.             ValueType = CustomPropertyValueType.Text;
  29.         }
  30.  
  31.         //Read-only property. Since custom property's value
  32.         //is very possibly used as text string for update
  33.         //drawing content, such as title block, hence this
  34.         //read-only property
  35.         public string ValueString
  36.         {
  37.             get
  38.             {
  39.                 string val = "";
  40.  
  41.                 switch (this.ValueType)
  42.                 {
  43.                     case CustomPropertyValueType.RealNumber:
  44.                         try
  45.                         {
  46.                             if (Value != null)
  47.                             {
  48.                                 double num = Convert.ToDouble(Value);
  49.                                 val = FormatString.Length > 0 ?
  50.                                     num.ToString(FormatString) :
  51.                                     num.ToString();
  52.                             }
  53.                         }
  54.                         catch { }
  55.                         break;
  56.                     case CustomPropertyValueType.Text:
  57.                         try
  58.                         {
  59.                             if (Value != null)
  60.                             {
  61.                                 val = Value.ToString();
  62.                             }
  63.                         }
  64.                         catch { }
  65.                         break;
  66.                     case CustomPropertyValueType.Date:
  67.                         try
  68.                         {
  69.                             if (Value != null)
  70.                             {
  71.                                 DateTime d = Convert.ToDateTime(Value);
  72.                                 val = FormatString.Length > 0 ?
  73.                                     d.ToString(FormatString) :
  74.                                     d.ToShortDateString();
  75.                             }
  76.                         }
  77.                         catch { }
  78.                         break;
  79.                     case CustomPropertyValueType.Time:
  80.                         try
  81.                         {
  82.                             if (Value != null)
  83.                             {
  84.                                 DateTime t = Convert.ToDateTime(Value);
  85.                                 val = FormatString.Length > 0 ?
  86.                                     t.ToString(FormatString) :
  87.                                     t.ToShortTimeString();
  88.                             }
  89.                         }
  90.                         catch { }
  91.                         break;
  92.                     case CustomPropertyValueType.DateAndTime:
  93.                         try
  94.                         {
  95.                             if (Value != null)
  96.                             {
  97.                                 DateTime dt = Convert.ToDateTime(Value);
  98.                                 val = FormatString.Length > 0 ?
  99.                                     dt.ToString(FormatString) :
  100.                                     dt.ToString();
  101.                             }
  102.                         }
  103.                         catch { }
  104.                         break;
  105.                     case CustomPropertyValueType.YesNo:
  106.                         try
  107.                         {
  108.                             if (Value != null)
  109.                             {
  110.                                 bool b = Convert.ToBoolean(Value);
  111.                                 val = b ? "Yes" : "No";
  112.                             }
  113.                         }
  114.                         catch { }
  115.                         break;
  116.                     default:
  117.                         try
  118.                         {
  119.                             if (Value != null)
  120.                             {
  121.                                 val = Convert.ToInt32(Value).ToString();
  122.                             }
  123.                         }
  124.                         catch { }
  125.                         break;
  126.                 }
  127.  
  128.                 return val;
  129.             }
  130.         }
  131.  
  132.         //This read-only property can be used for showing as property
  133.         //value type, for example, as column header text, when custom
  134.         //property data is shown in tabular format
  135.         public string ValueTypeString
  136.         {
  137.             get
  138.             {
  139.                 string str = "";
  140.  
  141.                 switch (this.ValueType)
  142.                 {
  143.                     case CustomPropertyValueType.RealNumber:
  144.                         str = "Real Number";
  145.                         break;
  146.                     case CustomPropertyValueType.Text:
  147.                         str = "Text";
  148.                         break;
  149.                     case CustomPropertyValueType.Date:
  150.                         str = "Date Only";
  151.                         break;
  152.                     case CustomPropertyValueType.Time:
  153.                         str = "Time Only";
  154.                         break;
  155.                     case CustomPropertyValueType.DateAndTime:
  156.                         str = "Date and Time";
  157.                         break;
  158.                     case CustomPropertyValueType.YesNo:
  159.                         str = "Yes or No";
  160.                         break;
  161.                     default:
  162.                         str = "Integer";
  163.                         break;
  164.                 }
  165.  
  166.                 return str;
  167.             }
  168.         }
  169.  
  170.         
  171.     }
  172.  
  173.     public class CustomProperties : Dictionary<string, CustomProperty>
  174.     {
  175.         
  176.     }
  177. }

The code shown above is fairly straightforward.

Now, a bit talk on "configurable". It is possible that business requirement to drawing custom properties can change due many different reasons. As a well-developed application, we all hope the application we developed have quite flexibility to adopt reasonable change without having to change the code each time business requirement changes, or at least minimize the possible code change. In the case of drawing custom properties, the goal is that when the business operation wants to add new custom property, to remove existing custom property, or to change existing custom property (its name, data type...), it would be ideal that these required changes can be done outside the application code and after the changes, the application still work the same way while he required changes to custom properties applied correctly. So, we need to separate custom property requirement and custom property applying as two different parts, then we use an Interface as the bridge to connect the 2 parts. In the first part (I create a class MyDrawingProperties, more details on it later), the code is responsible to set up custom properties in a drawing, according to custom property requirement supplied by second part, which is an class that implements a interface, called ICustomPropertiesFactory. Its name suggests that this interfaced class generates a set of custom properties according to business requirement and hand it over to the first part code for setting them up in drawing.

Here is the interface I use:

Code Snippet
  1. public interface ICustomPropertiesFactory
  2. {
  3.     CustomProperties GetCustomPropertySettings(object settingSourceInfo);
  4. }

Now, I can decide how and where I'd like the drawing custom properties is configured and where the configuration is persisted. The idea is that when business requirement changes (i.e. required drawing custom properties change due to drafting process change), I do not want to modify my code, at lease the code that actually writes/reads a drawing's custom properties while the CAD management is free to add new custom properties, remove existing custom properties. The trick, of course, is to implement the aforementioned Interface.

In this example, I use an XML to configure drawing custom properties. That is, if the CAD operation wants to make changes to currently used drawing custom properties (adding new properties or removing existing properties), simply going into the XML file and update it as needed. No code change is required. In reality, I'll prefer using database to persist custom property configuration than using XML file, though, especially in an enterprise environment.

Here is the XML file that defines drawing custom properties to be used:

Code Snippet
  1. <?xml version="1.0" encoding="utf-8" ?>
  2. <CustomProperties>
  3.   <CustomProperty name="ProjectNumber" valueType="Text" formatString="" />
  4.   <CustomProperty name="DrawnBy" valueType="Text" formatString="" />
  5.   <CustomProperty name="CheckedBy" valueType="Text" formatString="" />
  6.   <CustomProperty name="DrawnDate" valueType="Date" formatString="yyyy-MM-dd" />
  7.   <CustomProperty name="CheckedDate" valueType="Date" formatString="yyyy-MM-dd" />
  8.   <CustomProperty name="ClientName" valueType="Text" formatString="" />
  9.   <CustomProperty name="ProjectName" valueType="Text" formatString="" />
  10. </CustomProperties>

Here is the code that implements the interface ICustomPropertiesFacotry:

Code Snippet
  1. using System;
  2. using System.IO;
  3. using System.Xml;
  4.  
  5. namespace DwgCustomProps
  6. {
  7.     public interface ICustomPropertiesFactory
  8.     {
  9.         CustomProperties GetCustomPropertySettings(object settingSourceInfo);
  10.     }
  11.  
  12.     public class CustomPropertiesXmlFactory : ICustomPropertiesFactory
  13.     {
  14.         public CustomProperties GetCustomPropertySettings(object sourceInfo)
  15.         {
  16.             //Validat source Xml file
  17.             string filePath = ValidateInput(sourceInfo);
  18.  
  19.             CustomProperties settings = new CustomProperties();
  20.  
  21.             XmlDocument xmlDoc = new XmlDocument();
  22.             xmlDoc.Load(filePath);
  23.  
  24.             XmlNode root = xmlDoc.GetElementsByTagName("CustomProperties")[0];
  25.             foreach (XmlNode node in root.ChildNodes)
  26.             {
  27.                 CustomProperty setting = new CustomProperty();
  28.  
  29.                 setting.Name = node.Attributes["name"].Value;
  30.                 setting.FormatString = node.Attributes["formatString"].Value;
  31.                 setting.Value=null;
  32.                 string t = node.Attributes["valueType"].Value;
  33.                 switch (t)
  34.                 {
  35.                     case "RealNumber":
  36.                         setting.ValueType=CustomPropertyValueType.RealNumber;
  37.                         break;
  38.                     case "Text":
  39.                         setting.ValueType=CustomPropertyValueType.Text;
  40.                         break;
  41.                     case "Date":
  42.                         setting.ValueType=CustomPropertyValueType.Date;
  43.                         break;
  44.                     case "Time":
  45.                         setting.ValueType=CustomPropertyValueType.Time;
  46.                         break;
  47.                     case "DateAndTime":
  48.                         setting.ValueType=CustomPropertyValueType.DateAndTime;
  49.                         break;
  50.                     case "YesNo":
  51.                         setting.ValueType=CustomPropertyValueType.YesNo;
  52.                         break;
  53.                     default:
  54.                         setting.ValueType=CustomPropertyValueType.Integer;
  55.                         break;
  56.                 }
  57.  
  58.                 settings.Add(setting.Name,setting);
  59.             }
  60.  
  61.             return settings;
  62.         }
  63.  
  64.         #region private methods
  65.  
  66.         private string ValidateInput(object input)
  67.         {
  68.             string filePath = "";
  69.  
  70.             try
  71.             {
  72.                 filePath = (string)input;
  73.             }
  74.             catch
  75.             {
  76.                 throw new ArgumentException(
  77.                     "invalid input parameter: not file path to a Xml file.");
  78.             }
  79.  
  80.             if (!File.Exists(filePath))
  81.             {
  82.                 throw new FileNotFoundException(
  83.                     "Cannot find Xml file: \"" + filePath + "\".");
  84.             }
  85.  
  86.             if (!Path.GetExtension(filePath).ToUpper().EndsWith("XML"))
  87.             {
  88.                 throw new FileNotFoundException(
  89.                     "Invalid file type: must be a *.xml file.");
  90.             }
  91.  
  92.             return filePath;
  93.         }
  94.  
  95.         #endregion
  96.     }
  97. }

As you can see, the class does only one thing: generating a set of custom properties that defined in the persisted custom property configuration. Obviously, if the custom property configuration is stored in other format, such as in database, I can write different class (for example "CustomPropertiesSqlFactory") to read the configuration by implement the same interface.

Now, with drawing custom properties being defined outside the code that runs in AutoCAD, I can then focus on reading/writing drawing custom properties in AutoCAD without having to worry what if the requirement to custom properties changes later.

Here is a class called MyDrawingProperties that is derived from Autodesk.AutoCAD.DatabaseServices.DatabaseSummaryInfoBuilder:

Code Snippet
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using Autodesk.AutoCAD.DatabaseServices;
  6.  
  7. namespace DwgCustomProps
  8. {
  9.     public class MyDrawingProperties : DatabaseSummaryInfoBuilder
  10.     {
  11.         private ICustomPropertiesFactory _factory = null;
  12.         private CustomProperties _customProps = null;
  13.         private Database _db;
  14.  
  15.         public MyDrawingProperties(object settingSource, Database db)
  16.             : base(db.SummaryInfo)
  17.         {
  18.             _db = db;
  19.             Initialize(settingSource);
  20.         }
  21.  
  22.         public MyDrawingProperties(object settingSource,
  23.             Database db, bool attachMyProps)
  24.             : base(db.SummaryInfo)
  25.         {
  26.             _db = db;
  27.             Initialize(settingSource);
  28.             if (attachMyProps)
  29.             {
  30.                 SetCustomProperties(_customProps, true);
  31.             }
  32.         }
  33.  
  34.         #region public properties
  35.  
  36.         public string[] CustomPropertyNames
  37.         {
  38.             get
  39.             {
  40.                 return (from p in _customProps
  41.                         orderby p.Key ascending select p.Key).ToArray();
  42.             }
  43.         }
  44.  
  45.         public CustomProperty this[string key]
  46.         {
  47.             get
  48.             {
  49.                 return _customProps[key];
  50.             }
  51.         }
  52.  
  53.         public CustomProperties MyCustomProperties
  54.         {
  55.             get { return _customProps; }
  56.         }
  57.  
  58.         #endregion
  59.  
  60.         #region public methods
  61.  
  62.         public string GetCustomPropertyValueString(string key)
  63.         {
  64.             CustomProperty prop = this[key];
  65.             return prop.ValueString;
  66.         }
  67.  
  68.         public void RemoveCustomProperty(string key)
  69.         {
  70.             if (RemoveProperty(key))
  71.             {
  72.                 _db.SummaryInfo = this.ToDatabaseSummaryInfo();
  73.             }
  74.         }
  75.  
  76.         public void RemoveMyCustomProperties()
  77.         {
  78.             bool removed = false;
  79.  
  80.             foreach (KeyValuePair<string, CustomProperty> item in _customProps)
  81.             {
  82.                 if (RemoveProperty(item.Value.Name))
  83.                 {
  84.                     if (!removed) removed = true;
  85.                 }
  86.             }
  87.  
  88.             if (removed) _db.SummaryInfo = this.ToDatabaseSummaryInfo();
  89.         }
  90.  
  91.         public void RemoveForeignCustomProperties()
  92.         {
  93.             bool removed = false;
  94.             bool go = true;
  95.             while (go)
  96.             {
  97.                 go = false;
  98.                 foreach (DictionaryEntry entry in this.CustomPropertyTable)
  99.                 {
  100.                     string key = entry.Key.ToString();
  101.                     var propItems = _customProps.Where
  102.                         (p => p.Key == key).FirstOrDefault();
  103.  
  104.                     if (propItems.Value != null)
  105.                     {
  106.                         this.CustomPropertyTable.Remove(entry.Key);
  107.                         if (!removed) removed = true;
  108.                         go = true;
  109.                         break;
  110.                     }
  111.                 }
  112.             }
  113.  
  114.             if (removed) _db.SummaryInfo = this.ToDatabaseSummaryInfo();
  115.         }
  116.  
  117.         public void RemoveAllCustomProperties()
  118.         {
  119.             this.CustomPropertyTable.Clear();
  120.             _db.SummaryInfo = this.ToDatabaseSummaryInfo();
  121.         }
  122.  
  123.         public void ApplyCustomProperties()
  124.         {
  125.             SetCustomProperties(_customProps);
  126.             _db.SummaryInfo = this.ToDatabaseSummaryInfo();
  127.         }
  128.  
  129.         public void ApplyCustomProperties(
  130.             ICustomPropertyValueProvider custPropValueProvider)
  131.         {
  132.             Dictionary<string, object> props=
  133.                 custPropValueProvider.GetCustomPropertyValues(
  134.                     _db.Filename, _customProps);
  135.             if (props == null) return;
  136.  
  137.             foreach (KeyValuePair<string, object> item in props)
  138.             {
  139.                 this[item.Key].Value = item.Value;
  140.             }
  141.  
  142.             this.ApplyCustomProperties();
  143.         }
  144.  
  145.         #endregion
  146.  
  147.         #region private methods
  148.  
  149.         private void Initialize(object settingSource)
  150.         {
  151.             LoadSettings(settingSource);
  152.             GetCurrentPropertyValues();
  153.         }
  154.  
  155.         private void LoadSettings(object settingSource)
  156.         {
  157.             string source = settingSource.ToString();
  158.             if (source.ToUpper().EndsWith(".XML"))
  159.             {
  160.                 _factory = new CustomPropertiesXmlFactory();
  161.             }
  162.  
  163.             if (_factory != null)
  164.             {
  165.                 _customProps =
  166.                     _factory.GetCustomPropertySettings(settingSource);
  167.             }
  168.             else
  169.             {
  170.                 throw new NotSupportedException(
  171.                     "Setting source is not supported.");
  172.             }
  173.         }
  174.  
  175.         private void GetCurrentPropertyValues()
  176.         {
  177.             foreach (DictionaryEntry ent in CustomPropertyTable)
  178.             {
  179.                 string key = ent.Key.ToString();
  180.                 try
  181.                 {
  182.                     CustomProperty prop = this[key];
  183.                     object val = ent.Value;
  184.  
  185.                     switch (prop.ValueType)
  186.                     {
  187.                         case CustomPropertyValueType.RealNumber:
  188.                             try
  189.                             {
  190.                                 double num = Convert.ToDouble(val);
  191.                                 prop.Value = num;
  192.                             }
  193.                             catch
  194.                             {
  195.                                 prop.Value = null;
  196.                             }
  197.                             break;
  198.                         case CustomPropertyValueType.Text:
  199.                             prop.Value = val.ToString();
  200.                             break;
  201.                         case CustomPropertyValueType.Date:
  202.                             try
  203.                             {
  204.                                 DateTime d = Convert.ToDateTime(val);
  205.                                 prop.Value = val;
  206.                             }
  207.                             catch
  208.                             {
  209.                                 prop.Value = null;
  210.                             }
  211.                             break;
  212.                         case CustomPropertyValueType.Time:
  213.                             try
  214.                             {
  215.                                 DateTime t = Convert.ToDateTime(prop.Value);
  216.                                 prop.Value = val;
  217.                             }
  218.                             catch
  219.                             {
  220.                                 prop.Value = null;
  221.                             }
  222.  
  223.                             break;
  224.                         case CustomPropertyValueType.DateAndTime:
  225.                             try
  226.                             {
  227.                                 DateTime dt = Convert.ToDateTime(prop.Value);
  228.                                 prop.Value = val;
  229.                             }
  230.                             catch
  231.                             {
  232.                                 prop.Value = null;
  233.                             }
  234.                             break;
  235.                         case CustomPropertyValueType.YesNo:
  236.                             try
  237.                             {
  238.                                 bool b = Convert.ToBoolean(prop.Value);
  239.                                 prop.Value = val;
  240.                             }
  241.                             catch
  242.                             {
  243.                                 prop.Value = null;
  244.                             }
  245.                             break;
  246.                         default:
  247.                             try
  248.                             {
  249.                                 int i = Convert.ToInt32(prop.Value);
  250.                                 prop.Value = i;
  251.                             }
  252.                             catch
  253.                             {
  254.                                 prop.Value = null;
  255.                             }
  256.                             break;
  257.                     }
  258.                 }
  259.                 catch { }
  260.             }
  261.         }
  262.  
  263.         private void SetCustomProperty(
  264.             CustomProperty prop, bool createIfNotFound)
  265.         {
  266.             try
  267.             {
  268.                 this.CustomPropertyTable[prop.Name] = prop.ValueString;
  269.             }
  270.             catch
  271.             {
  272.                 if (createIfNotFound)
  273.                 {
  274.                     this.CustomPropertyTable.Add(prop.Name, prop.ValueString);
  275.                 }
  276.             }
  277.         }
  278.  
  279.         private void SetCustomProperties(
  280.             CustomProperties props, bool createIfNotFound)
  281.         {
  282.             _customProps = props;
  283.  
  284.             foreach (KeyValuePair<string, CustomProperty> item in props)
  285.             {
  286.                 SetCustomProperty(item.Value, createIfNotFound);
  287.             }
  288.         }
  289.  
  290.         private void SetCustomProperties(CustomProperties props)
  291.         {
  292.             SetCustomProperties(props, true);
  293.         }
  294.         
  295.         private bool RemoveProperty(string key)
  296.         {
  297.             bool removed = false;
  298.  
  299.             foreach (DictionaryEntry entry in this.CustomPropertyTable)
  300.             {
  301.                 if (entry.Key.ToString() == key)
  302.                 {
  303.                     this.CustomPropertyTable.Remove(entry.Key);
  304.                     removed = true;
  305.                     break;
  306.                 }
  307.             }
  308.  
  309.             return removed;
  310.         }
  311.  
  312.         #endregion
  313.     }
  314. }

One thing to mention: in the LoadSetting() method, for simplicity, I just test if the passed in parameter is a string representing a XML file name. If other type/format of custom property configuration is used, the hard coded approach obviously is not a good practice. I may post in future on a topic regarding how to load different classes that implement the same interface via configuration.

From the code we can see, the code acts upon a set of custom properties defined in custom property configuration. The interface ICustomPropertiesFactory effectively separates how custom properties is handled in AutoCAD and how they are defined.

Finally, here is the code that actually puts everything together and makes them useful in AutoCAD:

Code Snippet
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5.  
  6. using Autodesk.AutoCAD.ApplicationServices;
  7. using Autodesk.AutoCAD.DatabaseServices;
  8. using Autodesk.AutoCAD.EditorInput;
  9. using Autodesk.AutoCAD.Geometry;
  10. using Autodesk.AutoCAD.Runtime;
  11.  
  12. [assembly: CommandClass(typeof(DwgCustomProps.MyCommands))]
  13. [assembly: ExtensionApplication(typeof(DwgCustomProps.MyCommands))]
  14.  
  15. namespace DwgCustomProps
  16. {
  17.     public class MyCommands : IExtensionApplication
  18.     {
  19.         private const string MY_PROPERTIES_XML_SOURSE =
  20.             @"C:\Users\norm\Documents\Visual Studio 2010" +
  21.             @"\Projects\ACAD2012\DwgCustomProps\DwgCustomProps" +
  22.             @"\DwgCustomPropertySettings.xml";
  23.  
  24.         public void Initialize()
  25.         {
  26.             Document dwg = Application.DocumentManager.MdiActiveDocument;
  27.             Editor ed = dwg.Editor;
  28.  
  29.             try
  30.             {
  31.                 ed.WriteMessage(
  32.                     "\nAcad Addin \"MyDrawingProperties\" is loaded\n");
  33.             }
  34.             catch (System.Exception ex)
  35.             {
  36.                 ed.WriteMessage("\nAcad Addin initializing error: {0}\n",
  37.                     ex.Message);
  38.             }
  39.         }
  40.  
  41.         public void Terminate()
  42.         {
  43.  
  44.         }
  45.  
  46.         [CommandMethod("AttachMyProps")]
  47.         public static void AttachMyCustomProperties()
  48.         {
  49.             Document dwg = Application.DocumentManager.MdiActiveDocument;
  50.             Editor ed = dwg.Editor;
  51.  
  52.             try
  53.             {
  54.                 MyDrawingProperties myProps =
  55.                     new MyDrawingProperties(
  56.                         MY_PROPERTIES_XML_SOURSE, dwg.Database, true);
  57.                 myProps.ApplyCustomProperties();
  58.  
  59.                 ed.WriteMessage("\nMy custom drawing properties have been " +
  60.                     "created with current drawing.\n");
  61.             }
  62.             catch (System.Exception ex)
  63.             {
  64.                 ed.WriteMessage("\nError: " + ex.Message + "\n" +
  65.                     ex.StackTrace.ToString());
  66.                 ed.WriteMessage("\n*Cancel*\n");
  67.             }
  68.         }
  69.  
  70.         [CommandMethod("ClearMyProps")]
  71.         public static void ClearMyCustomProperties()
  72.         {
  73.             Document dwg = Application.DocumentManager.MdiActiveDocument;
  74.             Editor ed = dwg.Editor;
  75.  
  76.             try
  77.             {
  78.                 MyDrawingProperties myProps =
  79.                     new MyDrawingProperties(
  80.                         MY_PROPERTIES_XML_SOURSE, dwg.Database, false);
  81.                 myProps.RemoveMyCustomProperties();
  82.  
  83.                 ed.WriteMessage("\nMy custom drawing properties have been " +
  84.                     "removed from current drawing.\n");
  85.             }
  86.             catch (System.Exception ex)
  87.             {
  88.                 ed.WriteMessage("\nError: " + ex.Message + "\n" +
  89.                     ex.StackTrace.ToString());
  90.                 ed.WriteMessage("\n*Cancel*\n");
  91.             }
  92.         }
  93.  
  94.         [CommandMethod("EditMyProps")]
  95.         public static void EditMyCustomProperties()
  96.         {
  97.             Document dwg = Application.DocumentManager.MdiActiveDocument;
  98.             Editor ed = dwg.Editor;
  99.  
  100.             try
  101.             {
  102.                 MyDrawingProperties myProps =
  103.                     new MyDrawingProperties(
  104.                             MY_PROPERTIES_XML_SOURSE, dwg.Database, true);
  105.  
  106.                 ICustomPropertyValueProvider valueProvider =
  107.                     new CustomPropertyValueManualProvider();
  108.                 myProps.ApplyCustomProperties(valueProvider);
  109.  
  110.                 ed.WriteMessage("\nMy custom drawing properties with " +
  111.                     "curent drawing have been edited and updated.\n");
  112.             }
  113.             catch (System.Exception ex)
  114.             {
  115.                 ed.WriteMessage("\nError: " + ex.Message + "\n" +
  116.                     ex.StackTrace.ToString());
  117.                 ed.WriteMessage("\n*Cancel*\n");
  118.             }
  119.         }
  120.     }
  121. }

You may have noticed there is ICustomPropertyValueProvider type used in "EditMyProps" command. I'll explain it later.

After running command "AttachMyProps", use "DwgProps" command to open "Drawing Properties" dialog box. You should be able to see all the predefined custom properties defined in the XML file (or other custom properties configuration source, for that matter) are now available in the current drawing. Running command "ClearMyProps" clears these predefined custom properties.

Now let's look into ICustomPropertyValueProvider interface. Custom properties only are useful when they carry meaningful values. In reality, the custom properties could be populated in many ways: manually, or most desirably , automatically with data from production data source, such as project management database, document management system...So, once we have a way to attach custom properties to a drawing, there should be some kind of mechanism to populate custom properties. Since the data used for custom properties could from very different types of source, such as databases, XML file, text file, Excel sheet, or web/WCF services, it is important to define an interface for populating custom properties, so that the code that actually populates custom properties does not have to be changed when data source changes. Hence the ICustomPropertyValueProvider interface. In my case, I want to manually populate the custom properties by using a dialog box to get user inputs. So, I create a class CustomPropertyValueManualProvider, which implements ICustomPropertyValueProvider:

Code Snippet
  1. using System.Collections.Generic;
  2.  
  3. namespace DwgCustomProps
  4. {
  5.     public interface ICustomPropertyValueProvider
  6.     {
  7.         Dictionary<string, object> GetCustomPropertyValues(string fileName,
  8.             CustomProperties customProps);
  9.     }
  10.  
  11.     public class CustomPropertyValueManualProvider :
  12.         ICustomPropertyValueProvider
  13.     {
  14.         public Dictionary<string, object> GetCustomPropertyValues(
  15.             string fileName,
  16.             CustomProperties customProps)
  17.         {
  18.             Dictionary<string, object> props = null;
  19.  
  20.             using (dlgMyProperties dlg = new dlgMyProperties())
  21.             {
  22.                 dlg.SetGridView(customProps);
  23.                 if (Autodesk.AutoCAD.ApplicationServices.
  24.                     Application.ShowModalDialog(dlg) ==
  25.                     System.Windows.Forms.DialogResult.OK)
  26.                 {
  27.                     props = dlg.MyPropertyValues;
  28.                 }
  29.             }
  30.  
  31.             return props;
  32.         }
  33.     }
  34. }

There is no need to pay much attention on how the dialog box is designed to get user input here. All we need to know is that calling ICustomPropertyValueProvider.GetCustomPropertyValues() method would return a Dictionary object with each custom property's name as key. Notice that the method takes a file name as one of the input parameters. I assume data used for custom properties can be identified from the data source by drawing's file name in many cases. If drawings in an office are managed in some sort of document management system, such as Vault, SharePoint, then drawing might be identified by particular identifier other than file name.

Obviously, if you want to populate custom properties with data from certain data source other than manual input, say, from SharePoint drawing library, you just need to create a class that implements ICustomPropertyValueProvider (you could call it CustomPropertyValueSharePointProvider). You then write code in the class's GetCustomPropertyValues() method to grab data from SharePoint drawing library. Whatever you do here, there is no need to change code in MyDrawingProperties to update custom property values (by calling its ApplyCustomProperties(ICustomPropertyValueProvider provider) method).

Here is a video clip to show how the code works in AutoCAD.

Download source code here.

Blog Archive

Labels

.NET Programming 2D Drafting 3D 3D Animation 3D Art 3D Artist 3D CAD 3D Character 3D design 3D design tutorial 3D Drafting 3D effects 3D Engineering 3D Lighting 3D Materials 3D Modeling 3D models 3D Navigation 3D presentation 3D Printing 3D rendering 3D scanning 3D scene 3D simulation 3D Sketch Inventor 3D Texturing 3D visualization 3D Web App 3ds Max 4D Simulation ACC Adaptive Clearing adaptive components Add-in Development Additive Layers Additive Manufacturing Advanced CAD features Advanced Modeling advanced plot styles Advanced Sketch AEC Technology AEC Tools AEC Workflow affordable Autodesk tools AI AI animation AI Assistance AI collaboration AI Design AI Design Tools AI Experts AI for Revit AI Guide AI in 3D AI in Architecture AI in CAD AI in CNC AI in design AI in engineering AI in Manufacturing AI in Revit AI insights AI lighting AI rigging AI Strategies AI Tips AI Tools AI Tricks AI troubleshooting AI workflow AI-assisted AI-assisted rendering AI-Assisted Workflow AI-enhanced AI-powered templates Animation Animation Curves Animation Layers animation pipeline animation tips Animation Tutorial Animation workflow annotation Annotation Scaling annotation standards Annotations AR Architectural AI Architectural CAD architectural design Architectural Drawing architectural drawings architectural modeling architectural preservation Architectural Productivity architectural visualization Architecture architecture CAD architecture design Architecture Engineering Architecture Firm Architecture Productivity architecture projects architecture software architecture technology architecture tools Architecture Visualization Architecture Workflow Arnold Renderer Arnold Shader Artificial Intelligence As-Built Model assembly techniques Asset Management augmented reality Auto Rig Maya AutoCAD AutoCAD advice AutoCAD AI tools AutoCAD API AutoCAD automation AutoCAD Basics AutoCAD Beginner AutoCAD Beginners AutoCAD Blocks AutoCAD Civil 3D AutoCAD Civil3D AutoCAD commands AutoCAD efficiency AutoCAD Expert Advice AutoCAD features AutoCAD File Management AutoCAD Guide AutoCAD Hub AutoCAD Layer AutoCAD Layers AutoCAD learning AutoCAD print settings AutoCAD productivity AutoCAD scripting AutoCAD Scripts AutoCAD Sheet Set tips AutoCAD Teaching AutoCAD Techniques AutoCAD Templates AutoCAD tips AutoCAD tools AutoCAD training. AutoCAD tricks AutoCAD Tutorial AutoCAD workflow AutoCAD Xref Autodesk Autodesk 2025 Autodesk 2026 Autodesk 3ds Max Autodesk AI Autodesk AI Tools Autodesk Alias Autodesk AutoCAD Autodesk BIM Autodesk BIM 360 Autodesk Certification Autodesk Civil 3D Autodesk Cloud Autodesk community forums Autodesk Construction Cloud Autodesk Docs Autodesk Dynamo Autodesk features Autodesk for Education Autodesk Forge Autodesk FormIt Autodesk Fusion Autodesk Fusion 360 Autodesk help Autodesk InfraWorks Autodesk Inventor Autodesk Inventor Frame Generator Autodesk Inventor iLogic Autodesk Knowledge Network Autodesk License Autodesk Maya Autodesk mistakes Autodesk Navisworks Autodesk news Autodesk plugins Autodesk productivity Autodesk Recap Autodesk resources Autodesk Revit Autodesk Software Autodesk support ecosystem Autodesk Takeoff Autodesk Tips Autodesk training Autodesk tutorials Autodesk update Autodesk Upgrade Autodesk Vault Autodesk Video Autodesk Viewer Automate automate drawing updates Automate Printing automate publishing automate repetitive tasks Automated Design automated publishing Automated Sheets Automation Automation in AutoCAD Automation Tools Automation Tutorial automotive design automotive visualization Backup Basic Commands Basics batch drawing validation Batch Plot Batch Plotting Beginner beginner CAM Beginner Tips beginner tutorial beginners guide Bend Tools Best Practices Big Data BIM BIM 360 BIM Challenges BIM collaboration BIM Compliance BIM Coordination BIM Data BIM Design BIM Efficiency BIM for Infrastructure BIM Implementation BIM Library BIM Management BIM modeling BIM software BIM Standards BIM technology BIM Tips BIM tools BIM Trends BIM workflow Block Editor Block Management Block Organization Boolean Operations Building design Building Design Software Building Efficiency Building Maintenance building modeling Building Systems Building Technology business tools ByLayer CAD CAD API CAD assembly CAD Automation CAD best practices CAD Blocks CAD CAM CAD collaboration CAD commands CAD comparison CAD consistency CAD Customization CAD Data Management CAD Design CAD drawing checks CAD efficiency CAD errors CAD Evolution CAD file management CAD File Size Reduction CAD Integration CAD Learning CAD libraries CAD line thickness CAD management CAD Migration CAD mistakes CAD modeling CAD Optimization CAD organization CAD Oversight CAD plugins CAD Productivity CAD project management CAD Projects CAD Rendering CAD Scripting CAD Security CAD Sheet Management CAD sheet sets CAD Shortcuts CAD Skills CAD software CAD software 2026 CAD software training CAD standardization CAD standards CAD Tables CAD team CAD teams CAD technology CAD templates CAD Tips CAD Tools CAD Tracking CAD tricks CAD Tutorial CAD version control CAD workflow CAD workflow optimization CAD workflows CAM CAM Best Practices CAM for beginners CAM Optimization CAM simulation CAM strategies CAM Tips CAM tutorial CAM Workflow car design software Case Study central hub Central Hub Solutions centralized commands centralized documentation centralized management Centralized Sheet Set centralizing CAD CEO Guide CG Workflow CGI CGI design Character Animation Character Rig Character Rigging cinematic lighting Civil 3D Civil 3D hidden gems Civil 3D productivity Civil 3D tips civil design software civil engineering Civil engineering software Clash Detection Class-A surfacing clean CAD file cleaning command client engagement Cloth Simulation Cloud CAD cloud CAD storage Cloud Collaboration Cloud design platform Cloud Engineering Cloud Management Cloud Storage Cloud-Based CAD Cloud-First CNC CNC machining collaboration collaboration in CAD Collaboration Tools Collaborative CAD collaborative design Collaborative Drafting color management command abbreviations Complex Projects Complex Renovation concept car conceptual workflow Connected Design construction Construction Analytics Construction Automation Construction BIM Construction Cloud construction documentation construction drawings construction management Construction Phases Construction Planning Construction Project Construction Projects Construction Scheduling Construction Technology construction tools construction tracking Contractor contractor tools Contractor Workflow Contraints corridor design Cost Effective Design cost estimation Create resizable blocks Creative Teams creative tools CTB CTB STB Custom Hatch custom scripts custom tool palettes Custom visual styles Cutting Parameters Cybersecurity Data Backup Data Extraction data management Data Protection Data Reference Data Security Data Shortcut deadline tracking Demolition Design Design Automation Design Career Design Collaboration Design Comparison Design consistency Design Coordination Design Documentation design efficiency Design Engineering design errors Design Hacks Design Innovation design management design optimization Design Options Design Oversight design productivity design review Design Reviews design revisions Design Rules design software design software tips design standardization design standards Design Teams Design Technology design templates design tips Design Tools design tracking Design Workflow design-to-construction Designer designer hacks Designer Tools Designer Workflow Digital Art Digital Assets Digital Construction Digital Construction Technology Digital Content Digital Design Digital Drafting digital drawing Digital engineering digital fabrication Digital Library Digital Manufacturing digital marketing digital takeoff Digital Thread Digital Tools Digital Transformation Digital Twin Digital Twins digital workflow dimension dimension styles dimensioning Disaster Recovery document management Document Organization Documentation drafting drafting automation Drafting Efficiency Drafting productivity Drafting Shortcuts Drafting Standards Drafting Tips drafting tools Drafting Workflow Drawing Drawing Accuracy Drawing Automation drawing consistency drawing management Drawing Organization drawing revisions Drawing standards drawing templates drawing tips Dref DWG files DXF Export Dynamic Block Dynamic Block AutoCAD Dynamic Blocks dynamic data management Dynamic doors Dynamic windows Dynamics Dynamics Simulation Dynamo Dynamo automation early stage design eco design editing commands Efficiency efficient CAD efficient project management Electrical Systems Emerging Features Energy Analysis energy efficiency Energy Simulation Engineering Engineering Automation engineering CAD engineering data Engineering Design Engineering Documentation Engineering Drawing engineering drawings engineering efficiency Engineering Innovation Engineering Productivity engineering projects Engineering Skills engineering software Engineering Technology engineering tips engineering tools Engineering Tools 2025 Engineering Workflow Error Reduction Excel Export Workflow Express Tools External Reference Fabric Simulation facial animation Facial Rigging Facility Management Families Fast Structural Design faster delivery Field Documentation file auditing File Management file naming File Optimization File Recovery Fire Flame flange tips flat pattern Fluid Effects Fluid Simulation Forge Development Forge Viewer FreeCAD Fusion 360 Fusion 360 API Fusion 360 guide Fusion 360 Tips Fusion 360 tutorial Future of Design Future Skills Game Design Game Development Game Effects Gamification Generative Design Geospatial Data GIS Global design teams global illumination GPU Acceleration grading optimization Graph Editor Green Architecture green building Green Technology Grips Handoff Hatch Patterns HDRI health check Healthcare Facilities heavy CAD file Heavy CAD Files heritage building conservation hidden commands Hospital Design Hub Workflows HVAC HVAC Design Tools HVAC Engineering HVAC Optimization Hydraulic Modeling IK/FK iLogic Import Workflow Industrial Design Industry 4.0 Infrastructure infrastructure design Infrastructure Monitoring Infrastructure Planning Infrastructure Technology InfraWorks innovation Insight Intelligent AutoCAD Hub Intelligent automation Intelligent Design intelligent modeling Intelligent Repetition Control Intelligent Sheet Management Intelligent Sheet Sets intelligent tools Intelligent Workflow Interactive Design interactive presentation Interior Design Inventor Inventor API Inventor Drawing Template Inventor Frame Generator Inventor Graphics Issues Inventor IDW Inventor Tips Inventor Tutorial IoT ISO 19650 joints Keyboard Shortcuts keyframe animation Keyframe generation Landscape Design Large Projects Laser Scan layer conventions Layer Management Layer Organization layer standards layouts Learn AutoCAD Legacy CAD Library components Licensing light techniques Lighting Lighting and shading Lighting Techniques lineweight Linked Models Liquid Machine Learning Machine Learning in CAD Machine Optimization Machining Efficiency machining productivity Macros maintenance command Manage multiple projects from a single hub with a centralized project management system that improves collaboration Management manual plotting manufacturing Manufacturing Innovation Manufacturing Technology Mapping Technology marketing visuals master sheet index Material Creation Material Libraries Maya Maya Animation Maya character animation Maya lighting Maya Python Maya Rigging Maya Shader Maya Tips Maya tutorial Maya Workflow measurement Mechanical Design Mechanical Engineering Media & Entertainment MEP MEP Modeling Mesh-to-BIM Metal Fabrication Metal Structure milestone tracking modal analysis Model Clarity Model Management Model Optimization model space Modeling Secrets Modular Housing Monitoring Progress Motion capture Motion Design motion graphics motion simulation MotionBuilder Multi Office Workflow multi-axis machining Multi-Body Modeling Multi-Project Multi-Project Management Multi-User Environment multileader multiple sheet sets naming convention Navisworks Navisworks Best Practices nCloth Net Zero Design New Construction ObjectARX .NET API Open Source CAD Optimization Organization OVERKILL OVERKILL AutoCAD Override Layers Page Setup Palette paper space parametric assembly Parametric Components Parametric Constraints parametric design parametric family Parametric Modeling particle effects particle systems PDF PDF Export PDM system Personal Brand Phase Filters Phasing photorealism Photorealistic photorealistic render PlanGrid plot automation Plot Settings Plot Style Plot Style AutoCAD plot styles Plotting Plotting automation Plugin Tutorial Plumbing Design PM Tools point cloud Portfolio Post Construction Post-Processing Practice Drawing precision machining preconstruction workflow predictive analysis predictive animation Predictive Maintenance Predictive rigging Prefabrication Preloaded families Presentation-ready visuals Printing Printing Quality Problem Solving Procedural animation procedural motion Procedural Rig Procedural Textures Product Design Product Development product lifecycle product rendering Product Visualization Productivity productivity and workflow efficiency. productivity tips productivity tools Professional 3D design Professional CAD Professional Drawings professional printing Professional Tips Professional Workflow progress management Project Accuracy project automation Project Collaboration project consistency Project Coordination project dashboard Project Documentation project efficiency Project Goals project management Project Management Tools project milestones Project Monitoring project organization Project Oversight project planning Project Progress project quality project timeline project tracking Project Visualization project workflow PTC Creo Publish Drawings PURGE PURGE AutoCAD Rail Transit Rapid Prototyping Realism realistic rendering realistic scenes ReCap Redshift Shader reduce CAD errors reduce CAD file size Reduce Errors reduce manual updates Reducing redundancy Redundant Work Render Render Optimization Render Passes Render Quality Render Settings render tips Rendering rendering engine Rendering Engines Rendering Optimization rendering settings rendering software Rendering Techniques Rendering Tips Rendering Workflow RenderMan Renewable Energy Renovation Project Renovation Workflow repetition-free workflow repetitive drawing Repetitive Elements repetitive-free Reports Resizable Block restoration workflow Reusable Components Revision Control Revision Management Revision Tracking Revit Revit add-ins Revit API Revit automation Revit Best Practices Revit Collaboration Revit Documentation Revit Family Revit integration Revit MEP Revit Performance Revit Phasing Revit plugin Revit Plugins Revit Scripting Revit skills Revit Standards Revit Strategies Revit Structure Revit Tags Revit Template Revit templates Revit Tips Revit tutorial Revit Workflow Ribbon Rigging Rigid Body robotics ROI Room planning save hours of work Save Time save time CAD Scale Autodesk Schedules screen Scripts Sculpting Secure Collaboration Sensor Data Shader Networks sheet management Sheet Metal Sheet Metal Design Sheet Metal Tricks Sheet organization sheet set Sheet Set Automation Sheet Set Efficiency Sheet Set fields Sheet Set Management Sheet Set Manager Sheet Set Optimization Sheet Set Organization Sheet Set Software Sheet Set Standards Sheet Set Tips Sheet Set Tools Sheet Sets sheet sets workflow Sheets shortcut keys Shortcuts Siemens NX Simulation simulation tools Sketch Sketching Tricks Small Firms Smart Architecture Smart Block Smart Building Design Smart CAD smart CAD tools Smart City Smart Design smart dimensioning Smart Engineering Smart Factory Smart Infrastructur Smart Project Smart Sheet Management Smart Sheet Set Tools Smart Sheet Sets Smart Workflows Smoke Soft Body Software Compliance software ecosystem Software Management Software Trends software troubleshooting Software Update Solar Energy Solar Panels SolidWorks Space planning SSM standard part libraries Standardization Standardize standardized templates Startup Design static stress STB Steel Structure Design Stress-Free Structural Design Structural Modeling Structural Optimization subscription model Subscription Value surface finish Surface Modeling sustainability sustainable design Sustainable Manufacturing system performance T-Spline task management team collaboration Team Efficiency Team Productivity Team Projects team training guide technical documentation Technical Drawing technical support Template management Template Setup Template usage templates text settings text style Texture Mapping Texturing thermal analysis time efficiency Time Management time saving tools time savings time-saving time-saving tools Title Block title block automation Title Blocks Tool Libraries Tool Management Tool Palette Guide toolbar toolpath Toolpath Optimization Toolpaths Topography Track Track changes Troubleshooting Tutorial Tutorials Unfolding Techniques urban planning User Interface (UI) UV Mapping UV Unwrap V-Ray Vault Best Practices Vault Lifecycle Vault Mistakes Vector Plotting vehicle modeling version control VFX View Filters Viewport configuration viewports Virtual Environments virtual reality visual effects visualization workflow VR VR Tools VRED Water Infrastructure Water Management Weight Painting What’s New in Autodesk Wind Energy Wind Turbines Workbook workflow Workflow Automation workflow efficiency Workflow Optimization Workflow Tips Worksets Worksharing Workspace XLS Xref Xrefs เขียนแบบ