Returning a cast result from a generic method.

I recently needed to cast an object from the Enterprise Library Caching block back to a type, but start getting the popular System.NullReferenceException error in my tests if the value returned from the caching block was null.

The problem is that you cannot cast null back to a non-nullable type like an int.

The answer was to use default(T) this will return null or the default value for the type.

   public T Get(string cacheKey)
   {
       return (T) (_manager.GetData(cacheKey) ?? default(T));
   }

Create your own visual studio output window.

It can be handy to write messages to custom output window/s…

Here is some code to do that:

Usage

EnvdteHelpers.WriteMsgToCustomPane("WCF", "Hello");

Helper

    public static class EnvdteHelpers
    {
        private static OutputWindowPane _outputWindowPane;
        private static OutputWindowPane OutputWindowPane(string paneName) { return _outputWindowPane ?? (_outputWindowPane = CreateOutputWindowPane(paneName)); }
        private static OutputWindowPane CreateOutputWindowPane(string paneName)
        {
            var dte = (DTE)System.Runtime.InteropServices.Marshal.GetActiveObject("VisualStudio.DTE");
            var outputWindow = (OutputWindow)dte.Windows.Item(EnvDteConstants.VsWindowKindOutput).Object;
            OutputWindowPane pane;
            try
            {
                pane = outputWindow.OutputWindowPanes.Item(paneName);
            }
            catch (Exception)
            {
                pane = outputWindow.OutputWindowPanes.Add(paneName);
            }
            outputWindow.Parent.Activate();
            pane.Activate();
            return pane;            
        }
        //http://blogs.msdn.com/b/mshneer/archive/2009/12/07/interop-type-xxx-cannot-be-embedded-use-the-applicable-interface-instead.aspx
        internal abstract class EnvDteConstants
        {
            public const string VsWindowKindOutput = "{34E76E81-EE4A-11D0-AE2E-00A0C90FFFC3}";
        }

        /// Usage: EnvdteHelpers.WriteMsgToCustomPane("WCF", "Hello"); 
        public static void WriteMsgToCustomPane(string paneName,string message)
        {
            OutputWindowPane(paneName).OutputString(message + "\r\n");
        }
    }