Using MSBuild in C# - c#

I have some batch codes:
Path=C:\Windows\Microsoft.NET\Framework64\v4.0.30319
ECHO Trying TFS build...
msbuild D:\WORK\project\project.sln /p:Config="Debug" /p:Platform="Any CPU" /flp1:logfile=BuildLogProject.txt
That is working right. And I want to use MSBuild in my C# application.
I added Microsoft.Build.Engine reference and I'm using Engine class. I wrote some codes. But it is not working.
When I build project with Visual Studio or batch program "build succeeded" . When I build the project with my program it finds errors and warnings that are not in the project.
Engine engine = new Engine();
engine.BinPath = #"C:\Windows\Microsoft.NET\Framework64\v4.0.30319";
FileLogger logger = new FileLogger();
logger.Parameters = #"logfile=D:\WORK\project\BuildLogProject.txt";
engine.RegisterLogger(logger);
string projectPath = #"D:\WORK\project\project.sln";
try
{
bool success = engine.BuildProjectFile(projectPath);
}
catch (Exception ex)
{
System.Windows.Forms.MessageBox.Show(ex.Message);
}
finally
{
engine.UnregisterAllLoggers();
engine.UnloadAllProjects();
}

Your problem is that you trying to build .SLN file. Solution file isn't msbuild script itself.
only underlying .<XX>proj files are using msbuild format.
Actually when you run msbuild.exe someSLN.sln - msbuild autogenerates script based on your sln file and then execute it by engine. I don't know how you can generate it yourself, but you can peek into autogenerated file by using special environment variable (not working if you trying to pass it as property via command line).
Perform SET MSBuildEmitSolution = 1
and after execution msbuild.exe someSLN.sln you will find someSLN.sln.metaproj file near .sln one. This is what exactly shipped to build engine when you trying to build solution via command line and msbuild.exe

Related

JsReport using C# .NET core and Vs

I am trying to learn JsReport using c# and .NET core and visual studio. I have installed the required nuget packages (jsreport.binary and jsreport.Local). I am trying to replicate the code found Here. The problem is that I keep getting the following error.
***Severity Code Description Project File Line Suppression State
Error MSB3021 Unable to copy file "C:\Users\jmodiba\source\repos\js\js\obj\Debug\net6.0\apphost.exe" to "bin\Debug\net6.0\js.exe". Access to the path 'bin\Debug\net6.0\js.exe' is denied. js C:\Program Files\Microsoft Visual Studio\2022\Community\MSBuild\Current\Bin\amd64\Microsoft.Common.CurrentVersion.targets 5097***
here is the code,
using jsreport.Binary;
using jsreport.Local;
using jsreport.Types;
var rs = new LocalReporting().UseBinary(JsReportBinary.GetBinary()).AsUtility().Create();
await rs.RenderAsync(new RenderRequest()
{
Template = new Template()
{
Recipe = Recipe.ChromePdf,
Engine = Engine.None,
Content = "Hello from pdf"
}
});
I managed to find the problem. My antivirus kept on moving the .exe file created to quarantine. Once I created an exception in the antivirus setting my code ran correctly.

Selenium C# Mstest - chromedriver.exe does not exist. Getdirectory() referring some-other directory while executing vis mstest commands

when i'm running the selenium test from VS2017 it is able to pick the drivers successfully BUT when i run the same test using mstest command - internally it is referring some other directory!
C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\Common7\IDE\mstest.exe/
testcontainer:..\Test\Sun.TestAutomation.dll /test:"myfristtest"
/resultsfile:..\Test\TestResultLog.trx //Mstest commands
OpenQA.Selenium.DriverServiceNotFoundException: OpenQA.Selenium.DriverServiceNotFoundException: The file
C:\Test\xsed_2018-12-07 10_55_51\Out\chromedriver.exe does not exist.
The driver can be downloaded at
http://chromedriver.storage.googleapis.com/index.html.
code:
this.DriversPath = Path.GetFullPath(Path.Combine(Directory.GetCurrentDirectory()));
additional information:
drivers are available in debug folder why my mstest is referring the drivers in "Out" folder ??
This post is a bit old but since it was brought back to the the front, this may help someone.
I would download the ChromeDriver Nuget package. This way you always get the latest version.
Right click on your project > properties. Click on Build tab.
set Conditional compilation symbols = _PUBLISH_CHROMEDRIVER
under output path set: bin\Debug\
Once installed, clean solution and rebuild and you should see the file in the bin dir.
for your chromedriver call it should look something like this:
Driver = new ChromeDriver(Path.Combine(GetBasePath, #"bin\debug"), options);
Then add the GetBasePath code:
public static string GetBasePath
{
get
{
var basePath = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
basePath = basePath?.Substring(0, basePath.Length - 10);
return basePath;
}
}
This PC -> Properties -> advanced system settings -> Environment variables -> system variables -> Varible PATH add folder, where you have chromedriver.exe

mscorlib not found when building Xamarin.Android project with CakeBuild

I'm in the process of integrating a Xamarin Android project into our CI pipeline. We already use CakeBuild for other .NET projects and so I wanted to use it here, as well.
The problem is that I always get the following error message when trying to build with Cake:
C:\Program Files (x86)\MSBuild\Xamarin\Android\Xamarin.Android.Common.targets(406,2): error : Could not load assembly
'mscorlib, Version=0.0.0.0, Culture=neutral, PublicKeyToken='. Perhaps it doesn't exist in the Mono for Android profile? [C:\[myproject].csproj]
Building works in Visual Studio 2015 and using the Visual Studio Developer Command Prompt. Because of this, I was thinking it had something to do with the environment variables that are set in VS and via the VS command prompt. So what I did was make a small batch file:
call "%vs140comntools%vsvars32.bat"
Powershell.exe ./build.ps1 -Target Build
But I'm getting the exact same error. In my projects, there is no explicit reference to mscorlib.
The Cake build task looks like this:
Task("Build")
.IsDependentOn("Restore-NuGet-Packages")
.Does(() =>
{
var settings = new MSBuildSettings()
{
ArgumentCustomization = args =>
{
args = args.Append("/t:PackageForAndroid");
args = args.Append("/p:TargetFrameworkRootPath=\"C:\\Program Files (x86)\\Reference Assemblies\\Microsoft\\Framework\"");
return args;
},
Verbosity = Verbosity.Normal
};
settings.SetConfiguration(configuration);
MSBuild("../myproject.csproj", settings);
});
I had to add the TargetFrameworkRootPath because it won't find the reference assemblies if I do not set it explicitly.
I'm wondering what else to do to replicate the build environment of VS / VS command prompt.
Are you targeting .NET Standard or is this still using PCL?
What does the verbose output look like? It should give you the exact MSBuild command being executed.
call "%vs140comntools%vsvars32.bat"
Powershell.exe ./build.ps1 -Target Build -Verbosity Diagnostic

MSBuild failing. Missing Release/WinRTXamlToolkit

Trying to build a Windows 8.1 store app with msbuild but getting an error. This is my first battle with msbuild and I haven't had much luck with the documentation as it all appears to leverage UWP specific things. The error I'm getting reads
C:\git\adr\win8app\src\AppDataRoom.WinRT.Adr\AppDataRoom.WinRT.Adr.csproj" (default target) (1) ->
(_GenerateAppxPackageRecipeFile target) ->
C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v14.0\AppxPackage\Microsoft.AppXPackage.Targets(2156,5): error
APPX0702: Payload file 'C:\app\bin\x64\Release\WinRTXamlToolkit\WinRTXamlToolkit.xr.xml' do
es not exist.
There are 25 other errors following all related to WinRTXamlToolkit missing inside of the bin\x64\Release folder
My msbuild command I'm running is:
msbuild .\app.csproj /p:Configuration="Release" /p:Platform="x64
I understand WinRTXamlToolKit is a nuget package and I can see the dll inside of the release folder but how what do I do to solve this error? What am I missing?
I ended up finding a solution (although it still feels a little hacky). I ended up wrapping everything in an a powershell script. The script first restores the projects nuget packages, just in case it's not there for some reason. Then the script copies the WinRTXamlToolKit folder from packages into the bin/x64/Release folder and then I run the MSBuild command and now everything appears to build correctly. Here is what the script looks like (I don't write powershell scripts very often so my conventions may not be the best)
#create some alias
$nugetPath = $sourceControlRoot + ".nuget/nuget.exe";
$nugetPackagesPath = $sourceControlRoot + "/packages/";
$projectPath = $sourceControlRoot + "/TestingProject/"
Set-Alias nuget $nugetPath
#Nuget Restore
$solutionPath = $sourceControlRoot + "/TestingProject.sln"
nuget restore $solutionPath
#To Help MSBuild we need to copy the WinRTXamlToolkit into the bin/Release folders
$winRtXamlToolkitPath = $nugetPackagesPath + "WinRTXamlToolkit.1.6.1.3/lib/netcore451/WinRTXamlToolkit"
$copyOutput64 = $projectPath + "bin/x64/Release/WinRTXamlToolkit"
$copyOutput86 = $projectPath + "bin/x86/Release/WinRTXamlToolkit"
$testPath = $copyOutput64
if (!(Test-Path $testPath )) {
Copy-Item $winRtXamlToolkitPath $copyOutput64 -recurse
Copy-Item $winRtXamlToolkitPath $copyOutput86 -recurse
Write-Output "WinRTXamlToolkit copied into bin folders"
}
#build the project
$buildPath = $projectPath + "TestingProject.csproj"
msbuild $buildPath /p:Configuration="Release" /p:Platform="x64"

create nuget package fails with 'Path is not of a legal form'

In a post build step we create nuget packages. For some reasons this always fails on my machine, while it works on other developers machines.
The command executed is:
nuget.exe pack "$(ProjectPath)" -Properties Configuration=$(ConfigurationName) -OutputDir "$(ProjectDir)..\Apps"
The output i get is:
Packing files from ''.
Using 'Organisation.AppName.Modules.Kcs.nuspec' for metadata.
The path is not of a legal form.
For other developers the first line contains the directory. What can be the reason it is working differently on my box? Are there options i can set to change this behavior?
Edit:
I downloaded the nuget source and found the point things start to go wrong. With a small test program i can simulate it:
using System;
using Microsoft.Build.Evaluation;
namespace CheckTarget
{
class Program
{
static void Main(string[] args)
{
if (args.Length == 0)
{
Console.WriteLine("usage: CheckTarget projectfile.csproj");
Console.WriteLine();
return;
}
string path = args[0];
var project = new Project(path);
Console.WriteLine("TargetDir = {0}", project.GetProperty("TargetDir") != null ? project.GetProperty("TargetDir").EvaluatedValue : string.Empty);
Console.WriteLine("TargetPath = {0}", project.GetProperty("TargetPath").EvaluatedValue);
Console.ReadKey();
}
}
}
On my machine the targetdir is null, on another machine the targetdir points to valid directory.
Use property Platform to -Properties parameter in nuget program
-Properties Platform=$(Platform)
where $(Platform) is one of your project platform (defined in csproj file, typically x86, 'Any CPU', ..).
ie in your case, run something like:
nuget.exe pack "$(ProjectPath)" -Properties Configuration="$(ConfigurationName)" Platform="$(Platform)" -OutputDir "$(ProjectDir)..\Apps"
Finally found the answer. This thread helped me locate the problem:
http://social.msdn.microsoft.com/Forums/en-US/msbuild/thread/d3c6e2de-1e87-49c2-b059-df074868e315/
On my machine there was an environment variable 'platform' with value 'BWS'. Deleted it and things are working!
I had the same problem basically it was an old nuget version that I carried in my source control, I deleted the .nuget folder then I uninstalled nuget from visual studio, by selecting
tools > extensions & updates,
select nuget & uninstall and then do the same process but for Installing it, just make sure you al searching in the "online" repository.
I had to update the Nuget Manager from Updates And Extensions. Restarted VS, and it worked fine.
For me the problem was that no .dll was inside the Debug folder and without the -properties Configuration=Release option nuget usually tries to find a dll in the Debug folder.
Running nuget pack manually gave me an useful error message. Running it as post build event I got the same obscure error message as you.

Categories

Resources