0

I have a C# project that I am building via the command line and I want to be able to pass a value into the build such that it is available at runtime.

For example, if my app has a label and I want the text for that label to be specifiable when calling msbuild, I would want to build it using a command, somthing like this:

MSBuild MyProject.sln /p:MyCustomText="blue"

And then access that value at run time to set the label text, something like this:

myLabel.text = MyCustomText

What's the best way of achieving this? There must be a way to do this without overcomplicating it with prebuild steps and / or custom .cs file generation.

aatwo
  • 948
  • 6
  • 12
  • Why not just use application config? – phuzi Dec 17 '20 at 16:22
  • I'm curious to understand why you'd want to do this. What scenario are you attempting to implement? – Daniel Mann Dec 17 '20 at 16:22
  • Are compile time constants really so strange? I come from a C++ background where they are not. In this particular case I want to build a C# app as part of a larger build containing many projects, and to have the ability to embed a custom date into each binary which can be set when triggering a build on a build server. – aatwo Dec 17 '20 at 16:38
  • @aatwo Could this one help you? https://stackoverflow.com/questions/24157714/how-to-append-conditional-compilation-symbols-in-project-properties-with-msbuild – Saber Dec 17 '20 at 16:44
  • By design, C# has no separate preprocessor that can take arbitrary input, so without *any* code generation this is a non-starter. The question then remains what kind of code generation; it can be fairly simple, and is probably doable without any external tooling. A [source generator](https://devblogs.microsoft.com/dotnet/new-c-source-generator-samples/) reading a simple file is an option, for example. Generating (or textually replacing) a resource file is another way. – Jeroen Mostert Dec 17 '20 at 17:00
  • @aatwo *embed a custom date into each binary*. What are you trying to do? Why do you need a date embedded in the binary? – Daniel Mann Dec 17 '20 at 18:30

1 Answers1

0

As it turns out is only possible to pass in valueless flags to C# builds...

#if MY_COMPILATION_FLAG
// flag specific code
#endif

Therefore to solve this problem I created a pre-build script for my project (project properties -> build events -> pre-build event command line) that uses a JSON manifest file to generate a C# source file.

For example the following pre-build command line will execute a powershell script to turn my JSON file into a C# source file:

powershell -NoProfile -ExecutionPolicy RemoteSigned -file "$(SolutionDir)code-generation\scripts\generate-code.ps1" -ManifestFilepath "$(SolutionDir)code-generation\manifests\build-properties.json"

Using a JSON file in this way makes it relatively easy for my build server to modify and is flexible enough I can extend it in the future if I need to.

aatwo
  • 948
  • 6
  • 12