I want to build a freshly new added standard ASP (MVC) webapplication programmatically in Visual Studio 2017. I therefore use a console application that uses Microsoft.Build.Evaluation.Project.Build() to open and compile the project. The console application that builds is outlined below. The project that needs to be build is a standard ASP MVC .Net application just generated from the wizard in Visual Studio. In my Visual Studio version 2017 this compiles fine. However if I want to compile it using my application , at opening of the project, it comes up with the error :
Microsoft.Build.Exceptions.InvalidProjectFileException occurred HResult=0x80131500 Message=The imported project "C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v15.0\WebApplications\Microsoft.WebApplication.targets" was not found. Confirm that the path in the declaration is correct, and that the file exists on disk.
Now, if you open the csproj file of the webapplication in notepad it tells you that it wants to find it's imported projects in:
Import Project="$(VSToolsPath)\WebApplications\Microsoft.WebApplication.targets" Condition="'$(VSToolsPath)' != ''"
According tot the error it seems to me that the toolspath is "C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v15.0" However the WebApplications\Microsoft.WebApplication.targets is located in "C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v14.0"
A workaround obviously is to copy the WebApplications folder from v14.0 to v15.0. It then compiles happily. But the questions are : Why is a standard generated project pointing to a directory that does not exsist? Why can Visual Studio itself cope with this wrong path? Is there a better solution than to copy the WebApplications folder ?
Here is the code that opens and compiles the web project:
using System;
using Microsoft.Build.Logging;
namespace CompilerApp
{
class Program
{
static void Main(string[] args)
{
//string projectfile = @"C:\temp\CompilerApp\MyCSharp7\MyCSharp7.csproj";
string projectfile = @"C:\temp\CompilerApp\WebApplication1\WebApplication1.csproj";
UnloadAnyProject();
Microsoft.Build.Evaluation.Project p = new Microsoft.Build.Evaluation.Project(projectfile);
FileLogger loggerfile2 = new FileLogger();
loggerfile2.Parameters = @"logfile=C:\temp\CompilerApp\myapp.msbuild.log";
bool buildresult = p.Build(loggerfile2);
if (buildresult)
{
Console.WriteLine("project compiled");
}
else
{
Console.WriteLine("project not compiled, check {0}", @"C:\temp\myapp.msbuild.log");
}
p.Save();
UnloadAnyProject();
}
private static void UnloadAnyProject()
{
Microsoft.Build.Evaluation.ProjectCollection projcoll = Microsoft.Build.Evaluation.ProjectCollection.GlobalProjectCollection;
foreach (Microsoft.Build.Evaluation.Project pr in projcoll.LoadedProjects)
{
Microsoft.Build.Evaluation.ProjectCollection mypcollection = pr.ProjectCollection;
mypcollection.UnloadProject(pr);
}
}
}
}