You can find the answer here.
Some says that the issue occurs when Solution Explorer is not open.
Here is my solution based on upper link:
private Project getActiveProject(DTE2 dte)
{
Array projects = dte.ActiveSolutionProjects as Array;
if (projects == null || projects.Length == 0)
{
projects = dte.Solution.SolutionBuild.StartupProjects as Array;
if (projects == null || projects.Length == 0)
{
Projects pro = dte.Solution.Projects;
if (pro == null || pro.Count == 0)
return null;
return pro.Item(0);
}
}
return projects.GetValue(0) as Project;
}