cake custom MsBuild path - c#

Maybe simple question however I'm stuck. I try to configure cake script. I'm using the following script
Task("Build")
.Description("Builds the Solution")
.Does(() =>
{
MSBuild(SOLUTION_FILE, CreateSettings());
});
MSBuildSettings CreateSettings()
{
var settings = new MSBuildSettings { Verbosity = Verbosity.Minimal, Configuration = "Debug" };
settings.WithProperty("DebugType", "pdbonly");
settings.ToolVersion = MSBuildToolVersion.VS2017;
return settings;
}
When I execute it. I have the following issue:
========================================
Build
========================================
An error occurred when executing task 'Build'.
I have added MsBuild path to PATH environment but still not working.
How can i set custom MsBuild path ?
Thanks

Related

Can I get NugetRestore to work with build.cake on azure devops (TFS)

I am trying to extract build tasks from TFS to cake scripts so that the build tasks get versioned together with the code. I have managed to create a script which cleans, NuGet-restores, builds, and runs unit tests on my project. It all works fine locally. however, after configuring TFS to run my cake script it keeps failing on following error:
2019-07-24T11:30:58.0377820Z ##[error]Unable to find version '4.4.3' of package 'System.Data.SqlClient'.
2019-07-24T11:30:58.0385573Z ##[error]Unable to find version '11.0.1' of package 'Newtonsoft.Json'.
2019-07-24T11:30:58.0401542Z ##[error]An error occurred when executing task 'Restore-Nuget-Packages'.
2019-07-24T11:30:58.0449315Z ##[error]Error: One or more errors occurred.
2019-07-24T11:30:58.0450913Z ##[error] NuGet: Process returned an error (exit code 1).
2019-07-24T11:30:58.0739069Z ##[error]System.Exception: Unexpected exit code 1 returned from tool Cake.exe
I tried to change the Cake task settings to use different versions of Nuget and feed urls. Currently, they look like this:
Nuget Exe Location: https://dist.nuget.org/win-x86-commandline/latest/nuget.exe
Tool Feed Url: https://api.nuget.org/v3/index.json
We do have a private nuget host and I have tried modifying the tool feed url. However, from the logs it seems like the feed urls are OK.
Cake output:
Feeds used:
2019-07-24T11:30:55.7676783Z C:\Users\{usr}\AppData\Local\NuGet\Cache
2019-07-24T11:30:55.7677002Z C:\Users\{usr}\.nuget\packages\
2019-07-24T11:30:55.7677066Z http://{ournugeturl}
2019-07-24T11:30:55.7677233Z http://{ournugeturl2}
2019-07-24T11:30:55.7677301Z http://{ournugeturl3}
2019-07-24T11:30:55.7677572Z C:\Program Files (x86)\Microsoft SDKs\NuGetPackages\
Other nuget packages are installed, e.g,
2019-07-24T11:30:55.7882050Z Restoring NuGet package Autofac.4.8.1.
2019-07-24T11:30:55.9806596Z Adding package 'Autofac.4.8.1' to folder 'd:\w1\3263\s\packages'
I even set the verbosity level to Detailed in the Nuget-Restore task, however, I do not manage to find where the problem is.
Snippet from cake.build.
Task("Restore-Nuget-Packages")
.IsDependentOn("Clean")
.Does(() =>
{
NuGetRestore(solution, new NuGetRestoreSettings {
Verbosity = NuGetVerbosity.Detailed,
});
});
my NuGet.config
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<solution>
<add key="disableSourceControlIntegration" value="true" />
</solution>
<packageSources>
<add key="privaterepo1" value="http://privatenugetrepo/nuget/NTS" />
<add key="privaterepo2" value="http://privatenugetrepo/Default" />
<add key="nugetv3" value="https://api.nuget.org/v3/index.json" />
</packageSources>
<activePackageSource>
<add key="All" value="(Aggregate source)" />
</activePackageSource>
<packageRestore>
<add key="enabled" value="True" />
</packageRestore>
</configuration>
build.cake
#tool "nuget:?package=xunit.runner.console&version=2.4.1"
var target = Argument("target", "Default");
var configuration = Argument("configuration", "Release");
var solution = "./pathtosolution.sl";
////////////////////////////////////////////////
///// Clean the project packages
////////////////////////////////////////////////
Task("Clean")
.Does(() =>
{
CleanDirectory("./packages");
});
////////////////////////////////////////////////
///// Adds private Nuget feed links
////////////////////////////////////////////////
Task("Add-Private-NuGet-Feed")
.Does(() =>
{
string[] sources = {
"private-src1",
"private-src2",
"https://api.nuget.org/v3/index.json"
};
foreach(string feed in sources)
{
if (!NuGetHasSource(feed))
{
var accessToken = EnvironmentVariable("SYSTEM_ACCESSTOKEN")
?? throw new Exception("VSTS System Access Token is required to setup Private NuGet Feed");
Information($"Source {feed} is missing");
NuGetAddSource($"MyCompany-NuGet {feed}", feed, new NuGetSourcesSettings
{
UserName = "VSTS",
Password = accessToken,
}
);
} else
{
Information($"Source {feed} Exists");
}
}
});
////////////////////////////////////////////////
///// Restores all nuget packages.
////////////////////////////////////////////////
Task("Restore-Nuget-Packages")
.IsDependentOn("Add-Private-NuGet-Feed")
.Does(() =>
{
var solutions = GetFiles("./**/*.sln");
// Restore all NuGet packages.
foreach(var solution in solutions)
{
Information(solution);
Information("Restoring {0}", solution);
var nugetRestoreSettings = new NuGetRestoreSettings {
ConfigFile = new FilePath("./NuGet.Config"),
//MSBuildVersion = NuGetMSBuildVersion.MSBuild15
};
NuGetRestore(solution, nugetRestoreSettings);
}
});
////////////////////////////////////////////////
///// Runs DotNetCoreRestore
////////////////////////////////////////////////
Task("DotNetCoreRestore")
.Does(() =>
{
DotNetCoreRestore(
solution,
new DotNetCoreRestoreSettings()
{});
});
////////////////////////////////////////////////
///// Runs unit tests.
////////////////////////////////////////////////
Task("xUnit")
.IsDependentOn("Build")
.Does(() =>
{
var projects = GetFiles("./*.Tests/**/*.Tests.csproj");
foreach(var project in projects)
{
DotNetCoreTest(
project.FullPath,
new DotNetCoreTestSettings()
{
// Set configuration as passed by command line
Configuration = configuration
});
}
});
////////////////////////////////////////////////
///// Build
////////////////////////////////////////////////
Task("Build")
.IsDependentOn("Clean")
.IsDependentOn("Add-Private-Nuget-Feed")
.IsDependentOn("DotNetCoreRestore")
.IsDependentOn("Restore-Nuget-Packages")
.Does(() =>
{
MSBuild(solution, new MSBuildSettings {
ToolVersion = MSBuildToolVersion.VS2017});
});
////////////////////////////////////////////////
///// The main task.
////////////////////////////////////////////////
Task("Default")
.IsDependentOn("xUnit");
RunTarget(target);
Solved
By replacing the Cake task in TFS with a Powershell Script invoking build.ps1 on the build server resolved my problem.

Building Project Programmatically Fails Using Microsoft.Build

I installed the three following packages into my console application:
Microsoft.Build
Microsoft.Build.Framework
Microsoft.Build.Tasks.Core
Microsoft.Build.Utilities.Core
And I tried to use the following method to build a project:
static void Build(string projectPath)
{
var logger = new ConsoleLogger(LoggerVerbosity.Normal);
logger.ShowSummary = true;
var manager = BuildManager.DefaultBuildManager;
var projectInstance = new ProjectInstance(projectPath);
var result = manager.Build(
new BuildParameters()
{
DetailedSummary = true,
Loggers = new List<ILogger>() { logger }
},
new BuildRequestData(projectInstance, new string[] { "Build" }));
var buildResult = result.ResultsByTarget["Build"];
var buildResultItems = buildResult.Items;
}
However, after I ran the code, I got the error that described in the following image:
Why is this happening and how can I fix it?
I think you're not using tht right MSBuild version. Try to set the variable explicitly in your .proj :
<MSBuildExtensionsPath>C:\Program Files (x86)\MSBuild</MSBuildExtensionsPath>
It seems the best solution is to use MSBuild command line in Process class. A working sample is as follows:
var buildOutput = new List<string>();
var buildError = new List<string>();
var buildProcess = new Process
{
StartInfo = new ProcessStartInfo
{
FileName = "C:\\Program Files (x86)\\Microsoft Visual Studio\\2017\\Enterprise\\MSBuild\\15.0\\Bin\\MSBuild.exe",
Arguments = projectPath + " /t:Rebuild /p:Configuration=Debug",
UseShellExecute = false,
RedirectStandardOutput = true,
RedirectStandardError = true,
CreateNoWindow = true
}
};
buildProcess.Start();
while (!buildProcess.StandardOutput.EndOfStream)
{
buildOutput.Add(buildProcess.StandardOutput.ReadLine());
}
while (!buildProcess.StandardError.EndOfStream)
{
buildError.Add(buildProcess.StandardError.ReadLine());
}
And then you could use the output to determine whether the build was successful or not. The important note is that you have to find the correct path of MSBuild.exe file as there are several versions of this file and in my case (VS 2017) the correct path is the one in the sample code.
One of BuildRequestData constructor overloads supports a parameter called "toolVersion". Since you are using Visual Studio 2017, set it as "15.0".
EDIT: I quitted using the .Net Framework provided MSBuild version (the one located here):
System.Runtime.InteropServices.RuntimeEnvironment.GetRuntimeDirectory()
C:\Windows\Microsoft.NET\Framework\v4.0.30319
Instead, I'm using the one located here:
C:\Program Files (x86)\MSBuild\{version}\Bin
This version provide extra parameters as LangVersion or DeployOnBuild.

MSBuild threw error: "... task could not be instantiated from the assembly"

EDIT: Never mind, it turns that out the task does not actually implement the Microsoft.Build.Framework.ITask interface. I had made the erroneous assumption that it did. D'oh!
I use Visual Studio 2015.
Relevant code:
string solutionFilePath = args.Single();
var fileLogger = new FileLogger { Verbosity = LoggerVerbosity.Detailed, Parameters = #"logfile=C:\MSBuildResults.txt" };
var projectCollection = new ProjectCollection {DefaultToolsVersion = "14.0"};
var buildParameters = new BuildParameters(projectCollection) { Loggers = new List<ILogger> { fileLogger } };
var globalProperties = new Dictionary<string, string> { { "Configuration", "Debug" }, { "Platform", "Any CPU" } };
var buildRequestData = new BuildRequestData(solutionFilePath,
globalProperties,
targetsToBuild: new[] { "Build" },
toolsVersion: "14.0",
hostServices: null);
BuildResult buildResult = BuildManager.DefaultBuildManager.Build(buildParameters, buildRequestData);
buildResult.OverallResult is BuildResultCode.Failure, with error messages like the following printed to my log file:
C:\Workspaces\SomeProject.csproj(67,5): error MSB4127: The "DummyTask"
task could not be instantiated from the assembly
"\networkDrive\Dummy.dll". Please verify the task assembly has been
built using the same version of the Microsoft.Build.Framework assembly
as the one installed on your computer and that your host application
is not missing a binding redirect for Microsoft.Build.Framework.
Unable to cast object of type 'DummyTask' to type
'Microsoft.Build.Framework.ITask'.
Following the advice here, I added the <bindingRedirect> tag in the .exe.config file of my program. The same error messages were thrown nonetheless.
Instead of using Microsoft.Build libraries, I decided to invoke MSBuild.exe using Process.Start() (which I know is not recommended):
var processStartInfo = new ProcessStartInfo(#"C:\Program Files (x86)\MSBuild\14.0\Bin\MSBuild.exe")
{
Arguments = $"{solutionFilePath} /t:Build",
RedirectStandardOutput = false,
UseShellExecute = true,
CreateNoWindow = false
};
var process = Process.Start(processStartInfo);
process.WaitForExit();
process.Close();
This time, the build was successful and the process ran to completion with exit code 0.
What did I do wrong when using Microsoft.Build libraries to build my solution? What should I do instead to ensure that the build succeeds when I use BuildManager?
Let me know if you need any more information to help me with my issue.

How to setup Jenkins with ASP .NET Core

I am trying to create a Pipeline on Jenkins, to automate my build, test and deploy process.
pipeline {
agent any
environment {
myVersion = '0.9'
}
tools {
msbuild '.NET Core 2.0.0'
}
stages {
stage('checkout') {
steps {
checkout([$class: 'GitSCM', ...])
}
}
stage('restore') {
steps {
bat 'dotnet restore --configfile NuGet.Config'
}
}
stage('build') {
steps {
bat 'dotnet build'
}
}
stage('publish') {
steps {
...
}
}
}
}
When trying to run the build, I get this error message from Jenkins:
'dotnet' is not recognized as an internal or external command,
operable program or batch file.
What do I have to change to make this environment work?
I added my .NET CORE path etc. to the Jenkins Settings for MSBuild.
What am I missing?
Solved it like this:
environment {
myVersion = '0.9'
dotnet = 'path\to\dotnet.exe'
}
and than replaced my command with the %dotnet% variable.

How do I compile an XNA project from C# with MSBuild 14?

I have an XNA project I have that compiles perfectly fine in Visual Studio 2015, that makes use of C# 6 features.
Previously, I had some tools coded in C# that would auto-compile the project when it was using C# 5 under VS 2013, but the change to C# 6 has broken things somehow.
To reproduce this I created a new console application, referenced Microsoft.Build, Microsoft.Build.Framework, and Microsoft.Build.Utilities.Core assemblies from C:\Program Files (x86)\MSBuild\14.0\Bin.
I then created my C# compiler project with the following code:
namespace CompileXna
{
class Program
{
static void Main(string[] args)
{
const string solutionPath = #"D:\Code\My Projects\FrbTest\FrbTest.sln";
var properties = new Dictionary<string, string>()
{
{"Configuration", "Debug"},
{"Platform", "x86" }
};
var parameters = new BuildParameters
{
Loggers = new ILogger[] {new BuildLogger()}
};
var request = new BuildRequestData(solutionPath, properties, null, new string[] {"Build"}, null);
var manager = BuildManager.DefaultBuildManager.Build(parameters, request);
Console.WriteLine("Done");
Console.ReadLine();
}
}
class BuildLogger : Logger
{
public override void Initialize(IEventSource eventSource)
{
eventSource.ErrorRaised += (sender, args) =>
Console.WriteLine($"Error: File {args.File} line {args.LineNumber} message {args.Message}");
eventSource.WarningRaised += (sender, args) =>
Console.WriteLine($"Warning: File {args.File} line {args.LineNumber} message {args.Message}");
}
}
}
Unfortunately, when this runs I get the following error:
Error: File C:\Program Files (x86)\MSBuild\Microsoft\XNA Game Studio\v4.0\Microsoft.Xna.GameStudio.ContentPipeline.targets line 78 message The "BuildContent" task could not be instantiated from the assembly "Microsoft.Xna.Framework.Content.Pipeline, Version=4.0.0.0, Culture=neutral, PublicKeyToken=842cf8be1de50553". Please verify the task assembly has been built using the same version of the Microsoft.Build.Framework assembly as the one installed on your computer and that your host application is not missing a binding redirect for Microsoft.Build.Framework. Unable to cast object of type 'Microsoft.Xna.Framework.Content.Pipeline.Tasks.BuildContent' to type 'Microsoft.Build.Framework.ITask'.
I tried looking in the details of the build output in Visual Studio 2015 when it successfully compiles my XNA project, but even with Detailed logging all I could find (seemingly) relevant was:
1>Using "BuildContent" task from assembly "Microsoft.Xna.Framework.Content.Pipeline, Version=4.0.0.0, Culture=neutral, PublicKeyToken=842cf8be1de50553".
1>Task "BuildContent"
1>Done executing task "BuildContent".
Anyone have any success on this?

Categories

Resources