Write To Visual Studio’s Error List

When you’re developing an extension for Visual Studio, you might want to add errors, warnings or messages to Visual Studio’s Error List. Here is how to do it:

using System;
using Microsoft.VisualStudio.Shell;

namespace MunirHusseini.Demos
{
    internal static class TaskManager
    {
        private static ErrorListProvider _errorListProvider;

        public static void Initialize(IServiceProvider serviceProvider)
        {
            _errorListProvider = new ErrorListProvider(serviceProvider);
        }

        public static void AddError(string message)
        {
            AddTask(message, TaskErrorCategory.Error);
        }

        public static void AddWarning(string message)
        {
            AddTask(message, TaskErrorCategory.Warning);
        }

        public static void AddMessage(string message)
        {
            AddTask(message, TaskErrorCategory.Message);
        }

        private static void AddTask(string message, TaskErrorCategory category)
        {
            _errorListProvider.Tasks.Add(new ErrorTask
                {
                    Category = TaskCategory.User,
                    ErrorCategory = category,
                    Text = message
                });
        }
    }
}

Obviously, this method Initialize must be called prior to any other methods. The parameter serviceProvider can be the instance of the VSPackage. Example:

namespace MunirHusseini.Demos
{
    /// <summary>
    /// This is the class that implements the package exposed by this assembly.
    /// </summary>
    [PackageRegistration(UseManagedResourcesOnly = true)]
    [InstalledProductRegistration("#110", "#112", "1.0", IconResourceID = 400)]
    [Guid(GuidList.guidMyDemoPkgString)]
    public sealed class MyDemoPackage : Package
    {
        /// <summary>
        /// Initialization of the package; this method is called right after the package is sited, so this is the place
        /// where you can put all the initialization code that rely on services provided by VisualStudio.
        /// </summary>
        protected override void Initialize()
        {
            base.Initialize();

            TaskManager.Initialize(this);

            // Some other package initialization here ...
        }
    }
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s