appsettings.json in .netCore console application - json

I have an appsettings.json file with the following values
{
"MailOptions":
{
"Username": "ruskin",
"Password": "password"
}
}
When I read it via the ConfigurationBuilder I can only access the values via configuration["MailSettings:Username"]. I want to grab the entire MailOptions string, is there anyway to do that? I don't want to use Json to parse the file etc...I want to stick to configuration builder.
I would expect configuration.GetSection("MailOptions") to work? It simply returns null.
What I have tried
SomeSection aSection = new SomeSection();
ServiceCollection serviceCollection = new ServiceCollection();
serviceCollection.Configure<SomeSection>(options => configuration.GetSection("SomeSection").Bind(aSection));
var someSection = serviceCollection.BuildServiceProvider().GetService<IOptions<SomeSection>>();
// aSection is instantiated but no values in it
// someSection is null
My appsettings.json
{
"SomeSection": {
"UserName": "ruskin",
"Password": "dantra"
}
}
And my POCO class
public class SomeSection
{
public string UserName { get; set; }
public string Password { get; set; }
}

The configuration framework is an abstraction over the underlying source types. So MailOptions:Username could come from JSON, an environment variables or even INI files - and the configuration system can even be configured with multiple sources. If need a JSON string to configure your mail library and want to use the configuration abstraction, I suggest creating a class to hold the settings and serialize it to a JSON string again.
EDIT:
Using configuration.GetSection("SomeSection").Get<SomeSection>() I can successfully get the POCO from the app. see sample application.

Related

How do we parse JSON in Unity3d?

When I try to use JsonUtility to parse the JSON from a REST call returning an array of elements, it fails saying that top level must be an object. C'mon guys. That's ridiculous.
OK, moving on to figuring out how to use Newtonsoft.json because it works well everywhere else.
Tried using JSON .NET for Unity out of the asset store. Seemed like it would work fine and did in the editor, but didn't work (calls to it failed with exceptions) when I tried to use it in a Mac local build on my dev macbook pro. So if it doesn't work on my dev machine and for mac builds, then it's a no go. https://assetstore.unity.com/packages/tools/input-management/json-net-for-unity-11347
Tried using jilleJr's version from here: https://github.com/jilleJr/Newtonsoft.Json-for-Unity but the installation instructions caused the package manager to not be able to open. I get a null reference exception when following the directions to add the package directly into my manifest.json
So what's the secret to making JSON work in Unity 2019/2020 right now? Seems like a huge problem for a platform to have.
Open *YourUnityProject*/Packages/manifest.json and add the following line to the dependencies object.
"com.unity.nuget.newtonsoft-json": "2.0.0",
To serialize and deserialize data use these functions:
using Newtonsoft.Json;
public class Data
{
int[] numbers;
}
string json = JsonConvert.SerializeObject(new Data());
Data data = JsonConvert.DeserializeObject<Data>(json);
I wouldn't say it's a problem with Unity, back when I was trying to read data in from serialised JSON. JsonUtility worked a treat when serialising/deserialising to/from a class. I also preferred it to Newtonsoft.json, mainly because it was part of UnityEngine
For example:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;
public class JSONRW : MonoBehaviour
{
PersonData data;
string jsonPath = "Assets/TestJSON.json";
private void Start()
{
//Read in JSON file
string jsonString = File.ReadAllText(jsonPath);
data = JsonUtility.FromJson<PersonData>(jsonString);
Debug.Log(data.client[0].name); //Outputs A
//Write to JSON file
data.client[0].name = "Luc"; //Changes the name of the entry named A
File.WriteAllText(jsonPath, JsonUtility.ToJson(data)); //Writes updata back to file
}
}
[System.Serializable]
public class Person
{
public string name;
public int age;
public Person(string _name, int _age)
{
name = _name;
age = _age;
}
}
[System.Serializable]
public class PersonData
{
public List<Person> client;
}
JSON file:
{
"client": [
{
"name": "A",
"age": 10
},
{
"name": "B",
"age": 20
},
{
"name": "C",
"age": 30
},
{
"name": "D",
"age": 40
}
]
}

How can I represent a json array in an Environment Variable for aspnet vnext configuration

I have the following section in my appsettings.json file for my aspnet vnext application.
"Settings": {
"IgnoredServices" : ["ignore1", "ignore2"]
}
}
This works quite happily in mapping using IOptions<Settings>, where the settings class is
public class Settings
{
public List<string> IgnoredServices { get; set; }
}
However, I am struggling to override this json file option with an environment variable form. I have tried
Name Settings:IgnoredServices
Value "ignore1", "ignore2"
and
Name Settings:IgnoredServices
Value ["ignore1", "ignore2"]
Neither seem to map correctly and I get the following error message
System.InvalidOperationException: Failed to convert '["ignore1", "ignore2"]'
to type 'System.Collections.Generic.List`1[System.String]
What format should I put my values into environment variables to be successfully interpreted as the correct list of strings?
Try this:
Name Settings:IgnoredServices:0
Value ignore1
Name Settings:IgnoredServices:1
Value ignore2

Strategy for accessing an application-wide setting on the client in a .NET Core web app

We are in the process of re-writing one of our applications using ASP.NET Core. The architecture we're trying for has a Web API running on a different URL from the presentation. The root URL for this API will change in different environments, of course, so I'm trying to figure out how I can set up configuration and access to the Web API root URL in the JavaScript that requires it for retrieving data. For example, say I have an AJAX call to fetch some data from the API:
$.ajax({
dataType: "json",
url: "http://this.url.will.change/api/whatever", //this will change!
success: function(response) {
//load the items
}
});
I've set up appsettings.json files for various build/deploy scenarios and have them reading and injecting nicely, so I can store the URL there.
{
"Data": {
"DefaultConnection": {
"ConnectionString": "whatever"
}
},
"AppSettings": {
"ApiRootUrl": "http://apiroot/api/"
}
}
I considered writing a UrlHelper extension to provide the Web API root, but I don't think there's a way to inject the IOptions object into a static extension method. So, my question is really this: How can I make a configuration setting globally available in my CSHTML and JavaScript?
Update your Startup.cs like below
public class Startup {
public IConfigurationRoot Configuration { get; set; }
public Startup(IHostingEnvironment env, IApplicationEnvironment appEnv) {
IConfigurationBuilder builder = new ConfigurationBuilder()
.SetBasePath(appEnv.ApplicationBasePath)
.AddJsonFile("appsettings.json");
Configuration = builder.Build();
}
public void ConfigureServices(IServiceCollection services) {
services.AddSingleton(_ => Configuration);
}
}
Then on your controller you can inject configuration like this
public class ConfigurationController : Controller {
private readonly IConfigurationRoot config;
public ConfigurationController (IConfigurationRoot config) {
this.config = config;
}
public string Test() {
return config.Get<string>("AppSettings:ApiRootUrl");
}
}
We've used to create a special configuration controller which was responsible for creating a dynamic javascript file from selected configurations settings. You can inject IOptions to the controller. Then from the options you can construct a new custom configuration object which will hold only the properties you want to expose (you probably don't want to expose anything like connection string to your db).
Use a json library (like json.net) to serialize this custom configuration object to a JSON string and create file content out of it like
string fileContent = "var globalConf =" + JsonConvert.SerializeObject(configObject);
Convert the string to array of bytes and return it as FileContentResult.
We were also setting some cache headers so the browser didn't hit the controller each time and used cache.
Of course you need to setup routing o the call to specific URL will hit your controller and return the javascript file you have dynamically created. You can reference it on a website using usual script tag.
As for the server side rendering you can always include IOptions in the model (or create a new model which will wrap both options and the original model)

How to get data from settings json to mvc 6 view?

I want to load all settings key value pair from json file at once and use the settings key value in mvc 6 view page where required.I would be grateful if best solution is provided.I have a scenerio as below
if(Settings.enable_logo_text)
{
<span>Settings.logo_text</span>
}
The official documentation regarding the new configuration and options is quite good, I would recommend having a look there first.
Following the guidance provided there, start by creating a POCO class for your settings:
public class Settings
{
public string logo_text { get; set; }
public bool enable_logo_text { get; set; }
}
Update the ConfigureServices method of your startup class so you read your settings from the configured Configuration and is then available as a service that can be injected wherever you need to:
public void ConfigureServices(IServiceCollection services)
{
...
services.Configure<Settings>(Configuration);
services.AddOptions();
}
If you want to use a the appsettings.json file, make sure you also build your Configuration object including that json file. For example:
public Startup(IHostingEnvironment env)
{
// Set up configuration sources.
var builder = new ConfigurationBuilder()
.AddJsonFile("appsettings.json")
.AddEnvironmentVariables();
Configuration = builder.Build();
}
This way you can configure your values in the appsettings.json file and the values will be set on your Settings class:
{
...
"enable_logo_text": true,
"logo_text": "My Logo Text"
}
Finally, you can access the configured values by adding a IOptions<Settings> dependency. The most straightforward way would be to directly inject the options into the view (as explained in the docs), but you might want to consider injecting the options into the controller and passing them to the view in a more controlled way:
#inject IOptions<Settings> Settings
...
#if(Settings.Value.enable_logo_text)
{
<span>#Settings.Value.logo_text</span>
}

Share Json data between Asp.Net MVC 2 and Asp.Net server side C# code?

I created and love my Asp.Net MVC2 application. It's a very nice DDD app with Domain Model classes, View Model classes, a repository, and Json action methods to expose data.
My coworker wants to share my data with his Asp.Net Forms based C# code. He wants to pull through the Internet a class definition (like a Data Contract), then fill it with my Json results, effectively using something like a remote repository.
Any links or ideas on how to provide him with data contracts and data?
Darin Dimitrov had an excellent idea of consuming JSON data using data contracts here. Just wondering if it's possible to use MVC as the source for these items, then let him create the objects on his side, filled with data from my side.
The key to this question is how to send him my data classes, then send him my data.
class Program
{
[DataContract]
class Person
{
[DataMember(Name = "name")]
public string Name { get; set; }
[DataMember(Name = "surname")]
public string Surname { get; set; }
[DataMember(Name="age")]
public int Age { get; set; }
}
static void Main(string[] args)
{
var json = #"{""name"" : ""michael"", ""surname"" : ""brown"", ""age"" : ""35""}";
var serializer = new DataContractJsonSerializer(typeof(Person));
using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(json)))
{
var person = (Person)serializer.ReadObject(stream);
Console.WriteLine("Name : {0}, Surname : {1}, Age : {2}",
person.Name, person.Surname, person.Age);
}
}
}
Write an OData service. The format is JSON, but the tools to consume it easily -- from many languages -- are already written for you.
The nice thing about this is that your data is now not only consumable by your JS and your friend's ASP.NET app, it's consumable by Excel, PHP, etc.