Saturday, November 12, 2011

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.

6 comments:

B-) Jolley said...

This seems like you might be able to help me. I want to know how I can add new custom drawing props in the middle of a long list of them I have without deleting and reinserting them all. Is that possible through code?

Anonymous said...


thank you for u good work, pls can u put that file in downloadable

Norman Yuan said...

Source code is now downloadable. It was originally a Visual Studio 2010 solution. I have converted it to Visual Studio 2012 solution, since I do not use Visual Studio 2010 any more.

Anonymous said...

thank you so much

Steven Smith said...

Nowadays, finding a reliable real estate company is one of the challenging factors. As everyone says they are professional, but can't prove that with their work. The company Immobilienverwaltung Lüneburg can ensure you everything with their planning, dedication and communication with you. You can find Regular property inspection, including visual inspection, Supervision of craftsmen and other service providers, dunning and litigation, utility bill and so on.

Miroslav said...

Again you save my life. Thank you sir for sharing this.

Followers

About Me

My photo
After graduating from university, I worked as civil engineer for more than 10 years. It was AutoCAD use that led me to the path of computer programming. Although I now do more generic business software development, such as enterprise system, timesheet, billing, web services..., AutoCAD related programming is always interesting me and I still get AutoCAD programming tasks assigned to me from time to time. So, AutoCAD goes, I go.