Wednesday, March 23, 2011

Plugging Asynchronous Task Execution Into AutoCAD

There may be times when a custom AutoCAD application needs to perform a lengthy execution that mainly deals with external resources, such as checking remote resources for available update to certain applications/data. If the lengthy execution has nothing to do with drawing document/database opened in current AutoCAD session, it can be run in a separate thread other than AutoCAD UI thread, so AutoCAD would not be in a non-responsive state while the lengthy execution is running.

In this article, I demonstrate a component - AsyncTaskManager - that runs lengthy processes in background thread. With this component, a developer would focus his/her effort on developing the task itself, which would be executed in background thread once being plugged into the component.

I used a Windows system tray icon (System.Windows.Form.NotifyIcon) to prompt user for the start/end of each task being executed asynchronously.

Let take a look to the code.

Firstly, I defined an Interface ITask that represents a unified interface of possible tasks that can be executed by the AsyncTaskManager:

namespace StartupAsyncTask
{
    public interface ITask
    {
        string TaskName { get; }
        string CompletionMessage { get; }
        object ResultData { get; }
        bool Successful { get; }
        void Execute();
    }
}

In this interface, property TaskName is used to identify a task being executed and also used as balloon message title of system tray icon. CompletionMessage is used as balloon message text of the system tray icon. ResultData is possible data generated by the task during its execution.

Then, here is a class that actually dispatch tasks into background thread and activate system tray icon to give user feedback on the task execution (started/ended):

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
 
namespace StartupAsyncTask
{
    public class AsyncTaskRunner : IDisposable
    {
        private int _currentTaskCount = 0;
        private List<ITask> _tasks = null;
 
        private NotifyIcon _notifyIcon = null;
        private System.ComponentModel.BackgroundWorker _backWorker = null;
        private System.Timers.Timer _timer = null;
 
        public AsyncTaskRunner()
        {
 
        }
 
        public event System.EventHandler AllTasksCompleted;
        public event TaskCompletedEventHandler TaskCompleted;
 
        public void ExecuteTasks(List<ITask> tasks)
        {
            //Create system tray icon
            CreateNotifyIcon();
 
            _tasks = tasks;
            if (_tasks.Count == 0) return;
 
            //Run first task
            _currentTaskCount = 0;
            RunTask(_tasks[_currentTaskCount]);
        }
 
        private void RunTask(ITask task)
        {
            OnTaskStarted(task);
 
            //Configure BackgroundWorker component
            _backWorker = new System.ComponentModel.BackgroundWorker();
            _backWorker.DoWork += 
                new System.ComponentModel.DoWorkEventHandler(backWorker_DoWork);
            _backWorker.RunWorkerCompleted += 
                new System.ComponentModel.RunWorkerCompletedEventHandler(
                    backWorker_RunWorkerCompleted);
 
            //Run task as backgroud thread
            _backWorker.RunWorkerAsync(task);
        }
 
        private void backWorker_RunWorkerCompleted(
            object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
        {
            if (!e.Cancelled)
            {
                ITask task = e.Result as ITask;
                OnTaskComleted(task);
 
                if (TaskCompleted != null)
                {
                    TaskCompleted(this, 
                        new TaskCompletedEventArgs(task.TaskName, task.ResultData));
                }
            }
 
            _backWorker.DoWork -= 
                new System.ComponentModel.DoWorkEventHandler(backWorker_DoWork);
            _backWorker.RunWorkerCompleted -= 
                new System.ComponentModel.RunWorkerCompletedEventHandler(
                    backWorker_RunWorkerCompleted);
            _backWorker.Dispose();
            _backWorker = null;
        }
 
        private void backWorker_DoWork(
            object sender, System.ComponentModel.DoWorkEventArgs e)
        {
            ITask task = e.Argument as ITask;
            task.Execute();
            e.Result = task;
        }
 
        private void OnTaskStarted(ITask task)
        {
            ShowNotifyIconBalloon(
                task.TaskName, "Start " + task.TaskName + "...", 2000, true);  
        }
 
        private void OnTaskComleted(ITask task)
        {
            _currentTaskCount++;
 
            ShowNotifyIconBalloon(
                task.TaskName, task.CompletionMessage, 2000,task.Successful);
 
            //Wait 2 seconds to either go to next task, or dispose the NotifyIcon
            _timer = new System.Timers.Timer();
            _timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed);
            _timer.Interval = 2000;
            _timer.Start();
 
        }
 
        void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            _timer.Stop();
            _timer.Dispose();
 
            if (_currentTaskCount < _tasks.Count)
            {
                //Run next task
                RunTask(_tasks[_currentTaskCount]);
            }
            else
            {
                if (AllTasksCompleted != null)
                {
                    AllTasksCompleted(this, EventArgs.Empty);
                }
            }
        }
 
        private void CreateNotifyIcon()
        {
            _notifyIcon = new NotifyIcon();
            _notifyIcon.Icon=
                (Icon)Properties.Resources.ResourceManager.GetObject("AcadStartUp");
            _notifyIcon.Visible=true;
        }
 
        private void ShowNotifyIconBalloon(
               string title, string text, int timeout, bool successful)
        {
            _notifyIcon.BalloonTipTitle = title;
            _notifyIcon.BalloonTipText = text;
            if (successful)
            {
                _notifyIcon.BalloonTipIcon = System.Windows.Forms.ToolTipIcon.Info;
            }
            else
            {
                _notifyIcon.BalloonTipIcon = System.Windows.Forms.ToolTipIcon.Error;
            }
            _notifyIcon.ShowBalloonTip(timeout);
        }
 
 
        public void Dispose()
        {
            if (_notifyIcon != null)
            {
                _notifyIcon.Dispose();
            }
        }
    }
 
    public delegate void TaskCompletedEventHandler(
                object sendr, TaskCompletedEventArgs e);
 
    public class TaskCompletedEventArgs : System.EventArgs
    {
        private object _outputData;
        private string _taskName;
 
        public TaskCompletedEventArgs(string taskName, object outputData)
        {
            _taskName = taskName;
            _outputData = outputData;
        }
 
        public string TaskName
        {
            get { return _taskName; }
        }
 
        public object OutputData
        {
            get { return _outputData; }
        }
    }
}

As you can see, this class implements IDisposable interface, so that the System.Windows.Forms.NotifyIcon object used in this class can be disposed properly. The only public method ExecuteTasks() takes a list of ITask as argument, and execute the the tasks one by one sequentially. However, the sequence of execution i s not done in a "foreach..." or "while..." loop, because each task is sent to a background thread for the execution. I used RunWorkerCompleted event handler to count tasks being executed and start execution on next task. Also, in order for the system tray icon to have enough time to show a balloon message to user, I user a timer to display next task for a couple of seconds. This class will raise an event when each task execution is completed and raise another event when all tasks are completed.

Now the class AsyncTaskManager pulls things together:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
 
namespace StartupAsyncTask
{
    public class AsyncTaskManager
    {
        private List<ITask> _tasks = null;
        private AsyncTaskRunner taskRunner = null;
        private Dictionary<string, object> _resultData = null;
 
 
        public AsyncTaskManager()
        {
            InitializeTasks();
        }
 
        public event System.EventHandler TasksExecutionCompleted;
 
        public Dictionary<string, object> ResultData
        {
            get { return _resultData; }
        }
 
        public void RunTasks()
        {
            _resultData = new Dictionary<string, object>();
 
            taskRunner = new AsyncTaskRunner();
            taskRunner.TaskCompleted += 
                new TaskCompletedEventHandler(taskRunner_TaskCompleted);
            taskRunner.AllTasksCompleted += 
                new EventHandler(taskRunner_AllTasksCompleted);
 
            taskRunner.ExecuteTasks(_tasks);
        }
 
        public void RunTasks(List<ITask> tasks)
        {
            _tasks = tasks;
            RunTasks();
        }
 
        private void taskRunner_TaskCompleted(
            object sendr, TaskCompletedEventArgs e)
        {
            //Do something if necessary
        }
 
        private void taskRunner_AllTasksCompleted(
            object sender, EventArgs e)
        {
            taskRunner.Dispose();
 
            foreach (ITask t in _tasks)
            {
                if (t.ResultData != null)
                {
                    _resultData.Add(t.TaskName, t.ResultData);
                }
            }
 
            //Bubble up the event to AutoCAD calling process
            if (TasksExecutionCompleted != null)
            {
                TasksExecutionCompleted(this, EventArgs.Empty);
            } 
        }
 
        private void InitializeTasks()
        {
            //Get a task lists, hard coded here, 
            //It can also be set up in declarative style,
            //such as in acad.exe.config
            _tasks = new List<ITask>();
            _tasks.Add(new Task1());
            _tasks.Add(new Task2());
            _tasks.Add(new Task3());
        }
    }
}

This class simply holds tasks to be executed, calls AsyncTaskRunner's ExecuteTasks() method and stores possible data generated in task execution (in a Dictionary with task name as key).

Now let define a few tasks that will be executed by AsyncTaskManager. This what a developer can now focus his/her effort on without worrying how to do things in background thread.

Here are 3 ITask classes. For the simplicity, The classes do not do real thing other than to put the thread into sleep for a few seconds (to mimic a possible real world process that may takes a while to complete - that is the purpose to use background thread in most cases, right?).

using System.Text;
using System.Threading;
 
namespace StartupAsyncTask
{
    public class Task1 : ITask
    {
        private StringBuilder _errMsg = new StringBuilder();
        private bool _successful = false;
 
        public string TaskName
        {
            get { return "Check Available Update"; }
        }
 
        public string CompletionMessage
        {
            get { return _errMsg.ToString(); }
        }
 
        public bool Successful
        {
            get { return _successful; }
        }
 
        public object ResultData
        {
            get { return null; }
        }
 
        public void Execute()
        {
            _errMsg.Length = 0;
            _successful = true;
 
            //Do something
            DoTask();
        }
 
        private void DoTask()
        {
            Thread.Sleep(5000);
            _successful = false;
            _errMsg.Append("This startup task execution has failed!");
        }
    }
}


using System.Text;
using System.Threading;
 
namespace StartupAsyncTask
{
    public class Task2 : ITask
    {
        private StringBuilder _errMsg = new StringBuilder();
        private bool _successful = false;
 
        public string TaskName
        {
            get { return "Send Data To XXX Service"; }
        }
 
        public string CompletionMessage
        {
            get { return _errMsg.ToString(); }
        }
 
        public bool Successful
        {
            get { return _successful; }
        }
 
        public object ResultData
        {
            get { return null; }
        }
 
        public void Execute()
        {
            _errMsg.Length = 0;
            _successful = true;
 
            //Do something
            DoTask();
        }
 
        private void DoTask()
        {
            Thread.Sleep(5000);
            _errMsg.Append("This startup task has been completed successfully!");
        }
    }
}

using System.Collections.Generic;
using System.Text;
using System.Threading;
 
namespace StartupAsyncTask
{
    public class Task3 : ITask
    {
        private StringBuilder _errMsg = new StringBuilder();
        private bool _successful = false;
        private List<string> _returnData = null;
 
        public string TaskName
        {
            get { return "Retrieve Google Map Data"; }
        }
 
        public string CompletionMessage
        {
            get { return _errMsg.ToString(); }
        }
 
        public bool Successful
        {
            get { return _successful; }
        }
 
        public object ResultData
        {
            get { return _returnData; }
        }
 
        public void Execute()
        {
            _errMsg.Length = 0;
            _successful = true;
 
            _returnData = new List<string>();
 
            //Do something
            DoTask();
        }
 
        private void DoTask()
        {
            Thread.Sleep(10000);
            _errMsg.Append("This startup task has been completed successfully!");
 
            _returnData.AddRange(new string[] { "AAAA", "BBBB", "CCCC" });
        }
    }
}

Ideally, these ITask classes would be in their own project(s) and references the main project where ITask interface is in. So, if a new ITask class can be developed independently without affecting existing tasks.

Now, let take a look how to put the code in action in AutoCAD:

using System;
 
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.Runtime;
 
[assembly: ExtensionApplication(typeof(StartupAsyncTask.MyCommands))]
 
namespace StartupAsyncTask
{
    public class MyCommands : IExtensionApplication
    {
        #region IExtensionApplication Members
 
        private static frmGoogleData _frm = null;
 
        public void Initialize()
        {
            //If there are tasks to run on startup
            //RunAsyncTasks();
        }
 
        public void Terminate()
        {
 
        }
 
        #endregion
 
        [CommandMethod("DoTasks",CommandFlags.Session)]
        public static void RunAsyncTasks()
        {
            Document doc = Application.DocumentManager.MdiActiveDocument;
 
            if (doc != null)
            {
                doc.Editor.WriteMessage("\nStart tasks execution...\n");
            }
 
            try
            {
                AsyncTaskManager taskManager = new AsyncTaskManager();
                taskManager.TasksExecutionCompleted += 
                    new EventHandler(taskManager_TasksExecutionCompleted);
 
                //Run default tasks
                taskManager.RunTasks();
 
                //Or ===================================================
                //List<IStartupTask> tasks = new List<IStartupTask>();
                //tasks.Add(new Task1());
                //tasks.Add(new Task2());
                //taskManager.RunTasks(tasks);
                //======================================================
            }
            catch (System.Exception ex)
            {
                doc = Application.DocumentManager.MdiActiveDocument;
                if (doc != null)
                {
                    doc.Editor.WriteMessage(
                        "\nInitializing process error:\n" + ex.Message + "\n");
                }
            }
        }
 
        [CommandMethod("TaskData", CommandFlags.Session)]
        public static void ShowTaskData()
        {
            if (_frm != null)
            {
                Application.ShowModelessDialog(_frm);
            }
        }
 
        private static void taskManager_TasksExecutionCompleted(
            object sender, EventArgs e)
        {
            AsyncTaskManager taskManager = sender as AsyncTaskManager;
            if (taskManager != null)
            {
                if (taskManager.ResultData.Count > 0)
                {
                    if (taskManager.ResultData.ContainsKey("Retrieve Google Map Data"))
                    {
                        ShowTaskDataInForm(
                            taskManager.ResultData["Retrieve Google Map Data"]);
                    }
                }
            }
        }
 
        private static void ShowTaskDataInForm(object taskResultData)
        {
            if (_frm != null)
            {
                _frm.Dispose();
            }
 
            _frm = new frmGoogleData(taskResultData);
        }
    }
}

One will notice that a form is initialized if there is result data generated after task execution. For the simplicity, the form is very simple: only a label is place on the form the show the data:

using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
 
namespace StartupAsyncTask
{
    public partial class frmGoogleData : Form
    {
        public frmGoogleData()
        {
            InitializeComponent();
        }
 
        public frmGoogleData(object taskData)
        {
            InitializeComponent();
 
            SetData(taskData);
        }
 
        public void SetData(object taskData)
        {
            List<string> data = taskData as List<string>;
            if (data != null)
            {
                StringBuilder str = new StringBuilder();
                foreach (string s in data)
                {
                    str.Append(s + "\n");
                }
 
                lblData.Text = str.ToString();
            }
        }
 
        private void btnClose_Click(object sender, EventArgs e)
        {
            this.Visible = false;
        }
 
        private void frmGoogleData_FormClosing(object sender, FormClosingEventArgs e)
        {
            e.Cancel = true;
            this.Visible = false;
        }
    }
}

In the real world, the form should be designed according to the data generated by the task being executed, and the system tray icon's balloon message may prompt user for viewing task data in some way (maybe keeping the system tray icon for user to double-click to open a data viewing form would be a better option).

Go to this video clip to see the actual action of the code shown here. Pay attention to the lower right corner where Windows system tray is. As you can see, I deliberated setting a longer execution time for that 3 tasks. While the 3 tasks being executed in the background thread, I can keep drawing a polyline in AutoCAD. It worth pointing out, only the Execute() method of the tasks is done in background thread, while the task itself is created/initialized in the same thread as the AutoCAD, so if the task has a very complicated/heavy constructor to initialize and there a few tasks of this kind to be initialized, this initialization would be the normal load on the AutoCAD execution thread.

Extra interest: it may be possible to use Autodesk.AutoCAD.Windows.Pane in AutoCAD's status bar, instead of using Windows system tray icon as user prompting method.

Tuesday, February 15, 2011

Log AutoCAD's Plotting

One of the technical issues CAD managers oftern ask thenself is how do I tracking plottings done through AutoCAD.

There are many ways to do that. AutoCAD itself provides plot and publish logging (via Options dialog box->Plot and Publish tab). There be other software that can monitor printing tasks sent to one or more printers...

With AutoCD .NET API, we can fairly easily to build a custom plotting logging application, which is the topic of this article.

The Autodesk.AutoCAD.PlottingServices.PlotReactorManager class provides all the functionalities needed to track plotting from an running AutoCAD session. This class exposes a series of events that fire from the beginning of plotting to the end of plotting. Some plotting information that would be the interest of plot tracking is exposed through various EventArgs. Therefore, simply handling approriate events and retrieving needed plotting information, then saving the information into some sort of data store, these all a custom plot tracking application needs to do.

Let's look at the code.

First, I define a data class that hold plotting information I want to track when AutoCAD does a plotting:

using System;
using Autodesk.AutoCAD.DatabaseServices;
 
namespace TrackAcadPlotting
{
    public class PlotLog
    {
        public string DwgName { set; get; }
        public string DwgPath { set; get; }
        public int CopyCount { set; get; }
        public string PlotterName { set; get; }
        public DateTime PlottingTime { set; get; }
        public PlotPaperUnit PaperUnit { set; get; }
        public double PaperWidth { set; get; }
        public double PaperHeight { set; get; }
        public string MediaName { set; get; }
        public string UserName { set; get; }
        public string ComputerName { set; get; }
    }
}

The data store used to save plot tracking data can be different, from file (plain text, Xml...), to database. AutoCAD built-in plotting log is a plain text file, usually saved where the the plotted drawing is, if enabled. Of course these kind of plotting logs are not convenient for plotting management: they scattered everywhere. In general, file based store is not very ideal solution with this custom plot tracking application: the user who runs AutoCAD, thus the plot tracking application, must have read/write permission to the log file. So, it could be a security hole, if you want this plot tracking to be a serious CAD management tool. Ideally, the data store would be some sort of central database.

In order for this custom plot tracking application to be able to save plotting log to different data store, I created an Interface called IPlottingLogWriter. For different data store, we can write different code to save the plotting log, as long as the IPlottingLogWriter is implemented. In this article, the the simplicity, I implemented an file data store, called PlottingLogFileWriter to save plotting log to a text file. As aforementioned, I could implement the IPlottingLogWriter to save the data to database, or send the plotting log data to a WCF service to be saved somewhere. This way, no matter what data storage mechanism the application uses, the code to track plotting will not have to be changed.
Here is the Interface and its implementing:

The interface:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace TrackAcadPlotting
{
    public interface IPlottingLogWriter
    {
        void SavePlottingLog(PlotLog log);
    }
}


The interface implementing:


using System;
using System.IO;
 
namespace TrackAcadPlotting
{
    public class PlottingLogFileWriter : IPlottingLogWriter
    {
        private string _logFolder;
 
        public PlottingLogFileWriter(string folderPath)
        {
            _logFolder = folderPath;
 
            //Create log folder:
            if (!Directory.Exists(_logFolder))
            {
                Directory.CreateDirectory(_logFolder);
            }
        }
 
        #region IPlottingLogWriter Members
 
        public void SavePlottingLog(PlotLog log)
        {
            string fileName = _logFolder + 
                        "\\PlotTracking_" + 
                        DateTime.Today.ToString("yyyy-MM-dd") + 
                        ".txt";
 
            using (FileStream st = new FileStream(
                fileName, FileMode.Append, FileAccess.Write, FileShare.Write))
            {
                using (StreamWriter writer = new StreamWriter(st))
                {
                    writer.WriteLine(
                        "-------------Log begins------------------");
 
                    writer.WriteLine("Drawing: {0}", 
                        log.DwgName);
                    writer.WriteLine("File path: {0}", 
                        log.DwgPath);
                    writer.WriteLine("Plotting copy: {0}", 
                        log.CopyCount);
                    writer.WriteLine("Plotter name: {0}", 
                        log.PlotterName);
                    writer.WriteLine("Paper unit: {0}", 
                        log.PaperUnit.ToString());
                    writer.WriteLine("Paper width: {0}", 
                        log.PaperWidth.ToString("#######0.00") + "mm");
                    writer.WriteLine("Paper hight: {0}", 
                        log.PaperHeight.ToString("#######0.00") + "mm");
                    writer.WriteLine("Media name: {0}", 
                        log.MediaName);
                    writer.WriteLine("User name: {0}", 
                        log.UserName);
                    writer.WriteLine("CAD computer: {0}", 
                        log.ComputerName);
 
                    writer.WriteLine(
                        "-------------Log ends--------------------");
 
                    writer.Flush();
                    writer.Close();
                }
            }
        }
 
        #endregion
    }
}

Finally, this is the class "TrackPlotting" that does the actual work:

    1 using System;
    2 using System.Collections.Generic;
    3 using System.IO;
    4 
    5 using Autodesk.AutoCAD.ApplicationServices;
    6 using Autodesk.AutoCAD.EditorInput;
    7 using Autodesk.AutoCAD.PlottingServices;
    8 using Autodesk.AutoCAD.Geometry;
    9 using Autodesk.AutoCAD.Runtime;
   10 
   11 [assembly: CommandClass(typeof(TrackAcadPlotting.TrackPlotting))]
   12 [assembly: ExtensionApplication(typeof(TrackAcadPlotting.TrackPlotting))]
   13 
   14 namespace TrackAcadPlotting
   15 {
   16     public class TrackPlotting: IExtensionApplication
   17     {
   18         private static PlotReactorManager _plotManager;
   19         private static IPlottingLogWriter _logWriter;
   20         private static bool _cancelled=false;
   21         private static PlotLog _log=null;
   22 
   23         #region IExtensionApplication Members
   24 
   25         private List<string> _plotters = null;
   26 
   27         public void Initialize()
   28         {
   29             Document dwg = Autodesk.AutoCAD.ApplicationServices.
   30                 Application.DocumentManager.MdiActiveDocument;
   31 
   32             //Get plotter names to track
   33             _plotters = GetPlotterNames();
   34 
   35             try
   36             {
   37                 //Hard-coded log file folder path.
   38                 //In production, the file path could be
   39                 //set in acad.exe.confg or using other 
   40                 //configuing technique
   41                 //Note: here I instantiated an PlottingLogFileWriter
   42                 //I can also instantiate an PlottingLogSqlServerWriter, 
   43                 //if it is available
   44                 _logWriter = new PlottingLogFileWriter("E:\\Temp\\PlottingTrack");
   45             }
   46             catch
   47             {
   48                 if (dwg != null)
   49                 {
   50                     dwg.Editor.WriteMessage(
   51                         "\nInitializing plot tracking log writer faailed.");
   52                 }
   53 
   54                 return;
   55             }
   56 
   57             //Hook up event handlers
   58             _plotManager = new PlotReactorManager();
   59 
   60             _plotManager.BeginPlot += 
   61                 new BeginPlotEventHandler(PlotManager_BeginPlot);
   62 
   63             _plotManager.BeginDocument += 
   64                 new BeginDocumentEventHandler(PlotManager_BeginDocument);
   65 
   66             _plotManager.BeginPage += 
   67                 new BeginPageEventHandler(PlotManager_BeginPage);
   68 
   69             _plotManager.EndPage += 
   70                 new EndPageEventHandler(PlotManager_EndPage);
   71 
   72             _plotManager.EndDocument += 
   73                 new EndDocumentEventHandler(PlotManager_EndDocument);
   74 
   75             _plotManager.EndPlot += 
   76                 new EndPlotEventHandler(PlotManager_EndPlot);
   77 
   78             _plotManager.PageCancelled += 
   79                 new PageCancelledEventHandler(PlotManager_PageCancelled);
   80 
   81             _plotManager.PlotCancelled += 
   82                 new PlotCancelledEventHandler(PlotManager_PlotCancelled);
   83 
   84             if (dwg != null)
   85             {
   86                 dwg.Editor.WriteMessage("\nPlot tracking has been initialized.");
   87             }
   88         }
   89 
   90         public void Terminate()
   91         {
   92             //Remove event handlers
   93             _plotManager.BeginPlot -= 
   94                 new BeginPlotEventHandler(PlotManager_BeginPlot);
   95 
   96             _plotManager.BeginDocument -= 
   97                 new BeginDocumentEventHandler(PlotManager_BeginDocument);
   98 
   99             _plotManager.BeginPage -= 
  100                 new BeginPageEventHandler(PlotManager_BeginPage);
  101 
  102             _plotManager.EndPage -= 
  103                 new EndPageEventHandler(PlotManager_EndPage);
  104 
  105             _plotManager.EndDocument -= 
  106                 new EndDocumentEventHandler(PlotManager_EndDocument);
  107 
  108             _plotManager.EndPlot += 
  109                 new EndPlotEventHandler(PlotManager_EndPlot);
  110 
  111             _plotManager.PageCancelled -= 
  112                 new PageCancelledEventHandler(PlotManager_PageCancelled);
  113 
  114             _plotManager.PlotCancelled -= 
  115                 new PlotCancelledEventHandler(PlotManager_PlotCancelled);
  116         }
  117 
  118         #endregion
  119 
  120         #region private methods
  121 
  122         private List<string> GetPlotterNames()
  123         {
  124             List<string> plotters = new List<string>();
  125 
  126             //A plotter name list could be stored somewhere
  127             //and loaded in, such as acad.exe.config (user may change it!)
  128             //Or centrally stored in a DB (so only manager can set/change it)
  129             //Here I simply hard-coded one plotter name
  130             plotters.Add("CutePDF Writer");
  131 
  132             return plotters;
  133         }
  134 
  135         private void GetUserComputerName(
  136             out string userName, out string computerName)
  137         {
  138             userName = "";
  139             computerName = "";
  140 
  141             string domain = System.Environment.UserDomainName;
  142             string user = System.Environment.UserName;
  143 
  144             userName = domain + "\\" + user;
  145             computerName = System.Environment.MachineName;
  146         }
  147 
  148         private bool IsTracedDevice(string plotterName)
  149         {
  150             foreach (string plt in _plotters)
  151             {
  152                 if (plt.Equals(plotterName,
  153                     StringComparison.CurrentCultureIgnoreCase))
  154                 {
  155                     return true;
  156                 }
  157             }
  158 
  159             return false;
  160         }
  161 
  162         #endregion
  163 
  164         #region Private methods: plotting event handlers
  165 
  166         private void PlotManager_BeginPlot(object sender, BeginPlotEventArgs e)
  167         {
  168             _cancelled = false;
  169 
  170             if (e.PlotType == Autodesk.AutoCAD.
  171                 PlottingServices.PlotType.BackgroundPlot
  172                 || e.PlotType == Autodesk.AutoCAD.
  173                 PlottingServices.PlotType.Plot)
  174             {
  175 
  176                 _log = new PlotLog();
  177 
  178                 string user;
  179                 string comp;
  180                 GetUserComputerName(out user, out comp);
  181 
  182                 _log.UserName = user;
  183                 _log.ComputerName = comp;
  184             }
  185             else
  186             {
  187                 _log = null;
  188             }
  189         }
  190 
  191         private void PlotManager_BeginDocument(
  192             object sender, BeginDocumentEventArgs e)
  193         {
  194             if (e.PlotToFile)
  195             {
  196                 _log = null;
  197                 return;
  198             }
  199 
  200             _log.DwgName = Path.GetFileName(e.DocumentName);
  201             _log.DwgPath = Path.GetDirectoryName(e.DocumentName);
  202             _log.CopyCount = e.Copies;
  203         }
  204 
  205         private void PlotManager_BeginPage(
  206             object sender, BeginPageEventArgs e)
  207         {
  208             if (_log == null) return;
  209 
  210             if (e.PlotInfo.ValidatedConfig != null)
  211             {
  212                 if (e.PlotInfo.ValidatedConfig.IsPlotToFile)
  213                 {
  214                     _log = null;
  215                     return;
  216                 }
  217 
  218                 _log.PlotterName = e.PlotInfo.ValidatedConfig.DeviceName;
  219             }
  220 
  221             if (e.PlotInfo.ValidatedSettings != null)
  222             {
  223                 _log.PaperUnit = e.PlotInfo.ValidatedSettings.PlotPaperUnits;
  224                 _log.MediaName = e.PlotInfo.ValidatedSettings.CanonicalMediaName;
  225 
  226                 Point2d pt = e.PlotInfo.ValidatedSettings.PlotPaperSize;
  227                 if (pt.X > pt.Y)
  228                 {
  229                     _log.PaperWidth = pt.X;
  230                     _log.PaperHeight = pt.Y;
  231                 }
  232                 else
  233                 {
  234                     _log.PaperWidth = pt.Y;
  235                     _log.PaperHeight = pt.X;
  236                 }
  237             }
  238         }
  239 
  240         private void PlotManager_EndPage(
  241             object sender, EndPageEventArgs e)
  242         {
  243             if (e.Status != SheetCancelStatus.Continue) _cancelled = true;
  244         }
  245 
  246         private void PlotManager_EndDocument(
  247             object sender, EndDocumentEventArgs e)
  248         {
  249             if (e.Status != PlotCancelStatus.Continue) _cancelled = true;
  250         }
  251 
  252         private void PlotManager_EndPlot(
  253             object sender, EndPlotEventArgs e)
  254         {
  255             if (e.Status != PlotCancelStatus.Continue) _cancelled = true;
  256 
  257             if (_cancelled)
  258             {
  259                 _log = null;
  260                 _cancelled = false;
  261                 return;
  262             }
  263 
  264             if (_log == null) return;
  265 
  266             _log.PlottingTime = DateTime.Now;
  267 
  268             //Debug code here
  269             Document dwg = Autodesk.AutoCAD.ApplicationServices.
  270                 Application.DocumentManager.MdiActiveDocument;
  271             Editor ed = dwg.Editor;
  272 
  273             ed.WriteMessage("\nPlotted by: {0}", _log.UserName);
  274             ed.WriteMessage("\nPlotted on: {0}", _log.PlotterName);
  275             ed.WriteMessage("\nDwg Location: {0}", _log.DwgPath);
  276             ed.WriteMessage("\nPlotted Dwg: {0}", _log.DwgName);
  277             ed.WriteMessage("\nMedia: {0}", _log.MediaName);
  278             ed.WriteMessage("\nMedia size: " + 
  279                 _log.PaperWidth.ToString("#####0.00") + 
  280                 " (W) x " + 
  281                 _log.PaperHeight.ToString("#####0.00") + " (H)");
  282             ed.WriteMessage("\nCopy Count: {0}", _log.CopyCount);
  283 
  284             //Save Plotting log, if the plotting plotter is on printer list;
  285             if (IsTracedDevice(_log.PlotterName))
  286             {
  287                 _logWriter.SavePlottingLog(_log);
  288             }
  289         }
  290 
  291         private void PlotManager_PlotCancelled(object sender, EventArgs e)
  292         {
  293             _cancelled = true;
  294         }
  295 
  296         private void PlotManager_PageCancelled(object sender, EventArgs e)
  297         {
  298             _cancelled = true;
  299         }
  300 
  301         #endregion
  302     }
  303 }

Some descriptions of the code:

Line 16: this class implements IExtensionApplication. That means, as soon as the assembly is loaded, the code starts monitoring plotting done in the AutoCAD session.

Line 25 and Line 122 - 133: these lines of code defines a list of plotter/printer name that I want to track. The name should be the same as I can see in the printer dropdown list of AutoCAD's plot dialog box. Only plotters in this list is tracked.

Line 44: Notice the variable _logWriter is declared as IPlottingLogWriter, but here it points to a PlottingLogFileWriter (new PlottingLogFileWriter()). It is possible to declare the differently implemented IPlottingLogWriter in acad.exe.config, so that this class will be truly not affected when a new implemented log-writer is available/changed.

The rest of code would be quite obvious, no extra explanation is necessary.

This video clip shows how it works. Note, since I used CutePDF virtual plotter, each time after the plotting is done (e.g. the PDF has been produced), I simply cancelled the "Save As" dialog box. By then the plotting from AutoCAD has already completed, thus cancelling saving PDF file has no affect to the plot tracking process.

At my work, similar code is used to monitor AutoCAD plotting to some expensive color plotters office-wide. The plotting logs are saved to database and can be browsed by managers through a web application.

Finally, I'd like to thank Kean Walmsley for recommending me the VS addin tool CopySourceToHtml, which solves my code posting issue.

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.