I have an app.config file in our WPF project that is transformed using the following build target in the .csproj
<!-- MSbuild Task for transforming app.config based on the configuration settings -->
<UsingTask TaskName="TransformXml"
AssemblyFile="$(SolutionDir)\packages\MSBuild.Microsoft.VisualStudio.Web.targets.12.0.4\tools\VSToolsPath\Web\Microsoft.Web.Publishing.Tasks.dll" />
<Target Name="AfterBuild">
<!-- Transform the app.config into the correct config file associated to the current build settings -->
<TransformXml Source="App.config" Transform="App.$(Configuration).config" Destination="$(OutputPath)\App.config" />
<!-- Bit of .Net to get all folders and subfolders that we want to delete post-build -->
<ItemGroup>
<FoldersToClean Include="$([System.IO.Directory]::GetDirectories("$(OutputPath)"))" />
</ItemGroup>
<!-- Delete all of our localization folders and .pdb symbols. We only delete PDB files for Release builds. Debug builds we will leave them. -->
<RemoveDir Directories="#(FoldersToClean)" />
<Exec Command="del $(OutputPath)*.pdb" Condition=" '$(Configuration)'=='Release' " />
</Target>
This correctly generates an App.config after the compilation, with my transformed QA or Production configuration files created. The issue I ran into however is that the following code uses AppName.exe.config.
string encryptedString = ConfigurationManager.AppSettings["SqlConnection"];
After doing a bit of reading, I understand why it's doing that. The App.config file ultimately becomes the AppName.exe.config for use during runtime. That's fine; my transformation happens to late though. When the compilation is completed, the AppName.exe.config file contains my base App.config file information, and none of the transformed settings. I assume that is due to the transform happening as a post-build step, where it transforms the App.config after the original App.config file was used to generate AppName.exe.config.
It looks like there isn't any thing preventing me from changing
<TransformXml Source="App.config"
Transform="App.$(Configuration).config"
Destination="$(OutputPath)\App.config" />
so that it replaces the AppName.exe.config file post-build.
<TransformXml Source="App.config"
Transform="App.$(Configuration).config"
Destination="$(OutputPath)\AppName.exe.config" />
Is there anything wrong with this? There isn't much in the way of help when using app.config and transforms for desktop applications. Everything I've read online is for transforming things into a web-config file. I assume this is safe and more or less is the same thing. However I wanted to make sure I'm not missing any glaring side-effects or issues i'll encounter by replacing the original AppName.exe.config with the transformed App.config.
Install this https://github.com/acottais/msbuild.xdt NuGet package and you will be able to create transforms like a web.config.
There are several other Nuget packages that will transform the app.config just like the web.config.
I used this one the other day and it worked great.
Related
For the gurus out there in batch file writing and Visual Studio (most significantly Visual Studio 2013), I would like to know if it is possible to do the following:
I have a series of projects part of a solution, many of which are dependent on the dll's generated by other projects (in a waterfall fashion really). I would like to know if it is possible to write a batch file to build all projects to generate the corresponding dll's, and then update their references to the newly assembled dll's (also with the batch file).
Is this even possible? I would like avoid using extensions like NuGet or any other software.
You pick the right language/tool to do builds. msbuild is the tool (and kind of the language) that you write this kind of stuff. they are called build-scripts. they are NOT bat scripts. do not use .bat scripts. that's what people did 20 years ago.
Below is a basic msbuild script file. It will
Build the .sln
copy the files of one of the csproj's (usually the GUI csproj) to a folder
zip the files into a zip file
You would put this in a file called "MyBuildScript.proj" (or MyBuildScript.msbuild)
After you do that, you will execute the file with msbuild.exe
"%WINDIR%\Microsoft.NET\Framework\v4.0.30319\msbuild.exe" /target:AllTargetsWrapped "MyBuildScript.proj" /p:Configuration=Debug;FavoriteFood=Popeyes /l:FileLogger,Microsoft.Build.Engine;logfile=MyBuildScript.proj.Release.log
(MyBuildScript.proj)
<?xml version="1.0" encoding="utf-8"?>
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003" DefaultTargets="AllTargetsWrapped">
<PropertyGroup>
<!-- Get this project from http://msbuildextensionpack.codeplex.com/releases/view/105659 -->
<MSBuildExtensionPackFoundPath Condition="Exists('$(MSBuildExtensionsPath64)\ExtensionPack\4.0\MSBuild.ExtensionPack.tasks')">$(MSBuildExtensionsPath64)\ExtensionPack\4.0\MSBuild.ExtensionPack.tasks</MSBuildExtensionPackFoundPath>
<MSBuildExtensionPackFoundPath Condition="Exists('$(MSBuildExtensionsPath32)\ExtensionPack\4.0\MSBuild.ExtensionPack.tasks')">$(MSBuildExtensionsPath32)\ExtensionPack\4.0\MSBuild.ExtensionPack.tasks</MSBuildExtensionPackFoundPath>
<MSBuildExtensionPackFoundPath Condition="Exists('$(MSBuildExtensionsPath)\ExtensionPack\4.0\MSBuild.ExtensionPack.tasks')">$(MSBuildExtensionsPath)\ExtensionPack\4.0\MSBuild.ExtensionPack.tasks</MSBuildExtensionPackFoundPath>
<MSBuildExtensionPackFoundPath Condition="$(MSBuildExtensionPackFoundPath)==''">CouldNotFindBaseDirectoryCheckForInstalledProduct\MSBuild.ExtensionPack.tasks</MSBuildExtensionPackFoundPath>
</PropertyGroup>
<Import Project="$(MSBuildExtensionPackFoundPath)"/>
<PropertyGroup>
<!-- Always declare some kind of "base directory" and then work off of that in the majority of cases -->
<WorkingCheckout>.</WorkingCheckout>
<WorkingDir>.</WorkingDir>
<ArtifactDestinationFolder>$(WorkingCheckout)\ZZZArtifacts</ArtifactDestinationFolder>
<ZipArtifactDestinationFolder>$(WorkingDir)\ZZZZipArtifacts</ZipArtifactDestinationFolder>
</PropertyGroup>
<Target Name="AllTargetsWrapped">
<CallTarget Targets="CleanArtifactFolder" />
<CallTarget Targets="BuildItUp" />
<CallTarget Targets="CopyFilesToArtifactFolder" />
<CallTarget Targets="ZipItUp" />
</Target>
<Target Name="BuildItUp" >
<MSBuild Projects="$(WorkingCheckout)\Solution1.sln" Targets="Build" Properties="Configuration=$(Configuration)">
<Output TaskParameter="TargetOutputs" ItemName="TargetOutputsItemName"/>
</MSBuild>
<Message Text="BuildItUp completed" />
</Target>
<Target Name="CleanArtifactFolder">
<RemoveDir Directories="$(ArtifactDestinationFolder)" Condition="Exists($(ArtifactDestinationFolder))"/>
<MakeDir Directories="$(ArtifactDestinationFolder)" Condition="!Exists($(ArtifactDestinationFolder))"/>
<RemoveDir Directories="$(ZipArtifactDestinationFolder)" Condition="Exists($(ZipArtifactDestinationFolder))"/>
<MakeDir Directories="$(ZipArtifactDestinationFolder)" Condition="!Exists($(ZipArtifactDestinationFolder))"/>
<Message Text="Cleaning done" />
</Target>
<Target Name="CopyFilesToArtifactFolder">
<ItemGroup>
<MyExcludeFiles Include="$(WorkingDir)\**\*.doesnotexist" />
</ItemGroup>
<ItemGroup>
<MyIncludeFiles Include="$(WorkingDir)\CsProjectOne\bin\$(Configuration)\**\*.*" Exclude="#(MyExcludeFiles)"/>
</ItemGroup>
<Copy
SourceFiles="#(MyIncludeFiles)"
DestinationFiles="#(MyIncludeFiles->'$(ArtifactDestinationFolder)\%(Filename)%(Extension)')"
/> <!-- %(RecursiveDir) -->
</Target>
<Target Name="ZipItUp">
<ItemGroup>
<NonConfigFilesExcludeFiles Include="$(ArtifactDestinationFolder)\**\*.doesnotexist" />
</ItemGroup>
<ItemGroup>
<NonConfigFilesIncludeFiles Include="$(ArtifactDestinationFolder)\**\*" Exclude="#(NonConfigFilesExcludeFiles)"/>
</ItemGroup>
<!-- Create a zip file based on the FilesToZip collection -->
<MSBuild.ExtensionPack.Compression.Zip TaskAction="Create" CompressFiles="#(NonConfigFilesIncludeFiles)" RemoveRoot="$(ArtifactDestinationFolder)" ZipFileName="$(ZipArtifactDestinationFolder)\MyOutputFile.zip"/>
<!-- -->
</Target>
</Project>
That is how you write build-logic. There are other build tools out there, but this is the default dotNet one.
Do NOT write crappy, hard to maintain .bat files.
Use the correct tool for the job.
PS "msbuildextensionpack" is an example of extensions for msbuild. there are MANY MANY helpful extensions for msbuild. 99% of the time, somebody has written a msbuild extension to help do what you need to do.
Need to send a file to an ftp client destination? Somebody already wrote a task.
Need to manipulate some .xml file? Somebody already wrote a task.
Need to zip a file (like in this example). Somebody already wrote a task.
Need to do........anything mainstream........ Somebody already wrote a task.
It's a WPF application, with Wix Installer.
I have resourceses folder and I want to include these files in the installer to put next to the executable. I solved generating a resources.wxs file with necessary information about the files under the resources folder using the heat tool. I managed to includ into the main wxs file. For that reason I modified the .wixproj file, adding a before build target action to generate the wxs and include it in the main wxs.
Concern: .wixproj is kind of hidden, there thing that you cannot modify from visual studio, like adding a before build action (pre build action is a different story)
Question: How can I extract the before build action into a separate file?
The before build action in the .wixproj:
<Target Name='BeforeBuild'>
<Exec Command='"%WIX%bin\heat" dir $(SolutionDir)resources -dr ResourcesDir -var var.ResourcesDir -cg ResourceFilesGroup -gg -g1 -sfrag -srd -out $(ProjectDir)Resources.wxs' />
<ItemGroup>
<Compile Include='$(ProjectDir)Resources.wxs' />
</ItemGroup>
You can extract it into a separate fileāmost project file types do that already. That's how they provide common targets to all projects of a type. A .wixproj has this:
<Import Project="$(WixVersionTargetsPath)" />
To augment your own, simply:
Create an XML file like:
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Target Name='BeforeBuild'>
<!-- tasks -->
</Target>
</Project>
Add an Import element inside the Project element and refer to that file:
<Import Project="custom.targets" />
If such a file primarily has Target elements, the convention is for it to have the file extension ".targets".
But there are two drawbacks with Visual Studio:
Visual Studio caches all the project file dependencies and runs the MSBuild internally. So, it you edit the external file, it won't be part of builds using Visual Studio until the project is next loaded. To quickly unload and reload a project, use the project context menu in the Solution Explorer. Workaround: Call MSBuild yourself.
When Visual Studio loads a project, if it includes non-standard external files, it gives a warning. (You can disable it per user by project file path, in the registry, if I recall.)
As an alternative to calling heat directly, you might want to look at the Harvest* targets that WiX provides. Note: As the documentation says, you don't invoke them directly (they're already invoked by the Build target); You simply add items to the ItemGroup they process and set properties they use.
I'm investigating to OpenNI SDK ant it's wrappers for .NET. So, I created MSBuild AfterBuild target to copy files from SDK folder (path from environment variable) to build output folder. Now build works on each computer (even if SDK isn't installed). But in this case build is very heavy.
Is there the way to create links to this files in solution? I need build to execute only for computers with installed SDK.
Add an Exists condition to the AfterBuild target, this would prevent the AfterBuild target from running.
<Target Condition="Exists('$(SdkLocation)')" Name="AfterBuild">
...
</Target>
You could also make a BeforeBuild target containing an Error task that will cause the build to break if the SDK is not detected.
<Target Name="BeforeBuild">
<Error Condition="!Exists('$(SdkLocation)')" Text="OpenNI SDK not found." />
</Target>
MsBuild should also be copying the SDK files to the output file if you've added References in the dependent projects. Are you copying extra files?
I have a WPF application in C# that may need to be localized in the future. I want to support XAML/BAML localization and conventional resx localization. (The former is useful for most of the code, but some localized content comes from the view model, where it is more straightforward to use resx files.)
I have read the relevant parts of the WPF Localization Guidance. I have set the UICulture property in the msbuild file. I have added the following line to AssemblyInfo.cs:
[assembly: NeutralResourcesLanguage("en", UltimateResourceFallbackLocation.Satellite)]
I understand that I need to copy Resources.resx as Resources.en.resx so that my localized resources get written to the satellite assembly.
I have set the build target on Resources.resx to None and on Resources.en.resx to EmbeddedResource. The custom tool on Resources.resx is PublicResXFileCodeGenerator to generate the strongly typed resources class. I know that the generator only works on a file that doesn't have a culture-specific suffix.
At the moment I must manually keep Resources.resx and Resources.en.resx synchronized. They must be identical. (Rick Stahl explains that here.)
I have tried to modify my C# project file to copy the file automatically. However, I can't get this to work. I'm no msbuild expert! I added the following build target:
<Target Name="BeforeResGen">
<Copy SourceFiles="#(CopyAsLocalizedResources)" DestinationFiles="$(IntermediateOutputPath)Resources.$(UICulture).resx">
<Output ItemName="EmbeddedResource" TaskParameter="DestinationFiles"/>
</Copy>
</Target>
I changed the Build Action for Resources.resx from None to CopyAsLocalizedResources.
I see my Resources.en.resx file being copied to the intermediate directory during build, but my resources aren't found at runtime, and I get an exception. Presumaby they are never being compiled into the satellite assembly.
Can anyone help me achieve this using a modification to the project file?
The compiled language dll is expected to be in a folder named according to the ISO culture code for that culture. This culture-named folder is expected to be in the same directory as the parent assembly.
So, for some foo.dll:
(Default DLL)
bin\foo.dll
(Spanish(Mexico) Resources)
bin\es-mx\foo.Resources.dll
This folder structure and assembly will be made at compilation, so you just need to tweak your post-build action to move the dll in the culture folder to a matching folder in your target directory.
Note that you can perform this move via cp or other command line tools simply by typing the actions you need in the project post-build step box with the project properties in Visual Studio.
Eureka!
<Target Name="CreateLocalizedResources" BeforeTargets="AssignTargetPaths">
<Copy SourceFiles="#(CopyAsLocalizedResources)" DestinationFiles="$(IntermediateOutputPath)Resources.$(UICulture).resx" SkipUnchangedFiles="true" UseHardlinksIfPossible="true">
<Output TaskParameter="DestinationFiles" ItemName="GeneratedLocalizedResources" />
</Copy>
<ItemGroup>
<EmbeddedResource Include="#(GeneratedLocalizedResources)">
<ManifestResourceName>$(RootNamespace).Properties.Resources.$(UICulture)</ManifestResourceName>
</EmbeddedResource>
</ItemGroup>
<Message Text="Generated resources are: #(GeneratedLocalizedResources)" Importance="high" />
</Target>
I set the Build Action on my Resources.resx file to CopyAsLocalizedResources, and the custom build target handles tricking the build into making the proper satellite assembly.
I'm using Visual Studio 2010. In my Solution Explorer I like to sort my Project items into folders (a folder for Forms, a folder for Classes, a Misc folder, etc.)
It seems though that if I move the "app.config" file to a folder named "Config Files" everything works until I change a setting in the Settings.settings file. Once I do that, a new app.config is created and the one that was in the "Config Files" folder did not get updated.
I have searched the entire solution for the text "app.config" and did not find any results. How can I move this file so that my Solution Explorer looks nice and clean?
No, the app.config has to be in the main project folder - but you can "externalize" any configuration section inside the app.config by using the configSource= attribute:
<connectionStrings configSource="config\db\connectionstrings.config" />
<system.net>
<mailSettings>
<smtp configSource="config\mail\smtp.dev.config" />
</mailSettings>
</system.net>
<system.serviceModel>
<behaviors configSource="config\wcf\behaviors.config" />
<binding configSource="config\wcf\bindings.config" />
<client configSource="config\wcf\client.config" />
</system.serviceModel>
AFAIK, you cannot change the location of the default configuration file. Although if you need another configuration file, you can make use of ExeConfigurationFileMap class.