Visual Studio Build Tasks - TFS Operations - visual-studio

I'm looking to extend some post build tasks to include the checking out and then checking in of a DLL. We are using TFS and I know there are command line tools to do this. What I don't know how to do is to integrate these into my existing post build tasks. Right now my post build tasks are simple and are managed in Visual Studio through the project properties. Eventually I want to break out my custom build tasks into external files and call them in, but that is the subject of another question ;)

Without resorting to custom Build tasks you could try to use the Team Foundation Source Control Command-Line tool (tf.exe).
The example below shows how to use tf.exe to check out a file from TFS.
<PropertyGroup>
<TfCommand>
"C:\Program Files\Microsoft Visual Studio 8\Common7\IDE\tf.exe"
</TfCommand>
</PropertyGroup>
<Target Name="AfterCompile">
<Exec Command="$(TfCommand) get /force /noprompt "$(SolutionRoot)\sources\example.cs""
ContinueOnError="true" />
<Exec Command="$(TfCommand) checkout "$(SolutionRoot)\sources\example.cs""
ContinueOnError="true"/>
</Target>
Include this in your own MSBuild project file.
This example doesn't do anything useful and you need to change it to match your environment, but maybe it gives you a start.
I got this example from tfsbuild.com.

You could use the Team Foundation Server client API. TeamFoundationServer is the base class that should allow you to connect to a server, list and manipulate TFS projects.

Msbuildtasks has some extensions for msbuild with sourcecode (its opensource). You could use this to create your own checkin/checkout functionality. (in combination with what Darin suggests)
http://msbuildtasks.tigris.org/

Take a look at the SDC Tasks Library on CodePlex. It's a set of custom MSBuild tasks that includes Checkin and Checkout tasks (see the Microsoft.Sdc.Tasks.SourceTfs namespace in the accompanying documentation). You can incorporate these tasks in the "AfterBuild" target in your project file.
<SourceTfs.Checkout Path="Path" TfsVersion="tfsVersion"
WorkingDirectory="workingDirectory"/>
<SourceTfs.Checkin Path="Path" Comments="Comments" TfsVersion="tfsVersion"
WorkingDirectory="workingDirectory" Override="overrideText"/>
You would set TfsVersion to "2005" or "2008" as appropriate.

Our team has several small projects which output DLL's used by several other projects. Part of our release is to publish these DLL's. I use the AfterDropBuild target for this. Hopefully the comments in my build script snippet are clear enough to show what I am doing.
<!-- Get a reference to the new release address finalizer DLL and the existing published address finalizer DLL -->
<PropertyGroup>
<ReleaseDLL>$(DropLocation)\$(BuildNumber)\Release\Address_Finalizer.dll</ReleaseDLL>
<PublishedFolder>$(SolutionRoot)\3rd Party\bin\PG File Import</PublishedFolder>
<PublishedDLL>$(PublishedFolder)\Address_Finalizer.dll</PublishedDLL>
</PropertyGroup>
<!-- Check out the published DLL -->
<Exec WorkingDirectory="$(SolutionRoot)" Command='$(TfCommand) checkout /lock:checkout "$(PublishedDLL)"'/>
<!-- Copy release to published -->
<Copy SourceFiles="$(ReleaseDLL)" DestinationFolder="$(PublishedFolder)"/>
<!-- Check in the published DLL -->
<Exec WorkingDirectory="$(SolutionRoot)" Command='$(TfCommand) checkin /override:Automated /noprompt /comment:"$(VersionComment)" "$(PublishedDLL)"'/>

Related

Building NuGet packages from Visual Studio

I'm trying to share an internal company assembly via NuGet packages and a private source. This assembly targets .NET Framework 4.6.1. I want these NuGet packages to pack automatically from Visual Studio during the release build. I see I can add <GeneratePackageOnBuild>true</GeneratePackageOnBuild> to .csproj. I'm not sure if this is a .NET Standard-specific property but it seems to partially work. However, when I build, I get
error MSB4044: The "GetPackOutputItemsTask" task was not given a value for the required parameter "PackageOutputPath".
I've been trying to learn how to pass this parameter from within Visual Studio but I don't see a lot of documentation on parameters except when calling it from the command line manually. Is there an easy way to do this from within Visual Studio? Am I going about this wrong?
Edit: This is using a .NET Framework class library. I can run the pack command from the command line giving it the required parameters with /p:PackageOutputPath="path\here". It seems this might have been designed for .NET Core and Standard projects and Visual Studio might not handle packing .NET Framework projects.
To enable on-build packing in a "non SDK" project, using old .NET framework (eg:. 4.5.1) and visual studio 2019 without using custom Target. you need to do the following step:
add a first PropertyGroup tag on the csproj
add minimal tags Authors and PackageOutputPath
check that the same PropertyGroup has GeneratePackageOnBuild
Now the variables will be passed to the internally triggered msbuild -t:Pack command.
Here an example of working configuration, please make sure this will be the first <PropertyGroup> of the .csproj:
<PropertyGroup>
<Title>packageid</Title>
<Description>your description</Description>
<Version>1.1.1</Version>
<ReleaseNotes>New package system</ReleaseNotes>
<Authors>authors</Authors>
<Owners>owners</Owners>
<Copyright>your copyrights</Copyright>
<PackageOutputPath>bin\Package</PackageOutputPath>
<GeneratePackageOnBuild>true</GeneratePackageOnBuild>
</PropertyGroup>
If you are looking for the references, here:
how to create a nuget package with msbuild
all possible tags to set on the csproj on the first PropertyGroup
Am I going about this wrong?
This GeneratePackageOnBuild property is not something for .net framework projects. Create a new .net Standard or .net Core class library project, right-click the project you'll see a Pack command(not available for .net framework).
If we click the button, VS will pack that assembly into a nuget package. And if someone doesn't want to click that button every time manually, go Project=>Properties=>Package we can see the Generate Nuget Packages on build checkbox. Enable it, and then the nuget package will be created after every build.
Actually, enabling that checkbox in VS will add statement <GeneratePackageOnBuild>true</GeneratePackageOnBuild> to xx.csproj, but the Pack button or Package tab in Project=>Properties are not available for .net framework projects.
So I'm afraid the answer is negative, you should't use that property for .net framework projects.(I tested the property in VS2017 and VS2019, it all just did nothing, can't reproduce the partial work mentioned in your question)
Is there an easy way to do this from within Visual Studio?
You need to use nuget pack command to do that as Lex Li says. And to do this in VS automatically, you can consider configuring that command in Post-Build-Event or using custom after-build target to run that command.
Since you want these NuGet packages to pack automatically from Visual Studio during the release build. You can try adding this script into your xx.csproj file:
<Target Name="CustomPack" AfterTargets="build" Condition="'$(Configuration)'=='Release'">
<Message Text="Custom Pack command starts ..." Importance="high"/>
<Exec Command="nuget pack $(MSBuildProjectFile) -Properties Configuration=Release"/>
</Target>
To run this script successfully, you need to download the nuget.exe and add the path of it to Environment Variables. Or use the full path like "C:\SomePath\Nuget.exe" pack ...
If the build in release mode succeeds, you'll see a xx.nupkg file in project folder.
In addition:
1.For more details about nuget pack command please see this document.
2.And don't forget to create a xx.nuspec file in project folder to avoid encountering warnings like NU5115(xxx was not specified). Similar issue see here.
I have a unique situation of needing to Register for Com Interop for and older application but also needing to pack for use in other internal applications and development in our company. I actually got this to work for a .NET Framework project from Visual Studio. Manually adding GeneratePackageOnBuild did attempt to make a package for me in VS2017. I was also able to add other .NET Core project properties such as <Authors>,<Description>, etc. I haven't tried VS2019 yet so maybe that is more restricted but I hope not.
The issue is VS2017 doesn't feed the pack target the output parameter (in this type of project). So then I tried to call pack in the After Build events but that causes a recursive loop because packing also attempts to build (dotnet and nuget both seem to call the msbuild pack target which calls a build). I then found an option -p:NoBuild=true for msbuild that allows me to call the pack target without msbuild actually building the project. Therefore I added the following command to <PostBuildEvent> and it works.
"$(MSBuildBinPath)\msbuild" -t:Pack "$(ProjectPath)" -p:PackageOutputPath="$(SolutionDir)..\packages" -p:NoBuild=true
Edit: I eventually used the following in my csproj. Calling nuget directly worked better because I had a nuspec file that was not getting merged or fully used when calling MSBuild directly.
<Target Name="CustomPack" AfterTargets="Build" Condition="'$(Configuration)'=='Release'">
<Message Text="Custom Pack command starts ..." Importance="high" />
<Exec Command=""nuget" pack "$(ProjectPath)" -OutputDirectory "$(ProjectDir)..\..\packages" -Prop Configuration=Release" />
</Target>
Add this to your proj file to use the pack target on .net framework projects.
<PackageReference Include="NuGet.Build.Tasks.Pack" Version="6.4.0">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers</IncludeAssets>
</PackageReference>
if you want to run from command line then use this:
msbuild -t:restore

How to use external build system for Visual C++ 2013 project?

Is it possible to use an external build system for VC++ 2013?
I want Visual Studio do nothing but build by invoking my build tools.
I am thinking about something like this:
Put all build command in batches.
Invoke a project-level build batch by right clicking the project and choose build.
Invoke the a solution-level build batch by right clicking the solution and choose build.
Is there some walk-through tutorial? I searched a lot but no luck.
ADD 1 - Some progress...
After briefly reading about the MSBuild process, I tried as below.
First, I edit the *.vcxproj project file. I change the DefaultTargets from Build to MyTarget.
<Project DefaultTargets="MyTarget" ToolsVersion="12.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
Then I add a new target named MyTarget:
<Target Name="MyTarget">
<Message Text="Hello, Bitch!" />
</Target>
I hope this can bypass the VS2013 built-in built process and only carry out my own batch.
It works well on command prompt:
But in Visual Studio, when I right click the project and choose build command, it gives me a lot of link errors.
How to avoid these link errors? Since my batch can take care of all the build process, I don't need Visual Studio to do the link for me.
ADD 2
It seems these link errors show up because I include the *.c files with the ClCompile tag as below.
<ItemGroup>
<ClCompile Include="z:\MyProject1\source1.c" />
<ItemGroup>
Since I don't want VS2013 to invoke the compiler, I change it to <ClInclude> tag, the link errors disappeared, but the symbol resolution is not working... Seems I shouldn't change the tag.
ADD 3
Here's another way to compile without linking.
Is it possible for Visual Studio C++ to compile objects without linking
Seems it doesn't have the symbol resolution issue. But I still cannot invoke an external batch by click build/rebuild/clean.
You might want to look into Visual Studio's makefile projects (in the Visual C++/General project templates category).
You get to specify what commands to execute for each type of build (clean, build, rebuild). The command can invoke a make, run a batch file, or invoke some other build tool. It just executes a command. The commands can contain various macros that VS provides (similar to environment variables) so the command can be parametrized for things like making a target directory based on the solution or project name or type (debug vs. release).
(Michael Burr's reply pointed out a better direction, i.e. a better VC++ project template. You can combine my answer and his.)
Finally, I solved this issue!
The trick is the so-called target overriding. The Visual Studio context menu items Build\Rebuild\Clean correspond to MSBuild targets named Build\Rebuild\Clean, respectively. We just need to override them in the *.vcxproj file.
Such as this:
DO REMEMBER that:
The last target seen by MSBuild is the one that is used — this is why
we put the at the end of the existing *.vcxproj file.
And in the override.proj, do whatever you like as below:
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Target Name="Build">
<Message Text="Build override!" />
<Exec Command="kickass.bat" />
</Target>
</Project>
The following 2 links are good reference:
Hack the build
Hijacking the Visual Studio Build Process
Note that:
The 1st link take a CSharp project as example, but ALSO works with VC++ project.
The 2nd link doesn't work for VC++ project but the rational is similar. If you didn't include the Microsoft.Cpp.targets, you will see the following error when loading the project:
ADD 1
As I tried, we don't need another overrride.proj file. We can just place the specific target at the end of the *.vcxprj file. Such as below:
ADD 2
With target overriding mentioned above, I can run my customized bat file with project's Build/Rebuild/Clean commands. But I noticed that when I run solution's Build/Rebuild/Clean commands, I think it is just following some kind of project dependency order to build each project respectively, which is not exactly equivalent to what I want for an overall build in my scenario.
My current workaround is to create a dummy project and use it to trigger a batch for my overall build.

Visual Studio add pre-build event that always runs (C# project)

In my project, I am running an external tool to update some binary files. These files are included in the project as "content".
At the moment the tool is set to run during "pre-build event" in C# project properties. Unfortunately, this event is only executed if the project is out of date, which is not what I need.
I am working around this by always using "rebuild" instead of "build" on my project, but this is tedious and slow.
I need to execute this tool always, irrespective of whether a project is or is not up to date. Actually, even before MSBuild even determines whether the project is up-to-date, because the tool modifies some of the files included in the project, therefore affecting the up-to-date check result.
Is there a proper way to do it?
Here's the solution. Define this property in your project file:
<PropertyGroup>
<DisableFastUpToDateCheck>true</DisableFastUpToDateCheck>
</PropertyGroup>
PreBuildStep will then execute every time, regardless of whether the project is or isn't up to date.
It seems that Visual Studio is bypassing normal up-to-date checks of MSBuild and using some sort of custom check that is faster, but has a side effect of breaking customized build targets.
In project level, you have three options:
1) Pre-build action
<PropertyGroup>
<PreBuildEvent>notepad.exe Foo.txt</PreBuildEvent>
</PropertyGroup>
2) normal BeforeBuild target
<Target Name="BeforeBuild">
<Exec Command="notepad.exe Foo.txt" />
</Target>
3) "attached" to "Build" target (like stijn suggested)
<Target Name="BeforeBuild2" BeforeTargets="Build">
<Exec Command="notepad.exe Foo.txt" />
</Target>
Actually this solution (in case of Build) will not work, because DependsOnTargets is executed BEFORE BeforeTargets. And exactly in DependsOnTargets the real (CoreBuild) sits :)
This is why they invented the 'BeforeBuild' target ;)
In both cases VS check if something is changes (files are up-to-date). Why do you even want to run external program if nothing was changed? If this program work on file (eg. "content") msbuild and VS should detect files as out-of-date and process building.
Unfortunately IDE (Visual Studio) has it's own method to deal with msbuild projects. The main mechanism is the same, but when it's came to determine what project build or not, or in which order... VS act totalny different.
You can use external tool and run "msbuild" against your solution or project. This will also compile "the proper way" and binaries will be not different, but you will have full capabilities and potentials of MsBuild
There is also one additional pre build event that was not discussed here. Usually code analyzers are using that to check if code analyzer was downloaded by NuGet.
So if you want to execute something before code analyzers you need to use that target.
You just need to add <Target/> node under <Project/> node in your .csproj file:
<Target Name="DownloadNugetPackages" BeforeTargets="PrepareForBuild">
<Exec Command="notepad.exe Foo.txt"/>
</Target>
PrepareForBuild event will run before pre build events.
None of these solutions worked for me using Visual Studio for Mac.
I want to run a bash script before building the project but since I'm using Xamarin, some things are getting out of whack. I tried all different types of targets and even tried the CustomCommands in the project options but still I would get issues around MSbuild just running automatically or not truly running before the build
You can run the PreBuild events in a separate project that compiles before your main project.
Create a new project and name it something like "PreBuildEvent"
Add your MSbuild targets/commands as shown above to this new PreBuildEvent.csproj file for each property group/build configuration
In the project where you originally to do the PreBuild work, add a reference to this new project.
This new project will build first, executing any PreBuild events, and once this project is built, it will kick off the build for your original project. This is because when you add a reference to a project, visual studio makes sure to build them in the correct order
The solution that works for me is to have another project (configuration Makefile) and set that project as a BuildDependancy.
This avoid modification of how the prebuild step runs, and could allow you to regenerate your binary files in isolation to the rest of your build process if required.

Does Visual Studio support adding MSBuild tasks to projects?

I'm trying to add some simple MSBuild tasks to a Visual Studio project (VS 2012 Express) - specifically, to create a subdirectory then copy some files to a subdirectory of the output directory ready for packaging.
I see that VS supports custom build steps, which are command-line invocations. However, since VS is based on MSBuild it should be possible to add these directly as MSBuild tasks like the Copy Task in the AfterBuild pre-defined target.
What I can't find is any way to actually add such tasks within the framework of Visual Studio. The documentation only talks about it from an MSBuild perspective, not how it works within Visual Studio's UI. It also doesn't seem to discuss the properties that refer to build output etc there; presumably they're just those used by msbuild its self.
Is there support for MSBuild task management in Visual Studio's UI and it's just crippled out of my Express edition? Or do I have to go hack the project file XML to add MSBuild tasks? Is that supported and the way it's supposed to be done?
I'm used to working with Eclipse and Ant or Maven, where all this is supported within the IDE, though of course you can hack the XML directly. Finding no UI at all for MSBuild task management in Visual Studio is quite confusing. Am I missing the obvious or crippled by using the freebie edition?
For C++ projects, you can use the property
<CppCleanDependsOn>DeleteOutputs;$(CppCleanDependsOn)</CppCleanDependsOn>
instead of defining the BeforeClean target like you did.
From what I read, CallTarget is to be avoided. In your example, you should use DependsOnTargets to do that, as you see in many dummy targets in the MS supplied files. The analogous mechanism of a function where a target just "calls" other targets is done with DependsOnTargets. The flow is not really the same as procedural programming.
Intellisense: I never use it. Is that true for conditional AdditionalIncludeDirectories in the props file only? Go ahead and edit the entry in the proj file where the IDE put it, if you edit the property in the IDE with just one configuration chosen.
(After a bunch more reading I found out how this works):
Visual Studio doesn't seem to expose advanced MSBuild project editing, even though modern vcxproj files are just MSBuild project files with a bunch of extra labeled properties and other entries for Visual Studio IDE specifics. So you have to hack the project XML.
To make it cleaner, only add one line to your actual vcxproj file - an include of a .targets file that contains the rest of your build customisations. e.g, just before the end of the project file, insert:
<Import Project="pg_sysdatetime.targets" />
</Build>
Now create your .targets file with the same structure as any other MSBuild project. Here's mine from the project I've been working on:
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<!-- MSBuild extension targets for Visual Studio build -->
<PropertyGroup>
<DistDir>pg_sysdatetime_pg$(PGMAJORVERSION)-$(Configuration)-$(Platform)</DistDir>
</PropertyGroup>
<ItemGroup>
<DocFiles Include="README.md;LICENSE"/>
<ExtensionSourceFiles Include="pg_sysdatetime--1.0.sql;pg_sysdatetime.control"/>
<ExtensionDll Include="$(TargetDir)\pg_sysdatetime.dll"/>
</ItemGroup>
<Target Name="CopyOutputs">
<Message Text="Copying build product to $(DistDir)" Importance="high" />
<Copy
SourceFiles="#(DocFiles)"
DestinationFolder="$(DistDir)"
/>
<Copy
SourceFiles="#(ExtensionDll)"
DestinationFolder="$(DistDir)\lib"
/>
<Copy
SourceFiles="#(ExtensionSourceFiles)"
DestinationFolder="$(DistDir)\share\extension"
/>
</Target>
<Target Name="DeleteOutputs">
<Message Text="Deleting $(DistDir)" Importance="normal" />
<Delete Files="$(DistDir)"/>
</Target>
<!-- Attach to Visual Studio build hooks -->
<Target Name="BeforeClean">
<CallTarget Targets="DeleteOutputs"/>
</Target>
<Target Name="AfterBuild">
<CallTarget Targets="CopyOutputs"/>
</Target>
</Project>
This can contain whatver MSBuild tasks you want, grouped into targets. It can also have property groups, item groups, and whatever else MSBuild supports.
To integrate into Visual Studio you add specially named targets that invoke what you want. Here you can see I've defined the BeforeClean and AfterBuild targets. You can get the supported targets from the VS integration docs.
Now, when I build or rebuild, a new directory containing the product DLL and a bunch of static files is automatically created, ready to zip up. If I wanted I could add the Nuget package for MSBuild Community Extensions and use the Zip task to bundle the whole thing into a zip file at the end too.
BTW, while you can define properties in your .targets files it's better to define them in property sheets instead. That way they're visible in the UI.
I'm using VS2010 Pro, and it doesn't expose the AfterBuild target, at least in C++ projects which is what I'm doing. As you see, it does have the "Events", which according to what I've read are for backward compatibility with converted projects from VSBuild. I agree, a MSBuild task rather than a command script is the way to go.
Forget the UI. It's made to support free editing of the XML files, and continue using the UI too as it respects what you had in there and uses labels for its own stuff so it can find it to update it.
But to keep it neat, you could use a property page; a stand-alone XML file with *.props name, and put what you want in it. Then add that props file to the projects using the UI. You won't hand-edit the project file that the UI is maintaining, and it won't touch the props file unless you go through the property manager view and open it explicitly.
Oh, I also recall seeing additional standard targets something like Package and Publish. Maybe those are not used on your project type, but you could use those entry points anyway.

Does Msbuild recognise any build configurations other than DEBUG|RELEASE

I created a configuration named Test via Visual Studio which currently just takes all of DEBUG settings, however I employ compiler conditions to determine some specific actions if the build happens to be TEST|DEBUG|RELEASE.
However how can I get my MSBUILD script to detect the TEST configuration??
Currently I build
<MSBuild Projects="#(SolutionsToBuild)" Properties="Configuration=$(Configuration);OutDir=$(BuildDir)\Builds\" />
Where #(SolutionsToBuild) is a my solution. In the Common MsBuild Project Properties it states that $(Configuration) is a common property but it always appears blank?
Does this mean that it never gets set but is simply reserved for my use or that it can ONLY detect DEBUG|RELEASE. If so what is the point in allowing the creation of different build configurations?
I haven't done much with defining an MSBUILD configuration file but I have done builds of different configurations using a batch file like this
msbuild /v:n /p:Configuration=Release "Capture.sln"
msbuild /v:n /p:Configuration=ReleaseNoUploads "Capture.sln"
I defined the ReleaseNoUploads configuration inside Visual Studio.
Here's what I had to do for that (this is Visual Studio 2005):
Open the Tools:Options menu, go to the Projects and Solutions:General option, and check Show advanced build configurations.
From there, go to the Build:Configuration Manager menu
In the dialog that pops up, click on the Active solution configuration pulldown and click <New...> to create a new build configuration.
Sure, you can have as many custom build configurations as you want to define. See this related question for how the setup might look.
How to conditionally deploy an app.config based on build configuration?
Note that when 'inside visual studio', the $(Configuration) and $(Platform) are always set by VS using the Configuration Manager stuff in the dropdowns at the top. Whereas if you want to set these values using msbuild from the command line, you must pass in the values explicitly (as in #MarkBiek's answer).
(Most VS project templates will 'default in' a value for Configuration/Platform, so that you can use the command-line MSBuild without specifying these values explicitly. This is good, but makes these two useful/common properties appear a little more magical/weird than they actually are.)
Normally what I do to have Release and Debug both build from a single MSBuild script is:
<PropertyGroup Condition="'$(Configuration)'==''">
<Configuration>Debug;Release</Configuration>
</PropertyGroup>
Then add this but of MSBuild secret sauce:
<Target Name="configurations">
<CreateItem Include="$(Configuration)">
<Output TaskParameter="Include" ItemName="Configuration" />
</CreateItem>
</Target>
And then for each target do something like this:
<Target Name="Compile" DependsOnTargets="configurations" Inputs="#(Configuration)" Outputs="target\%(Configuration.FileName)">
<MSBuild Projects="#(MyProjects)" Targets="Build" Properties="Configuration=%(Configuration.Identity);WarningLevel=1" />
</Target>

Resources