Configure MSBuild to launch PowerShell and run Import-Module $(TargetFileName) - c#

I am learning how to develop PowerShell module in c# but there is no Visual Studio integration to launch PowerShell with the module imported.
I would like to configure MSBuild to launch PowerShell and run Import-Module $(TargetFileName).
I configured my project as a library project and set the debug options to launch PowerShell and set the command line argument to -NoExit -Command "Import-Module .\PowerShellModule.dll". However I am not satisfied with this solution.
My goal is to launch PowerShell with the module i'm working loaded and the debugger attached when I press F5 in Visual Studio. Ideally I would like to use the MSBuild Macro to create a reusable template and avoid using the csproj.user file.
Here is the relevent csproj.user file:
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="12.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|AnyCPU'">
<StartArguments>-NoExit -Command "Import-Module .\PowerShellModule.dll "</StartArguments>
<StartAction>Program</StartAction>
<StartProgram>C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe</StartProgram>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|AnyCPU'">
<StartAction>Program</StartAction>
<StartProgram>C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe</StartProgram>
<StartArguments>
</StartArguments>
</PropertyGroup>
</Project>

I was able to achieve what I wanted by adding the following lines under PropertyGroup in my csproj.
<StartAction>Program</StartAction>
<StartProgram>C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe</StartProgram>
<StartArguments>-NoExit -Command "Import-Module .\$(AssemblyName).dll"</StartArguments>

Related

Azure Devops dotnet build don't respect configuration

In the csproj file of a project I have conditionals for TreatWarningsAsErrors.
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
<TreatWarningsAsErrors>False</TreatWarningsAsErrors>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|AnyCPU'">
<TreatWarningsAsErrors>True</TreatWarningsAsErrors>
</PropertyGroup>
On my computer running
dotnet build solution.sln --Configuration Debug
vs
dotnet build solution.sln --Configuration Release
produces the different results with success and failure as expected.
On our on-prem azure devops server however, even though the log clearly states "--Configuration Release" they show the problems as Warnings. Not failures as expected.
What can be wrong here?
The build log excerpts:
Starting: dotnet build
==============================================================================
Task : .NET Core
Description : Build, test, package, or publish a dotnet application, or run a custom dotnet command
Version : 2.181.0
Author : Microsoft Corporation
Help : https://learn.microsoft.com/azure/devops/pipelines/tasks/build/dotnet-core-cli
==============================================================================
C:\Windows\system32\chcp.com 65001
Active code page: 65001
Info: .NET Core SDK/runtime 2.2 and 3.0 are now End of Life(EOL) and have been removed from all hosted agents. If you're using these SDK/runtimes on hosted agents, kindly upgrade to newer versions which are not EOL, or else use UseDotNet task to install the required version.
F:\A\BUILDEDUI12C-B01\_work\_tool\dotnet\dotnet.exe build F:\A\BUILDEDUI12C-B01\_work\754\s\Modules\ScheduleMaker\Backend\ScheduleMaker.sln "-dl:CentralLogger,\"F:\A\BUILDEDUI12C-B01\_work\_tasks\DotNetCoreCLI_5541a522-603c-47ad-91fc-a4b1d163081b\2.181.0\dotnet-build-helpers\Microsoft.TeamFoundation.DistributedTask.MSBuild.Logger.dll\"*ForwardingLogger,\"F:\A\BUILDEDUI12C-B01\_work\_tasks\DotNetCoreCLI_5541a522-603c-47ad-91fc-a4b1d163081b\2.181.0\dotnet-build-helpers\Microsoft.TeamFoundation.DistributedTask.MSBuild.Logger.dll\"" --configuration Release -p:CustomBeforeMicrosoftCommonTargets=F:\A\BUILDEDUI12C-B01\_work\754\s\WE.CI.Tools.Build\Utilities\Education.SonarQube.ImportBefore.targets -p:SQProjectKey=WE.Education.ScheduleMaker
Microsoft (R) Build Engine version 17.1.1+a02f73656 for .NET
[warning]Modules\ScheduleMaker\Backend\Service\WE.Education.ScheduleMaker.Business\Services\ActivityService.cs(61,13): Warning S125: Remove this commented out code.
Edit:
From the diagnostics log i can see that the condition works, it says it changes the variable to True.
2022-04-14T07:06:33.6901214Z Property reassignment: $(TreatWarningsAsErrors)="True" (previous value: "false") at F:\A\BUILDEDUI12A-B01\_work\650\s\Modules\ScheduleMaker\Backend\Service\WE.Education.ScheduleMaker.Business\WE.Education.ScheduleMaker.Business.csproj (19,5)
But It dosen't act as it's true.
The solution, to get it listed as errors in Azure Devops was to add a property so it looked like this:
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
<TreatWarningsAsErrors>False</TreatWarningsAsErrors>
<MSBuildTreatWarningsAsErrors>False</MSBuildTreatWarningsAsErrors>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|AnyCPU'">
<TreatWarningsAsErrors>True</TreatWarningsAsErrors>
<MSBuildTreatWarningsAsErrors>true</MSBuildTreatWarningsAsErrors>
</PropertyGroup>
Then the setting was property forwarded in Azure Devops to.

Dotnet publishing via cmd not possible

I'm successfully publishing a .NET Core App via Visual Studio but am unable to do the same via command-line (or using the Developer Command Prompt for VS 2019).
I'm using the Publish profile generated by VS2019 and doing:
dotnet publish -p:PublishProfile=Properties\PublishProfiles\MyProfile.pubxml
where MyProfile is:
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<PublishProtocol>FileSystem</PublishProtocol>
<Configuration>Release</Configuration>
<Platform>Any CPU</Platform>
<TargetFramework>netcoreapp3.1</TargetFramework>
<PublishDir>..\Build\Release\publish\</PublishDir>
<RuntimeIdentifier>win-x64</RuntimeIdentifier>
<SelfContained>true</SelfContained>
<PublishSingleFile>False</PublishSingleFile>
<PublishReadyToRun>False</PublishReadyToRun>
<PublishTrimmed>False</PublishTrimmed>
</PropertyGroup>
</Project>
And the error that I always get is:
MyCustom.dll. Could not load type
'Microsoft.Build.Utilities.AppDomainIsolatedTask' from assembly
'Microsoft.Build.Utilities.Core, Version=15.1.0.0, Culture=neutral,
PublicKeyToken=b03f5f7f11d50a3a'. 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.
What am I missing?
I found a workaround, rather than a fix.
If we use msbuildto publish, I'm able to have the same result as dotnet publish and it runs successfully in the command-line:
msbuild /restore /t:Publish /p:RuntimeIdentifier=win-x64 /p:configuration=Release

How can bindings for azure function be added at compile time with MSBuild?

I have an azure function C# project in visual studio which has a few service bus topic triggers. I have a powershell script which can be run to copy the function.json files generated in bin and convert them to queue bindings. The only problem is that azure functions introduce a private target in msbuild after the Build target called _GenerateFunctionsPostBuild . So I am trying to look for a way to run a powershell script after this step so my changes dont get erased by the unique builds for azure functions.
So I am trying to look for a way to run a powershell script after this step so my changes dont get erased by the unique builds for azure functions.
To accomplish this, you can add a custom to execute the powershell script after the target _GenerateFunctionsPostBuild, like <Target Name="InvokePowerShell" AfterTargets="_GenerateFunctionsPostBuild">.
Details steps:
Right your project, select Edit YourProjectName.csproj.
At the very end of the project, just before the end-tag </Project>
, place below scripts:
<Target Name="InvokePowerShell" AfterTargets="_GenerateFunctionsPostBuild">
<PropertyGroup>
<PowerShellExe Condition=" '$(PowerShellExe)'=='' ">
%WINDIR%\System32\WindowsPowerShell\v1.0\powershell.exe
</PowerShellExe>
<ScriptLocation Condition=" '$(ScriptLocation)'=='' ">
C:\Path With Spaces\LogDeploy.ps1
</ScriptLocation>
<LogFileLocation Condition=" '$(LogFileLocation)'=='' ">
C:\Path With Spaces\ContactManagerDeployLog.txt
</LogFileLocation>
</PropertyGroup>
<Exec Command="$(PowerShellExe) -NonInteractive -executionpolicy Unrestricted
-command "& {
&&apos;$(ScriptLocation)&apos;
&apos;$(LogFileLocation)&apos;
&apos;$(MSDeployComputerName)&apos;} "" />
</Target>
Then the powershell script would be executed after the target _GenerateFunctionsPostBuild.
For Target Build Order and Running Windows PowerShell Scripts from MSBuild Project Files for some more details.
Hope this helps.

Using a publish profile with msbuild

I'm trying to use a publish profile with the msbuild command in a PowerShell window on a machine that does not have the full Visual Studio IDE installed. I have tried the following:
msbuild.exe .\Web.Admin.csproj /p:'DeployOnBuild=true;PublishProfile=Default;'
MSBuild.exe .\Web.Admin.csproj /p:PublishProfile=Default /p:VisualStudioVersion=14.0
msbuild.exe .\Web.Admin.csproj /p:PublishProfileRootFolder=C:\Users\username\Projects\Web\Web.Admin\Properties\PublishProfiles /p:PublishProfile=Default
In both cases, the publish profile seems to be ignored. This is the publish profile, generated by Visual Studio (in Properties\PublishProfiles\Default.pubxml):
<?xml version="1.0" encoding="utf-8"?>
<!--
This file is used by the publish/package process of your Web project. You can customize the behavior of this process
by editing this MSBuild file. In order to learn more about this please visit https://go.microsoft.com/fwlink/?LinkID=208121.
-->
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<WebPublishMethod>FileSystem</WebPublishMethod>
<PublishProvider>FileSystem</PublishProvider>
<LastUsedBuildConfiguration>Release</LastUsedBuildConfiguration>
<LastUsedPlatform>Any CPU</LastUsedPlatform>
<SiteUrlToLaunchAfterPublish />
<LaunchSiteAfterPublish>True</LaunchSiteAfterPublish>
<ExcludeApp_Data>True</ExcludeApp_Data>
<publishUrl>C:\Sites\Test</publishUrl>
<DeleteExistingFiles>True</DeleteExistingFiles>
<PrecompileBeforePublish>True</PrecompileBeforePublish>
<EnableUpdateable>True</EnableUpdateable>
<DebugSymbols>False</DebugSymbols>
<WDPMergeOption>DonotMerge</WDPMergeOption>
</PropertyGroup>
</Project>
The files are not published to the C:\Sites\Test directory specified, as they would be if I ran this with the Publish command in Visual Studio 2017. Instead they go to the project bin directory.
MSBuild Version: 14.0.23107.0

No DEBUG constant define, #if DEBUG returns true on release build

We have a console app, that we use to call DbUp (create db, update, test data, etc..).
We have a configuration, Stable, that is configured to NOT define the DEBUG constant:
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Stable|AnyCPU'">
<OutputPath>bin\Stable\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<Optimize>true</Optimize>
<DebugType>pdbonly</DebugType>
<PlatformTarget>AnyCPU</PlatformTarget>
<ErrorReport>prompt</ErrorReport>
<CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
<Prefer32Bit>true</Prefer32Bit>
</PropertyGroup>
Yet when this gets run on Octopus, this always returns true and holds up the deployment:
#if DEBUG
Console.ReadLine();
#endif
When I switch to the Stable configuration locally (VS), it runs and exits as expected.
When I switch to the Debug configuration locally (VS), it runs and waits for input, as expected.
If I comment out the lines completely, it runs fine on Octopus (exits, deployment finishes on Octopus).
This has me questioning all my choices in life.
Any idea why this may be happening?
EDIT - Command used to build the project (using TeamCity)
# Database
Invoke-Msbuild "$rootDir\artifacts\output\Database" `
"$rootDir\MyClient.Database\MyClient.Database.csproj" `
-target 'build' `
-toolsVersion 4.0 `
-maxCpuCount 8 `
-VisualStudioVersion 14.0 `
-logPath "$rootDir\artifacts\logs\Database" `
-namespace 'MyClient' `
-customParameters #('/property:RunOctoPack=true', "/property:OctoPackPackageVersion=$version", "/property:OctoPackNuGetProperties=env=$environment")
Build servers build. Octopus deploys.
So i do not think that Octopus has something to do with this problem.
Do you have a build server like TeamCity? Perhabs is there something wrong in the configuration?
EDIT:
Do you try this Parameter?
-MsBuildParameters "/target:Clean;Build /property:Configuration=Stable;Platform=""Mixed Platforms""

Categories

Resources