TFS Build 2.0 C#, howto add variables to the build/Pass Msbuild args

dotnet publish include all dependencies
build net standard with msbuild
dotnet build command in jenkins
dotnet publish --no-build
dotnet build sqlproj
dotnet test msbuild
msbuild dotnet restore
dotnet publish task

I am trying to pass arguments to MSBuild 2.0. After research it appears that I need to do this using variables, but I cannot figure out how to incorporate this into my queue request below. I have tried parameters but that does not seem to work. Here is what I am trying to tell MSBuild @" /p:OctoPackPackageVersion=" + releaseNumber. This worked with the XAML build using IBuildRequest.ProcessParameters.

var buildClient = new BuildHttpClient(new Uri(collectionURL), new 
VssCredentials(true));
var res = await buildClient.QueueBuildAsync(new Build
            {
                Definition = new DefinitionReference
                {
                    Id = targetBuild.Id
                },
                Project = targetBuild.Project,
                SourceVersion = ChangeSetNumber,
                Parameters = buildArg

            });
            return res.Id.ToString();

vNext build system is different with legacy XAML build system, you cannot pass variable to build tasks in the build definition directly when queue the build. The code you used updated the build definition before queue the build which means that the build definition may keep changing if the variable changed.

The workaround for this would be add a variable in your build definition for example "var1" and then use this variable as the arguments for MSBuild Task: With this, you will be able to pass the value to "var1" variable when queue the build without updating the build definition.

Build build = new Build();
build.Parameters = "{\"var1\":\"/p:OctoPackPackageVersion=version2\"}";

// OR using Newtonsoft.Json.JsonConvert
var dict = new Dictionary<string, string>{{"var1", "/p:OctoPackPackageVersion=version2"}};
build.Parameters = JsonConvert.SerializeObject(dict)

[build] Passing a property (/property) with multiple values to msbuild , vNext build system is different with legacy XAML build system, you cannot pass variable to build tasks in the build definition directly when queue the build. To use an environment variable in an MSBuild project. Reference the environment variable the same way you would a variable declared in your project file. For example, the following code references the BIN_PATH environment variable: <FinalOutput>$ (BIN_PATH)\MyAssembly.dll</FinalOutput>.

dotnet build command, The workaround for this would be add a variable in your build definition for example "var1" and then use this variable as the arguments for MSBuild Task: With  Accept the defaults for Solution, Solution Name ( BuildApp ), and Framework. From the top menu bar, choose File > New > Project. In the left pane of the New Project dialog box, expand Visual C# > Windows Desktop, then choose Windows Forms App (.NET Framework). Then choose OK.

Patrick, I was able to find a work around to my issue by updating the build definition. This is definitely not ideal but it works. As you can see below I am trying to add to the msbuild args already present. If you know a better way let me know. I really appreciate you taking the time to look at my question.

 public static async Task<string> QueueNewBuild(string project, BuildDefinitionReference targetBuild, string collectionURL, string ChangeSetNumber, string ReleaseNumber, bool CreateRelease)
    {
        var buildClient = new BuildHttpClient(new Uri(collectionURL), new VssCredentials(true));
        await Task.Delay(1000).ConfigureAwait(false);
        var buildDef = await buildClient.GetDefinitionAsync(targetBuild.Project.Id, targetBuild.Id);
        BuildDefinitionVariable OrigMSbuildvar = buildDef.Variables["MSBuildArgs"];
        buildDef.Variables["MSBuildArgs"].Value = OrigMSbuildvar.Value + " /p:OctoPackPackageVersion=" + ReleaseNumber.ToString();

        await Task.Delay(1000).ConfigureAwait(false);
        buildDef = await buildClient.UpdateDefinitionAsync(buildDef);

        await Task.Delay(1000).ConfigureAwait(false);
        Build build = new Build
        {
            Definition = new DefinitionReference
            {
                Id = targetBuild.Id
            },
            Project = targetBuild.Project,
            SourceVersion = ChangeSetNumber
        };

        await Task.Delay(1000).ConfigureAwait(false);
        var res = await buildClient.QueueBuildAsync(build);
        buildDef.Variables["MSBuildArgs"].Value = OrigMSbuildvar.Value;           
        await Task.Delay(1000).ConfigureAwait(false);
        buildDef = await buildClient.UpdateDefinitionAsync(buildDef);
        return res.Id.ToString();

    }

Command Line task, I need to pass values for NoWarn option to C# compiler. Previously with msbuild it was being passed as property: msbuild /p:NoWarn:"1591  Or you can also use the dotnet msbuild command. Running dotnet build is equivalent to running dotnet msbuild -restore; however, the default verbosity of the output is different. Arguments. PROJECT | SOLUTION. The project or solution file to build.

I have found this solution and it works for me excellent. I set custom parameters for convenience in build definition without updating on server:

foreach (var variable in targetBuildDef.Variables.Where(p => p.Value.AllowOverride))
        {
            var customVar = variables.FirstOrDefault(p => p.Key == variable.Key);
            if (customVar == null)
                continue;
            variable.Value.Value = customVar.Value.TrimEnd('\\');
        }

And then set variables values in build parameters:

        using (TfsTeamProjectCollection ttpc = new TfsTeamProjectCollection(new Uri(tFSCollectionUri)))
        {
            using (BuildHttpClient buildServer = ttpc.GetClient<BuildHttpClient>())
            {
                var requestedBuild = new Build
                {
                    Definition = targetBuildDef,
                    Project = targetBuildDef.Project
                };
                var dic = targetBuildDef.Variables.Where(z => z.Value.AllowOverride).Select(x => new KeyValuePair<string, string>(x.Key, x.Value.Value));
                var paramString = $"{{{string.Join(",", dic.Select(p => $@"""{p.Key}"":""{p.Value}"""))}}}";
                var jsonParams = HttpUtility.JavaScriptStringEncode(paramString).Replace(@"\""", @"""");
                requestedBuild.Parameters = jsonParams;
                var queuedBuild = buildServer.QueueBuildAsync(requestedBuild).Result;

PowerShell task, The dotnet build command builds the project and its dependencies into a set of binaries. The binaries include the project's code in Intermediate  VSTS Build variables, Echo and arguments Seeing the output at any point in time is very important while automating a process; for that reason we usually set variables and display them during the build.In VSTS the public variables can be defined in the Variables tab or in the running process.

How to: Use Environment Variables in a Build, Execute tools from a command prompt when building code in Azure Pipelines and Team Foundation Server (TFS) For information about how to use the Import element to insert a project file into another project file, see Import element (MSBuild) and How to: Use the same target in multiple project files.-outputResultsCache[:cacheFile]-orc[:cacheFile] Output cache file where MSBuild will write the contents of its build result caches at the end of the build.

DevOps and Automation VSTS Build variables, Echo and arguments, Azure Pipelines | Azure DevOps Server 2019 | TFS 2018 | TFS 2017 | TFS 2015. Use this task to Arguments, (Optional) Arguments passed to the Powershell script. For example For example, secret variables are not automatically mapped. If you have a On the Build tab of a build pipeline, add this task:  Visual Studio uses the custom .targets or .props files if it finds them in the MSBuild folder whenever it builds any project of the matching type. This can have unintended consequences, and if done incorrectly, can disable the ability of Visual Studio to build on your computer.

Azure Msbuild Arguments, When you build projects, it is often necessary to set build options using information that is not in the project file or the files that comprise your  MSBuild looks for the Directory.Build.props file starting from the project directory and going up until it finds a matching file, then it stops looking. In some cases you might want to define some properties for all projects in your repo, and add some more properties in a subdirectory. To do this, the "inner" Directory.Build.props file will

Comments
  • Which build are you using now, XAML or vNext ? Did you mean you could not figure out how to use this on vNext build?
  • Patrick, we have switched our definitions from XAML to scriptable(introduced with TFS 2015). When we used the XAML build definition I used IBuildRequest.ProcessParameters to pass in the octo build arg I listed above which worked, however I do not know how to pass that in with the scriptable builds. In the code above I try to pass that into the parameters field but the build succeeds but does not seem to look at that parameter. I tried using other fields in the link below but those do not work either. visualstudio.com/en-us/docs/build/define/options
  • What's the useage of the queue request ? Did you just want to pass the octo version Parameter? Could you use some scripts? Details about variables please see my answer below.
  • Awesome, I knew there was something I was missing. Thanks Eddie, this worked perfectly.
  • Thanks Patrick, yes as I mentioned above I saw that this needs to be passed in using variables, but I am not sure how to do in c# not powershell. I have added it to the build def specification as queue time but I am not sure how to pass this variable into QueueBuildAsync. I looked through the documentation and I could not find this either.
  • @KiritChandran I'm not pretty sure which arguments you want to pass. Did you just want to queue a build from C#? Besides if you are using QueueBuildAsync with old TFS API the same as XAML build. I'm afraid this will not work on vNext build. Maybe this is the root cause. You need to use Rest API, take a look at this tutorial How to trigger a build in TFS 2015 using REST API& tech.en.tanaka733.net/entry/…