How to integrate conditional logic in postbuild events - c#

Hi I have a visual studio project which includes postbuildevents in the following form:
MyTool.exe $(ProjectDir)somesrcfile.txt $(TargetDir)sometargetfile.bin
Now I want to add some logic saying that these steps are taking place only if the files have changed. In peudocode:
if (somesrcfile.txt is newer than sometargetfile.bin)
{
MyTool.exe $(ProjectDir)somesrcfile.txt $(TargetDir)sometargetfile.bin
}
Can I do this with MsBuild?
EDIT:
I just tried it with a simple copy command but it seems not to work. Also the message is not displayed when I build the solution.
<ItemGroup>
<MyTextFile Include="*.txt" />
</ItemGroup>
<Target Name="Build" Inputs="#(MyTextFile)" Outputs="#(MyTextFile->'%(Filename).bin')">
<CustomBuild>
<Message>Encoding files...</Message>
<Command>
copy %(Identity) %(Filename).bin
</Command>
<Outputs>$(OutDir)%(Identity)</Outputs>
</CustomBuild>
</Target>

Yes, it is possible by using the Inputs and Outputs attributes on your target.
See: How to: Build incrementally
In your case, it would look something like this:
<Target Name="AfterBuild" DependsOnTargets="Test">
</Target>
<ItemGroup>
<MyTextFile Include="*.txt" />
</ItemGroup>
<Target Name="Test" Inputs="#(MyTextFile)" Outputs="#(MyTextFile->'%(FileName).bin')">
<Message Text="Copying #(MyTextFile)" Importance="high"/>
<Copy SourceFiles="#(MyTextFile)" DestinationFiles="#(MyTextFile->'%(FileName).bin')" />
</Target>
This target will only run if input files are newer than output files.

Related

MSBuild target before build

I have project A that need to insert a TextId.cs before build. And, there is project B. TextId.cs would generated after project B is compiled and executed.
Now I'd like to integrate the compile and execute in Directory.Build.targets in project A. It is not worked as I expect. TextId.cs will generate but the build would still failed as no TextId.cs if I set BeforeTargets="BeforeBuild" as below.
Anyone knows that which target is OK? or, any other solution?
<Project>
<ItemGroup>
<ProjectReferences Include="c:\code\textidfilegenerator\*.*proj" />
</ItemGroup>
<Target Name="BuildOtherProjects">
<Message Importance="High" Text="-----------------------" />
<MSBuild
Projects="#(ProjectReferences)"
Targets="Build">
</MSBuild>
</Target>
<Target Name="CopyText" DependsOnTargets="BuildOtherProjects" BeforeTargets="BeforeBuild">
<Message Importance="High" Text="**********************" />
<Exec Command="C:\Code\TextIdFileGenerator\bin\Debug\net6.0\TextIdFileGenerator.exe C:\Code\Sys1500TestDriver\TextProvider\TextIds.cs" IgnoreExitCode="true"/>
</Target>
</Project>
Before you will dive into the comments below, go through these docs:
MSBuild reserved and well-known properties
Common MSBuild project properties
<Project>
<ItemGroup>
<ProjectReferences Include="c:\code\textidfilegenerator\*.*proj" /> <!--you should use relative path like <ProjectReference Include="../**/*.csproj or absolute with MSBuild well-known properties" />-->
</ItemGroup>
<Target Name="BuildOtherProjects"> <!--you don't need this target if you have project reference-->
<Message Importance="High" Text="-----------------------" />
<MSBuild
Projects="#(ProjectReferences)"
Targets="Build">
</MSBuild>
</Target>
<Target Name="CopyText" DependsOnTargets="BuildOtherProjects" BeforeTargets="BeforeBuild"><!-- 'BeforeBuild' will not work because TextIdFileGenerator.exe needs to be created before you will do anything with it so you should use 'AfterTargets="Build"'-->
<Message Importance="High" Text="**********************" />
<Exec Command="C:\Code\TextIdFileGenerator\bin\Debug\net6.0\TextIdFileGenerator.exe C:\Code\Sys1500TestDriver\TextProvider\TextIds.cs" IgnoreExitCode="true"/><!-- again, you should use relative paths or absolute ones with combination of MSBuildProjectDirectory and OutDir -->
</Target>
</Project>

Disabling a specific C# 9 source generator

Is there any way to disable a specific C# 9 source generator? Or alternatively disable them all?
the package in question is https://github.com/Husqvik/GraphQlClientGenerator#c-9-source-generator which is mean to be able to be used as both a lib and a source generator. but those are mutually exclusive, ie the majority of use cases it make no sense to gen code both by executing code and by code gen
seems this will disable all
<Target Name="DisableAnalyzers"
BeforeTargets="CoreCompile">
<ItemGroup>
<Analyzer Remove="#(Analyzer)" />
</ItemGroup>
</Target>
removing a named one uses the file path
<Target Name="DisableAnalyzers"
BeforeTargets="CoreCompile">
<ItemGroup>
<Analyzer Remove="D:\nugets\nugetx\0.9.2\analyzers\dotnet\cs\NugetXAnalizer.dll" />
</ItemGroup>
</Target>
ok and finally u can remove based on filename
<Target Name="DisableAnalyzers"
BeforeTargets="CoreCompile">
<ItemGroup>
<Analyzer Remove="#(Analyzer)"
Condition="'%(Filename)' == 'NugetXAnalizer'"/>
</ItemGroup>
</Target>

How to add custom compiled file (in Target/Exec) as resource in .csproj's?

I'm doing a few shadereffects in a wpf_c# project and i don't know and i didn't find how to add the bytecode pixelshader (.ps) as Resource after be compiled by a target/exec. This is my csproj code fragment:
<ItemGroup>
<AvailableItemName Include="PixelShader"/>
</ItemGroup>
<ItemGroup>
<PixelShader Include="Shaders\BlueToneShader.fx" />
bla bla bla other shaders bla bla
</ItemGroup>
<Target Name="PixelShaderCompile" Condition="#(PixelShader)!=''" BeforeTargets="Build">
<Exec Command=""C:\Program Files (x86)\Windows Kits\10\bin\10.0.18362.0\x64\fxc.exe" %(PixelShader.Identity) /T ps_3_0 /E main /Fo%(PixelShader.RelativeDir)%(PixelShader.Filename).ps" />
</Target>
Everything goes fine and the .ps files are correctly generated, as example:
PixelShaderCompile:
"C:\Program Files (x86)\Windows Kits\10\bin\10.0.18362.0\x64\fxc.exe" Shaders\BlueToneShader.fx /T ps_3_0 /E main /FoShaders\BlueToneShader.ps
Microsoft (R) Direct3D Shader Compiler 10.1 Copyright (C) 2013 Microsoft. All rights reserved.
compilation object save succeeded; see "folder"...
But now i dont know how to add that .ps file as 'Resource' during the compilation. Any one knows how? I didn't find any clear documentation.
After 3-4 hours of trial-error i found a (i think dirty) way to do it: the msbuild (.csproj) looks like:
<PropertyGroup>
<BuildDependsOn>
PixelShaderCompile
$(BuildDependsOn)
</BuildDependsOn>
</PropertyGroup>
<ItemGroup>
<AvailableItemName Include="PixelShader">
<Visible>true</Visible>
</AvailableItemName>
</ItemGroup>
<ItemGroup>
<PixelShader ... />
...
</ItemGroup>
<Target Name="PixelShaderCompile" Condition="#(PixelShader)!=''" BeforeTargets="BeforeBuild;BeforeRebuild">
<MakeDir Directories="$(IntermediateOutputPath)%(PixelShader.RelativeDir)" Condition="!Exists('$(IntermediateOutputPath)%(PixelShader.RelativeDir)')" />
//You put your fxc.exe command here
<Exec Command=""C:\bla bla bla\fxc.exe" %(PixelShader.Identity) /T ps_3_0 /E PSmain /O3 /Fo$(IntermediateOutputPath)%(PixelShader.RelativeDir)%(PixelShader.Filename).ps" Outputs="$(IntermediateOutputPath)%(PixelShader.RelativeDir)%(PixelShader.Filename).ps">
<Output ItemName="CompiledPixelShader" TaskParameter="Outputs" />
</Exec>
<ItemGroup>
<Resource Include="#(CompiledPixelShader)" />
</ItemGroup>
</Target>
//If you want to clear the .ps generated file
<Target Name="PixelShaderClean" Condition="#(PixelShader)!=''" AfterTargets="AfterBuild;AfterRebuild">
<Delete Files="$(IntermediateOutputPath)%(PixelShader.RelativeDir)%(PixelShader.Filename).ps" />
</Target>
That's it... So hard because there aren't so many made examples of msbuild files.

Access MS Build Parameter within a project

I have a project within a solution, and a MS Build that builds the solution. As a part of the build, I can add MS Build arguments. Is there anyway that I can reference that build argument within my code inside the project?
A sort of "quick and dirty" way I've achieved this before is by dynamically generating a source file in MSBuild and adding it to the Compile item group.
This is assuming you mean MSBuild Properties by "MS Build Parameter(s)", specified like /p:MyProperty=foo on the command-line.
<Target Name="WriteToFile" BeforeTargets="PrepareForBuild">
<ItemGroup>
<_Lines Include='// auto-generated!' />
<_Lines Include='public class MyProperties {' />
<_Lines Include=' public string Property1="$(Property1)"'; />
<_Lines Include='}'; />
</ItemGroup>
<WriteLinesToFile
File="autogen.cs"
Lines="#(_Lines)"
Overwrite="true" />
</Target>
<ItemGroup>
<Compile Include="autogen.cs">
</ItemGroup>
</Target>

How does the MSBuild:Compile generator work

I'm trying to use the MSBuild:Compile generator to trigger a compilation of my custom file type when the file is saved in Visual Studio (should work like a custom tool but with msbuild). The build process itself is working but it doesn't seem to be triggered if the file is saved.
Can someone explain what exactly the MSBuild:Compile entry is doing? As far I have just seen this used in the antlr msbuild scripts and for XAML.
Below I have an extract of the msbuild setup I use to compile a *.myext file to a *.g.ts file.
My targets file:
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<UsingTask TaskName="SampleNamespace.CustomCompilerTask" AssemblyFile="MyTask.dll" />
<PropertyGroup>
<PrepareResourcesDependsOn>
CustomLayoutCompile;
$(PrepareResourcesDependsOn)
</PrepareResourcesDependsOn>
</PropertyGroup>
<ItemDefinitionGroup>
<CustomTypeCompile>
<Generator>MSBuild:Compile</Generator>
</CustomTypeCompile>
</ItemDefinitionGroup>
<Target Name="CustomLayoutCompile" Inputs="#(TypeScriptCompile);#(CustomTypeCompile)" Outputs="#(CustomTypeCompile->'%(RootDir)%(Directory)%(Filename).g.ts')">
<CustomCompilerTask TypeScriptFiles="#(TypeScriptCompile)" LayoutFiles="#(CustomTypeCompile)" />
</Target>
</Project>
Entries in the project file:
....
<ItemGroup>
<TypeScriptCompile Include="MyControl.ts">
<DependentUpon>MyControl.myext</DependentUpon>
</TypeScriptCompile>
<TypeScriptCompile Include="MyControl.g.ts">
<DependentUpon>MyControl.myext</DependentUpon>
</TypeScriptCompile>
</ItemGroup>
<ItemGroup>
<CustomTypeCompile Include="MyControl.myext">
<Generator>MSBuild:Compile</Generator>
</CustomTypeCompile>
</ItemGroup>
....
<Import Project="path/to/my/target/file/mytargets.targets" />
....
I am using VS 2019 and was suffering from the same exact issue. I finally figured out a workaround, which make the issue looks more like a VisualStudio/MSBuild bug to me. My workaround is that when you define your ItemDefinitionGroup, define a custom/extended file property page like below. It worked for me. Hope it also works for everyone else too.
<ItemGroup>
<PropertyPageSchema Include="$(MSBuildThisFileDirectory)CustomPerperties.CSharp.xml">
<Context>File;BrowseObject</Context>
</PropertyPageSchema>
<AvailableItemName Include="CustomTypeCompile" />
</ItemGroup>

Categories