What is a good approach to managing a debug and release connection string in a .NET / SQLServer application?
I have two SQL Servers, a production and a build/debug and I need a method of switching between the two when my ASP.NET application is deployed.
Currently I simply store them in the web.config and comment one or the other out, however that is error prone when deploying.
Create a Debug and Release version of the Web.config file, e.g. Web.debug.config and Web.release.config. Then add a pre-compile condition that copies the relevant version into the web.config based upon the current Target.
Edit: To add the pre compile condition right click on you project and select "Properties" then goto the "Build Events" tab and add the code below to the precompile condition. Obviously, you will have to ammend the code to your needs, see image below.
#echo off
echo Configuring web.config pre-build event ...
if exist "$(ProjectDir)web.config" del /F / Q "$(ProjectDir)web.config"
if "$(ConfigurationName)" == "Debug Test" goto test
if "$(ConfigurationName)" == "Debug M" goto M
if "$(ConfigurationName)" == "Debug BA" goto BA
if "$(ConfigurationName)" == "Release Test" goto test
if "$(ConfigurationName)" == "Release M" goto M
if "$(ConfigurationName)" == "Release BA" goto BA
echo No web.config found for configuration $(ConfigurationName). Abort batch.
exit -1
goto :end
:test
copy /Y "$(ProjectDir)web.config.test" "$(ProjectDir)web.config"
GOTO end
:BA
copy /Y "$(ProjectDir)web.config.BA" "$(ProjectDir)web.config"
GOTO end
:M
copy /Y "$(ProjectDir)web.config.M" "$(ProjectDir)web.config"
GOTO end
:end
echo Pre-build event finished
Project Properties http://img442.imageshack.us/img442/1843/propsa.jpg
The good news is that .NET4 has a provision for just that, you can have separate configs for each Configuration (web.Release.config, web.Debug.config).
The bad news is ... you're probably not using that yet.
Use preprocessor directives: when your project is configured to run in the debug mode, the debug connection string will be chosen, otherwise the release connection string will be chosen automatically.
In Visual studio you will notice that statements are dimmed exclusively according to the project configuration (debug or release).
Just add something like the following in your code:
string myConnectionString;
#if DEBUG
myConnectionString = "your debug connection string";//may be read from your debug connection string from the config file
#else
myConnectionString = "your release connection string"; //may be read from your relase connection string from the config file
#endif
for more detail,check this.
I usually set an Environment variable on my production servers that denotes the server is a production server. I then read the correct connection string from my web.config based on whether this Environment variable exists and is set to the production value.
I use a combination of Sameh's and Obalix's method in .net 3.5.
public static class DataConnection
{
#if LOCALDEV
public const string Env = "Debug";
#endif
#if STAGING
public const string Env="Staging";
#endif
#if RELEASE
public const string Env="Release";
#endif
private static ConnectionStringSettingsCollection _connections;
static DataConnection()
{
_connections = ConfigurationManager.ConnectionStrings;
}
public static string BoloConnectionString
{
get
{
return _connections["DB1."+Env].ConnectionString;
}
}
public static string AOAConnectionString
{
get
{
return _connections["DB2."+Env].ConnectionString;
}
}
public static string DocVueConnectionString
{
get
{
return _connections["DB3."+Env].ConnectionString;
}
}
}
Then in my project properties, I define the right conditional compilation symbols. This way I don't have to keep my connection strings hard coded like Sameh's, but the code only looks for the string based on how it was built. This lets me have (if I need to) one config file for all the builds, but in reality I don't deploy the config files in my build process. Although the conditional app.Relase.config stuff for .net 4 looks like the right way to go in the future.
As of 2018 for newer versions of Visual Studio, Microsoft has taken over the SlowCheetah extension. Installing this will give you an option to split the app.config file into three separate files. One is a base file that has code that always applies, and then you get an app.debug.config file and an app.release.config file.
Note that pulling this as a NuGet package in the project is not enough. If you want the Visual Studio UI menu option, you need to actually download the installer from the site below and run it. Then, install SlowCheetah specifically on any projects you want to use this on using NuGet.
Also note that the original SlowCheetah program by the original developer still exists, but use the one published by Microsoft for newer versions of Visual Studio.
https://marketplace.visualstudio.com/items?itemName=VisualStudioProductTeam.SlowCheetah-XMLTransforms
Well perhaps this is a bit outdated, but the ODBC DSN solves this problem quite well -- I still use -- with rigour -- DNS settings to differentiate between production and debug environments.
p.s., I am expecting loads of down-votes, perhaps this will be a gauge of what people think of a level of indirection for database identifiers.
I can say other solution for this issue. In csproj file file create folow:
<Content Include="DB.config">
<SubType>Designer</SubType>
</Content>
<Content Include="DB.Debug.config">
<DependentUpon>DB.config</DependentUpon>
<SubType>Designer</SubType>
</Content>
<Content Include="DB.Release.config">
<DependentUpon>DB.config</DependentUpon>
<SubType>Designer</SubType>
</Content>
In xml written set the two version for release and debug.
When you open a web project you'll get 2 extra files of the Web.Config out of the box - Web.Debug.config & Web.Release.config.
1.Add your desired connection string to those files with XSLT attributes xdt:Transform="SetAttributes" xdt:Locator="Match(name)"
<connectionStrings>
<add name="myConnectionString" connectionString="myConnectionString" xdt:Transform="SetAttributes" xdt:Locator="Match(name)" />
</connectionStrings>"
2.Edit your csproj and add a TransformXml target:
<Target Name="TransformActiveConfiguration" Condition="Exists('$(ProjectDir)/Web.$(Configuration).config')" BeforeTargets="Compile" >
<TransformXml Source="$(ProjectDir)/Web.Config" Transform="$(ProjectDir)/Web.$(Configuration).config" Destination="$(TargetDir)/Web.config" />
</Target>
The second step will make the transform on each build (according to your active configuration) and not only on publish, giving you a better debug experience. I learnt it from this post.
Related
I've created a simple unit test project to read an app.config file. Target framework is Core 2.0. I also created a Core 2.0 console app, to sanity-check myself to make sure I wasn't doing anything weird (same test passed as expected in a .NET 4.6.1 unit test project).
The console app reads the app.config fine, but the unit test method fails and I cannot figure out why. Both are using a copy of the same app.config (not added as a link) and both have the System.Configuration.ConfigurationManager v4.4.1 NuGet package installed.
The App.config
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="Test1" value ="This is test 1."/>
<add key="Test2" value ="42"/>
<add key="Test3" value ="-42"/>
<add key="Test4" value="true"/>
<add key="Test5" value="false"/>
<add key="Test6" value ="101.101"/>
<add key="Test7" value ="-1.2345"/>
</appSettings>
</configuration>
The Unit Test
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Configuration;
namespace ConfigTest
{
[TestClass]
public class UnitTest1
{
[TestMethod()]
public void ConfigTest()
{
foreach (string s in ConfigurationManager.AppSettings.AllKeys)
{
System.Console.WriteLine(s);
System.Diagnostics.Debug.WriteLine(s);
}
//AllKeys.Length is 0? Should be 7...
Assert.IsTrue(ConfigurationManager.AppSettings.AllKeys.Length == 7);
}
}
}
The Console App
using System;
using System.Configuration;
namespace ConfigTestApp
{
class Program
{
static void Main(string[] args)
{
foreach (string s in ConfigurationManager.AppSettings.AllKeys)
{
Console.WriteLine(s);
System.Diagnostics.Debug.WriteLine(s);
}
//Outputs 7 as expected
Console.WriteLine(ConfigurationManager.AppSettings.AllKeys.Length);
}
}
}
Given that I'm still pretty new to the whole .NET Core world, am I doing something totally incorrect here? I sort of just feel crazy at the moment...
Looking through the github issue's comments, I found a work around that can go in the msbuild file...
<Target Name="CopyCustomContent" AfterTargets="AfterBuild">
<Copy SourceFiles="app.config" DestinationFiles="$(OutDir)\testhost.dll.config" />
</Target>
This makes it easier to verify existing tests under .NET Core before porting the configuration data over to json configuration files.
Edit
If running under Resharper, the previous answer doesn't work as Resharper proxies the assembly, so you need
<Target Name="CopyCustomContent" AfterTargets="AfterBuild">
<Copy SourceFiles="app.config" DestinationFiles="$(OutDir)\ReSharperTestRunner64.dll.config" />
</Target>
If you check the result of the call to ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
It should tell you where the required configuration file should be while running unit tests for that assembly.
I found that instead of having an app.config file, ConfigurationManager was looking for a testhost.dll.config file.
This was for a project targeting netcoreapp2.1, with a reference to Microsoft.NET.Test.Sdk,NUnit 3.11 and Nunit3TestAdapter 3.12.0
.CORE 3.1
To find out what dll.config file was being used, I debugged the test by adding this line and looking to see what the value is.
string path = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None).FilePath;
Then I found out resharper was using testhost.dll.config and VStest was using testhost.x86.dll.config. I needed to add the following lines to the project file.
<Target Name="CopyCustomContent" AfterTargets="AfterBuild">
<Copy SourceFiles="app.config" DestinationFiles="$(OutDir)\testhost.dll.config" />
<Copy SourceFiles="app.config" DestinationFiles="$(OutDir)\testhost.x86.dll.config" />
</Target>
I came across the same issue with my xunit tests and solved it by using the instance of Configuration from ConfigurationManager. I put the static (normal) way it works in core, framework (but not unit tests) before I show the alternative way it works in all three:
var appSettingValFromStatic = ConfigurationManager.AppSettings["mySetting"];
var appSettingValFromInstance = ConfigurationManager.OpenExeConfiguration(Assembly.GetExecutingAssembly().Location).AppSettings.Settings["mySetting"].Value;
And here is a similar/related issue. In case anyone needs to get a section you can do a similar thing, though the type must change in the app config:
<configSections>
<section name="customAppSettingsSection" type="System.Configuration.AppSettingsSection"/>
<section name="customNameValueSectionHandlerSection" type="System.Configuration.NameValueSectionHandler"/>
</configSections>
<customAppSettingsSection>
<add key="customKey" value="customValue" />
</customAppSettingsSection>
<customNameValueSectionHandlerSection>
<add key="customKey" value="customValue" />
</customNameValueSectionHandlerSection>
Code to grab section:
var valFromStatic = ((NameValueCollection)ConfigurationManager.GetSection("customNameValueSectionHandlerSection"))["customKey"];
var valFromInstance = ((AppSettingsSection)ConfigurationManager.OpenExeConfiguration(Assembly.GetExecutingAssembly().Location).GetSection("customAppSettingsSection")).Settings["customKey"].Value;
I feel like I am also crazy, and I know there are newer ways of doing config in core, but if one wants to do something cross-platform this is the only way I know how. I'd be very interested if anyone has alternatives
For my mixed .NET-Core & .NET-Framework project, I added the following to the unit test global setup:
#if NETCOREAPP
using System.Configuration;
using System.IO;
using System.Reflection;
#endif
...
// In your global setup:
#if NETCOREAPP
string configFile = $"{Assembly.GetExecutingAssembly().Location}.config";
string outputConfigFile = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None).FilePath;
File.Copy(configFile, outputConfigFile, true);
#endif
This copies the config file to the output path testhost.dll.config but should be resilient enough to account for future changes in the testing framework.
Or you can copy to below, which amounts to the same thing:
string outputConfigFile = Path.Combine(Path.GetDirectoryName(configFile), $"{Path.GetFileName(Assembly.GetEntryAssembly().Location)}.config");
Credit to #stop-cran and #PaulHatcher's solutions, this is a combination of those two.
None of the answers given here provide a viable workaround when you're dealing with code accessing directly the static ConfigurationManager properties such as AppSettings or ConnectionStrings.
The truth is, it is not possible at the moment. You can read through the discussion here to understand why:
https://github.com/dotnet/corefx/issues/22101
There is talk to implement the support for it here:
https://github.com/Microsoft/vstest/issues/1758
In my opinion it makes sense to support this scenario since it's been working on the .NET Framework plus System.Configuration.ConfigurationManager is a .NET Standard 2.0 library now.
A hacky, but working way is to copy the config to the same folder as an entry assembly, whatever it is:
[SetUpFixture]
public class ConfigKludge
{
[OneTimeSetUp]
public void Setup() =>
File.Copy(
Assembly.GetExecutingAssembly().Location + ".config",
Assembly.GetEntryAssembly().Location + ".config",
true);
[OneTimeTearDown]
public void Teardown() =>
File.Delete(Assembly.GetEntryAssembly().Location + ".config");
}
Apart from adding this class, the only thing to make it work is to include app.config file in test project (without any copying options). It should be copied to the output folder as <your test project name>.dll.config at the build step, because it's kind of default logic.
Note the documentation for OneTimeSetUpAttribute:
Summary:
Identifies a method that is called once to perform setup before any child tests are run.
Although it should work for parallel test runs for a single project, there could be obvious troubles when running two test projects simultaneously, since the config would get overwritten.
However, it is still suitable for containerized test runs, like in Travis.
When we answer such well-researched and well-articulated question, we should better assume that it is being asked by an informed and intelligent being. And instead of patronizing them with the obvious about new, great ways of writing tonnes of boilerplate code to parse all sort of JSON et al, being forced on us and shoved down our throat by know-betters, we should focus on answering to the point.
Since the OP is already using System.Configuration to access settings, they already know how to arrive at this point. The only thing that is missing is one little touch: adding this line to the post-build event:
copy $(OutDir)<appname>.dll.config $(OutDir)testhost.dll.config
where <appname> is the project being unit-tested.
I applaud everyone who is still using (originally lame but workable) implementation of app.config because doing so protects our and our clients' investment in technology instead of reinventing the wheel. Amen.
Mercifully there is now a way to set the name of the expected configuration file at runtime. You can set the APP_CONFIG_FILE data for the current app domain.
I created the following SetUpFixture to do this automatically:
[SetUpFixture]
public class SetUpFixture
{
[OneTimeSetUp]
public void OneTimeSetUp()
{
var testDllName = Assembly.GetAssembly(GetType())
.GetName()
.Name;
var configName = testDllName + ".dll.config";
AppDomain.CurrentDomain.SetData("APP_CONFIG_FILE", configName);
}
}
The relevant GitHub discussions are:
ConfigurationManager doesn't find config file with "dotnet test" · Issue #22720 · dotnet/runtime
Provide a way to override the global configuration file path · Issue #931 · dotnet/runtime
Respect AppContext.SetData with APP_CONFIG_FILE key by krwq · Pull Request #56748 · dotnet/runtime
The ConfigurationManager API will only use the configuration of the app that is currently running. In a unit test project, this means the app.config of the test project, not the console application.
.NET Core Applications aren't supposed to use app.config or ConfigurationManager, as it is a legacy "full framework" configuration system.
Consider using Microsoft.Extensions.Configuration instead to read JSON, XML or INI configuration files. See this doc: https://learn.microsoft.com/en-us/aspnet/core/fundamentals/configuration
Usually in .NET Framework projects, any App.config file was copied to the bin folder by Visual Studio, with the name of your executable (myApp.exe.config) so it could be reachable in runtime. Not anymore in .NET Standard or Core Framework. You must manually copy and set the file in the bin/debug or release folder. After that it could be get with something like:
string AssemblyName = System.IO.Path.GetFileName(System.Reflection.Assembly.GetEntryAssembly().GetName().CodeBase);
AppConfig = (System.Configuration.Configuration)System.Configuration.ConfigurationManager.OpenExeConfiguration(AssemblyName);
While app.config exists in the root project folder add below string to Post-build event command line
xcopy /Y $(ProjectDir)app.config $(ProjectDir)$(OutDir)testhost.dll.config*
Add the configuration file
First, add a appconfig.json file to the Integration test project
Configure the appconfig.json file to be copied to the output
directory by updating
Add NuGet package
Microsoft.Extensions.Configuration.Json
Use the configuration in your unit tests
[TestClass]
public class IntegrationTests
{
public IntegrationTests()
{
var config = new ConfigurationBuilder().AddJsonFile("appconfig.json").Build();
_numberOfPumps = Convert.ToInt32(config["NumberOfPumps"]);
_numberOfMessages = Convert.ToInt32(config["NumberOfMessages"]);
_databaseUrl = config["DatabaseUrlAddress"];
}
}
When using TeamCity and running a build I get the following error message.
13:20:31]Step 1/1: MSBuild (1s)
[13:20:32][Step 1/1] src\DystopiaOnline.proj.teamcity: Build target: BuildSolution
[13:20:32][src\DystopiaOnline.proj.teamcity] BuildSolution
[13:20:32][BuildSolution] C:\TeamCity\buildAgent\work\8c8eb5050252f271\src\DystopiaOnline.proj(36, 5): error MSB4062: The "DystopiaOnline.Build.Tasks.GetUnixTimestamp" task could not be loaded from the assembly C:\TeamCity\buildAgent\work\8c8eb5050252f271\src\DystopiaOnline.Build.Tasks/bin/Release/DystopiaOnline.Build.Tasks.dll. Could not load file or assembly 'file:///C:\TeamCity\buildAgent\work\8c8eb5050252f271\src\DystopiaOnline.Build.Tasks\bin\Release\DystopiaOnline.Build.Tasks.dll' or one of its dependencies. The system cannot find the file specified. Confirm that the <UsingTask> declaration is correct, that the assembly and all its dependencies are available, and that the task contains a public class that implements Microsoft.Build.Framework.ITask.
[13:20:32][Step 1/1] Step MSBuild failed
However when I run the build from the developer command prompt the build works fine. Taking a look inside the C:\TeamCity\buildAgent\work\8c8eb5050252f271\src\D ystopiaOnline.Build.Tasks\bin only shows a Debug folder rather than a Release folder. Running the build from the developer command prompt works ok just building from Team City doesn't.
shouldn't the Release folder be created when the build is run from Team City with the Env variable set to prod? what could be causing this? Anyone any ideas?
In my project solution .proj file have the following conditions set to determine a build configuration. can anyone with any experience working with team city offer any advice as to what the problem may be? thanks.
<PropertyGroup>
<Env Condition="'$(Env)' == ''">dev</Env>
<VersionNumber Condition="'$(VersionNumber)' == ''">1</VersionNumber>
<MSBuildCommunityTasksPath>$(MSBuildThisFileDirectory)/Tasks</MSBuildCommunityTasksPath>
<UnityPath Condition="'$(UnityPath)' == ''">c:\Program Files (x86)\Unity</UnityPath>
</PropertyGroup>
<PropertyGroup Condition="'$(Env)' == 'dev'">
<BuildConfig>Debug</BuildConfig>
<Domain>mmo.dystopiaOnline.dev</Domain>
<SetParamsFile>Parameters.Local.config</SetParamsFile>
</PropertyGroup>
<PropertyGroup Condition="'$(Env)' == 'prod'">
<BuildConfig>Release</BuildConfig>
<Domain>mmo.DystopiaOnline.com</Domain>
<SetParamsFile>Parameters.Production.config</SetParamsFile>
</PropertyGroup>
<PropertyGroup Condition="'$(Env)' == 'sta'">
<BuildConfig>Release</BuildConfig>
<Domain>mmo.DystopiaOnline.sta</Domain>
<SetParamsFile>Parameters.Staging.config</SetParamsFile>
</PropertyGroup>
TeamCity build log
[11:45:53]Checking for changes
[11:45:53]Collecting changes in 1 VCS root (1s)
[11:45:55]Clearing temporary directory: C:\TeamCity\buildAgent\temp\buildTmp
[11:45:55]Publishing internal artifacts
[11:45:55]Checkout directory: C:\TeamCity\buildAgent\work\8c8eb5050252f271
[11:45:55]Updating sources: server side checkout
[11:45:55]Step 1/1: MSBuild (4s)
[11:45:55][Step 1/1] Starting: C:\TeamCity\buildAgent\plugins\dotnetPlugin\bin\JetBrains.BuildServer.MsBuildBootstrap.exe /workdir:C:\TeamCity\buildAgent\work\8c8eb5050252f271 "/msbuildPath:C:\Program Files (x86)\MSBuild\12.0\bin\MSBuild.exe"
[11:45:55][Step 1/1] in directory: C:\TeamCity\buildAgent\work\8c8eb5050252f271
[11:45:59][Step 1/1] src\DystopiaOnline.proj.teamcity: Build target: BuildSolution
[11:45:59][src\DystopiaOnline.proj.teamcity] BuildSolution
[11:45:59][BuildSolution] MSBuild
[11:45:59][BuildSolution] C:\TeamCity\buildAgent\work\8c8eb5050252f271\src\DystopiaOnline.proj(36, 5): error MSB4062: The "DystopiaOnline.Build.Tasks.GetUnixTimestamp" task could not be loaded from the assembly C:\TeamCity\buildAgent\work\8c8eb5050252f271\src\DystopiaOnline.Build.Tasks/bin/Release/DystopiaOnline.Build.Tasks.dll. Could not load file or assembly 'file:///C:\TeamCity\buildAgent\work\8c8eb5050252f271\src\DystopiaOnline.Build.Tasks\bin\Release\DystopiaOnline.Build.Tasks.dll' or one of its dependencies. The system cannot find the file specified. Confirm that the <UsingTask> declaration is correct, that the assembly and all its dependencies are available, and that the task contains a public class that implements Microsoft.Build.Framework.ITask.
[11:45:59][Step 1/1] Process exited with code 1
[11:45:59][Step 1/1] MSBuild output
[11:45:59][Step 1/1] Step MSBuild failed
[11:45:59]Publishing internal artifacts
[11:45:59]Build finished
This is how my project setup look witht the build folder.
link to .proj file on OneDrive
Error after copying release file into TeamCity manually
C:\Program Files (x86)\MSBuild\12.0\bin\Microsoft.Common.CurrentVersion.targets(3797, 5): error MSB3027: Could not copy "C:\TeamCity\buildAgent\work\8c8eb5050252f271\src\DystopiaOnline.Base\bin\Release\DystopiaOnline.Base.dll" to "bin\Release\DystopiaOnline.Base.dll". Exceeded retry count of 10. Failed.
C:\Program Files (x86)\MSBuild\12.0\bin\Microsoft.Common.CurrentVersion.targets(3797, 5): error MSB3021: Unable to copy file "C:\TeamCity\buildAgent\work\8c8eb5050252f271\src\DystopiaOnline.Base\bin\Release\DystopiaOnline.Base.dll" to "bin\Release\DystopiaOnline.Base.dll". The process cannot access the file 'bin\Release\DystopiaOnline.Base.dll' because it is being used by another process.
There is a typo in your DystopiaOnline.proj file in the word "Configuraton":
<MSBuild Projects="DystopiaOnline.Build.Tasks/DystopiaOnline.Build.Tasks.csproj" Properties="Configuraton=$(BuildConfig)" />
I think that this is the reason of the incorrect configuration building.
How have you setup the parameter in the build? It's most likely that it's value is not being passed to the build runner so it defaults to dev
<Env Condition="'$(Env)' == ''">dev</Env>
If you are using teamcity parameters it should be a system or environment parameter. You can also check the parameters used in a build by clicking on it and going to the parameters tabs, might want to double check that it has the value you want.
First keep in mind, that Windows path is '\' NOT '/'. In normal cases there is not any different (eg. when you want to put path in Explorer), but sometimes (I run in to some problems with some task in MsBuild) the mechanism doesn't recognize that this is proper path. So change the path to
<MSBuildCommunityTasksPath>$(MSBuildThisFileDirectory)\Tasks\</MSBuildCommunityTasksPath>
(Also MsBuild convention told us to put trailing slash)
And whenever you have reference to "DystopiaOnline.Build.Tasks.dll": [...]src\DystopiaOnline.Build.Tasks\bin\Release\DystopiaOnline.Build.Tasks.dll.
In the build log, there is not any sign that the MsBuild try to build the DystopiaOnline.Build.Tasks. HOW you specify the order of building your projects? Can you add this project that we can see exactly what MsBuild want to do and in what order.
If you use <UsingTask> inside the same project file that want to build DystopiaOnline.Build.Tasks... It will never work, because MsBuild first try to resolve task and then run targets to build.
It could work on your machine when you already build the project but not in clean environment when there is not (yet) any task.
try creating new system parameter called system.Configuration and set value "Release"
I have an application with the next two Post-Compilation commands:
call editbin /LARGEADDRESSAWARE $(TargetPath)
call editbin /LARGEADDRESSAWARE $(ProjectDir)obj\$(PlatformName)\$(ConfigurationName)\$(TargetFileName)
and works fine.
But when I publish into a server as the ClickOne Application works with no errors but when I try install in a client the hash of file is different than the value calculated in the manifest.
I tryed to use the next command:
sn -Ra $(ProjectDir)obj\$(PlatformName)\$(ConfigurationName)\$(TargetFileName) PublicPrivateKeyFile.snk
but does not work and it shows the next message:
app.exe does not represent any strong-named assembly.
I suppose it's because all my projects has the "signing the assembly" option with false value. Before using LARGEADDRESSAWARE the ClickOnce Application worked fine.
It is necesary to set the "signing the assembly" option with true value for all projects or are there any way to use LARGEADDRESSAWARE with false value for this option?
EDIT:
Solution of Mark Sowul works fine:
Also I added in AfterBuild the next lines in order to check if the AfterCompile works fine
call "$(VS110COMNTOOLS)vsvars32.bat"
dumpbin /headers "$(TargetPath)" > "$(TargetPath).info"
findstr "(>2GB)" "$(TargetPath).info"
set BUID_ERRORLEVEL=%ERRORLEVEL%
del "$(TargetPath).info"
if [%BUID_ERRORLEVEL%]==[0] echo EXE program updated to use more than 2GB
if [%BUID_ERRORLEVEL%]==[1] echo ERROR: EXE PROGRAM WAS NOT UPDATED TO USE MORE THAN 2GB
set ERRORLEVEL=%BUID_ERRORLEVEL%
Post Build events are too late in the game. You have found this out to an extent, as I did, by realizing you need to alter the file in obj.
However, Post Build occurs after the manifest generation. So editing the obj file there is too late. The better place to do it is in the AfterCompile build target.
You'll have to edit the csproj; add after the lines you'll already see for this:
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
**<Target Name="AfterCompile">
<Exec Command="
call "$(VS110COMNTOOLS)\vsvars32.bat"
editbin /largeaddressaware "$(IntermediateOutputPath)$(TargetFileName)"
" />
</Target>**
how can i configure my Visual Studio 2010 C# solution/project so
that when i select a Debug configuration - ConnectionString#1 would be used
Release - Connection string #2
and
"Myconfiguarion1" (which was copied from debug) -> Connection string #3
I got to it work with debug in such a way:
if (ConfigurationManager.ConnectionStrings["ConnectionString1"] != null)
{
winApplication.ConnectionString = ConfigurationManager.ConnectionStrings["ConnectionString1"].ConnectionString;
}
#if DEBUG
if(ConfigurationManager.ConnectionStrings["ConnectionString2"] != null)
{
winApplication.ConnectionString = ConfigurationManager.ConnectionStrings["ConnectionString2"].ConnectionString;
}
#endif
but this doesn't work with "MybuildConfiguration"
If you're trying to do this for the web.config file of an ASP.NET project in Visual Studio 2010, it's built-in via XML Transformations for web.config.
Web Deployment: Web.Config Transformations
If you're trying to do this for an app.config file, you can use the same transformations but working with them is a bit of a hack:
Visual Studio App.config XML Transformations
Both boil down to actually using separate config files for the different environments you are going to be running your app in. That allows you to supply different values for any of the keys based on what environment you're running in.
I think you can use conditional compilation constants. To define them,
you have to open project property window, select compilation tab, and define a name in the conditional constants field, e.g. CONN1.
This constants get defined only for your active build configuration, so you can define CONN1 for Debug configuration,CONN2 for Release configuration,CONN3 for your custom configuration etc.
then, in your code, you can use:
#ifdef CONN1
//use connection 1
#else
#ifdef CONN2
//use connection 2
#else
//use connection 3
#endif
#endif
I have a .NET application which has different configuration files for Debug and Release builds. E.g. the debug app.config file points to a development SQL Server which has debugging enabled and the release target points to the live SQL Server. There are also other settings, some of which are different in debug/release.
I currently use two separate configuration files (debug.app.config and release.app.config). I have a build event on the project which says if this is a release build then copy release.app.config to app.config, else copy debug.app.config to app.config.
The problem is that the application seems to get its settings from the settings.settings file, so I have to open settings.settings in Visual Studio which then prompts me that the settings have changed so I accept the changes, save settings.settings and have to rebuild to make it use the correct settings.
Is there a better/recommended/preferred method for achieving a similar effect? Or equally, have I approached this completely wrong and is there a better approach?
Any configuration that might differ across environments should be stored at the machine level, not the application level. (More info on configuration levels.)
These are the kinds of configuration elements that I typically store at the machine level:
Application settings
Connection strings
retail=true
Smtp settings
Health monitoring
Hosting environment
Machine key
When each environment (developer, integration, test, stage, live) has its own unique settings in the c:\Windows\Microsoft.NET\Framework64\v2.0.50727\CONFIG directory, then you can promote your application code between environments without any post-build modifications.
And obviously, the contents of the machine-level CONFIG directory get version-controlled in a different repository or a different folder structure from your app. You can make your .config files more source-control friendly through intelligent use of configSource.
I've been doing this for 7 years, on over 200 ASP.NET applications at 25+ different companies. (Not trying to brag, just want to let you know that I've never seen a situation where this approach doesn't work.)
This might help some people dealing with Settings.settings and App.config: Watch out for GenerateDefaultValueInCode attribute in the Properties pane while editing any of the values in the Settings.settings grid in Visual Studio (Visual Studio 2008 in my case).
If you set GenerateDefaultValueInCode to True (True is the default here!), the default value is compiled into the EXE (or DLL), you can find it embedded in the file when you open it in a plain text editor.
I was working on a console application and if I had defaulted in the EXE, the application always ignored the configuration file placed in the same directory! Quite a nightmare and no information about this on the whole Internet.
There is a related question here:
Improving Your Build Process
Config files come with a way to override the settings:
<appSettings file="Local.config">
Instead of checking in two files (or more), you only check in the default config file, and then on each target machine, you put a Local.config, with just the appSettings section that has the overrides for that particular machine.
If you are using config sections, the equivalent is:
configSource="Local.config"
Of course, it's a good idea to make backup copies of all the Local.config files from other machines and check them in somewhere, but not as a part of the actual solutions. Each developer puts an "ignore" on the Local.config file so it doesn't get checked in, which would overwrite everyone else's file.
(You don't actually have to call it "Local.config", that's just what I use)
From what I am reading, it sounds like you are using Visual Studio for your build process. Have you thought about using MSBuild and Nant instead?
Nant's xml syntax is a little weird but once you understand it, doing what you mentioned becomes pretty trivial.
<target name="build">
<property name="config.type" value="Release" />
<msbuild project="${filename}" target="Build" verbose="true" failonerror="true">
<property name="Configuration" value="${config.type}" />
</msbuild>
<if test="${config.type == 'Debug'}">
<copy file=${debug.app.config}" tofile="${app.config}" />
</if>
<if test="${config.type == 'Release'}">
<copy file=${release.app.config}" tofile="${app.config}" />
</if>
</target>
To me it seems that you can benefit from the Visual Studio 2005 Web Deployment Projects.
With that, you can tell it to update/modify sections of your web.config file depending on the build configuration.
Take a look at this blog entry from Scott Gu for a quick overview/sample.
We used to use Web Deployment projects but have since migrated to NAnt. Instead of branching and copying different setting files we currently embed the configuration values directly in the build script and inject them into our config files via xmlpoke tasks:
<xmlpoke
file="${stagingTarget}/web.config"
xpath="/configuration/system.web/compilation/#debug"
value="true"
/>
In either case, your config files can have whatever developer values you want and they'll work fine from within your dev environment without breaking your production systems. We've found that developers are less likely to arbitrarily change the build script variables when testing things out, so accidental misconfigurations have been rarer than with other techniques we've tried, though it's still necessary to add each var early in the process so that the dev value doesn't get pushed to prod by default.
My current employer solved this issue by first putting the dev level (debug, stage, live, etc) in the machine.config file. Then they wrote code to pick that up and use the right config file. That solved the issue with the wrong connection string after the app gets deployed.
They just recently wrote a central webservice that sends back the correct connection string from the value in the machine.config value.
Is this the best solution? Probably not, but it works for them.
One of the solutions that worked me fine was using a WebDeploymentProject.
I had 2/3 different web.config files in my site, and on publish, depending on the selected configuration mode (release/staging/etc...) I would copy over the Web.Release.config and rename it to web.config in the AfterBuild event, and delete the ones I don't need (Web.Staging.config for example).
<Target Name="AfterBuild">
<!--Web.config -->
<Copy Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' " SourceFiles="$(SourceWebPhysicalPath)\Web.Release.config" DestinationFiles="$(OutputPath)\Web.config" />
<Copy Condition=" '$(Configuration)|$(Platform)' == 'Staging|AnyCPU' " SourceFiles="$(SourceWebPhysicalPath)\Web.Staging.config" DestinationFiles="$(OutputPath)\Web.config" />
<!--Delete extra files -->
<Delete Files="$(OutputPath)\Web.Release.config" />
<Delete Files="$(OutputPath)\Web.Staging.config" />
<Delete Files="#(ProjFiles)" />
</Target>
You'll find another solution here: Best way to switch configuration between Development/UAT/Prod environments in ASP.NET? which uses XSLT to transfor the web.config.
There are also some good examples on using NAnt.
Our project has the same issue where we had to maintain configs for dev, qa, uat and prod. Here is what we followed (only applies if you are familiar with MSBuild):
Use MSBuild with the MSBuild Community tasks extension. It includes the 'XmlMassUpdate' task that can 'mass-update' entries in any XML file once you give it the correct node to start with.
To Implement:
1) You need to have one config file which will have your dev env entries; this is the config file in your solution.
2) You need to have a 'Substitutions.xml' file, that contains only the entries that are DIFFERENT (appSettings and ConnectionStrings mostly) for each environment. Entries that do not change across the environment need not be put in this file. They can live in the web.config file of the solution and will not be touched by the task
3) In your build file, just call the XML mass update task and provide the right environment as a parameter.
See example below:
<!-- Actual Config File -->
<appSettings>
<add key="ApplicationName" value="NameInDev"/>
<add key="ThisDoesNotChange" value="Do not put in substitution file" />
</appSettings>
<!-- Substitutions.xml -->
<configuration xmlns:xmu="urn:msbuildcommunitytasks-xmlmassupdate">
<substitutions>
<QA>
<appSettings>
<add xmu:key="key" key="ApplicationName" value="NameInQA"/>
</appSettings>
</QA>
<Prod>
<appSettings>
<add xmu:key="key" key="ApplicationName" value="NameInProd"/>
</appSettings>
</Prod>
</substitutions>
</configuration>
<!-- Build.xml file-->
<Target Name="UpdateConfigSections">
<XmlMassUpdate ContentFile="Path\of\copy\of\latest web.config" SubstitutionsFile="path\of\substitutionFile" ContentRoot="/configuration" SubstitutionsRoot="/configuration/substitutions/$(Environment)" />
</Target>
replace '$Environment' with 'QA' or 'Prod' based on what env. you are building for. Note that you should work on a copy of a config file and not the actual config file itself to avoid any possible non-recoverable mistakes.
Just run the build file and then move the updated config file to your deployment environment and you are done!
For a better overview, read this:
http://blogs.microsoft.co.il/blogs/dorony/archive/2008/01/18/easy-configuration-deployment-with-msbuild-and-the-xmlmassupdate-task.aspx
Like you I've also set up 'multi' app.config - eg app.configDEV, app.configTEST, app.config.LOCAL. I see some of the excellent alternatives suggested, but if you like the way it works for you, I'd add the following:
I have a
<appSettings>
<add key = "Env" value = "[Local] "/>
for each app I add this to the UI in the titlebar:
from ConfigurationManager.AppSettings.Get("Env");
I just rename the config to the one I'm targetting (I have a project with 8 apps with lots of database/wcf config against 4 evenioments). To deploy with clickonce into each I change 4 seetings in the project and go. (this I'd love to automate)
My only gotcha is to remember to 'clean all' after a change, as the old config is 'stuck' after a manual rename. (Which I think WILL fix you setting.setting issue).
I find this works really well (one day I'll get time to look at MSBuild/NAnt)
Web.config:
Web.config is needed when you want to host your application on IIS. Web.config is a mandatory config file for IIS to configure how it will behave as a reverse proxy in front of Kestrel. You have to maintain a web.config if you want to host it on IIS.
AppSetting.json:
For everything else that does not concern IIS, you use AppSetting.json.
AppSetting.json is used for Asp.Net Core hosting. ASP.NET Core uses the "ASPNETCORE_ENVIRONMENT" environment variable to determine the current environment. By default, if you run your application without setting this value, it will automatically default to the Production environment and uses "AppSetting.production.json" file. When you debug via Visual Studio it sets the environment to Development so it uses "AppSetting.json". See this website to understand how to set the hosting environment variable on Windows.
App.config:
App.config is another configuration file used by .NET which is mainly used for Windows Forms, Windows Services, Console Apps and WPF applications. When you start your Asp.Net Core hosting via console application app.config is also used.
TL;DR
The choice of the configuration file is determined by the hosting environment you choose for the service. If you are using IIS to host your service, use a Web.config file. If you are using any other hosting environment, use an App.config file.
See Configuring Services Using Configuration Files documentation
and also check out Configuration in ASP.NET Core.
It says asp.net above, so why not save your settings in the database and use a custom-cache to retrieve them?
The reason we did it because it's easier (for us) to update the continuously database than it is to get permission to continuously update production files.
Example of a Custom Cache:
public enum ConfigurationSection
{
AppSettings
}
public static class Utility
{
#region "Common.Configuration.Configurations"
private static Cache cache = System.Web.HttpRuntime.Cache;
public static String GetAppSetting(String key)
{
return GetConfigurationValue(ConfigurationSection.AppSettings, key);
}
public static String GetConfigurationValue(ConfigurationSection section, String key)
{
Configurations config = null;
if (!cache.TryGetItemFromCache<Configurations>(out config))
{
config = new Configurations();
config.List(SNCLavalin.US.Common.Enumerations.ConfigurationSection.AppSettings);
cache.AddToCache<Configurations>(config, DateTime.Now.AddMinutes(15));
}
var result = (from record in config
where record.Key == key
select record).FirstOrDefault();
return (result == null) ? null : result.Value;
}
#endregion
}
namespace Common.Configuration
{
public class Configurations : List<Configuration>
{
#region CONSTRUCTORS
public Configurations() : base()
{
initialize();
}
public Configurations(int capacity) : base(capacity)
{
initialize();
}
public Configurations(IEnumerable<Configuration> collection) : base(collection)
{
initialize();
}
#endregion
#region PROPERTIES & FIELDS
private Crud _crud; // Db-Access layer
#endregion
#region EVENTS
#endregion
#region METHODS
private void initialize()
{
_crud = new Crud(Utility.ConnectionName);
}
/// <summary>
/// Lists one-to-many records.
/// </summary>
public Configurations List(ConfigurationSection section)
{
using (DbCommand dbCommand = _crud.Db.GetStoredProcCommand("spa_LIST_MyConfiguration"))
{
_crud.Db.AddInParameter(dbCommand, "#Section", DbType.String, section.ToString());
_crud.List(dbCommand, PopulateFrom);
}
return this;
}
public void PopulateFrom(DataTable table)
{
this.Clear();
foreach (DataRow row in table.Rows)
{
Configuration instance = new Configuration();
instance.PopulateFrom(row);
this.Add(instance);
}
}
#endregion
}
public class Configuration
{
#region CONSTRUCTORS
public Configuration()
{
initialize();
}
#endregion
#region PROPERTIES & FIELDS
private Crud _crud;
public string Section { get; set; }
public string Key { get; set; }
public string Value { get; set; }
#endregion
#region EVENTS
#endregion
#region METHODS
private void initialize()
{
_crud = new Crud(Utility.ConnectionName);
Clear();
}
public void Clear()
{
this.Section = "";
this.Key = "";
this.Value = "";
}
public void PopulateFrom(DataRow row)
{
Clear();
this.Section = row["Section"].ToString();
this.Key = row["Key"].ToString();
this.Value = row["Value"].ToString();
}
#endregion
}
}