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
- using System;
- using System.Collections.Generic;
-
- namespace DwgCustomProps
- {
- public enum CustomPropertyValueType
- {
- Integer=0,
- RealNumber=1,
- Text=2,
- Date=3,
- Time=4,
- DateAndTime=5,
- YesNo=6,
- }
-
- public class CustomProperty
- {
- public string Name { set; get; }
- public CustomPropertyValueType ValueType { set; get; }
- public string FormatString { set; get; }
- public object Value { set; get; }
-
- public CustomProperty()
- {
- Name = "";
- FormatString = "";
- ValueType = CustomPropertyValueType.Text;
- }
-
- //Read-only property. Since custom property's value
- //is very possibly used as text string for update
- //drawing content, such as title block, hence this
- //read-only property
- public string ValueString
- {
- get
- {
- string val = "";
-
- switch (this.ValueType)
- {
- case CustomPropertyValueType.RealNumber:
- try
- {
- if (Value != null)
- {
- double num = Convert.ToDouble(Value);
- val = FormatString.Length > 0 ?
- num.ToString(FormatString) :
- num.ToString();
- }
- }
- catch { }
- break;
- case CustomPropertyValueType.Text:
- try
- {
- if (Value != null)
- {
- val = Value.ToString();
- }
- }
- catch { }
- break;
- case CustomPropertyValueType.Date:
- try
- {
- if (Value != null)
- {
- DateTime d = Convert.ToDateTime(Value);
- val = FormatString.Length > 0 ?
- d.ToString(FormatString) :
- d.ToShortDateString();
- }
- }
- catch { }
- break;
- case CustomPropertyValueType.Time:
- try
- {
- if (Value != null)
- {
- DateTime t = Convert.ToDateTime(Value);
- val = FormatString.Length > 0 ?
- t.ToString(FormatString) :
- t.ToShortTimeString();
- }
- }
- catch { }
- break;
- case CustomPropertyValueType.DateAndTime:
- try
- {
- if (Value != null)
- {
- DateTime dt = Convert.ToDateTime(Value);
- val = FormatString.Length > 0 ?
- dt.ToString(FormatString) :
- dt.ToString();
- }
- }
- catch { }
- break;
- case CustomPropertyValueType.YesNo:
- try
- {
- if (Value != null)
- {
- bool b = Convert.ToBoolean(Value);
- val = b ? "Yes" : "No";
- }
- }
- catch { }
- break;
- default:
- try
- {
- if (Value != null)
- {
- val = Convert.ToInt32(Value).ToString();
- }
- }
- catch { }
- break;
- }
-
- return val;
- }
- }
-
- //This read-only property can be used for showing as property
- //value type, for example, as column header text, when custom
- //property data is shown in tabular format
- public string ValueTypeString
- {
- get
- {
- string str = "";
-
- switch (this.ValueType)
- {
- case CustomPropertyValueType.RealNumber:
- str = "Real Number";
- break;
- case CustomPropertyValueType.Text:
- str = "Text";
- break;
- case CustomPropertyValueType.Date:
- str = "Date Only";
- break;
- case CustomPropertyValueType.Time:
- str = "Time Only";
- break;
- case CustomPropertyValueType.DateAndTime:
- str = "Date and Time";
- break;
- case CustomPropertyValueType.YesNo:
- str = "Yes or No";
- break;
- default:
- str = "Integer";
- break;
- }
-
- return str;
- }
- }
-
-
- }
-
- public class CustomProperties : Dictionary<string, CustomProperty>
- {
-
- }
- }
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
- public interface ICustomPropertiesFactory
- {
- CustomProperties GetCustomPropertySettings(object settingSourceInfo);
- }
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
- <?xml version="1.0" encoding="utf-8" ?>
- <CustomProperties>
- <CustomProperty name="ProjectNumber" valueType="Text" formatString="" />
- <CustomProperty name="DrawnBy" valueType="Text" formatString="" />
- <CustomProperty name="CheckedBy" valueType="Text" formatString="" />
- <CustomProperty name="DrawnDate" valueType="Date" formatString="yyyy-MM-dd" />
- <CustomProperty name="CheckedDate" valueType="Date" formatString="yyyy-MM-dd" />
- <CustomProperty name="ClientName" valueType="Text" formatString="" />
- <CustomProperty name="ProjectName" valueType="Text" formatString="" />
- </CustomProperties>
Here is the code that implements the interface ICustomPropertiesFacotry:
Code Snippet
- using System;
- using System.IO;
- using System.Xml;
-
- namespace DwgCustomProps
- {
- public interface ICustomPropertiesFactory
- {
- CustomProperties GetCustomPropertySettings(object settingSourceInfo);
- }
-
- public class CustomPropertiesXmlFactory : ICustomPropertiesFactory
- {
- public CustomProperties GetCustomPropertySettings(object sourceInfo)
- {
- //Validat source Xml file
- string filePath = ValidateInput(sourceInfo);
-
- CustomProperties settings = new CustomProperties();
-
- XmlDocument xmlDoc = new XmlDocument();
- xmlDoc.Load(filePath);
-
- XmlNode root = xmlDoc.GetElementsByTagName("CustomProperties")[0];
- foreach (XmlNode node in root.ChildNodes)
- {
- CustomProperty setting = new CustomProperty();
-
- setting.Name = node.Attributes["name"].Value;
- setting.FormatString = node.Attributes["formatString"].Value;
- setting.Value=null;
- string t = node.Attributes["valueType"].Value;
- switch (t)
- {
- case "RealNumber":
- setting.ValueType=CustomPropertyValueType.RealNumber;
- break;
- case "Text":
- setting.ValueType=CustomPropertyValueType.Text;
- break;
- case "Date":
- setting.ValueType=CustomPropertyValueType.Date;
- break;
- case "Time":
- setting.ValueType=CustomPropertyValueType.Time;
- break;
- case "DateAndTime":
- setting.ValueType=CustomPropertyValueType.DateAndTime;
- break;
- case "YesNo":
- setting.ValueType=CustomPropertyValueType.YesNo;
- break;
- default:
- setting.ValueType=CustomPropertyValueType.Integer;
- break;
- }
-
- settings.Add(setting.Name,setting);
- }
-
- return settings;
- }
-
- #region private methods
-
- private string ValidateInput(object input)
- {
- string filePath = "";
-
- try
- {
- filePath = (string)input;
- }
- catch
- {
- throw new ArgumentException(
- "invalid input parameter: not file path to a Xml file.");
- }
-
- if (!File.Exists(filePath))
- {
- throw new FileNotFoundException(
- "Cannot find Xml file: \"" + filePath + "\".");
- }
-
- if (!Path.GetExtension(filePath).ToUpper().EndsWith("XML"))
- {
- throw new FileNotFoundException(
- "Invalid file type: must be a *.xml file.");
- }
-
- return filePath;
- }
-
- #endregion
- }
- }
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
- using System;
- using System.Collections;
- using System.Collections.Generic;
- using System.Linq;
- using Autodesk.AutoCAD.DatabaseServices;
-
- namespace DwgCustomProps
- {
- public class MyDrawingProperties : DatabaseSummaryInfoBuilder
- {
- private ICustomPropertiesFactory _factory = null;
- private CustomProperties _customProps = null;
- private Database _db;
-
- public MyDrawingProperties(object settingSource, Database db)
- : base(db.SummaryInfo)
- {
- _db = db;
- Initialize(settingSource);
- }
-
- public MyDrawingProperties(object settingSource,
- Database db, bool attachMyProps)
- : base(db.SummaryInfo)
- {
- _db = db;
- Initialize(settingSource);
- if (attachMyProps)
- {
- SetCustomProperties(_customProps, true);
- }
- }
-
- #region public properties
-
- public string[] CustomPropertyNames
- {
- get
- {
- return (from p in _customProps
- orderby p.Key ascending select p.Key).ToArray();
- }
- }
-
- public CustomProperty this[string key]
- {
- get
- {
- return _customProps[key];
- }
- }
-
- public CustomProperties MyCustomProperties
- {
- get { return _customProps; }
- }
-
- #endregion
-
- #region public methods
-
- public string GetCustomPropertyValueString(string key)
- {
- CustomProperty prop = this[key];
- return prop.ValueString;
- }
-
- public void RemoveCustomProperty(string key)
- {
- if (RemoveProperty(key))
- {
- _db.SummaryInfo = this.ToDatabaseSummaryInfo();
- }
- }
-
- public void RemoveMyCustomProperties()
- {
- bool removed = false;
-
- foreach (KeyValuePair<string, CustomProperty> item in _customProps)
- {
- if (RemoveProperty(item.Value.Name))
- {
- if (!removed) removed = true;
- }
- }
-
- if (removed) _db.SummaryInfo = this.ToDatabaseSummaryInfo();
- }
-
- public void RemoveForeignCustomProperties()
- {
- bool removed = false;
- bool go = true;
- while (go)
- {
- go = false;
- foreach (DictionaryEntry entry in this.CustomPropertyTable)
- {
- string key = entry.Key.ToString();
- var propItems = _customProps.Where
- (p => p.Key == key).FirstOrDefault();
-
- if (propItems.Value != null)
- {
- this.CustomPropertyTable.Remove(entry.Key);
- if (!removed) removed = true;
- go = true;
- break;
- }
- }
- }
-
- if (removed) _db.SummaryInfo = this.ToDatabaseSummaryInfo();
- }
-
- public void RemoveAllCustomProperties()
- {
- this.CustomPropertyTable.Clear();
- _db.SummaryInfo = this.ToDatabaseSummaryInfo();
- }
-
- public void ApplyCustomProperties()
- {
- SetCustomProperties(_customProps);
- _db.SummaryInfo = this.ToDatabaseSummaryInfo();
- }
-
- public void ApplyCustomProperties(
- ICustomPropertyValueProvider custPropValueProvider)
- {
- Dictionary<string, object> props=
- custPropValueProvider.GetCustomPropertyValues(
- _db.Filename, _customProps);
- if (props == null) return;
-
- foreach (KeyValuePair<string, object> item in props)
- {
- this[item.Key].Value = item.Value;
- }
-
- this.ApplyCustomProperties();
- }
-
- #endregion
-
- #region private methods
-
- private void Initialize(object settingSource)
- {
- LoadSettings(settingSource);
- GetCurrentPropertyValues();
- }
-
- private void LoadSettings(object settingSource)
- {
- string source = settingSource.ToString();
- if (source.ToUpper().EndsWith(".XML"))
- {
- _factory = new CustomPropertiesXmlFactory();
- }
-
- if (_factory != null)
- {
- _customProps =
- _factory.GetCustomPropertySettings(settingSource);
- }
- else
- {
- throw new NotSupportedException(
- "Setting source is not supported.");
- }
- }
-
- private void GetCurrentPropertyValues()
- {
- foreach (DictionaryEntry ent in CustomPropertyTable)
- {
- string key = ent.Key.ToString();
- try
- {
- CustomProperty prop = this[key];
- object val = ent.Value;
-
- switch (prop.ValueType)
- {
- case CustomPropertyValueType.RealNumber:
- try
- {
- double num = Convert.ToDouble(val);
- prop.Value = num;
- }
- catch
- {
- prop.Value = null;
- }
- break;
- case CustomPropertyValueType.Text:
- prop.Value = val.ToString();
- break;
- case CustomPropertyValueType.Date:
- try
- {
- DateTime d = Convert.ToDateTime(val);
- prop.Value = val;
- }
- catch
- {
- prop.Value = null;
- }
- break;
- case CustomPropertyValueType.Time:
- try
- {
- DateTime t = Convert.ToDateTime(prop.Value);
- prop.Value = val;
- }
- catch
- {
- prop.Value = null;
- }
-
- break;
- case CustomPropertyValueType.DateAndTime:
- try
- {
- DateTime dt = Convert.ToDateTime(prop.Value);
- prop.Value = val;
- }
- catch
- {
- prop.Value = null;
- }
- break;
- case CustomPropertyValueType.YesNo:
- try
- {
- bool b = Convert.ToBoolean(prop.Value);
- prop.Value = val;
- }
- catch
- {
- prop.Value = null;
- }
- break;
- default:
- try
- {
- int i = Convert.ToInt32(prop.Value);
- prop.Value = i;
- }
- catch
- {
- prop.Value = null;
- }
- break;
- }
- }
- catch { }
- }
- }
-
- private void SetCustomProperty(
- CustomProperty prop, bool createIfNotFound)
- {
- try
- {
- this.CustomPropertyTable[prop.Name] = prop.ValueString;
- }
- catch
- {
- if (createIfNotFound)
- {
- this.CustomPropertyTable.Add(prop.Name, prop.ValueString);
- }
- }
- }
-
- private void SetCustomProperties(
- CustomProperties props, bool createIfNotFound)
- {
- _customProps = props;
-
- foreach (KeyValuePair<string, CustomProperty> item in props)
- {
- SetCustomProperty(item.Value, createIfNotFound);
- }
- }
-
- private void SetCustomProperties(CustomProperties props)
- {
- SetCustomProperties(props, true);
- }
-
- private bool RemoveProperty(string key)
- {
- bool removed = false;
-
- foreach (DictionaryEntry entry in this.CustomPropertyTable)
- {
- if (entry.Key.ToString() == key)
- {
- this.CustomPropertyTable.Remove(entry.Key);
- removed = true;
- break;
- }
- }
-
- return removed;
- }
-
- #endregion
- }
- }
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:
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
- using System.Collections.Generic;
-
- namespace DwgCustomProps
- {
- public interface ICustomPropertyValueProvider
- {
- Dictionary<string, object> GetCustomPropertyValues(string fileName,
- CustomProperties customProps);
- }
-
- public class CustomPropertyValueManualProvider :
- ICustomPropertyValueProvider
- {
- public Dictionary<string, object> GetCustomPropertyValues(
- string fileName,
- CustomProperties customProps)
- {
- Dictionary<string, object> props = null;
-
- using (dlgMyProperties dlg = new dlgMyProperties())
- {
- dlg.SetGridView(customProps);
- if (Autodesk.AutoCAD.ApplicationServices.
- Application.ShowModalDialog(dlg) ==
- System.Windows.Forms.DialogResult.OK)
- {
- props = dlg.MyPropertyValues;
- }
- }
-
- return props;
- }
- }
- }
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.