I would like my Windows Phone application to access an environment variable of the build machine.
In my scenario I specifically want to pass the USERNAME variable, so when I am looking at phone application’s analytics reports in case of debug builds – I can see which developer was running the application and see whether it was me or someone else. I could think of other similar scenarios where it would be useful to have a build-time value accessed at runtime, so I would like to find a generic solution to the problem.
I can think of one solution – use a pre-build event definition to create or update a .cs file with a constant set to the build-time environment variable value, but it seems a bit ugly and I am expecting to see problems with version control systems. I was hoping maybe there was some trick to use DefineConstants or otherwise set it using some simple msbuild project customization?
You could do as you suggested: creating a
.csfile with a constant during build time. To circumvent potential issues with version control systems, don’t add this file to version control and create it in a location ignored by version control (likeobj\Debugorobj\Releasefolders).In MSBuild it could look like the following:
Add the following after the final “Import”-Element in your CSPROJ file.
You might consider putting the above in a custom
.projfile, which you import into your CSPROJ files.Oh, and I don’t find that ugly at all. Personally, I use it for all kinds of such tasks, like assembly version attributes, etc.
Update:
To prevent the target from being called on every build (or F5, etc.) you can use the
InputsandOutputsattributes of theTargetelement. The MSDN page is not too helpfull, but basically it works as follows: MSBuild will check if all files specified in theOutputattribute are up-to-date with respect to the files specified in theInputsattribute.You could thus change the target definition like so (PropertyGroup element remains the same and only added for completeness):
The trick here is the following: if EnvVars.cs does not exist it will be created. If it does exist (then) it will no longer be created, thus not forcing a build on F5. However, we have to provide some way of getting rid of the file. Hence adding it to the
FileWritesItemGroup, which contains the files to be removed when the “clean” or “rebuild” targets (or the respective menu commands in Visual Studio) will be called. So if you want a new EnvVars.cs file, just do a rebuild or clean.