How can I read a value from appSettings.config in CSPROJ conditional - c#

I would like to read an option out of my appSettings.config file to create a conditional section in my CSPROJ. I know how to do the conditional references with help from visual studio 2010 conditional references but I am not sure how to access the appSettings file from within.
Is this possible and if so, could someone provide some guidance please.
EDIT Following #palo's answer I now have:
<Target Name="BeforeBuild">
<XmlPeek XmlInputPath="SiteSettings.config" Query="appSettings/add[#key='cProjectNumber']/#value">
<Output TaskParameter="Result" ItemName="value" />
</XmlPeek>
<Message Text="TESTING: #(value)" Importance="high" />
</Target>
This works well and prints out the project number i.e Testing: 012. Now, how do I go about using it in some compile includes? I have tried:
<ItemGroup>
<Compile Include="Accounts\#(value)\Controls\MyControl.ascx.cs">
<SubType>ASPXCodeBehind</SubType>
</Compile>
</ItemGroup>
But I get an error saying:
The expression "Accounts\#(value)\Controls\MyControl.ascx.cs" cannot
be used in this context. Item lists cannot be concatenated with other
strings where an item list is expected. Use a semicolon to separate
multiple item lists.

If I understand correctly you need to read elements’ value for appconfig (xml file) and then use its value in your csproj file.
Try to use XmlPeek - http://msdn.microsoft.com/en-us/library/ff598684.aspx ; How to use XmlPeek task?
Keep in mind you the order of evaluation.
You cannot override global properties/items. But with msbuild 4.0 you can override items within BeforeTargets or by AfterTargets

Following #palo's answer I came up with the following (I will mark this as the answer as it details information on how to achieve what I wanted):
<Target Name="BeforeBuild">
<XmlPeek XmlInputPath="SiteSettings.config" Query="appSettings/add[#key='cProjectNumber']/#value">
<Output TaskParameter="Result" ItemName="value" />
</XmlPeek>
<Message Text="TESTING: #(value)" Importance="high" />
<PropertyGroup>
<ProjectNumber>#(value)</ProjectNumber>
</PropertyGroup>
<ItemGroup>
<Compile Include="Accounts\$(ProjectNumber)\Controls\MyControl.ascx.cs">
<SubType>ASPXCodeBehind</SubType>
</Compile>
</ItemGroup>
</Target>
With an XML structure like:
<appSettings>
<add key="cProjectNumber" value="123" />
</appSettings>

Related

MSBuild ItemGroup Condition Project Reference

I'm trying to include a Project Reference based on a value in the ItemGroup Condition
This is what I have tried. With BeforeTargets Compile it does recognize the project but it won't let me build the project.
<Target Name="ErpSystemToUse" BeforeTargets="Compile">
<ReadLinesFromFile File="$(MSBuildProjectDirectory)\..\..\Presentation\Nop.Web\App_Data\erpSystemToUse.txt">
<Output TaskParameter="Lines" ItemName="ValueTextFile" />
</ReadLinesFromFile>
<Message Text="#(ValueTextFile)" Importance="high" />
<ItemGroup Condition="'#(ValueTextFile)' == 'Twinfield'">
<ProjectReference Include="..\..\Dimerce.Twinfield\Dimerce.Plugin.Misc.Twinfield\Dimerce.Plugin.Misc.Twinfield.csproj" />
</ItemGroup>
</Target>
Is what I am trying to achieve possible?
I have a project where I had to inspect output of System.Reflection.Emit. Decided to include package reference only when appropriate constant is defined
Main difference is that target executes before CollectPackageReferences. Try to change BeforeTargets.
Also use Inputs and Outputs to reduce build time
<Target Name="IncludeIlPackReference"
Inputs="$(DefineConstants)" Outputs="#(PackageReference)"
BeforeTargets="CollectPackageReferences"
Condition="$(DefineConstants.Contains('TRACE_GENERATED_IL'))">
<ItemGroup>
<PackageReference Include="Lokad.ILPack" Version="0.1.6" />
</ItemGroup>
</Target>

how to remove auto generated proto files from generated folder

I have the below MSBuild to generate .cs files from my proto files. The build works fine until I do a rebuild where it complains of Source file 'generated-proto-output/Trade.cs# specified multiple times.
How do I delete my .cs files before building/rebuilding everytime?
Error
Severity Code Description Project File Line Suppression State
Warning CS2002 Source file 'generated-proto-output\ErrorTrade.cs' specified multiple times MyComp.Trade.Model C:\dev\workspaces\trade-model-workspace\model\csharp\MyComp.Trade.Model
build snippet in csproj file
<ItemGroup>
<Protobuf Remove="%(RelativePath)generated-proto-output/**/*.cs" />
<Protobuf Include="../../proto/**/*.proto" ProtoRoot="../../proto/" OutputDir="%(RelativePath)generated-proto-output/" GrpcServices="None" />
<Protobuf Update="../../proto/**/*Service.proto" GrpcServices="Both" />
</ItemGroup>
UPDATE - Complete CSProj file (as requested by Lance)
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<PackageId>TradeStore.Model</PackageId>
<ProtoIncludes>.;../../proto</ProtoIncludes>
<OutputType>Library</OutputType>
<TargetFramework>netstandard2.0</TargetFramework>
<Protobuf_NoWarnMissingExpected>true</Protobuf_NoWarnMissingExpected>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Google.Protobuf" Version="3.6.1" />
<PackageReference Include="Grpc" Version="1.19.0" />
<PackageReference Include="Grpc.Tools" Version="1.19.0" PrivateAssets="All" />
</ItemGroup>
<ItemGroup>
<FilesToDelete Include="%(RelativePath)generated-proto-output/*.cs" />
</ItemGroup>
<Target Name="DeleteSpecificFiles" BeforeTargets="Build">
<Message Text="Specific Files: #(FilesToDelete)"/>
<Message Text ="Beginning to delete specific files before build or rebuild..."/>
<Delete Files="#(FilesToDelete)"/>
</Target>
<ItemGroup>
<Protobuf Include="../../proto/**/*.proto" ProtoRoot="../../proto/" OutputDir="%(RelativePath)generated-proto-output/" GrpcServices="None" />
<Protobuf Update="../../proto/**/*Service.proto" GrpcServices="Both" />
</ItemGroup>
</Project>
Try adding CompileOutputs="false" to the directive. This will suppress the warning and won't require you to delete files before building csharp protobuf build integration
How do I delete my .cs files before building/rebuilding everytime?
Try the following script with BeforeTargets below:
<Project...>
...
<ItemGroup>
<FilesToDelete Include="MyPath/*.cs" />
</ItemGroup>
<Target Name="DeleteSpecificFiles" BeforeTargets="build">
<Message Text="Specific Files: #(FilesToDelete)"/>
<Message Text ="Beginning to delete specific files before build or rebuild..."/>
<Delete Files="#(FilesToDelete)"/>
</Target>
</Project>
In addition:
Not seeing the whole content of your .csproj, so I can't figure out why the build snippet you use can't work. But a message task may help output some message whether the engine finds the files by your given path.
In visual studio, if you go Tools=>Options=>Project and Solutions=>Build and Run to change the build out verbosity to Detailed, you will see detailed output message after every build and rebuild.Ctrl+Fand type the Target name you will find the details about delete process:
Hope it makes some help for your trouble-shooting.

Using Msbuild variables in Project Extensions

I currently have a solution with a web.api project that I want to deploy to different virtual directories in my local IIS. Currently I am doing the following in the .csproj of the api:
<Project ToolsVersion="12.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup Condition="'$(Configuration)' == 'CustomerOne.Debug'">
<CustomerName>CustomerOne</CustomerName>
....
</PropertyGroup>
...
These variables are used extenisvely further on for web.config transforms, copying to different locations, etc., by referencing them like $(CustomerName).
The only place where it does not work is in the definition of the virtual directory, i.e., I'd like to connect the build configuration to the IISUrl below, which you can hardcode:
<ProjectExtensions>
<VisualStudio>
<FlavorProperties GUID="{349c5851-65df-11da-9384-00065b846f21}">
<WebProjectProperties>
...
<IISUrl>http://localhost/api/something</IISUrl>
...
</WebProjectProperties>
</FlavorProperties>
</VisualStudio>
</ProjectExtensions>
Replacing this by <IISUrl>http://localhost/api/$(CustomerName)</IISUrl> does not work. Ideas?
Replacing this by http://localhost/api/$(CustomerName) does not work. Ideas?
That because Anything inside of a ProjectExtensions element will be ignored by MSBuild.
You can get the detailed info from this document ProjectExtensions Element (MSBuild):
Allows MSBuild project files to contain non-MSBuild information.
Anything inside of a ProjectExtensions element will be ignored by
MSBuild.
That is the reason why the Msbuild variables not work in Project Extensions.
Hope this helps.
You could update the underlying project file. A Target like this in your project file would do it.
<Target Name="AfterBuild">
<PropertyGroup>
<NewUrl>http://localhost/api/$(CustomerName)</NewUrl>
</PropertyGroup>
<Message Text="Updating IISUrl: $(NewUrl) in $(MSBuildProjectFile)" />
<XmlPeek Namespaces="<Namespace Prefix='msb' Uri='http://schemas.microsoft.com/developer/msbuild/2003'/>" XmlInputPath="$(MSBuildProjectFile)" Query="/msb:Project/msb:ProjectExtensions/msb:VisualStudio/msb:FlavorProperties/msb:WebProjectProperties/msb:IISUrl/text()">
<Output TaskParameter="Result" ItemName="Peeked" />
</XmlPeek>
<Message Text="Current Url: #(Peeked)" />
<!-- Only update the IISUrl if its changed -->
<XmlPoke Condition=" '#(Peeked)'!='$(NewUrl)' " XmlInputPath="$(MSBuildProjectFile)" Namespaces="<Namespace Prefix='msb' Uri='http://schemas.microsoft.com/developer/msbuild/2003'/>" Query="/msb:Project/msb:ProjectExtensions/msb:VisualStudio/msb:FlavorProperties/msb:WebProjectProperties/msb:IISUrl" Value="$(NewUrl)" />
</Target>
However it does have side affects. Changing the underlying project file means Visual Studio decides it should reload the project.
To use it you cannot go directly into Debug. Instead build, reload the project and then go into debug. If you go directly into Debug (with a compile) it will use the old url.

TextTransform on MSBuild only when file modified? (or an alternate route of doing this)

I have a project that integrates TextTransform with MSBuild, but I am now at the point that the files are too many and it is slowing down development time.
The process that I have is, I have a POCO.cs; I use Roslyn to Parse the .cs file to gather some metadata; hand the metadata to a .tt file that will then generate a [Implementation].cs
Here is part of the .csproj file that pertains to my question:
<PropertyGroup>
<_CommonProgramFiles>$([System.Environment]::GetEnvironmentVariable('CommonProgramFiles(x86)'))</_CommonProgramFiles>
<_CommonProgramFiles Condition=" '$(_CommonProgramFiles)' == '' ">$(CommonProgramFiles)</_CommonProgramFiles>
<TextTransformPath Condition="'$(TextTransformPath)' == ''">$(_CommonProgramFiles)\Microsoft Shared\TextTemplating\$(VisualStudioVersion)\TextTransform.exe</TextTransformPath>
<!-- Initial default value -->
<_TransformExe>$(TextTransformPath)</_TransformExe>
<_RoslynDllPath>$(ProjectDir)Lib\RoslynWrapper.dll</_RoslynDllPath>
<!-- Cascading probing if file not found -->
<_TransformExe Condition="!Exists('$(_TransformExe)')">$(_CommonProgramFiles)\Microsoft Shared\TextTemplating\10.0\TextTransform.exe"</_TransformExe>
<_TransformExe Condition="!Exists('$(_TransformExe)')">$(_CommonProgramFiles)\Microsoft Shared\TextTemplating\11.0\TextTransform.exe"</_TransformExe>
<_TransformExe Condition="!Exists('$(_TransformExe)')">$(_CommonProgramFiles)\Microsoft Shared\TextTemplating\12.0\TextTransform.exe"</_TransformExe>
<!-- Future proof 'til VS2013+2 -->
<_TransformExe Condition="!Exists('$(_TransformExe)')">$(_CommonProgramFiles)\Microsoft Shared\TextTemplating\13.0\TextTransform.exe"</_TransformExe>
<_TransformExe Condition="!Exists('$(_TransformExe)')">$(_CommonProgramFiles)\Microsoft Shared\TextTemplating\14.0\TextTransform.exe"</_TransformExe>
</PropertyGroup>
<ItemGroup>
<Compile Include="SomePoco.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="SomePocoMetadata.cs">
<AutoGen>True</AutoGen>
<DesignTime>True</DesignTime>
<DependentUpon>SomePocoMetadata.tt</DependentUpon>
</Compile>
</ItemGroup>
<ItemGroup>
<None Include="SomePocoMetadata.tt">
<Generator>TextTemplatingFileGenerator</Generator>
<LastGenOutput>SomePocoMetadata.cs</LastGenOutput>
</None>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<Target Name="TransformOnBuild" AfterTargets="BeforeBuild">
<Error Text="Failed to find TextTransform.exe tool at '$(_TransformExe)." Condition="!Exists('$(_TransformExe)')" />
<ItemGroup>
<_TextTransform Include="#(None)" Condition="'%(None.Generator)' == 'TextTemplatingFileGenerator'" />
</ItemGroup>
<!-- Perform task batching for each file -->
<Exec Command=""$(_TransformExe)" "%(_TextTransform.FullPath)" -r "$(_RoslynDllPath)"" Condition="'%(_TextTransform.Identity)' != ''" />
</Target>
With the above, the .tt files are always transforming and it takes a couple of minutes to compile the DLL. Is there a way to do this in MSBuild to only transform when the SomePoco.cs file is modified only?
Is there maybe another approach that I should look into to get what i want accomplished?
Make sure you specify Inputs and Outputs attributes for your target.
In your specific case you seem to obtain name of one of the inputs inside the target, so you cannot use it in the enclosing Target's Input attribute. A workaround for you is to move the definition of _TextTransform item group outside of the target.
what i ended up doing was using with ITaskItem[] as one of the input parameters and in there i used C# to figure out the last modified of the files and determined if i needed to generate that way.

Dynamic Versioning

I have a situation where i want the versioning to be dynamic at build time.
Version Pattern: <year>.<month>.<day>.<hhmm>
But i have read where the String value used in the Attribute is reparsed at compile time.
Any advise on how to get this dynamic versioning completed?
Ideal situation:
<Assembly: AssemblyVersion("4.0.0.0")>
<Assembly: AssemblyFileVersion(Year(Now) & "." & Month(Now()) & "." & Day(Now()) & "." & String.format("hhmm", now()))>
I know it wont work but should get the point acrossed.
You can use the MsbuildCommunityTasks to generate the build number and to customize the assembly file version on pre-build time.
Download the zip at MsbuildCommunityTasks
Unzip to the folder [SolutionFolder]\MsBuildExtensions\MSBuildCommunityTasks
Add the sample below on your project (csproj), just after the Microsoft.CSharp.Targets import.
<PropertyGroup>
<MSBuildCommunityTasksPath>$(MSBuildThisFileDirectory)..\MsBuildExtensions\MSBuildCommunityTasks</MSBuildCommunityTasksPath>
<My-PropertiesDir>Properties</My-PropertiesDir>
</PropertyGroup>
<Import Project="$(MSBuildCommunityTasksPath)\MSBuild.Community.Tasks.Targets"/>
<Target Name="BeforeBuild">
<Time Format="yyyy.MM.dd.HHmm">
<Output TaskParameter="FormattedTime" PropertyName="My-VersionNumber" />
</Time>
<Message Text="Building $(My-VersionNumber) ...">
</Message>
<ItemGroup>
<My-AssemblyInfo Include="$(My-PropertiesDir)\AssemblyVersionInfo.cs" />
<Compile Include="#(My-AssemblyInfo)" />
</ItemGroup>
<MakeDir Directories="$(My-PropertiesDir)" />
<AssemblyInfo OutputFile="#(My-AssemblyInfo)"
CodeLanguage="CS"
AssemblyFileVersion="$(My-VersionNumber)"
AssemblyInformationalVersion="$(My-VersionNumber)"
Condition="$(My-VersionNumber) != '' "
/>
</Target>
<Target Name="AfterBuild">
<Delete Files="#(My-AssemblyInfo)" />
</Target>
Wipe the AssemblyFileVersion attribute from your AssemblyInfo.cs. It will be generated at build time.
You'll see the version number being printed on the console when you build. The generated file is deleted on the AfterBuild target, to keep your source control clean.
BeforeBuild:
Building 2013.01.14.1016 ...
Created AssemblyInfo file "Properties\AssemblyVersionInfo.cs".
(...)
AfterBuild:
Deleting file "Properties\AssemblyVersionInfo.cs".
If you want do this to many projects with less msbuild code, it will be necessary to create a customized build script to wrap up your solution.

Categories

Resources