How do I integrate StyleCop 4.5.25 into msbuild in VS2010? - visual-studio-2010

How do I setup StyleCop 4.5.25 (via NuGet package manager in VS2010) to integrate with MSBuild?
I currently have StyleCop 4.4 and the following setup:
http://stylecop.codeplex.com/wikipage?title=Running%20StyleCop%20in%20VS2005%20or%20VS%20Express&referringTitle=Documentation
My goal is to switch from the current setup to using Nuget as my package manager for Stylecop while retaining the biuld integration. There are only 2 files in the package installed by Nuget(src\packages\StyleCop.4.5.25.0\lib\net35): StyleCop.dll and StyleCop.CSharp.dll. Since there is no targets file, I am not sure how to integrate this new version.

In your msbuild file add:
<!--this will import stylecop as a task -->
<UsingTask AssemblyFile="$(StyleCopInstallDirectory)Microsoft.StyleCop.dll" TaskName="StyleCopTask"/>
<Target Name="RunStyleCop" >
<StyleCopTask
ProjectFullPath="$(MSBuildProjectFile)"
SourceFiles="#(StyleCopFiles)"
ForceFullAnalysis="$(StyleCopForceFullAnalysis)"
DefineConstants="$(DefineConstants)"
TreatErrorsAsWarnings="$(StyleCopTreatErrorsAsWarnings)"
CacheResults="$(StyleCopCacheResults)"
OverrideSettingsFile="$(StyleCopOverrideSettingsFile)" />
</Target>

A colleague recently tried to do something similar. It looks like the NuGet package contains only the libraries for creating StyleCop rules. It does not contain everything you need to run StyleCop as part of the build process.
For now, we just committed the StyleCop stuff, but we're hoping a NuGet package to set it all up appears soon!

Related

Automate Artifactory NuGet download during build in Visual Studio

I have been working with Artifactory NuGet packages in Visual Studio 2019 recently, and have a workflow which looks sort of like this:
Add private Artifactory repo as NuGet Package Source
Download specific older version of my NuGet package [either using Package Manager UI or Package Manager Console]
Once NuGet package is installed, build VS2019 project
I need to eliminate the need for a user to know how to go through these steps, and make it as simple as possible for a Visual Studio 2019 project to automatically install a specific version of my private NuGet package hosted in artifactory.
I've been trying to accomplish this but with no luck, I'm not sure if this would best be done by editing the Visual Studio project file, or by editing the windows global nuget.config file, or create a custom nuget.config file for my visual studio project.
Any advice/help would be appreciated, thanks.
Since your question does not contain relevant information like if you're using a Visual Studio Solution (*.sln file), Git, etc., I can only have a guess 😉
Assuming you're using Git and having a folder structure like this:
- MyProject
- .git
- MyProject.sln
- ProjectA
- ProjectA.csproj
- ProjectB
- ProjectB.csproj
Now you can create a file MyProject/NuGet.config with the following content and put it under version control:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<packageSources>
<add key="Your Artifactory source" value="https://your.artifactory.source/v3/index.json" />
</packageSources>
</configuration>
According to the docs, NuGet should pick up NuGet.config automatically.

Self-hosted Azure Devops build cant resolve packages

I have a Azure DevOps build pipeline that runs as expected on a hosted vs2017 agent, but fails on a self-hosted agent.
The error I get in the Visual Studio build step is:
C:\WINDOWS\TEMP\.NETStandard,Version=v2.0.AssemblyAttributes.cs(4,20): Error CS0400: The type or namespace name 'System' could not be found in the global namespace (are you missing an assembly reference?)
The two agents seems to run the same version of msbuild.
From the diagnostic output from msbuild I can see that the output from the ResolvePackageDependencies task contains a lot of packages where the ResolvedPath is empty, for instance:
runtime.native.System/4.3.0
Name=runtime.native.System
Path=runtime.native.system/4.3.0
ResolvedPath=
Type=package
Version=4.3.0
But the NuGet restore step seems to complete without problems.
Any suggestions for what I am missing?
I believe I had a similar issue. I ended up having to install the latest Nuget and then run Nuget on the solution including a NuGet.config file.
Add a nuget.config to your solution so it is part of your repo/pull. Mine is in the same directory as the solution file. Example below
Add a task "NuGet Tool Installer" - I install NuGet 4.4.1, just put 4.4.1 in the Version to install input.
Add a task "NuGet Installer" - Different from above. Version 0.* - I have not tried the other versions.
Set the Path to the solution. IE. $(Build.Repository.LocalPath)/Source/Sample.sln
Add the path to the Nuget config file. Example $(Build.Repository.LocalPath)/Source/nuget.config
Nuget.config contains how to get the packages. Add other locations if you get packages from other sources like a local folder or something.
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<!--
Used to specify the default Sources for list, install and update.
See: nuget.exe help list
See: nuget.exe help install
See: nuget.exe help update
-->
<packageSources>
<add key="nuget.org" value="https://api.nuget.org/v3/index.json" protocolVersion="3" />
</packageSources>
<packageRestore>
<!-- Allow NuGet to download missing packages -->
<add key="enabled" value="True" />
<!-- Automatically check for missing packages during build in Visual Studio -->
<add key="automatic" value="True" />
</packageRestore>
Your build task should run fine now and find all the packages.
Self-hosted Azure Devops build cant resolve packages
According to the error message, it seem nuget not restore the reference from SDK.
To resolve this issue, we need update our nuget.exe version to 4.0 and above.
In the NuGet tool installer we could specify the nuget.exe version:
As you comment above, it seems you have already use nuget installer, in this case, you can try to update Visual Studio to 15.3 and above on the build server. Because VS only adds proper support for .NET Core 2.0 SDK in version 15.3.
Finally, if your project/solution is .net core/standard you can use dotnet restore and then run dotnet build to compile your app.
Hope this helps.

VS 2013 Run StyleCop Option

I have enabled StyleCop in VS2013 using following steps
Installed StyleCop with command install-package stylecop.msbuild
Updated below lines in .csproj file
a. <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<Import Project="$(ProgramFiles)\MSBuild\StyleCop\v4.7\StyleCop.targets" />
b. <StyleCopTreatErrorsAsWarnings>false</StyleCopTreatErrorsAsWarnings> in first <PropertyGroup> of the .csproj file.
Copy Settings.StyleCop in the project solution folder from C:\Program Files\StyleCop 4.7 on solution root folder or add as a solution item.
Double click the Settings.StyleCop file as configure the rules. You should be able to use the stylecops in your project.
When I build the application, StyleCop functionality is working as expected.
But when I right click on any project I don't see the option "Run StyleCop" or "Run StyleCop (Rescan All).
Can anybody help me on this ?
The nuget package StyleCop.MSBuild simplifies the adding of the properties to a csproj required to run StyleCop as part of the build. It also references a StyleCop instance inside /packages/ which means that it is downloaded from sourcecontrol and each developer does not need StyleCop installed.
To get the context menus, you need to install StyleCop on your local machine.

NuGet restoring PostSharp package before the build begins

I am using PostSharp and I have the following target description in my project file:
<Target Name="EnsurePostSharpImported" BeforeTargets="BeforeBuild" Condition="'$(PostSharp30Imported)' == ''">
<Error Condition="!Exists('..\..\packages\PostSharp.3.1.33\tools\PostSharp.targets')" Text="This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them. For more information, see http://www.postsharp.net/links/nuget-restore." />
<Error Condition="Exists('..\..\packages\PostSharp.3.1.33\tools\PostSharp.targets')" Text="The build restored NuGet packages. Build the project again to include these packages in the build. For more information, see http://www.postsharp.net/links/nuget-restore." />
</Target>
As far as I understand, this is added to the project when PostSharp is referenced through NuGet, and the error conditions check the following:
The first error condition breaks the build when PostSharp is not available (i.e. NuGet did not restore it successfully).
The second error condition breaks the build when PostSharp was successfully restored by NuGet on the last build but was therefore not included in the project, so therefore a rebuild is necessary.
BUT, if I have the following configuration in NuGet.Config and .csproj file, is the second error condition even necessary?
NuGet.Config file:
<configuration>
<packageRestore>
<!-- Allow NuGet to download missing packages -->
<add key="enabled" value="True" />
<!-- Automatically check for missing packages during build in Visual Studio -->
<add key="automatic" value="True" />
</packageRestore>
...
</configuration>
.csproj file:
<RestorePackages>true</RestorePackages>
As far as I understand, NuGet will then restore the missing packages BEFORE the build even starts. The second error condition will essentially break the build for no reason at all.
Note: I am using Visual Studio 2013 and NuGet 2.8.
It depends on how the restore is done and which version of NuGet you have installed. It looks like the error messages are trying to cover three scenarios:
Building without the MSBuild based package restore enabled (which is configured inside Visual Studio by right clicking the solution and selecting Enable Package restore).
Building outside of Visual Studio when the MSBuild based package restore is not enabled.
Building with Visual Studio using an old version of NuGet which does not support the automatic restore before a build.
If you are using the MSBuild based package restore then the restore will occur during the build and the PostSharp files will not be imported at this point so the $(PostSharp30Imported) will be empty and the second error message will be displayed. At least I suspect that is the case.
If you building from the command line and not using the MSBuild based package restore then you would see the first error message if the NuGet packages were missing.
If you are not using the MSBuild based package restore, and are building from within Visual Studio with a recent version of NuGet, then you are correct that the packages will be restored before anything is built at all. So the PostSharp imports should be available to MSBuild before it is even executed.
As PostSharp dlls are required during msbuild loading (so targets referencing this dlls are available during build) they must be available during final call to msbuild.
While in VS it is acceptable to click build twice, I was using PostSharp in CI environment, and requirement to call build on solution two times was frustrating (first build restore nugets but also failed build due to error).
I ended up with separate build steps:
Restore nuget Packages (this downloads PostSharp packages and return success code to environment):
NuGet.exe restore SolutionWithProjectsUsingPostSharp.sln
Build solution.
You need to edit the second error condition in the target in the csproj
<Target Name="EnsurePostSharpImported" BeforeTargets="BeforeBuild" Condition="'$(PostSharp30Imported)' == ''">
<Error Condition="!Exists('....\packages\PostSharp.3.1.33\tools\PostSharp.targets')" Text="This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them. For more information, see http://www.postsharp.net/links/nuget-restore." />
<Error Condition="Exists('....\packages\PostSharp.3.1.33\tools\PostSharp.targets')" Text="The build restored NuGet packages. Build the project again to include these packages in the build. For more information, see http://www.postsharp.net/links/nuget-restore." />
</Target>>
I have answered in detail in a different post at SO
We are using 'old' MSBuild-Integrated package restore ( .nuget\NuGet.targets file is present) and normally do not store in source control packages, but rely on build to restore them for each build.
But for PostSharp on TeamCity build server I am getting error :
The build restored NuGet packages. Build the project again to include
these packages in the build.
The simplest way is to explicitly include in source control packages\PostSharp.VerXXX.
Alternatively solution could be migrating to automatic package restore,
as it was advised in Issue Using PostSharp 3.x with NuGet Auto Restore
Right click on the solution, Manage Nuget packages; and remove the packages you dont want .
This error also shows up , when trying to restore the packages from the web. Just connect your self to the internet and then try opening the project.
The errors went away for me on following the above steps.

TransformXml task could not be loaded from Microsoft.Web.Publishing.Tasks.dll

Has anyone seen this error and know how to fix it?
The "TransformXml" task could not be loaded from the assembly C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v11.0\Web\Microsoft.Web.Publishing.Tasks.dll.
Could not load file or assembly 'file:///C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v11.0\Web\Microsoft.Web.Publishing.Tasks.dll' or one of its dependencies. The system cannot find the file specified.
Confirm that the declaration is correct, that the assembly and all its dependencies are available, and that the task contains a public class that implements Microsoft.Build.Framework.ITask.
I read elsewhere that the problem is when you don't have SQL Server installed. But I do have SQL Express 2012 x64 installed with SP1. I am also running VS 2013 Professional.
I have ran this exact same solution in VS 2012 express with no problems.
The answers provided by Dai Bok and emalamisura work fine as long as you use Visual Studio 2012.
For VS 2013 this fails as well. In order to make this work with all versions of Visual Studio you should:
Open the project file (.csproj) of the project failing to load
Search for <Import Project="$(MSBuildExtensionsPath)\Microsoft\VisualStudio\v10.0\Web\Microsoft.Web.Publishing.targets" />
Change it to <Import Project="$(MSBuildExtensionsPath)\Microsoft\VisualStudio\v$(VisualStudioVersion)\Web\Microsoft.Web.Publishing.targets" />
Reload the project
That will set the correct version of Visual Studio dynamically and properly.
To get mine to work, I just copied my v10.0 folder and renamed it to v11.0, and things seems to work well from then on. That's the quick fix for now.
As this is probably not the best solution, and although it works, I was going to try installing the Microsoft Windows SDK for Windows 7 and .NET Framework 4 Windows SDK for Windows 7 and .NET Framework 4, but it is taking to long to download.
To fix the issue,
Find the Visual studio Installer in your computer
Click or tap to start the installer, and then select Modify.
From the Individual Components screen, select Asp.net and web development tools and then select Modify/Install.
This solved the issue as it creates the dll's in the mentioned path.
I've been combating this problem on our build server for several days, so I figured I'd document the resolution I came to. First, my build server has the web publishing extensions installed. I can use the TransformXml task to my heart's content inside of a web application project.
To use it outside of a web application project, I tried to add the UsingTask element to my project and point it to the right place using ms build properties (as Benjamin demonstrated). However, they weren't there on my build server (those with easy access to the file system of their build server can probably skip this and just install the relevant package to Visual Studio). I even went so far as to hard code visual studio versions, but it always dropped that error on me.
I finally gave up, pulled the DLLs from my local PC:
C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v12.0\Web\Microsoft.Web.Publishing.Tasks.dll
C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v12.0\Web\Microsoft.Web.XmlTransform.dll
I uploaded them to source control and added that folder to my build's workspace (Edit Build Definition -> Source Settings -> Source Control Folder). From there, I don't even need to reference the folder -- here's what my UsingTask looks like:
<UsingTask TaskName="TransformXml" AssemblyFile="Microsoft.Web.Publishing.Tasks.dll" />
Now I can use the TransformXml task to my heart's content from any project.
For VS2019
<UsingTask TaskName="TransformXml" AssemblyFile="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(MSBuildToolsVersion
I replaced MSBuildToolsVersion with VisualStudioVersion.
Because there are only v12.0, v14.0 and v15.0 in my VisualStudio folder, I edit my project file and change the reference path from v10.0 to v14.0. Then the project builds successfully.
Before:
<UsingTask TaskName="TransformXml" AssemblyFile="$(MSBuildExtensionsPath)\Microsoft\VisualStudio\v10.0\Web\Microsoft.Web.Publishing.Tasks.dll" />
After:
<UsingTask TaskName="TransformXml" AssemblyFile="$(MSBuildExtensionsPath)\Microsoft\VisualStudio\v14.0\Web\Microsoft.Web.Publishing.Tasks.dll" />
Solutions provided seem to work for using VS as an IDE, but if you use DotnetCore via CLI or on a unix based system this does not work.
I found that the following seem to work
<PropertyGroup>
<XmlTransformDllPath Condition="'$(XmlTransformDllPath)' == '' AND '$(MSBuildRuntimeType)' == 'core'">$(MSBuildSDKsPath)/Microsoft.NET.Sdk.Publish/tools/net5.0/Microsoft.NET.Sdk.Publish.Tasks.dll</XmlTransformDllPath>
<XmlTransformDllPath Condition="'$(XmlTransformDllPath)' == '' AND '$(MSBuildRuntimeType)' != 'core'">$(MSBuildSDKsPath)/Microsoft.NET.Sdk.Publish/tools/net472/Microsoft.NET.Sdk.Publish.Tasks.dll</XmlTransformDllPath>
<XmlTransformDllPath Condition="!Exists($(XmlTransformDllPath))">$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\Web\Microsoft.Web.Publishing.Tasks.dll</XmlTransformDllPath>
</PropertyGroup>
<UsingTask TaskName="TransformXml" AssemblyFile="$(XmlTransformDllPath)" />
This solution takes into account netcore, full .net
For some reason MSBuildSDKsPath and MSBuildExtensionsPath32 are different on windows when using CLI vs VS2019
CLI:
MSBuildSDKsPath = C:\Program Files\dotnet\sdk\5.0.103\Sdks
MSBuildExtensionsPath32 = C:\Program Files\dotnet\sdk\5.0.103
Vs2019
MSBuildSDKsPath = C:\Program Files (x86)\Microsoft Visual Studio\2019\Enterprise\MSBuild\Sdks
MSBuildExtensionsPath32 = C:\Program Files (x86)\Microsoft Visual Studio\2019\Enterprise\MSBuild
Which on my Mac returns /usr/local/share/dotnet/sdk/5.0.201
Only problem I see is with the tools/net5.0 part of the name which changes ever release
Also created https://github.com/dotnet/sdk/issues/16469 and answers this on The "TransformXml" task was not found (error MSB4036) on TeamCity build
The correct answer to this is to unload the project in question and then edit the csproj file, look for an entry where they are referencing the 10.0 path and change it to point to 11.0 instead.
You need two things to make it work:
1) Install Visual Studio Build Tools (You don't need the whole Visual Studio, only the VS Build Tools) with selected "Web development build tools" option on your build server
https://www.visualstudio.com/pl/thank-you-downloading-visual-studio/?sku=BuildTools&rel=15
2) Ensure that path to Microsoft.Web.Publishing.Tasks.dll is correct
<UsingTask TaskName="TransformXml" AssemblyFile="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(MSBuildToolsVersion)\Web\Microsoft.Web.Publishing.Tasks.dll" />
For me it started working just by adding reference to the NuGet package MSBuild.Microsoft.VisualStudio.Web.targets v14.0.0.3
Even no need to add UsingTask element to the project file as it mentioned by the package author
https://github.com/pdonald/nuget-webtargets
Just install the NuGet package. The package automatically sets the
$(VSToolsPath) property to use the targets file in the tools folder.
And then I was able to use TransformXml and other tasks, defined in the package, for instance to transform app.config
<Target Name="app_config_AfterCompile" AfterTargets="AfterCompile" Condition="Exists('app.$(Configuration).config')">
<!--Generate transformed app config in the intermediate directory-->
<TransformXml Source="app.config" Destination="$(IntermediateOutputPath)$(TargetFileName).config" Transform="app.$(Configuration).config" />
<!--Force build process to use the transformed configuration file from now on.-->
<ItemGroup>
<AppConfigWithTargetPath Remove="App.config" />
<AppConfigWithTargetPath Include="$(IntermediateOutputPath)$(TargetFileName).config">
<TargetPath>$(TargetFileName).config</TargetPath>
</AppConfigWithTargetPath>
</ItemGroup>
</Target>
Just in case someone is using an SDK-style csproj, you can achieve this without having to install Visual Studio on the build server.
First you should install the SlowCheetah nuget package to your project. Once you install it, you'll see the following in your SDK-style project.
<PackageReference Include="Microsoft.VisualStudio.SlowCheetah" Version="3.2.20">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers</IncludeAssets>
</PackageReference>
Then make sure you add the GeneratePathProperty="true" attribute (see below). This is very important for the next part because it'll help you grab the path of where the nuget package is restored on your machine. George Dangl explains it in his article here.
<PackageReference Include="Microsoft.VisualStudio.SlowCheetah" Version="3.2.20" GeneratePathProperty="true">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers</IncludeAssets>
</PackageReference>
Import the SlowCheetah targets into your project:
<Import Project="$(PkgMicrosoft_VisualStudio_SlowCheetah)\build\Microsoft.VisualStudio.SlowCheetah.targets" />
You can now use an target command (in this case after publish) to apply some custom transformations. If you need to, you can always hard-code the file names below instead of using the variables in the below example.
<Target Name="AfterPublishs" AfterTargets="Publish">
<TransformTask Source="Web.config" Transform="Web.$(Configuration).MyCustomTransformFile.config" Destination="$(PublishDir)\Web.config" />
</Target>
If you haven't used SlowCheetah before, I recommend checking it out. They have a Visual Studio extension that will make it easier for you to preview transform files.

Resources