How do I set Properties for Seq in my appsettings.json file? - .net-core

In my seq logs there are no properties set and I couldn't find a way to set them via appsettings.json. I could set them with the method
.Enrich.WithProperty("App", "Absence Service")
but for dotnet core dependency injection I would prefer it to be set in the appsettings.json where it look like this:
"Seq": {
"ServerUrl": "xxxx",
"ApiKey": "xxxx",
"MinimumLevel": "Warning",
"LevelOverride": {
"Microsoft": "Error"
}
}
How do I set properties like for example the app or environment inside the appsettings.json?

Related

How can I view .net core 2 sites served from vs code from a remote machine?

I'm playing with vs code and a new asp.net core 2 webapi project.
When I debug it or run it without debugging I can access the site from the same machine using http://localhost:5000 but I can't work out (and haven't found anything for the new .net core 2 way of doing things) to allow me to change the listening url to something like http://0.0.0.0:5000 or even http://*:5000 so I can access the dev site from another machine on the network to test with IE (it's running on a Mac).
I have found plenty of examples for .net core <2 that show editing the Program.cs file and adding a host config but that file has changed now (simplified) and I can't find or work out a way to apply the same changes to the new layout.
As well as other questions and solutions like this that modify a hosting.json or project.json which both appear from my reasearch to have been removed or more replaced with the .csproj file. And again I have been unable to work out or find information on how to implement the same changes in the new .csproj file.
So could someone please point me in the right direction. I expected changing the host/listening url to be a LOT easier than this so I'm sure I am missing something obvious.
Here is my program.cs class in .NET Core 2.0 :
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
namespace MyNamespace
{
public class Program
{
public static void Main(string[] args)
{
BuildWebHost(args).Run();
}
public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.UseUrls("http://*:5000")
.Build();
}
}
Note the .UseUrls("http://*:5000") that accept any incoming requests from port 5000. This is only used when you publish your application (right click on the projet, publish...).
When you run your application from VS 2017 (for exemple), VS takes the settings under Properties/launchSettings.json. You can edit this file anytime.
Hope this will help someone else because I wasted too much time on this!
Update:
I have just come across the Environment variables which seem a FAR better place to set this, also this is how I would have done it in VS 2017.
In JetBrains Rider they are under the build configs (Run dropdown then Edit Configurations...).
Under this window you can edit your build configurations. Find the one you use (I only have one currently but you might have a dev, staging etc...) and then find the Environment variables: (green) and click the button on the right (blue).
In the new window you can change the ASPNETCORE_URLS to what ever you require. For me I set it to http://*:5000 which causes it to pick up any incoming requests. For example localhost:5000 or 192.168.0.10:5000. I then pointed my dev.somedomain.com to 192.168.0.10:5000 and I can use https though NGINX to test on my dev site running on my Mac.
This also allows for easily changing it on a PC my PC basis by not checking in the JetBrains Rider settings.
Original Answer:
I have finally found the answer to this and #M├ętoule was right in the comment. I just didn't understand what it meant until now.
Basically the changes in the Program.cs in ASP.NET CORE 2.0 is just a way to hide away the stuff that will always be the same.
Instead of calling all these (like you needed to in Core 1):
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseIISIntegration()
.UseStartup<Startup>()
.UseApplicationInsights()
.Build();
You're just calling the ones you're likely to want to change:
.UseStartup<Startup>()
.Build();
SO you can still add UseUrls() as before just put it before the .Build();` like this:
.UseStartup<Startup>()
.UseUrls("http://192.168.2.10:5000")
.Build();
SO to change the Url of a brand new ASP.NET CORE 2 project I changed the Program class in the Program.cs file from:
public class Program
{
public static void Main(string[] args)
{
BuildWebHost(args).Run();
}
public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.Build();
}
To:
public class Program
{
public static void Main(string[] args)
{
BuildWebHost(args).Run();
}
public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.UseUrls("http://192.168.2.22:5000")
.Build();
}
Only adding the 3rd from last line: .UseUrls("http://192.168.2.22:5000")
As long as there are no firewalls in the way I can now access the above url from another machine on the network and see my dev site! :D
This may be a bit late to the conversation, but if you are still trying to get this to work with VS Code, you are able to set ENVIRONMENT variables directly in your VS Code launch.json.
{
// Use IntelliSense to find out which attributes exist for C# debugging
// Use hover for the description of the existing attributes
// For further information visit https://github.com/OmniSharp/omnisharp-vscode/blob/master/debugger-launchjson.md
"version": "0.2.0",
"configurations": [
{
"name": ".NET Core Launch (web)",
"type": "coreclr",
"request": "launch",
"preLaunchTask": "build",
// If you have changed target frameworks, make sure to update the program path.
"program": "${workspaceFolder}/bin/Debug/netcoreapp2.0/vscode-env.dll",
"args": [],
"cwd": "${workspaceFolder}",
"stopAtEntry": false,
"internalConsoleOptions": "openOnSessionStart",
"launchBrowser": {
"enabled": true,
"args": "${auto-detect-url}",
"windows": {
"command": "cmd.exe",
"args": "/C start ${auto-detect-url}"
},
"osx": {
"command": "open"
},
"linux": {
"command": "xdg-open"
}
},
"env": {
"ASPNETCORE_ENVIRONMENT": "Development",
"ASPNETCORE_URLS": "http://*:5000"
},
"sourceFileMap": {
"/Views": "${workspaceFolder}/Views"
}
},
{
"name": ".NET Core Attach",
"type": "coreclr",
"request": "attach",
"processId": "${command:pickProcess}"
}
]
}

Sharing configuration properties between spock and ratpack?

I'm using serverConfig to load properties at runtime into my ratpack app.
ratpack {
serverConfig {
// Load the environment and system properties
env()
sysProps()
require("/search", SearchConfig)
}
where SearchConfig is
class SearchConfig {
String limit
}
and the config file is like so
{
"search": {
"limit" : 100
}
}
For a more complete example, see http://kyleboon.org/blog/2016/01/10/layering-ratpack-configuration/ ).
Basically what I'm doing is passing in a gradle project property to define which JSON file holds the configuration I want, then parsing that JSON file into a hierarchical set of properties (the example above would be something like search.limit).
Is there a way to mimic that in spock?

Using appsettings.json to configure Kestrel listen port Dotnet core 2 preview 2

From what I understand the correct way of setting listen ports for ASP Dotnet Core 2 preview 1/2 is by creating a Kestrel section in the appsettings.json in the following format:
"Kestrel": {
"EndPoints": { //Could also be Endpoints, it's a bit unclear
"Http": {
"Address": "127.0.0.1",
"Port": 9001 //the port you want Kestrel to run on
},
I have tried to set up the sample webapp on a Debian machine, but when I start the app, it writes out that the app is listing on port 5000, the default port..
I know that the appsettings.json is read, because when I change the logging level to Trace, I get more info upon startup, including that no Endpoints are found and the app will use the standard 5000 port.
I have tried to search the aspnet source code on Github, and I can find a area where the Kestrel section is read from configuration (https://github.com/aspnet/Identity/blob/e38759b8a2de1b7a4a1c19462e40214b43c1cf3b/samples/IdentityOIDCWebApplicationSample/MetaPackage/KestrelServerOptionsSetup.cs), but as you can see it looks like a sample project.
What am I missing, isn't this the standard way to configure Kestrel in ASP Dotnet core 2?
Support for Kestrel configuration via appsettings.json has been dropped in 2.0.
See this issue comment:
kestrel config file support was cut from 2.0.0. Config values need to be read manually in your initialization code.
To get around this, you can do something like this in program.cs:
public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup < Startup > ()
.UseKestrel((hostingContext, options) =>
{
if (hostingContext.HostingEnvironment.IsDevelopment) {
options.Listen(IPAddress.Loopback, 9001);
options.Listen(IPAddress.Loopback, 9002, listenOptions => {
listenOptions.UseHttps("certificate.pfx", "password");
});
}
})
.Build();
As mentioned in a comment on the accepted answer, 2.1 has support for appsettings.json, see https://blogs.msdn.microsoft.com/webdev/2018/02/02/asp-net-core-2-1-roadmap/#security
A working appsettings.json:
"Kestrel": {
"EndPoints": {
"Http": {
"Url": "http://localhost:5555"
}}}
This is for a Program.cs using (created by "dotnet new webapi"):
WebHost.CreateDefaultBuilder(args)
Relevant source code in github https://github.com/aspnet/MetaPackages/blob/master/src/Microsoft.AspNetCore/WebHost.cs#L163
options.Configure(builderContext.Configuration.GetSection("Kestrel"));
and https://github.com/aspnet/MetaPackages/blob/master/src/Microsoft.AspNetCore/WebHost.cs#L169
config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
I am use Program.cs and hosting.json file to config Kestrel. Example:
var config = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("hosting.json", optional: true, reloadOnChange: true)
.Build();
var host = new WebHostBuilder()
.UseConfiguration(config)
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseStartup<Startup>();
hosting.json:
{
"urls": "http://localhost:4444;http://localhost:4445;"
}
This is exapmle for the latest version dotnet core.
For earlier versions:
hosting.json:
{
"server.urls": "http://localhost:4444;http://localhost:4445;"
}
I know that this is an old post but to run visual studio with kestrel.
just edit the appsettings.json and add the config like this (tested with NetCore 2.0 and 2.1)
"profiles" : {
"Kestrel": {
"commandName": "Project",
"launchBrowser": true,
"applicationUrl": "http://localhost:6969/"
}
}
I had the same issue whereby my Kestrel configuration in appsettings.json is not being picked up. From this article about migrating from asp.net core 2.0 to 2.1, I updated the bootstraping code to become like the below, and it worked for me.
public static void Main(string[] args)
{
CreateWebHostBuilder(args).Build().Run();
}
public static IWebHostBuilder CreateWebHostBuilder(string[] args)
{
return WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>();
}

How to generate application version using Spring Boot, Gradle, Semantic Versioning and Jenkins

I have a Spring Boot web application with actuator enabled. When I open <app_url>/info, I see below
{
"git": {
"commit": {
"time": "2016-08-31T17:53:28.000+0000",
"id": "0a52a2f"
},
"branch": "master"
},
"build": {
"version": "unspecified",
"artifact": "my-app",
"name": "my-app",
"group": "",
"time": "2016-09-02T21:09:42.000+0000"
}
}
I'm not sure how to generate a version number here. I want to use Semantic Versioning MAJOR.MINOR.PATCH+timestamp+Build_Number
What is the general consensus w.r.t storing build information of a package ? I don't want to store it in application.yml because it is managed by Puppet and is external to the application war. I would like it to be generated by Jenkins into some file and Spring Boot can pick it up from that file. Should I let Jenkins write into build-info.properties that is generated by spring-boot-gradle-plugin buildInfo ? or should the version be generated by Gradle itself when it generates the file? How does Gradle know MAJOR.MINOR.PATCH details ? I'm running out of ideas on how to integrate all these together.
A little late, but this is how I am doing it (seems to work).
springBoot {
buildInfo {
additionalProperties = [
"version" : System.properties["version"] != null ? System.properties["version"] : "unspecified"
]
}
}
and then in my Jenkins Pipeline
./gradlew clean build -Dversion=${MAJOR}.${MINOR}.${PATCH}
The output jar then will have a build-info.properties
build.version=1.0.1

Debugging xUnit tests in .NET Core and Visual Studio Code

I'm on a Mac, running .NET Core 1.0 and Visual Studio Code.
I have a console project and a test project. I have setup launch.json so that I can debug the console project.
How do I set up a launch configuration that launches my unit tests and attaches the debugger?
See Tyler Long's answer. The steps below are not required in the newest versions of Visual Studio Code :)
I made a repository to demonstrate.
First off, the only way I could get the debugger to hit the test was to add a file, Program.cs, take control of the entry point from xUnit, and manually add code to test. It's not ideal, but I imagine you aren't going to be doing this very often, and it's easy to flip it back to normal.
Program.cs:
using System;
namespace XUnitDebugging
{
public class Program
{
public static void Main(string[] args)
{
var test = new TestClass();
test.PassingTest();
Console.WriteLine("Enter text...");
Console.ReadLine();
}
}
}
Next, in project.json add the following:
"buildOptions": {
"emitEntryPoint": true,
"debugType": "portable"
},
project.json:
{
"version": "1.0.0-*",
"testRunner": "xunit",
"buildOptions": {
"emitEntryPoint": true,
"debugType": "portable"
},
"dependencies": {
"Microsoft.NETCore.App": {
"type": "platform",
"version": "1.0.0"
},
"xunit": "2.2.0-beta2-build3300",
"dotnet-test-xunit": "2.2.0-preview2-build1029"
},
"frameworks": {
"netcoreapp1.0": {
"dependencies": {
"Microsoft.NETCore.App": {
"type": "platform",
"version": "1.0.0"
}
}
}
}
}
This will allow you to debug an xUnit unit test project.
If you install the latest software and library, it is super easy to debug:
As you can see from the screenshot, just click "debug test" and debug it!
I was able to run the debugger on an entire xUnit project with the following complicated launch config. I inspected the calls the "debug test" link (in #Tyler Long response above) was making through the C# (Omnisharp) VS Code extension to figure this out. Things to note: 1) you must provide the absolute path to the dotnet program 2) you must provide the absolute path (i.e. you cannot use ~/ or $HOME/) to .nuget/packages folders 3) in the example below, the name of my test project namespace is Tests. Once you have this launch config in place, you can place breakpoints(s), launch the debugger using this config and it should hit all the breakpoints.
{
"name": "Debug xunit tests",
"type": "coreclr",
"request": "launch",
"preLaunchTask": "build",
"program": "/usr/local/share/dotnet/dotnet",
"args": [
"exec",
"--runtimeconfig",
"${workspaceRoot}/AppNameHere/bin/Debug/netcoreapp1.0/AppNameHere.runtimeconfig.json",
"--depsfile",
"${workspaceRoot}/AppNameHere/bin/Debug/netcoreapp1.0/AppNameHere.deps.json",
"--additionalprobingpath",
"/Users/jdoe/.nuget/packages",
"/Users/jdoe/.nuget/packages/dotnet-test-xunit/1.0.0-rc2-build10015/lib/netcoreapp1.0/dotnet-test-xunit.dll",
"${workspaceRoot}/AppNameHere/bin/Debug/netcoreapp1.0/AppNameHere.dll",
"-namespace",
"Tests"
],
"cwd": "${workspaceRoot}",
"stopAtEntry": false
}
Tyler's answer of clicking the debug test code lens icons is the easiest way of debugging a single test.
A way of testing all unit tests would be to add while(!Debugger.IsAttached) Thread.Sleep(500); inside the tests. This will make the tests wait until you attach a debugger.
using System;
using System.Diagnostics;
using System.Threading;
using NUnit.Framework;
namespace SomeNamespace
{
[TestFixture]
public class SomeClassTests
{
[Test]
public void ShouldDoTest()
{
while(!Debugger.IsAttached) Thread.Sleep(500);
Assert.That(true, Is.True);
}
[Test]
public void ShouldDoTest2()
{
while(!Debugger.IsAttached) Thread.Sleep(500);
Assert.That(true, Is.True);
}
}
}
This then allows you to attach the Visual Studio Code debugger to the running testhost.dll. Simple select .NET Core Attach and then the dotnet testhost.dll.

Resources