Add appsettings.json to .NET 6 Console App

 When you start a new .NET 6 Console app, you will have little more than what you see here.  











If one wants to use the json configuration files typically used in a web app, there are a few things we need to add.

(1) Add package references to the following: 
Microsoft.Extensions.Configuration
Microsoft.Extensions.Configuration.Json
Microsoft.Extensions.Configuration.FileExtensions

(2) Right-click on the project, add new item, Json configuration file. Call it "appsettings.json". Then add some settings in the file, eg. 

{

  "TestSettings": {

    "Option1": "some string value",

    "Option2": 42

  }

}

Now just setup your host and builder, read the config file values and use them. In program.cs use something like this

using Microsoft.Extensions.Configuration;

var builder = new ConfigurationBuilder()

    .SetBasePath(Directory.GetCurrentDirectory())

    .AddJsonFile("appsettings.json", optional: false);

IConfiguration config = builder.Build();

var Option1 = config.GetSection("TestSettings:Option1");

string Opt = Option1.Value;


Console.WriteLine($"The answer is {Opt}");



Using powershell to parse web requests


Overview

With powershell, you can make a request to a url, parse the results and submit a form.  Basically, if you can do it in a browser with your mouse and keyboard, you can do it with powershell.  If you find yourself doing having to get data or update something on a website manually on a regular basis, you can automate it via powershell and a windows scheduled task.

Examples

Using COM and Internet Explorer automation
https://westerndevs.com/simple-powershell-automation-browser-based-tasks/

Using Invoke-WebRequest commandlet
https://4sysops.com/archives/powershell-invoke-webrequest-parse-and-scrape-a-web-page/

https://adamtheautomator.com/invoke-webrequest-powershell/


.NET Core Conditional output of appsettings.json for multiple environments

If you only ever deal with one target machine for your app, life is simple.  In the "real world" you often have to deal with multiple environments - local workstation, dev server, qa, production etc.
With the introduction of .net core, the json-based configuration came on the scene.  Now you can separate your environment-specific settings into different files, eg.  appsettings.json, appsettings.Dev.json etc

Ok, great.  So when I publish to a dev server, if I also have 2 other environment config files, they get published into the build directory as well.  I really don't want the settings related to production published on the dev server.  Yes, I could write a powershell script to delete the "extra" files, or just manually delete them.  Surely there had to be a way to do this from either a publish profile, or the csproj file, since both are just msbuild scripts.  After many hours scouring the interweb, I managed to put this section together that deals just with these files.  This goes into the csproj file.  I tried various shenaigans with a publish profile to no avail, all files were published to the destination.

Here goes.  Note the use of <Choose> 
see msbuild reference here


Think of a Switch in C# with case statements.  Only one of the 'When' blocks should get evaluated based on the build config (which you can set in a publish profile, that much at least works).

The end result?  Only the appsettings.json and the desired target-specific json file deployed to the destination.


  <ItemGroup>
    <None Update="appsettings.json">
      <CopyToPublishDirectory>Always</CopyToPublishDirectory>
    </None>
  </ItemGroup>

  <Choose>
    <When Condition="'$(Configuration)' == 'Local' ">
      <ItemGroup>
        <Content Update="appsettings.Local.json">
          <CopyToOutputDirectory>Always</CopyToOutputDirectory>
        </Content>
        <Content Update="appsettings.Dev.json">
          <CopyToOutputDirectory>Never</CopyToOutputDirectory>
        </Content>
        <Content Update="appsettings.Release.json">
          <CopyToOutputDirectory>Never</CopyToOutputDirectory>
        </Content>
      </ItemGroup>
    </When>
    <When Condition="'$(Configuration)' == 'Dev'">
      <ItemGroup>
        <Content Update="appsettings.Local.json">
          <CopyToOutputDirectory>Never</CopyToOutputDirectory>
        </Content>
        <Content Update="appsettings.Dev.json">
          <CopyToOutputDirectory>Always</CopyToOutputDirectory>
        </Content>
        <Content Update="appsettings.Release.json">
          <CopyToOutputDirectory>Never</CopyToOutputDirectory>
        </Content>
      </ItemGroup>
    </When>
    <When Condition="'$(Configuration)' == 'Release'">
      <ItemGroup>
        <Content Update="appsettings.Local.json">
          <CopyToOutputDirectory>Never</CopyToOutputDirectory>
        </Content>
        <Content Update="appsettings.Dev.json">
          <CopyToOutputDirectory>Never</CopyToOutputDirectory>
        </Content>
        <Content Update="appsettings.Release.json">
          <CopyToOutputDirectory>Always</CopyToOutputDirectory>
        </Content>
      </ItemGroup>
    </When>
  </Choose>

Coming up to speed with Entity Framework Core 2.x



Having used Entity Framework since 4.x, I have seen plenty of examples of what works and what doesn't regarding this library.  One of the things that has been a big headache is using the EDMX designer.  This is primarily related to using source control.  This part of EF will lead to scenarios where code can not be merged easily back into a main branch.  Since this was on an existing project, it couldn't be done away with immediately due to time constraints. 

Looks like I'm not the only one, judging from the comments on this article.
https://forums.theregister.co.uk/forum/1/2014/10/23/entity_framework_goes_codefirst_only_as_microsoft_shutters_yet_another_visual_modelling_tool/


[ update 4/10/2019 ]
The solution for dealing with the EDMX designer, was to use an extension called "Reverse POCO Generator"
https://marketplace.visualstudio.com/items?itemName=SimonHughes.EntityFrameworkReversePOCOGenerator


This extension lets you have a code-first, EDMX-free approach with an existing database. See the docs at the link for more info.  I've been using it well over a year now.  However, its unnecessary for EF Core now.

There are plenty of examples out there about using the Dotnet CLI for EF Core, but here is just an example for the command you will need to get familiar with.

dotnet ef dbcontext scaffold "Server=MyDbInstance;Database=MyDbName;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer -c MyDbContextName -d -f -o Entities

Notice that this is using a trusted connection, as opposed to your actual application context might use either sql auth or windows auth with the app pool running as a domain account(preferred).  The "workflow" will involve using this command after updating your database schema.  Contrast this with EF 6.x and the Reverse POCO generator, which will require you to "touch" a TT(T4 Template) file to initiate a rebuild of the db model.







Angular vocabulary

If you're still not on the bandwagon for using Angular yet, the learning curve can be steep.  One of the things that comes with any new framework is the vocabulary involved.  So here is a list of the terms you will need to get familiar with.  One of the go-to resources to start is angular.io

Component
Module
Service
Template 
Route








Why I prefer entity framework to stored procedures



Why Entity Framework (and ORM in general) instead of stored procedures? Below is a an article that pretty well sums up my thoughts on this matter as well.  Believe it or not, the debate over the use of an ORM with respect to data access for an application still comes up.


https://kevinlawry.wordpress.com/2012/08/07/why-i-avoid-stored-procedures-and-you-should-too/

 To summarize my points:
(1) This is the big one - compile time checking.  If your underlying schema changes (e.g. rename a column), and you missed one of the stored procedures that use it, the error will be evident only when hitting that code at run-time.  If instead, you used an ORM like Entity Framework, this will be caught at compile-time.
(2) There is still a place for stored procedures, but the vast majority of your data access code will likely be get-something(s) and sort it.  Its frustrating to maintain dozens of stored procedures that do little other than fetch a list of customers.
(3) Looping.  TSQL is optimized to operate on sets of data.  Yes, you can write a while loop in TSQL, but wouldn't you rather do this with C#?  It's more often the case, that something done in TSQL can just as easily be done with LINQ and EF, and usually cleaner.

There are more, those are probably the big three.

With regards to Entity Framework, there are generally 2 approaches - code first and database first.  Each has its merit, but if you use any kind of source control (and if you're not shame on you), then the database first approach presents a problem with what's known as concurrent development. What this means is that you branch your code and start making changes, and something requires a change in the main branch, merging the EDMX file will often result in conflicts.  These days, I prefer the code first approach, but with an existing database, preferring to design the schema myself so as to control the data types and FK relations myself.  To do this, I now use extensions such as the Reverse POCO generator.  This lets me do concurrent development, while letting me build my own schema. The flow mor eor less goes like this:
- Make SQL changes
- Reverse the EF model changes via the POCO tool
- Code against the updated EF model




Is the .NET Core pie fully baked yet?

Overview of .NET Core vs .NET Framework
I must admit, I have not thought too highly of the whole .NET core effort that has been going on the last 2 years or so.  When Microsoft changes its technology stack, its often a big bucket of Legos dumped on you all at once.  However, this time it was even more confusing because there was more than one bucket! That said, I have had the view that this was the direction things were headed for a while, regardless of Microsoft's claim that they will continue to develop both the framework and .net core stacks. Its hard to imagine them eventually not developing things to the point they are one set of API's, which isn't the case now. That might mean yet another name change...

Where are we now?
As it stands, you can still develop a new application with MVC5 or use MVC6 (ASP.NET core) with the full framework, or use the .NET core libraries.  Confused yet?  Then there is .NET Standard.  Uh oh. I'm not the only one. However, things seem to be settling down now, and at least for new applications, ASP.NET Core might just make sense.  If for no other reason, than the new project structure which makes using something like Angular and associated NPM libraries much easier.
 
Where is this headed?
Good question.  Even though Microsoft claims they will continue to develop the full framework AND .net core, its likely that the focus will be on the .net core stack.  Just a guess.

When to choose one over the other. link



Add appsettings.json to .NET 6 Console App

  When you start a new .NET 6 Console app, you will have little more than what you see here.   If one wants to use the json configuration fi...