Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Build visual studio solution from code

I'm writing a console application to get a solution from a tfs server, build it and publish on iis, but I'm stuck at building...

I found this code, which works like a charm

public static void BuildProject()
{
    string solutionPath = Path.Combine(@"C:\MySolution\Common\Common.csproj");

    List<ILogger> loggers = new List<ILogger>();
    loggers.Add(new ConsoleLogger());
    var projectCollection = new ProjectCollection();
    projectCollection.RegisterLoggers(loggers);
    var project = projectCollection.LoadProject(solutionPath);
    try
    {
        project.Build();
    }
    finally
    {
        projectCollection.UnregisterAllLoggers();
    }
}

but my solution it's pretty big and contains multiple projects which depends from each other (e.g. project A has a reference to project B)

how to get the correct order to build each project? is there a way to build the entire solution from the .sln file?

like image 487
Doc Avatar asked Jan 12 '23 01:01

Doc


1 Answers

Try using the following code to load a solution and compile it:

string projectFilePath = Path.Combine(@"c:\solutions\App\app.sln");

ProjectCollection pc = new ProjectCollection();

// THERE ARE A LOT OF PROPERTIES HERE, THESE MAP TO THE MSBUILD CLI PROPERTIES
Dictionary<string, string> globalProperty = new Dictionary<string, string>();
globalProperty.Add("OutputPath", @"c:\temp");

BuildParameters bp = new BuildParameters(pc);
BuildRequestData buildRequest = new BuildRequestData(projectFilePath, globalProperty, "4.0", new string[] { "Build" }, null);
// THIS IS WHERE THE MAGIC HAPPENS - IN PROCESS MSBUILD
BuildResult buildResult = BuildManager.DefaultBuildManager.Build(bp, buildRequest);
// A SIMPLE WAY TO CHECK THE RESULT
if (buildResult.OverallResult == BuildResultCode.Success)
{              
    //...
}
like image 79
Erwin Avatar answered Jan 20 '23 13:01

Erwin