How to generate the appsettings.<EnvironmentName>.json file? - c#

I have an ASP.NET Core 2 WebAPI which will be deployed across the following environments:
INT, QA, STAGE, PRODUCTION environments.
Based on the above, I need to have appsettings.<EnvironmentName>.json file for each environment. From the link : https://learn.microsoft.com/en-us/aspnet/core/fundamentals/environments?view=aspnetcore-2.1, I see that
In case of local development environment, the Environment Variable called ASPNETCORE_ENVIRONMENT is set to Development. In case of the deployment where ASPNETCORE_ENVIRONMENT is not set, the default is Production
I would like to know what are the steps required to take care while preparing the appsettings.<EnvironmentName>.json file for INT, QA and STAGE environment. Do I need to set the environment explicitly for each environment web server:
set ASPNETCORE_ENVIRONMENT=Development.
Can anyone help me to by providing their guidance?

I might be missing something, but this seems pretty straight-forward. To create the environment-specific setting files, you literally just create them in your project, i.e. create a new file called appsettings.Foo.json in the root of your project. Visual Studio will automatically put it under appsettings.json as a parent in the Solution Explorer.
On the server, yes, you'd need to set the environment you want to run under to ASPNETCORE_ENVIRONMENT. If it's supposed to use appsettings.QA.json, then set it to QA. That's all there is to it.

You will have to set the ASPNETCORE_ENVIRONMENT on the server with the configuration you wish to host the app.
Take a look at the sample project provided by Microsoft on Github
Sample Environment project

First, in Visual Studio you will have to right click your project name and add a new item.
Inside 'Add new Item' window chose 'Scripts' on the left column, and look for JavaScript JSON Configuration File template.
Name it as appsettings.Production.json, for example, and click 'Add'.
It's going to connect automatically to appsettings.json.
To set which environment your application runs on, just set up the
ASPNETCORE_ENVIRONMENT environment variable.
Set the variable through the command prompt by typing set
ASPNETCORE_ENVIRONMENT=Production in Windows or export
ASPNET_CORE_ENVIRONMENT=Production in Linux.

Related

How to determine which environment asp.net core app will run in?

The documentation states that If ASPNETCORE_ENVIRONMENT isn't set, it defaults to Production.
My machine doesn't seem to have ASPNETCORE_ENVIRONMENT environment variable set at all, as evidenced by running:
c:\>set ASPNETCORE_ENVIRONMENT
Environment variable ASPNETCORE_ENVIRONMENT not defined
So theoretically, my project (brand new from Visual Studio template), should run in Production, but...
c:\dotnet run
Hosting environment: Development
What am I missing?
This is because the dotnet run command uses the the launchsetting.json file.
You can execute the command with --no-launch-profile option so that run command does not load the launch settings file and thereby the environment variables.
If you want to use launchsetting file and sepcific profile setting from that file, then create one and use switch --launch-profile <NAME>
Hope this helps. Refer documentation for command line switches usage.

What files are published when using Click Once deployment?

When I click "Publish" in my project properties, what files are actually getting published? I spent some time yesterday searching MSDN, but didn't find a clear answer.
I assumed (perhaps incorrectly) that it was publishing the latest version in source control, so I always made sure I had my changes checked in before clicking "Publish". But now I'm highly suspicious, based on a bug that was reported, that it has been publishing the Debug configuration on my laptop. I have code that should only execute in debug mode (#if DEBUG...), and it seems to be executing that code in production.
This is my first WinForms application and first time using ClickOnce deployment. Any guidance would be greatly appreciated.
What code is getting published? Latest in source control, most
recent build on build server or from local machine?
What settings do I need to set (and where are they) to ensure that my
application is published using the Release configuration?
TIA
UPDATE(S):
Here is what I see on the Publish tab
Does the Build tab come into play at all?
The Configuration setting on the Build tab is what matters when Publishing, correct? Not the selection in the toolbar?
For ASP.NET applications, when you go to publish, there will be a configuration option under settings:
The code you have locally is what gets compiled and published through Click Once. For non ASP.NET applications, the build configuration selected in visual studio is what ultimately gets published.
For this specific case, you have "Define DEBUG constant checked". That will cause the code marked as #DEBUG to be executed. It doesn't matter what the build configuration is if that is checked.
I tried on some settings on my project.
1) Select Configuration Manager by right clicking on your Solution.
2) When i clicked publish, here is what i get in output window
3) If you want to control what files (dependencies) are included as part of deployment, this can be controlled from Application Files button on the publish tab of project properties.
Here is an image.
Hope that helps.

Deploying C# Console App - How do I update ENV PATH via the "Publish Now" settings?

Here's the thing. I have built a console app in .NET (C#). It works good and all is well. It's an internal tool for folks on our network, but could be used anywhere in the world (larger company). I thought I'd be able to use the simple install /deploy Wizard that comes with MS VisualStudio 2013 to generate a nice little installer. I got it set up and it works nice.
HOWEVER, once the app is installed on a target machine I want it to be usable from anywhere on the command line. Either I need to update PATH variables or have the app installed in a PATH location. The latter seems dangerous to do (putting something in SYSTEM and such), so I am wondering:
How can I get the simple Microsoft deploy wizard to update the appropriate path on the target machine while the app is being installed? I don't want to have to write some installer. I was hoping there would be some basic deployment options that let me do some custom things like this without hassle...
what am I missing? help? thanks...
Just to follow up, to answer my question--- I had to create a custom install step that would update the PATH environment variable to make the computer see my new console app from any CMD window. This meant doing 2 steps:
Reading the current Path (without expanding the variables in each string) as follows:
string RegKeyName = #"SYSTEM\CurrentControlSet\Control\Session Manager\Environment";
string pathvariable = (string)Microsoft.Win32.Registry.LocalMachine.OpenSubKey(RegKeyName).GetValue
("Path", "", Microsoft.Win32.RegistryValueOptions.DoNotExpandEnvironmentNames);
I then split the pathvariable by semicolons and loaded it into an allpaths array variable (ignoring empty entries). Then, I iterated through allpaths in a foreach loop and rebuilt the master path, plus set a boolean to tell me if the directory I wanted to add was already in the path . Then, once I was done that, I did the following:
if (NeedtoUpdate)
{
Environment.SetEnvironmentVariable("Path", MasterPath + MyNewPathEntry + ";", EnvironmentVariableTarget.Machine);
}
That was how the custom install step worked for me.

Unable to create new build configuration

Here's an annoying one.
I have a solution in Visual Studio 2012 that contains a .Net 4.5 class library, a .NET 4.5 web application and a .NET 4.5 website.
I want to create a new build configuration, let's call it Publish or Live, mainly so that I can select it when publishing the web application and use a web.config transform.
So I click my Solution, go to Build then Configuration Manager. In the configuration dropdown, I choose , and I get the little popup asking me for the name of the new configuration etc. I fill this in, click OK, and......nothing. Nada.
No matter what I call the new configuration, whether I choose to copy from an existing configuration etc, no new configuration is created. Am I missing something blindingly obvious?
Thanks,
Matt
I had the same issue, but when I deselected 'create new project configurations', I was able to create a new solution configuration.
I recently had the same problem. I figured out that VS 2019 doesn't like it to have projects grouped in an project folder (virtual folder) which is named the same way as the project is. Or where the "virtual" folder name has the same name as an actual project
Example:
(virtual) project folder name: CompanyName.Webservice
Content: CompanyName.Webservice (from CompanyName.Webservice.csproj)
In that case I couldn't neither add or rename project configurations nor execute transformation of web.config files of that project
Hope that helps someone after so many years...
If you cannot find solution configuration settings on the Standard toolbar or cannot access the Configuration Manager, you may have Visual Basic developer settings applied. For more information, see How to: Manage Build Configurations with Visual Basic Developer Settings Applied.
Link : http://msdn.microsoft.com/en-us/library/kkz9kefa.aspx
Solution :
Link : http://msdn.microsoft.com/en-us/library/ms165414.aspx

Automated Deployment using CI server

In our project, deployment is always a pain, mostly because of the mistakes done by the release management team. Either they screw up the configuration or get the wrong version installed somehow. We use teamcity as our CI server, and it produces the artifacts as zip files(dll's and exe) which is usually passed on to the release team. My question is, is there a way to automate the whole deployment process?
Is there a commercial tool, which supports this?
We will want to do the following:
Update the config files with environment specific values.
Install windows services to the server.
Upload the UI(WPF) bundle to the centralized location(which is pulled down by another application, sort of a launcher).
Change the DB connection strings.
Do all the above for various environments(like int,uat and prod)
DB deployment since is a separate beast as such, need not be covered in this.
Any best practices, tools or solutions will be highly helpful.
Thanks,
-Mike
I have used TeamCity for some fairly large projects and I have automated every aspect of deployments apart from the database. The main steps I use for each project are:
Get a TeamCity agent installed on the production server
Have the build get everything out of source control (you do have everything in source control right?).
Have a build step that builds and publishes your solution. This can be achieved by adding the following command line argument to your MSBuild call:
/p:Configuration=[Your Config];DeployOnBuild=True;PackageAsSingleFile=False
Your published files (and tranformed config files) will be written to the following directory:
[Your Project Directory]\obj\[Your Config]\Package\PackageTmp
Using a scripting language (in my case Powershell) to copy the published artifacts to your deployment directory and make environment specific changes you mentioned. E.g. extracting archives, copying files, starting/stopping websites etc..
Run any automated testing (e.g. nUnit, Selenium etc...)
I find the best strategy is to have a .Net post-build event that invokes an appropriate powershell script passing in relevant details like the solution path and configuration name (alternatively, I have also had TeamCity pass the environment name to the Powershell script) so that it knows what it needs to do (e.g. Staging, Production etc...). You should find that a scripting language like Powershell can do everything that a person can do (and about 100x faster and 100% reliably).
There is so much content on Powershell out there that you can just google anything you need to do in Powershell and you will get an example. E.g. "powershell deploy WPF", "powershell upload FTP" etc...
In a previous job I needed to deploy windows services remotely and I found that with enough research, I was able to get the MSI for the service to uninstall the existing service and install the new one completely silently (i.e. no dialogs). This will help a lot in your quest for automation. I can elaborate on this if you would like.
Below is an example of a Powershell post build script I generally use:
Note how I use some default parameter values so that I can execute the script directly from my Powershell editor to simulate and test different configurations on my local machine.
param(
[string]$configurationName="Debug",
[string]$sourceDirectory="C:\SVN\<Your local solution location>")
Set-StrictMode -v latest
$ErrorActionPreference = "Stop"
# Load required functions
$private:scriptFolder = & { (Split-Path $MyInvocation.ScriptName -Parent) }
. (Join-Path $scriptFolder DebugBuild.ps1)
. (Join-Path $scriptFolder StagingBuild.ps1)
. (Join-Path $scriptFolder ProductionBuild.ps1)
. (Join-Path $scriptFolder CommonBuildFunctions.ps1)
#Execute appropriate build
switch ($configurationName) {
"Debug" { RunDebugBuild $sourceDirectory }
"Staging" { RunStagingBuild $sourceDirectory }
"Production" { RunReleaseBuild $sourceDirectory }
}
To execute a publish on development machines, I setup a VS publish profile for the solution that is committed to SVN so the other developers can use it. This profile publishes directly to the local deployment directory.
We use TeamCity for our deployments in addition to CI and it works really well. Here are a couple things that may help:
If you're using VS2010, check out the SlowCheetah plugin. It can do the config file transforms to do what you need to replace DB connection strings and other environmental-sensitive variables. These transforms happen automatically when you build based on the selected build configuration.
Check out MSDeploy. While it gets most of it's attention for deploying web applications, it can do a lot of other things, like installing windows services and syncing files to a destination directory. While most people install it as an IIS add-in, it can be installed as a separate service that has no dependencies on IIS.
If you're not using VS2010 (or don't want to use SlowCheetah), here's how we you could handle the config settings:
Create an app config for each different environment (I'm assuming you
have a build configuration set up for each environment). Add the
configuration name to the end of the config file, so in Prod we have
App.config.Prod and QA we have App.config.QA.
Put your complete configuration for each environment in it's respective config file for
that environment.
As part of your build (we use the "BeforeBuild" target in the project file), use msbuild to copy the environmentally specific app.config over the actual one. Here's a custom msbuild target we use to do this:
<PropertyGroup>
<EnvironmentAppConfig>App.config.$(Configuration)</EnvironmentAppConfig>
</PropertyGroup>
<Target Name="ReplaceAppConfig">
<Message Condition="Exists('$(ProjectDir)$(EnvironmentAppConfig)')"
Text="Copying $(EnvironmentAppConfig) -> App.config" Importance="high" />
<Message Condition="!Exists('$(ProjectDir)$(EnvironmentAppConfig)')"
Text="No $(EnvironmentAppConfig) found. Leaving App.config as is." Importance="high" />
<Copy SourceFiles="$(ProjectDir)$(EnvironmentAppConfig)"
DestinationFiles="$(ProjectDir)App.config"
Condition="Exists('$(ProjectDir)$(EnvironmentAppConfig)')" />
</Target>
Let me know if you need any other details.
Teamcity + Octopus deploy
Octopus for windows service automated deploys
Our release team uses Anthill Pro - this also has ability to do CI, but they just use it to deploy packages (in our case mostly web site code).
The cool thing about Anthill is the whole client(agent)-server setup, so it traverses firewalls, NAT etc with some effort. And it has approval and scheduling workflow.
As far as configs, this is a different beast - unfortunately both devs and release team have to change these, and somehow merge the result. Consider that you want to add new config key, but release team has to add production settings for DB connection. The trick is that devs are not supposed to know production DB connection string.
So this is not automated (in our case anyways).
I'm partial to TeamCity, which is a Jetbrains product, the company that makes the essential ReSharper (no, I don't work for them, drat the luck). TeamCity, at least last time I checked, is a free product for up to 20 users and 20 build configurations. It has some nice auto-build and blame features. Excellent, really.
You mention a Commercial tool...
TFS, or specifically Team Build, completely supports building the code and deploying it. Whenever we build a web app, it auto deploys to our Dev and QA servers. After deployment we have it run through a suite of web tests to ensure everything is functional. Then the real fun begins with our QA team ;)
Although we don't auto deploy to production, we could certainly do that as well.

Categories