Application Types

Application Types Header Image

Today’s header image was created by Tim Gouw, the original source for the image is available here

Seeing as this is my final post before the holidays

You say that like you’ve written loads of posts, Jamie.

… wait, 12 published posts (including the one by Zac from The Reactionary) in just over 2 months?

I thought that I’d take the chance to talk about the different types of applications that you can build with .NET Core and why you might use them. This is not going to be a deep dive into each of these types of applications, but more of a generic look at each one with links to posts that I’ve already written, where applicable.

.NET Core allows you to build and deploy many different types of applications, amongst them are:

Each of those list items is a clickable link, which will take you directly to the relevant section of this article.

Let’s look at each of these in turn.

Class Library

A Class Library is a collection of related and reused methods and properties. They are frequently found in .dll files (if you’re running Windows) or in .so, .a or .la files (if you’re running Linux or a Unix-like operating system).

Although, if you’re clever enough, you can package them in any way that you want.

These can contain helper or extension methods, or common classes and are frequently shipped as part of a bigger application.

.NET Framework and DirectX are two examples. But OpenGL and Vulkan are other examples. Pretty much any application that you’ve ever used has had class libraries hanging off of it.

Creating a Class library

I’ve already written tutorial on how to create a Class Library.

Here is a link to that article.

You can go there to learn a little more about how to create a Class Library if you want. I’m going to go into a little more detail here about why you might create one, which is something I didn’t cover in that post.

Where You Might Use One

So you’ve built your application, and it runs fantastically. But when you start to code review it, you realise that you could refactor that one massive .cs file and separate things out.

Let’s say that you have a single program.cs, and this file contains ALL of your logic.

I’m not saying that this is a bad thing (TM)… but it is.

Here’s an extremely trivial example:

using System;
namespace ConsoleApplication
{
public class Program
{
public static void Main(string[] args)
{
var filePath = GenerateAReportAndReturnFilePath(Math.PI, Math.E);
// do something with the file path
}
public static double CalculateSomeStuff(double inVarOne,
double inVarTwo)
{
return inVarOne *= Math.Pow(inVarTwo, 2);
}
public static bool CheckSomeFileSystemThing(string filePath)
{
return File.Exists(filePath);
}
public static string GenerateAReportAndReturnFilePath(double inVarOne,
double inVarTwo)
{
// do some file generation
var generatedFileName = $"Financials Report - {DateTime.Now.ToString("dd-MM-yyyy")}.pdf";
var totalValue = CalculateSomeStuff(inVarOne,inVarTwo);
if(CheckSomeFileSystemThing(generatedFileName)
{
return Path.Combine(directoryFileIsIn, fileName);
}
}
}
}

I told you it was a trivial example.

If we ended up needing to generate that same report in a bunch of different places, then we’d have to either do some clever calling of the GenerateAReportAndReturnFilePath method

And if we’re not calling it from the within program.cs itself, it get’s hard to manage.

Or we’d have to copy-paste the code into all of the files where we want to call it, and this can lead to spaghetti code.

So why not take everything but the Main method and place it in a library? Something like this would do it:

using System;
namespace Reporting
{
public static class FinancialsGenerator
{
private static double CalculateSomeStuff(double inVarOne,
double inVarTwo)
{
return inVarOne *= Math.Pow(inVarTwo, 2);
}
private static bool CheckSomeFileSystemThing(string filePath)
{
return File.Exists(filePath);
}
public static string GenerateAReportAndReturnFilePath(double inVarOne,
double inVarTwo)
{
// do some file generation
var generatedFileName = $"Financials Report - {DateTime.Now.ToString("dd-MM-yyyy")}.pdf";
var totalValue = CalculateSomeStuff(inVarOne,inVarTwo);
if(CheckSomeFileSystemThing(generatedFileName)
{
return Path.Combine(directoryFileIsIn, fileName);
}
}
}
}

Here I’ve extracted all of our logic for report generation into a single static class. I’ve also made the supporting methods private (I’ve assumed that a consumer of this class library wouldn’t want to access those methods).

And here is how we might consume it.

using Reporting; //our reporting namespace
using System;
namespace ConsoleApplication
{
public class Program
{
public static void Main(string[] args)
{
var filePath = FinancialsGenerator
.GenerateAReportAndReturnFilePath(Math.PI, Math.E);
// do something with the file path
}
}
}

Going forward, this will mean that you can simplify the calls to this code. Maybe you could even strip the common stuff out.

using System;
namespace Reporting
{
public static class Generator
{
private static double CalculateSomeStuff(double inVarOne,
double inVarTwo)
{
return inVarOne *= Math.Pow(inVarTwo, 2);
}
private static bool CheckSomeFileSystemThing(string filePath)
{
return File.Exists(filePath);
}
}
public static class FinancialsGenerator : Generator
{
public static string GenerateAReportAndReturnFilePath(double inVarOne,
double inVarTwo)
{
// do some file generation
var generatedFileName = $"Financials Report - {DateTime.Now.ToString("dd-MM-yyyy")}.pdf";
var totalValue = CalculateSomeStuff(inVarOne,inVarTwo);
if(CheckSomeFileSystemThing(generatedFileName)
{
return Path.Combine(directoryFileIsIn, fileName);
}
}
}
}

Here we’ve extracted out the calculation and file path checking methods so that they can be used for a different type of report generator.

When it comes to class libraries, it’s all about extracting common code. Once you’ve extracted the common code out, you can start to use it in your applications wherever you need to. You could make a library that deals with vector mathematics, or a basic physics engine, or maybe a card payment system, or maybe a battle engine for a video game.

The soft rule would be: if it’s code that gets called in more than one place, extract it out and put it in a class library.

Console Application

Console Applications are the types of applications which run in the console or terminal.

Pretty original name, huh?

You’ve seen these types of applications in TV shows and Movies before, usually whenever a character is being a sneaky hacker, or to show what the production team think cyber space looks like.

Dating myself with the use of cyber space, there. Interesting fact: author William Gibson invented that term

They’re also a great place to start writing an application, so that you can get the business logic down before adding the complexity of a GUI to it.

Also, everything that you build in .NET Core (with the exception of class libraries) will run as a console application, and you can get a whole host of useful debugging data without having to use a flavour of Visual Studio.

Creating a Console Application

As with the Class Library, I’ve already written a tutorial on how to create a Console Application.

And here is a link to that article.

Again, as with the Class Library tutorial, you can head over to the Console Application tutorial to learn about how to create one. But I’m about to go into a little more detail about what they are and how they can be used.

Where You Might Use One

Let’s say that you have some kind of prototype desktop application and that you want to make sure that your business logic is correct before you add a fancy user interface to it. So the first thing to you could do is create a Console Application to load those classes into and test it all out.

Perhaps you’re building an enterprise level banking application, or you’re building a DBMS, or maybe you’re putting together something mathematically intensive like ray tracing.

Well, you want to know that the application logic does what it’s meant to before you spend time wiring up a GUI. Otherwise the codebase might end up ballooning in size before you’ve added the basic functionality.

Building a windowed GUI into your application, formatting the data correctly for the controls which sit on a windowed application and ensuring that calculations and window updates are done in separate threads (with communication between them) is quite hard.

Once you know how, it’s a doddle. But going from nothing to a GUI on one thread and your tasks on another is a big step.

So creating a Console Application makes starting development on these gargantuan applications easier. Plus, you might want your application to be a console app anyway.

There are plenty of reasons for this; for instance, you might need to squeeze as much performance out of your application as possible, or you might expect a certain level of competency with the terminal from your users (this can be true in the Linux/Unix world, as a lot of sysadmin tools are terminal based). Or the console might just make more sense for your application.

Not everything has to have a flashy GUI, you know.

MVC Web Application

MVC stands for Model-View-Controller, and is a design pattern that’s used mostly with Web Applications. It allows you to separate the business logic and response generation (Controller) from the mark up (View) and data models (Model).

Creating an MVC Application

As with the other types, I’ve already written tutorial on how to create an MVC app

Here is a link to that article.

You can go there to learn a little more about how to create an MVC app if you want. I’m going to go into a little more detail here about why you might use one.

Where You Might Use One

Imagine that you have a blog, an online newspaper, an online store, or some other page which could have the need for a Content Management System. In those instances MVC would be a great choice.

It can do static page sites, too. But MVC really shines with dynamic pages 

MVC really helps to drive home the idea of separation of concerns it does this via the separation between Models, Views and Controllers. Any one of those pieces can be replaced without impacting any of the others.

Also, the default routing makes it really easy for users to figure out where, within the site, they are.

MVC controllers can be decorated with Authorisation attributes.

Something I didn’t cover in my tutorial (linked earlier), but I’m working on one that will include it

This means that access to certain areas in the system can be blocked to unauthorised users without having to clutter up your controllers with code to perform authorisation.

This can be done at both the Controller and ActionMethod levels – meaning that you can have a Controller which is off limits to an unauthorised user, unless you give them access a certain ActionMethod.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace mvcApp.Controllers
{
[Authorize(Roles = "SuperAdmin"]
public class MyController : Controller
{
public IActionResult SuperSecretActionMethod()
{
// shh! don't tell the average users
}
[AllowAnonymous]
public IActionResult EveryOneCanAccess()
{
// the difference is that even users who aren't
// logged in can see this ActionMethod
}
}
}
view raw mvc-controller.cs hosted with ❤ by GitHub

In the above example, the only ActionMethod which is available to all users is EveryOneCanAccess. The ActionMethod SuperSecretActionMethod is locked down to users who are in the SuperAdmin role.

I’ll cover all of this in much greater detail in a post next year.

Unit Tests

Unit Tests are small blocks of code that are run outside of your source code; their main purpose is to make assertions about and to test the processes and algorithms used in your application’s source code.

Creating a Unit Test Library

I’ve also written a tutorial on how to create Unit Tests in the past, too.

Here is a link to that article.

As with the others, you can click through to that link and learn more about how to create unit tests. But here comes a little more detail about where you might use them.

Where You Might Use A Unit Test Library

The short answer here is:

Everywhere

Test Driven Development is huge (even though it has is detractors). Even if you’re not partaking in test driven development you should still have unit tests for as much of your code base as possible.

The golden rule is above 90%, trending as close to 100% as possible

How else can you prove that your code works without having to run through the entire system, calling every method in every possible permutation with every possible input value yourself?

Writing that sentence felt tedious (and I’m pretty sure that reading it was tedious too). Now imagine having to do that for your entire code base.

Your development machine and build server

You do have a build server, don’t you?

can operate at a much higher speed than you can, so why not get them to do the boring bit for you.

Testing, that is

If it can be automated, then why not automate it? Plus, unit tests are great for regression testing.

If you change something, how do you know for certain that it doesn’t affect other areas of the application?

Even if you don’t practise TDD, you should be adding unit tests to your code base. Here is an article (written by a colleague) are a bunch of reasons why you should add them to your code base.

That article’s main focus is on why you should practise TDD, but the points are still valid if you don’t 

WebApi Application

Creating a WebApi Application

WebApi applications are the only ones that I haven’t written a tutorial on, so I’ll give a basic run down on how to create one here.

And expand on it at a later date.

WebApi applications are .NET Core’s answer to web servers and services. Using the WebApi application type you can create and run a web server in moments.

To create a WebApi application, we’re going to go back to the terminal and use the Yeoman generator

What? Again?!

yo asptnet
view raw webapi-terminal.sh hosted with ❤ by GitHub

As per the other tutorials where I’ve mentioned Yeoman, you need to give the application a name, then cd into the new source directory and restore packages. May as well run it while we’re here, too.

dotnet restore
dotnet run
view raw webapi-terminal.sh hosted with ❤ by GitHub

Once the build completes, you’ll be told that your WebApi application is running on localhost and be given a port number.

I tend to get given port 5000, but your milage may very

Heading to localhost (with the relevant port number) wont give you much, in fact you might even get a 404:

WebApi initial boot
Is the WebApi application responding?

This is because, by default, a WebApi application will only respond if you perform HTTP Verb based requests on it’s exposed api end points.

So what are it’s endpoints?

Project Layout

If you open the WebApi project with Visual Studio Code, you should see something like this:

WebApi Project Open
Our WebApi project open in Visual Studio

I’ll go into this in a little more detail in an upcoming post

A WebApi application has a similar layout to an MVC one, it even uses a very similar startup.cs file. In fact, if you take a look at the startup.cs file that Yeoman has created for you:

public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddMvc();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
app.UseMvc();
}
view raw webapi-startup.cs hosted with ❤ by GitHub

It’s added calls to the MVC service for us. You’ll also notice that there’s no routing, unlike an MVC application.

A WebApi application responds only to HTTP Verb based requests to its exposed by it’s end points. Those endpoints are defined in the controllers, so let’s take a look at the default one in our demo project:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace webApiApp.Controllers
{
[Route("api/[controller]")]
public class ValuesController : Controller
{
// GET api/values
[HttpGet]
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
// GET api/values/5
[HttpGet("{id}")]
public string Get(int id)
{
return "value";
}
// POST api/values
[HttpPost]
public void Post([FromBody]string value)
{
}
// PUT api/values/5
[HttpPut("{id}")]
public void Put(int id, [FromBody]string value)
{
}
// DELETE api/values/5
[HttpDelete("{id}")]
public void Delete(int id)
{
}
}
}
view raw webapi-controller.cs hosted with ❤ by GitHub

Let’s take a look at some of the contents of this file.

Ignoring the using statements and the namespace declaration, the first thing we have is a RouteAttribute which is decorating our class

[Route("api/[controller]")]
view raw webapi-controller.cs hosted with ❤ by GitHub

This instructs our WebApi application that the route for the Values controller is at

/api/values

Because it will automatically substitute the keyword “controller” for the name of the controller. In this case “Values”

Looking at the first method in the Values controller, we can see:

// GET api/values
[HttpGet]
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
view raw webapi-controller.cs hosted with ❤ by GitHub

This is a GET method, as you can see from the GetAttribute which is decorating the method.

We needed the MVC service adding so that we could use the HTTP attributes.

Why don’t we send a GET request and see what happens?

WebApi GET Response
We can see the response being formed in the terminal

The response was exactly what our Get method said it would return, which is pretty cool.

Although, having a method called Get which response to GET requests is a little confusing. No?

If you take a look at the terminal, you can see the steps taken to deal with the request and serve the response:

info: Microsoft.AspNetCore.Hosting.Internal.WebHost[1]
Request starting HTTP/1.1 GET http://localhost:5000/api/Values
info: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[1]
Executing action method webApiApp.Controllers.ValuesController.Get (webApiApp) with arguments () - ModelState is Valid
info: Microsoft.AspNetCore.Mvc.Internal.ObjectResultExecutor[1]
Executing ObjectResult, writing value Microsoft.AspNetCore.Mvc.ControllerContext.
info: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[2]
Executed action webApiApp.Controllers.ValuesController.Get (webApiApp) in 2.6894ms
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[2]
Request finished in 5.2741ms 200 application/json; charset=utf-8
view raw webapi-terminal.sh hosted with ❤ by GitHub

This can be super useful when debugging your WebApi application. Especially if you get a 404, when you expect to hit a controller method.

Here’s a quick dissection of what’s happening (note: the lines in the snippet are wrapped)

  • Line 1 tells us that a GET request for /api/values was received
  • Line 2 tells us that the Get method within the ValuesController was called (and that the model state was valid)

I’ll go into Model State in a longer post all about WebApi applications.

  • Line 3 tells us that our application is preparing the payload data for our response
  • Line 4 tells us that our application has exited from the call to the Get method
  • Line 5 tells us that it has dealt with the request and sent the response back to the client (and that it took 2.6894ms from start to finish)
Custom Endpoints

This WebApi application is a little boring as it is, so let’s add our own GET endpoint.

Between the two Get methods in our Values controller, insert the following code:

We’re looking at line 18, but you can put this anywhere in the ValuesController

// GET api/values
[HttpGet]
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
[HttpGet("SayHello")]
public string SayHello()
{
return "Hello, world!";
}
// GET api/values/5
[HttpGet("{id}")]
public string Get(int id)
{
return "value";
}

I’ve highlighted the relevant lines, and kept the other two controllers in this snippet for context.

The new method (SayHello) responds to a GET request sent to the SayHello endpoint only. Interestingly enough, we could name the method whatever we want, as it’s the argument given to the GetAttribute which tells our WebApi application which end point our method belongs to.

You’ll have to stop the server (Ctrl+C will do it) and start it back up again (with our old friend dotnet run) to be able to use the new controller method because it will need to be recompiled.

Now if we do a GET request for /api/Values/SayHello, we’ll get the following:

WebApi SayHello Method
That’s pretty cool, isn’t it?
Where You Might Use One

Let’s say that you had a WebServer, maybe one that allows users to perform GET requests for the latest football scores, or maybe one which returns the next public holiday. Or maybe you have a mobile application which needs to get data from a server, that’s precisely what WebApi is aimed at.

As you’ll see (once I’ve had the chance to write a full post on WebApi), you can connect a WebApi application up to a database

Actually, you can use as many databases as you want.

And return data formatted as strings, XML or even JSON. Super useful.

With All That Said

As I said at the top of this article, this is my final piece before the holidays. I’ve only been doing this for a few months, and the response has been great so far.

At the time of writing this post, I’ve had more than 5,600 page hits since my first article was posted on October 4th.

It’s given me the drive to want to continue, and remain on my schedule of pushing out a new post every Thursday at 8:30pm (ish).

I’m still going to be working on posts and pages over the holidays, but I’m not going to publish anything until next year.

Which is only a week and a bit away. I’m sure that you’ll allow me a week off.

Who knows, this time next year I might be some sort of expert on .NET Core.

Eep!

Anyway, with all that said I want to wish you all a happy and restful holiday season, and a fantastic new year.

A .NET developer specialising in ASP.NET MVC websites and services, with a background in WinForms and Games Development. When not programming using .NET, he is either learning about .NET Core (and usually building something cross platform with it), speaking Japanese to anyone who'll listen, learning about languages, writing for his non-dev blog, or writing for a blog about Retro Gaming (which he runs with his brother)