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 ...
        }
    }
}