Home > Sample chapters

Programming Microsoft Dynamics CRM 4.0: Plug-ins

Debugging Plug-ins

The first thing you will probably do after deploying a plug-in is attempt to execute it to see whether it works. If you are greeted with a vague error message, you can check the Event Viewer on the CRM server for more information, but eventually you will find that you need more information, especially for more advanced plug-ins. Remote debugging and logging are two common techniques used to chase down errors in plug-ins.

Remote Debugging

By far the most powerful option, remote debugging allows you to set breakpoints in your plug-in code and step through the process in Visual Studio. The steps for setting up remote debugging are detailed in Chapter 9 in the companion book to this one: Working With Microsoft Dynamics CRM 4.0 by Mike Snyder and Jim Steger. The CRM SDK also has information to help you set up remote debugging.

The downside to remote debugging is that it blocks other calls to the CRM application while you are stepping through your code. This can be a problem if you have multiple developers working with the same environment at the same time, and it will definitely be a problem if you are trying to debug something in a production environment.

Logging

The next-best option to discovering errors is to include extensive logging code in your plug-ins. Plug-ins typically execute in a process that is running as the Network Service user andshould have rights to access the file system. You could then write some simple logging logicto output to a text file. Example 5-17 demonstrates some simple logging code.

Example 5-17. Simple logging code

private static readonly object _logLock = new Object();
protected static void LogMessage(string message)
{
    try
    {
        if (IsLoggingEnabled)
        {
            lock (_logLock)
            {
                File.AppendAllText(LogFilePath, String.Format("[{0}] {1} {2}",
                    DateTime.Now, message, Environment.NewLine));
            }
        }
    }
    catch
    {
    }
}

The IsLoggingEnabled and LogFilePath properties could be initialized once at startup or be implemented to check the registry at a certain frequency to determine whether logging should occur and where the log file should be created. With this method implemented, you can add logging messages to your plug-ins to help chase down those hard-to-interpret errors:

if (IsLoggingEnabled)
{
    StringBuilder message = new StringBuilder();
    message.Append("InputParameters: ");
    foreach (PropertyBagEntry entry in context.InputParameters.Properties)
    {
        message.Append(entry.Name);
        message.Append(" ");
    }

    LogMessage(message.ToString());
}