Thursday, July 17, 2014

Try, Catch, Retry with DTE2 interface.

I had a task to create multiple solutions while adding projects into them by parsing a list file containing the path and names of solutions and their related projects. So using C#, I started writing a utility consuming Visual Studio 2013 Automation Interface.

While creating the Com object of EnvDTE80.DTE2 it sometimes throwing exception with message:

The message filter indicated that the application is busy.

However, while debugging, on resuming 1 or 2 times, it went fine. So this makes me to find some Try Catch and Retry solution. After some googling, Here is the most basic way, I used to get rid of this problem:

EnvDTE80.DTE2 dte=null;
Solution4 solutionObject=null;
Console.WriteLine("Creating DTE Object...");
for (int r = 0; r < 5; r++)
{
  try
    {
     Console.WriteLine(string.Format("Tried {0} times", r));
     System.Type type = System.Type.GetTypeFromProgID("VisualStudio.DTE.12.0");
     //DTE2 dte2 = (DTE2)Microsoft.VisualBasic.Interaction.CreateObject("VisualStudio.DTE.12.0", "");
     Object obj = System.Activator.CreateInstance(type, true);
     dte = (EnvDTE80.DTE2)obj;
     solutionObject = (Solution4)dte.Solution;
     ConsoleWrite("Done", ConsoleColor.Cyan);
     break; //reaching here means, it was successful, so get out of loop
    }
    catch (Exception)
    {
	 System.Threading.Thread.Sleep(TimeSpan.FromSeconds(2)); //let give a delay of 2 seconds
     if (r >= 4)
        throw; //So if it is not successful after 4 retries, throw the exception
    }
}

No comments: