Adding AppSettings.json Configuration to a .NET Core Console Application

This post will walk you through the steps necessary to add a strongly typed appsettings.json configuration file to your console application. I’ll dispense with the formalities of writing a detailed introduction on why you would be interested in doing this and jump right into the steps involved.

Note: This post assumes .NET Core 2.1, but I believe any 2.x version will work.

1. Add the following NuGet packages to your console application:

2. Right-click your console application, and select “Unload project“. Once the project has been unloaded, right click the project and select “Edit <your_console_project_name>.csproj“.

3. Add the following just below the <TargetFramework> element:
<UserSecretsId>93d033dc-12eb-446a-91a6-efec88dfb437</UserSecretsId>
(note: you should replace this guid with your own)

4. Add the following to a <ItemGroup> with other CliToolReference elements, or add your own:

5. Right-click your console application and select the “Reload project” option.

6. Open the developer command prompt and navigate to the directory with your console application, then run:

Note: This will create a secrets.json file located at: %APPDATA%\Microsoft\UserSecrets\<SecretId_From_Step_3>\secrets.json
Edit the newly created file and change the contents to:

7. Create a new JSON configuration file for your console application and name it appsettings.json. Set the following to the contents of the file to the JSON below. Important: Be sure to right-click this file and select properties. Change the “Copy to Output Directory” option to “Copy if newer”.

8. Create a class named MySettingsConfig:

9. Add the following code to your Main routine inside Program.cs

If your console shows your settings correctly, congratulations! If you’re missing the AccountName and ConnectionString settings, be sure you followed the step to “Copy to Output Directory” listed in step 7.

 

NDC Minnesota 2018 Recap

NDC Minnesota is the inaugural NDC Conference event for the United States. I’ve long followed the event online as they post most of their conference sessions on Vimeo. The event was held in the very well appointed St. Paul RiverCentre in downtown St. Paul, MN. Absolutely no complaints about the venue, the event itself, or any of the speaker presentations. I honestly was expecting a number of hang-ups since the first year for a conference is usually a learning experience but it feels as though the NDC team is really on top of everything given their past events at other locations.

Sessions & Speakers

I attended a number of really great sessions. Some of my favorites were Steve Sanderson talking about Blazor, the new experimental WebAssembly transpiler, Scott Allen discussing his opinionated approach to .NET Core development, and Nik Molnar talking about progressive web apps (PWAs).

On top of my favorites there were other really wonderful sessions on AWS Lambda, Azure Functions, React + TypeScript, Docker, Azure Data Lake, and Webpack. All of the speakers were well prepared, well rehearsed, and there were no technical issues in any of the talks I attended. It was a great way to process a lot of information in a very short period of time.

Final Thoughts

I always leave a developer conference feeling inspired. NDC Minnesota was no different. During the sessions I’m usually furiously pounding notes away on OneNote and I have a laundry list of topics I’d like to spend more time learning in the near future. Most of my current weaknesses are on the client, centered around TypeScript, Unit Testing, and React. I’d really like to spend more time on those technologies in the near future and NDC Minnesota provided a lot of really great material to help point me in the right direction to improve those before the year is out.

 

Setting Up A React & Web API Development Environment in Visual Studio 2017

Front-end frameworks like React, Angular, and Vue are making big waves in software development. Microsoft makes great tooling for working with JS frameworks like those in the form of Visual Studio Code. There is also a large trove of information and tutorials getting setup inside the VS Code environment. One specific resource I really appreciated was Cory House’s Pluralsight course on setting up a JS development environment.

Unfortunately, at least in my experience, there isn’t much available out there on how to setup a React dev environment using Visual Studio 2017, for those of us who wish to use only a single editor to maintain our .NET applications. My hope is, that the rest of this guide will serve as a useful resource for anyone else who is facing this same impediment to getting started and will end up saving them time.

Some pre-requisites before we get started:

Disabling Package Restore in Visual Studio

Visual Studio tries to take care of a number of things for you when dealing with npm pacakges. Some people prefer this, other’s don’t. I fall into the latter camp. It took me a bit of headache to figure this out, but by default, when you save a packages.config file, Visual Studio attempts to run ‘npm update’ for you automatically when you save the file or open the solution. So, if you are trying to run the command yourself after updating packages.config, then you are going to run into file locks with the /node_modules/ folder.

Thankfully Visual Studio offers you a way to disable the automatic updates when saving packages.config. Navigate to Tools > Options, then to Projects and Solutions > Web Package Management > Package Restore and set the following settings for NPM (below). What this does is prevents npm from being executed every time you open a project, or run a command line ‘npm update’/’npm install’. You can leave these on if you wish, but for me I found the experience better by being able to execute the npm command line syntax myself.

Setting Up The Application

Instead of walking you through line by line of each step you need to follow, please download the sample application from Github. There are a few important areas that I think are worth mentioning.

  • If you changed the package restore settings above, you’ll want to run “npm install” inside each project after cloning.
  • The ‘Empty’ solution assumes the webpack-dev-server for hosting, so when you run ‘npm start’, webpack will host a simple webserver at the port listed in webpack.config.js.
  • The ‘MVC’ solution assumes it will be hosted by IIS Express or the built in webserver. The ‘npm start’ command on this application will actively watch for JS file changes and rebundle them for you. No need to recompile to see your changes unless you something managed by .net.
  • This approach does leverage Babel as the transpiler. If you would like to use TypeScript, you could do that as well.
  • The webpack configuration assumes that the application start/root is /ClientApp/index.js.
  • The webpack configuration also assumes that everything is written to the /wwwroot/ folder as is convention with ASP.net Core projects in Visual Studio 2017.

I hope you find this post useful. It took me a bit of searching to figure some of this out since most tutorials focus on Visual Studio Code. Feel free to reach me on twitter if you have questions about any of this. Happy programming.

 

Generate Test Data With Faker.js

Here is a common scenario for you. You’re building an application… any application. It could be your side project, a sales tool, an ecommerce site, a REST api, a video game, a reporting dashboard. Anything. You’re building your app, and you reach a point that you’d like to try it out, to see how it would look to a user. How do you simulate a production scenario with no data to test with? If you’re lucky, you have data from an existing customer you can use, or there is a sample dataset available online. If you’re unlucky, you’re left generating dummy data using garbage inputs (random strings, random numbers, etc) – data that passes the regex, but doesn’t provide a good simulation.

Do you wish there was a library that allowed you to programatically generate test data? Enter Faker.js. Faker.js allows you to generate a variety of data types in an intelligent and structured way. You can generate: Addresses, Products (Ecommerce), Companies, Dates, Images, URLs, and random objects as well (numbers, strings, words, uuid, etc). Click here to see a demo.

If you’d like to consume data from faker in another programming language, such as c#, you could use their hosted microservice at http://faker.hook.io (i.e. http://faker.hook.io?property=name.findName&locale=de). A second option would be Bogus, a port of Faker for .net. There are ports available for other languages as well and the API surface is roughly the same in each instance.

I setup a very simple Github repo that demonstrates how to use Faker in a variety of scenarios to help you accomplish your goals. Hopefully you find this utility as useful as I do for prototyping new functionality before it goes into production.

 

Switching from Mac to PC for .NET Development

Just like hammers, drills, and screwdrivers are the tools of the modern tradesman, so to is the computer the trade tool of the modern software engineer. How it is constructed and how well it performs determines how well you can accomplish the tasks you set out to complete.

With this notion in mind, it was time for me to sell my 2014 MacBook Pro 15. It was a great machine from a performance standpoint. It had a wonderful display, fantastic keyboard to type on for long sessions, and a trackpad that could beat any others in the year I bought it.

So why sell the laptop? Well, frankly, because it’s hard to be a .NET developer on MacOS. Sure, there are great IDEs like Visual Studio Code, but that pales in comparison to the feature offering of a full fledged Visual Studio IDE when working with a large solution compromised of multiple projects. What about Visual Studio for Mac you ask? Also wonderful if you’re primarily working on Xamarin apps. They’ve made fantastic strides with it, but support is behind for several features not directly benefiting Xamarin, such as TypeScript. Honestly, I don’t mind the idea using a cloud Mac provider like Macincloud.com to handle my Xamarin builds remotely as there is nice support for this now. The final nail in the coffin is Parallels. Yes, it works, but it’s expensive (including recurring fees), it’s clunky, and it’s not nearly as performant as a native OS. Throw in applications like Docker and you have strange Inception level virtualization issues to wrestle with.

So, where does that leave us? In the past, this may have been difficult to swallow, because one reason so many developers love their Macbook is because it runs a variation of unix, and subsequently has great capabilities beyond the wonderful UI it offers. A .NET developer looking to verify their apps run cross-platform could have considered this, but thankfully, today we have Linux subsystem for Windows. I just installed Ubuntu… from the Microsoft Store… crazy!

Ultimately, after a lot of research, I settled on the Lenovo X1 Carbon (5th Gen). It is a fantastic laptop, and “everything works” despite my belief that was only possible on a Mac. I went with the 16GB model, 512GB of storage, and the WQHD display. It’s got great battery life (I spent about 5 or 6 hours on it with pretty heavy load tweaking settings, installing all my applications, and it lasted on battery only no problem).

Some additional features of the laptop I plan to leverage but haven’t yet, are the fact this unit has 4 PCIe lanes, so an external GPU such as the Gigabyte Aorus GTX 1070 will allow me in the future to have the dream setup: one single machine for both work and play. I looked at other models like the Dell XPS 15 but this had some shortcomings like the webcam position (I do video calls for work sometimes) and also I didn’t want the 4K display to avoid some high dpi compatibility issues and battery drain. Another positive, on modern laptops in general, is the fact that USB-C charging is nearly ubiquitous and getting my laptop charged is now less of a concern than before with the proprietary Macbook charging adapter.

Also, if I ever decide to convert this into a Linux laptop, it’s good to know that this model has good support already for it and all of the hardware should be compatible for me. It will allow the laptop to last quite a long time if necessary.

All in all, I’m really, really happy with this laptop. And the best part about it: Windows has come a long way and is actually pretty nice to use. More applications run on it, it has the Linux subsystem support, and it’s improving constantly with the “Creator” updates they are releasing.

 

My Favorite Visual Studio Shortcuts and Tips

Hey everyone – I’ve been maintaining a list of little shortcuts to save me time and ease my development efforts and figured they would be worth sharing here. If you have any you would like to share here, please email me and I’ll include them as well.

Visual Studio Keyboard Shortcuts

  • Ctrl+. opens up the ‘Smart Tag’. Use it when you see the red squiggle line to add a missing reference, or implement an interface.
  • Ctrl+K,C will comment either the current line, or any block of code you have highlighted.
  • Ctrl+K,U will uncomment either the current line, or any block of code you have highlighted.
  • Ctrl+, opens smart search to quickly find and jump to a class or method name.
  • Ctrl+I allows you to do an inline search (basically search quickly without dialog box)
  • Shift+Alt+Enter for enter and leave full screen mode.
  • Ctrl+- moves cursor to last known position (helpful to navigate back, Ctrl+Shift+- is forward)

Visual Studio Features

  • Snippets, like ‘prop‘ will inject a property into your code, or ‘foreach‘
  • Custom snippets, click here for a starter list and how-to.
  • Right-click file in Solution Explorer, select Source Control > Annotate. This shows all history of the file and who checked in what line of code.
  • Use ‘Package Manager Console’ to install Nuget packages (Alt+T,N,O). (ex: PM> Install-Package Newtonsoft.Json)
  • Tell debugger to ‘break’ when an exception is thrown even if no breakpoint exists (Ctrl+Alt+E, then check Thrown on CLR).
  • From Visual Studio Command prompt, use this command to get a list of all checked out files (and to who): tf status /collection:http://my-tfs-server:8080/tfs/MyCollection $/pathto/mytfsproject /user:* /recursive
 

Techniques For Improving Website Performance

Annotated below is a presentation from Nik Molnar, co-founder of the open source debugging and diagnostics tool Glimpse, who demonstrates several different strategies for improving the performance of your web application. This is easily one of the most useful conference presentations I have ever seen and I wanted to share it with everyone. If were curious about how to do any of the following tasks, this presentation will cover those for you. Next to each point is a bookmark for you to jump to that portion of the presentation.

  • Using browser tools to analyze usable content and latency for each request [13:00]
  • How to use HAR files for analyzing performance metrics [14:30]
  • Using the ‘Audits’ tab in Chrome to make recommendations [15:40]
  • Adding Google PageSpeed to the browser tools and how to use it [16:45]
  • Specifying in the web.config how to use compression for static and dynamic files. [17:50]
  • How to enable client side caching with the expires header [19:00]
  • How to use bundling in ASP.NET to bundle and minify CSS and JS files. [19:35]
  • How to use Web Essentials Visual Studio plugin to easily do image sprites [20:40]
  • Using TinyPNG.com to optimize PNG images with lossy compression [22:00]
  • Using Web Essentials to embed small images as base64 encoded text in CSS [24:22]
  • Using async script attribute and img lazyload attribute to lazy load resources [26:19]
  • Pre-caching client data using dns-prefetch, prefetch, and prerender HTML tags [28:30]
  • Using the RedGate CPU profiler to identify bottleneck code (note: Visual Studio has a simpler built in feature) [35:00]
  • High level thoughts on how to improve server side performance [35:55]
  • Using browser tools like Octane to profile Javascript CPU performance [38:30]
  • High level thoughts on how to improve javascript performance [42:25]
  • Understanding frame rates and the concept of jank [44:05]

Resources:
Link to the video in it’s entirety
Link to baseball demo site used in presentation

 

ThatConference 2014

For the past three years, a group of very smart and very generous people, have hosted a wonderful summer camp themed conference in Wisconsin titled ‘That Conference’.   It’s hosted at a giant indoor/outdoor waterpark and convention center, Kalahari Resorts.  The number and quality of the sessions is impressive, and may shock you a bit when you consider the entire ticket cost is currently under $400.

Most of the presentations I attended were put on by Microsoft MVPs, people who are recognized by Microsoft as leaders in the community and have demonstrated a strong ability to teach and inform others about the technology stack.

Each day starts off with a keynote.  Day 1 was Elizabeth Naramore,  who artfully spoke about how destructive FUD (fear, uncertainty, and doubt) can be.  Day 2 was Tim Huckaby, a long time Microsoft collaborator  turned entrepreneur and founder of Interknowlogy, who spoke on the importance of design.  Day 3 was Mike Mcgee, who is the co-founder of Starter League, a rapid learning school hosted in Chicago.  Mike gave us his inspiring story of how he took risks, turned down offers, and maintained a focus on his business until it reached success.

Some of the favorite talks I participated in were:

SDK for your API by Wade Wegner

Understanding OWIN by Keith Dahlby (author of Posh Git)

RavenDB for the .NET Developer by Judah Himango

ORMs – You’re doing it wrong by Jimmy Bogard (founder of Automapper)

Building a Flexible Client API Library by Darrel Miller

Full Stack Web Performance by Nik Molnar (co-founder of Glimpse)

In addition to all the wonderful technical presentations, there were great opportunities to meet other like minded individuals.  There was a meet & greet for early check-in attendees, a happy hour with great food the first night, a full pig roast the second, and plenty of chances to interact and reflect on the final day.

Generous sponsors brought technology for everyone to experiment with.  Omni Resources brought an Oculus DK2 which I thought was amazing, Skyline Technologies made a flappy bird clone that utilized the Kinect to wave your arms to move, another company brought Google Glasses for people to try.   All the sponsors were developer focused, knowledgeable, and polite to the “campers”.

ThatConference will be 8/10/15 to 8/12/15 next year and I already have it noted on my calendar.

 

Future of Technology

The number of technologies in development, that are real and not science fiction, is astounding. These are technological advances are that are just over the horizon and are simply a matter of time to come to market at a reasonable cost for all of us.

Do you remember what life was like before GPS, cell phones, personal computers, the internet? Sure, life was good, and we all got by just fine, but these advances all make life so much more enjoyable and interactive for all of us lucky enough to inhabit it.

I believe will permeate all our lives within the next 10 years, and these are just a few of many:

– Wearable devices (watches, glasses)
– Bitcoin
– Virtual Reality (Oculus VR)
– Self driving cars
– Gene therapy
– 3d Printing
– Stem cell technology (new organs, disease treatment)
– Mind controlled prosthetics
– Electric cars
– Artificial intelligence / Learning systems

It’s a great time to be alive as a technology enthusiast. The future is bright, and I’m glad to be a part of it.

 

Create a push notification system with SignalR and Toastr

Do you have events in your application that you would like to trigger a notification to other users? How about if a user places an order on a website and you want the website administrator to see a notification, or a sale on Apple products is initiated and you want to notify customers?

Note: If you wish to download the code to follow along instead of going step by step, you may download it on Github here.

SignalR is a library for .NET that enables real-time communication. It does this via web-sockets, which is typically available in modern browsers, but also degrades gradually to other methods that are supported by the older browsers. You just need to worry about the SignalR framework not the underlying architecture. Toastr is javascript framework for non-blocking notifications. With just a few lines of code you can get a nice popup system in place.

Let’s walk through the steps, it’s not too difficult.

1. Create a new MVC project in your favorite language, I’ll be using C#. I disable user authentication and name it ‘SignalrToastr’ but you can name it whatever you would like.

2. Open ‘package manager console’ for your application, and install the SignalR package.

3. Create a class file named ‘Startup.cs’ and place it in the root of your application. Give the following contents to your new file. This file is an Owin startup file, which is outside the scope of this discussion, but is worth noting as Owin will become a larger part of ASP.NET vNext. It is a middleware framework that resides outside of IIS. Microsoft also uses Owin for the ‘Individual Accounts’ user manager, so if you left user authentication enabled in step #1, you can simply add the ‘MapSignalR’ line below to the Startup.cs class it created for you.

using Microsoft.Owin;
using Owin;

[assembly: OwinStartup(typeof(SignalrToastr.Startup))]
namespace SignalrToastr
{
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            // Any connection or hub wire up and configuration should go here
            app.MapSignalR();
        }
    }
}

4. Create a folder called ‘Hubs’ and add a file named ‘ContactHub.cs’. Enter the following contents into the file.

using Microsoft.AspNet.SignalR;

namespace SignalrToastr.Hubs
{
    public class ContactHub : Hub
    {
        public void ContactFormSubmitted(string name, string message)
        {
            // Calls the 'notifyUsers' method on the client side.
            //  Note:  You can change 'All' to target only certain clients.
            //  Note:  Code after 'All' is dynamic, and you can specify whatever name you wish.
            Clients.All.notifyUsers(name);
        }
    }
}

SignalR uses ‘Hub’ objects to communicate between the client and the server. We will go over more on what is actually happening here in a later step. For now, you should note that ‘ContactFormSubmitted’ is a method being called on the server, from the client. The client passes this server method two parameters, name and message. This server side method then notifies ‘All’ clients to execute a JS method named ‘notifyUsers’ which takes one parameter, name. Outside the scope of this tutorial is how you can narrow down which clients you want to send the message to.

5. Modify the ASP.NET templated view that comes installed ‘~/Views/Home/Contact.cshtml’ and replace it’s contents entirely with the following:


<form class="form-horizontal">
    <fieldset>

        <!-- Form Name -->
        <legend>Contact</legend>

        <!-- Text input-->
        <div class="control-group">
            <label class="control-label" for="txtName">Name</label>
            <div class="controls">
                <input id="txtName" name="txtName" type="text" class="input-medium">

            </div>
        </div>

        <!-- Textarea -->
        <div class="control-group">
            <label class="control-label" for="txtComments">Comments</label>
            <div class="controls">
                <textarea id="txtComments" name="txtComments"></textarea>
            </div>
        </div>

        <!-- Button -->
        <div class="control-group">
            <label class="control-label" for="btnSubmit"></label>
            <div class="controls">
                <button id="btnSubmit" name="btnSubmit" class="btn btn-primary">Submit</button>
            </div>
        </div>

    </fieldset>
</form>


@section scripts
{
    <script src="~/Scripts/jquery.signalR-2.0.3.js"></script>
    <script src="~/signalr/hubs"></script>    
    <script type="text/javascript">
        $(function() {
            var contact = $.connection.contactHub;

            // Callbacks to the client should be defined here.
            contact.client.notifyUsers = function (name) {
                
            };

            $.connection.hub.start().done(function() {
                // Calls to server should be included within the hub.start() method.
                $('#btnSubmit').click(function() {
                    // Call the ContactFormSubmitted method on the hub.
                    contact.server.contactFormSubmitted($('#txtName').val(), $('#txtComments').val());
                    // Clear text boxes and reset focus for next comment.
                    $('#txtName').val('');
                    $('#txtComments').val('');
                    return false;  // prevent 'form' from submitting.
                });
            });
        });
    </script>
}

This creates a simple two field bootstrap form, and also adds our required JS includes to make SignalR work (jquery.signalR-*, and ~/signalr/hubs). It also creates a placeholder for our client callback notifyUsers, and also adds an event handler for our contactFormSubmitted method to push to the server. If you build your solution at this point and open your browser to your projects location for /signalr/hubs/ (i.e. http://localhost:62279/signalr/hubs/) you’ll see some generated JS markup that SignalR created based on your hub. Note how it lower cases your hub name, and methods. This is what the SignalR framework is creating for you automatically based on your Hub classes.

        proxies.contactHub = this.createHubProxy('contactHub'); 
        proxies.contactHub.client = { };
        proxies.contactHub.server = {
            contactFormSubmitted: function (name, message) {
                return proxies.contactHub.invoke.apply(proxies.contactHub, $.merge(["ContactFormSubmitted"], $.makeArray(arguments)));
             }
        };

6. Repeat step #2, but install the Toastr framework.

7. Add the toastr.css file to either the top of Contact.cshtml or to your Layout.cshtml file:

<link href="~/Content/toastr.css" rel="stylesheet" />

8. Modify your scripts section of Contact.cshtml to look as follows. Note how we have added a reference to taostr.js and also placed the toastr.info call inside our notifyUsers callback method.

 <script src="~/Scripts/toastr.js"></script>
    <script src="~/Scripts/jquery.signalR-2.0.3.js"></script>
    <script src="~/signalr/hubs"></script>    

    <script type="text/javascript">
        $(function() {
            var contact = $.connection.contactHub;

            // Callbacks to the client should be defined here.
            contact.client.notifyUsers = function (name) {
                toastr.info('New contact form submitted by ' + name);
            };

            $.connection.hub.start().done(function() {
                // Calls to server should be included within the hub.start() method.
                $('#btnSubmit').click(function() {
                    // Call the ContactFormSubmitted method on the hub.
                    contact.server.contactFormSubmitted($('#txtName').val(), $('#txtComments').val());
                    // Clear text boxes and reset focus for next comment.
                    $('#txtName').val('');
                    $('#txtComments').val('');
                    return false;  // prevent 'form' from submitting.
                });
            });
        });
    </script>

9. You are done at this point, so let’s try it out. Open two different browsers side-by-side, I’ll be using Chrome and Firefox. This is done to show you how the server is making a callback to ‘All’ clients as shown in step #4. You can narrow this down in the future if you want, to only administrative users for example. If all goes well, you should be able to fill the form out in one browser, and see the popup in both.

toast-notification