How does .Net 6 determine it Enviroment - console-application

I've created a .Net 6.0 Console application. I need it to be able to migrate the database using the Entity Framework. Now when I run it, it says it's environment is 'Production'. Where is that configured?
Here's the startup code for the application.
static void Main(string[] args)
{
using IHost host = Host.CreateDefaultBuilder(args)
.UseSerilog((context, loggerConfiguration) => loggerConfiguration
.ReadFrom.Configuration(context.Configuration)
.WriteTo.Console())
.ConfigureServices((context, services) =>
{
services.RegisterCoreServices(context.Configuration);
})
.Build();
CallBatch(host.Services, args);
host.RunAsync();
}

Production is the default.
Check out Use multiple environments in ASP.NET Core
Environments
To determine the runtime environment, ASP.NET Core reads from the following environment variables:
DOTNET_ENVIRONMENT
ASPNETCORE_ENVIRONMENT when the WebApplication.CreateBuilder method is called. The default ASP.NET Core web app templates call WebApplication.CreateBuilder. The ASPNETCORE_ENVIRONMENT value overrides DOTNET_ENVIRONMENT.
IHostEnvironment.EnvironmentName can be set to any value, but the following values are provided by the framework:
Development: The launchSettings.json file sets ASPNETCORE_ENVIRONMENT to Development on the local machine.
Staging
Production: The default if DOTNET_ENVIRONMENT and ASPNETCORE_ENVIRONMENT have not been set.

Related

AWS hosted .Net Core 2.0 website won't start when using anything but default app.UseStaticFiles()

So I've been trying to serve images from my Uploads directory from the root level of my AWS hosting using the below static files config in my .Net Core 2.1 app. It works locally but when I deploy to AWS it won't even start the application with the error below.
app.UseStaticFiles();
app.UseStaticFiles(new StaticFileOptions
{
FileProvider = new PhysicalFileProvider(Path.Combine(env.ContentRootPath, "Uploads")),
RequestPath = new PathString("/Uploads")
});
The AWS error is just the critical crash on startup below:
An error occurred while starting the application.
.NET Core 4.6.26814.03 X64 v4.0.0.0 | Microsoft.AspNetCore.Hosting version 2.1.1-rtm-30846 | Microsoft Windows 6.1.7601 S | Need help?
In case anyone else finds this it seems that AWS doesn't allow files below the root level of deployed websites. To get around the startup crash I've just settled for the default below despite it being a bit of a security issue.
app.UseStaticFiles();

Disabling development environment in .NET Core 2.0 app in AWS

I have a .NET Core MVC app that I deployed to AWS ElasticBeanstalk. But when i go to the app i get an error with message:
Development environment should not be enabled in deployed applications
In launchsettings.json file i have set ASPNETCORE_ENVIRONMENT's
value to Production.
When i deploy app using Visual Studio (AWS toolkit) i set Project
build configuration's value to Release.
I have also created environment variable with name
ASPNETCORE_ENVIRONMENT and value Production in EB Software Configuration.
But I am still getting the same error, any idea what would be the fix ?
My launchSettings.json file looks like this:
{
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://DUMMY.us-west-2.elasticbeanstalk.com/",
"sslPort": 0
}
},
"profiles": {
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"launchUrl": "http://DUMMY.us-west-2.elasticbeanstalk.com/",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"AlacsWeb": {
"commandName": "Project",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
},
"applicationUrl": "http://DUMMY.us-west-2.elasticbeanstalk.com/"
}
}
}
And startup.cs file:
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
// Add application services.
services.AddTransient<IEmailSender, EmailSender>();
services.AddMvc();
// Add http context
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseBrowserLink();
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();
app.UseAuthentication();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
}
Thanks for posting your code. I'm answering here because there's more to say than the comment form will allow.
TLDR
Your environment variables are ignored in EBS because your startup isn't picking them up.
I don't know what influence launchSettings.json has in EBS but given that the environment variables in that file are ignored I suspect the answer is none whatsoever.
You can save environment variables in EBS.
launchSettings.json
I don't use these myself, so what follows is research and trivial testing.
This MS article claims that this file only kicks in for running in Visual Studio
When using Visual Studio, environment variables may be set in the launchSettings.json file.
However I know from a simple test that these are also picked up by dotnet run in the project directory. Also, I know that VS Code ignores it in favour of .vscode/launch.json.
What I do not know is whether IIS pays any attention to it. (IIS in an EBS instance I mean, as opposed to IIS Express on your dev box).
Environment variables
I think I can see why environment variables are being ignored.
Startup.cs has an alternative constructor which lets you build the configuration object from environment variables, configuration files, and so on. It accepts an IHostingEnvironment instance.
public class Startup
{
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.AddEnvironmentVariables(); // <--- This picks up env variables
Configuration = builder.Build();
}
public IConfigurationRoot Configuration { get; }
// etc ....
}
EB environment variables
As I explained in a comment, EB + dotnet core 2 are in a right mess over environment variables. Our solution is not to parse the infernal file per my earlier answer but to Dockerise our dotnet apps.
That said, you can save environment variables in EB. As you say, Software Configuration is the correct place to enter them. Then, click on your environment (the green/grey/whatever card as it appears in EB), go to the Actions menu, and Save Configuration.
launchsettings.json is visual studio build specific. It doesn't impact deployment.
Following question has provided some insight on the issue
AWS Elastic Beanstalk environment variables in ASP.NET Core 1.0
a crazy solution:
replace:
if (env.IsDevelopment())
{
app.UseBrowserLink();
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
to
app.UseBrowserLink();
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();

Yii2 HTTP session on build server

I'm attempting to get our PHPunit tests to run on our build server (Windows jenkins server).
They run on my local Ubuntu 16.04 system correctly, but when I get over to the windows build server I'm having some weird session issues.
I have a light wrapper around the Yii2 Session class that we use so that if we change frameworks I only need to update the session calls in one place.
Here's that class:
<?php
use \yii\web\Session AS Session;
class SessionHelper {
public static function get($key, $defaultValue = null) {
$yiiSession = new Session();
return $yiiSession->get($key, $defaultValue);
}
public static function set($key, $data) {
$yiiSession = new Session();
return $yiiSession->set($key, $data);
}
} //EOF
I'm using this SessionHelper for all things session in my app and inside my Test classes.
The issue i'm running into is this: when I call SessionHelper::set('something', 'something'); from my test case it will correctly set the property into the session. However, the very next time I call SessionHelper::set('something-different', 'something-different'); it loses all previous session data and only has this new session field.
Is this due to the generation of a "new Session();" in each get/set request? I checked and the session settings are identical between servers and the session_id() is the same all of the time.

Neo4jServer in Neo4jConfiguration - 4.1.0?

I've been using the latest code in 4.1.0-BUILD-SNAPSHOT as I need some of the new bug fixes in the 4.1 branch and just noticed that "neo4jServer()" is no longer a method exposed by Neo4jConfiguration. What is the new way to initialize a server connection and an in-memory version for unit tests? Before I was using "RemoteServer" and "InProcessServer", respectively.
Please note, the official documentation will be updated shortly.
In the meantime:
What's changed
SDN 4.1 uses the new Neo4j OGM 2.0 libraries. OGM 2.0 introduces API changes, largely due to the addition of support for Embedded as well as Remote Neo4j. Consequently, connection to a production database is now accomplished using an appropriate Driver, rather than using the RemoteServer or the InProcessServer which are deprecated.
For testing, we recommend using the EmbeddedDriver. It is still possible to create an in-memory test server, but that is not covered in this answer.
Available Drivers
The following Driver implementations are currently provided
http : org.neo4j.drivers.http.driver.HttpDriver
embedded : org.neo4j.drivers.embedded.driver.EmbeddedDriver
A driver implementation for the Bolt protocol (Neo4j 3.0) will be available soon.
Configuring a driver
There are two ways to configure a driver - using a properties file or via Java configuration. Variations on these themes exist (particularly for passing credentials), but for now the following should get you going:
Configuring the Http Driver
The Http Driver connects to and communicates with a Neo4j server over Http. An Http Driver must be used if your application is running in client-server mode. Please note the Http Driver will attempt to connect to a server running in a separate process. It can't be used for spinning up an in-process server.
Properties file configuration:
The advantage of using a properties file is that it requires no changes to your Spring configuration.
Create a file called ogm.properties somewhere on your classpath. It should contain the following entries:
driver=org.neo4j.ogm.drivers.http.driver.HttpDriver
URI=http://user:password#localhost:7474
Java configuration:
The simplest way to configure the Driver is to create a Configuration bean and pass it as the first argument to the SessionFactory constructor in your Spring configuration:
import org.neo4j.ogm.config.Configuration;
...
#Bean
public Configuration getConfiguration() {
Configuration config = new Configuration();
config
.driverConfiguration()
.setDriverClassName
("org.neo4j.ogm.drivers.http.driver.HttpDriver")
.setURI("http://user:password#localhost:7474");
return config;
}
#Bean
public SessionFactory getSessionFactory() {
return new SessionFactory(getConfiguration(), <packages> );
}
Configuring the Embedded Driver
The Embedded Driver connects directly to the Neo4j database engine. There is no server involved, therefore no network overhead between your application code and the database. You should use the Embedded driver if you don't want to use a client-server model, or if your application is running as a Neo4j Unmanaged Extension.
You can specify a permanent data store location to provide durability of your data after your application shuts down, or you can use an impermanent data store, which will only exist while your application is running (ideal for testing).
Create a file called ogm.properties somewhere on your classpath. It should contain the following entries:
Properties file configuration (permanent data store)
driver=org.neo4j.ogm.drivers.embedded.driver.EmbeddedDriver
URI=file:///var/tmp/graph.db
Properties file configuration (impermanent data store)
driver=org.neo4j.ogm.drivers.embedded.driver.EmbeddedDriver
To use an impermanent data store, simply omit the URI property.
Java Configuration
The same technique is used for configuring the Embedded driver as for the Http Driver. Set up a Configuration bean and pass it as the first argument to the SessionFactory constructor:
import org.neo4j.ogm.config.Configuration;
...
#Bean
public Configuration getConfiguration() {
Configuration config = new Configuration();
config
.driverConfiguration()
.setDriverClassName
("org.neo4j.ogm.drivers.embedded.driver.EmbeddedDriver")
.setURI("file:///var/tmp/graph.db");
return config;
}
#Bean
public SessionFactory getSessionFactory() {
return new SessionFactory(getConfiguration(), <packages> );
}
If you want to use an impermanent data store (e.g. for testing) do not set the URI attribute on the Configuration:
#Bean
public Configuration getConfiguration() {
Configuration config = new Configuration();
config
.driverConfiguration()
.setDriverClassName
("org.neo4j.ogm.drivers.embedded.driver.EmbeddedDriver")
return config;
}

embedded zookeeper for unit/integration test

Is there an embedded zookeeper so that we could use it in unit testing? It can be shipped with the test and run out of the box. Maybe we could mock some service and register to the embedded zookeeper
The Curator framework has TestingServer and TestingCluster classes (see https://github.com/Netflix/curator/wiki/Utilities) that are in a separate maven artifact (curator-test - see the Maven/Artifacts section of https://github.com/Netflix/curator/wiki).
They're pretty self explanatory, or you can download the curator code base and see how they're used internally in their own test cases.
We've used both successfully within unit tests at $DAY_JOB.
You could use Apache Curator Utilities provided in-process ZooKeeper server TestingServer that can be used for testing.
With maven you can dependency as follows
<dependency>
<groupId>org.apache.curator</groupId>
<artifactId>curator-test</artifactId>
<version>3.2.1</version>
</dependency>
And you can create in process zookeeper server as folows
TestingServer zkServer;
#Before
public void setUp() throws Exception
{
zkServer = new TestingServer(2181, true);
}
#After
public void tearDown() throws Exception
{
zkServer.stop();
}
For testing Cluster use can use TestingCluster, which creates an internally running ensemble of ZooKeeper servers
You could use the zookeeper-maven-plugin, which is documented here.
The zookeeper project produces a "fat-jar" that it uses itself for system test.
There is a written up README, showing how easy it is to launch, but unfortunately it is not being made as an artifact, so cannot be linked to maven.