I can’t think to the last ASP.net project I worked on that didn’t involve Automapper in one way or another. In some ways, it’s become a bit like JSON.net where it’s just a defacto package to install when you start a new project. Automapper has, over time, been moving away from it’s static class origins into a more dependency injection type interface. This of course then lends itself perfectly for ASP.net Core’s new Service Collection framework!

This post will go over getting things up and running in ASP.net Core, but it does presume you already have quite a bit of knowledge about Automapper already. Let’s jump right in!

Setup

Inside your project, install the following Nuget package from the Package Manager console :

This will also in turn install the Automapper nuget package if you don’t have it already.

Inside your ConfigureServices method of your startup.cs, add a call to add the AutoMapper required services like so :

If you want to see what this call does, the actual code is open source and available here. In short, it trawls through your code finding all configuration profiles (See below), and registers the IMapper interface to be used in your classes. It is also rather particular about which scopes it will register them under – which we will also talk about shortly.

Adding Profiles

Automapper Profiles haven’t changed when you move to .NET Core. Take the example profile below where I have created a class called “DomainProfile” to add mappings, and inside the constructor setup a mapping.

When your application runs, Automapper will go through your code looking for classes that inherit from “Profile”, and will load their configuration. Simple!

Using IMapper

Once you’ve loaded up your profiles, using the IMapper interface is exactly the same if you used Automapper with any other DI Framework. You inject in IMapper to your constructor of your class, and are then able to map objects.

Again, it may look like a bit of black magic since you never registered IMapper in the ServiceCollection. But the Nuget package and the call to “AddAutoMapper” in your ConfigureServices takes care of all of this for you.

Scopes

One final thing to end on is how scopes work inside Automapper. Great care has been given so that you can write custom resolvers that rely on things like repositories that may be of transient scope. Confused? Let’s break it down a bit more.

Your configuration (e.g. Automapper Profiles) are singletons. That is, they are only ever loaded once when your project runs. This makes sense since your configurations will not change while the application is running.

The IMapper interface itself is “scoped”. In ASP.net terms, it means that for every individual request, a new IMapper is created but then shared across the entire app for that whole request. So if you use IMapper inside a controller and inside a service for a single request, they will be using the same IMapper instance.

But what is really important, is that anything that derives from IValueResolver, ITypeConverter or IMemberValueResolver will be of transient scope. They will also be created using the .NET Core Service Collection DI. Take the following code that may be used to resolve a particular mapping whereby I want to map across a username based on the source models “Id”. To do this I want to access my UserRepository.

Because this is instantiated as a transient instance using .NET Core’s Service Collection, my repository will also be resolved correctly and I will be able to do mappings that are more than just mapping across simple values. Super handy!

Have I missed anything? Drop a comment below and let me know!

In a previous post, I talked about getting Cookie Authentication up and running in ASP.net Core 1.X. In ASP.net Core 2.0, there has been a couple of changes to the API that are pretty easy to trip up on. Most of the changes are just a simple naming difference, but it can be pretty infuriating following a tutorial where one word trips you up! So let’s go!

Firstly, remember that this tutorial is for adding authentication to your app when you don’t want to use the out of the box “identity” services provided by ASP.net Core. It’s a very simple way to provide authentication cookies based on any logic you want, with any backing database you want.

Setup

If you are creating a new project, ensure that the “Authentication Type” when creating the project in Visual Studio is set to No Authentication. The other authentication types you can pick revolve around the inbuilt identity service, but since we are looking to do something more custom we don’t want this.

With your project up and going. In your nuget package manager, install the following package :

In the configure method of your startup.cs. Add the following line. Note that it should always come above your call to “UseMVC”, and likely above any other middleware calls that will return a result. Middleware runs in order, so you obviously want authentication to kick in before your MVC pipeline does!

In the ConfigureServices method of your startup.cs, you need to add the Cookie Authentication services with their configuration. It should look pretty similar to the following :

Where the Login Path is the URL to your login page. Remember this page should be excluded from authorization checks!

Disabling Automatic Challenge

Microsoft has decided that any time you access an endpoint that should be authorized, you should be redirected to the login page regardless. In ASP.net Core 1.X, this was not the case. You could set a flag called “AutomaticChallenge” to false. If you do not wish to always redirect the user (e.g. You would prefer to simply return a 401 response code – a Web API using shared Cookie Authentication is a good example where this would be relevant), you can override the redirect logic like so :

This overrides the redirect logic and instead returns a simple 401. There are other events you may wish to override at the same time (For example the UnAuthorized redirect etc).

Registering A User

In exactly the same manner as Cookie Authentication in ASP.net Core 1.X, registering a user will be entirely on you and will live outside any authentication code provided out of the box by Microsoft.

Logging In A User

For logging in a user, let’s create a quick model.

Now let’s create a controller called “Account” and create a POST method that accepts our login.

If you’ve followed our previous tutorial on Cookie Authentication in ASP.net Core 1.X, then this should look pretty familiar. And that’s because it’s the exact same code with one notable exception. This line here :

In ASP.net Core 1.X is actually

So that’s the only difference here.

Authorizing Controllers

This stays the same in ASP.net Core 2.0. You can simple add the “Authorize” attribute onto any controller or action.

Logging Our A User

Logging out a user stays fairly simple with one small change. The line to sign a user out inside an action is now

Previously in ASP.net Core 1.X it was :

With the release of .NET Core 2.0 comes a large “meta package” with the name Microsoft.AspNetCore.All. It’s a sort of god mode package that contains all you need to get up and running on ASP.net Core without having to figure out which nuget package does what. But it does have some massive pitfalls in my opinion.

Why Have A Meta Package At All?

When ASP.net Core is split into multiple smaller packages, the “versions” of these packages start to get all out of sync over time. This is especially true if you have ever tried to upgrade a project between .NET core versions, you end up having to go through all your smaller AspNetCore packages and work out which ones you should be version bumping. Take the following for example :

Here you have many aspnetcore and EntityFramework packages that all have slightly off versions. In ASP.net Core 2.0, using the “Microsoft.AspNetCore.All” meta package, your package references instead look like this :

What this should mean is that by updating a single package, you will be able to run on the latest ASP.net Core version. It also makes your csproj a bit easier on the eye with a single package being your “framework”, and any other package references being ones you have added explicitly.

What’s Inside The Microsoft.AspNetCore.All package

The meta package contains :

  • Every single AspNetCore package published by Microsoft
  • Every EntityFrameworkCore package published by Microsoft
  • Any supporting packages required for the framework to run (For example Json.Net)

Now, that probably sounds huge and you will probably ask yourself,  won’t the resulting deployment be out of control? You would essentially be “shipping” the entire framework right? Well..

Deployment and Runtime Store

Microsoft have gone back to something called the “Runtime Store“. I say the words “gone back” because this functions almost the same as the GAC on .net Full Framework projects. That is, your target machine would have to have the .NET Core runtime installed on it for you to be able to use the aspnetcore meta package. When you deploy, you won’t actually deploy any of the framework packages, your code will instead utilize the ones already on the machine.

And if the machine doesn’t have the runtime installed? Well, that’s where things start to fall down. If you are looking to do self contained deployments (Which was a massive selling point of .NET Core), then you cannot use the meta package. You would need to reference packages manually. I can see how this could turn into a headache down the road because it makes the creation of the project and whether you use the meta package so important. Imagine getting to the point you are ready to deploy, and your dev ops team prefers going down a self contained deployment route. Now you will have to go back and work out which packages you are using from the meta and add them all in manually. Painful!

Getting Started

By default, when you create any project using ASP.net Core 2.0, you will be using the meta package. If you know you won’t be using self contained deployments any time soon, then it’s safe to go ahead and use, and really, it does alleviate some headaches of knowing which packages have what. I can’t tell you how many times I start a new project and I have to go back and manually add in the packages for authentication, entityframework, staticfiles etc. Give it a go and let me know what you think below!

In a previous post, I wrote about how there was no way to send email on .NET Core. In version 1.0 of the framework and 1.6 of the standard, the SMTP client code in .NET was not yet ported over , that is until the release of .NET Core 2.0.

With things ported over, the interfaces and classes are virtually identical to ones you might have used in the full framework. Consider the following written in .NET Core 2.0.

For the most part, if you had code that could send email via SMTP in the full framework, it’s likely a matter of a copy and paste job to get it going in .NET Core now!

If you are having issues with this, ensure that you are on .NET Core 2.0 framework. You can check this by editing your csproj file, it should look like the following :

Where TargetFramework is set to 2.0. Anything lower and you will not have access to the SmtpClient class!

This will be the third and last part of our series that will help you to get up and running to do F# development with .NET Core on Linux.

We’ve made this far and all we’re missing are just the finishing touches.

As promised we’ll be looking at how we can link our build, run and debug workflow into vscode.

The editor expects the project’s configuration to be located on a folder called .vscode  at the project’s root folder, containing to 2 files called launch.json  and tasks.json . We’ll be looking at how we can create and update them both manually and automatically.

Build

Let’s start with an easy one, the build task.

Anywhere in the editor just run the default build command ( ctrl+shift+b ) and vscode will let you know that it couldn’t find a build task for the project and it’ll offer you to create one.

We’re going to select ‘Configure Build Task’ and choose ‘.NET Core’

That’s going to create a tasks.json file inside your .vscode folder (which it’ll get created automatically if it didn’t existed). If the .NET Core option doesn’t show up for you, don’t worry, manually create the tasks.json file and paste the following.

Now we’re ready to build our project! Run the build command again ( ctrl+shift+b ) and this time you’ll see the following output.

Run

Now that we’ve set up our build task, adding one for running our project is trivial. Jump again into the tasks.json file and just add another task to the “tasks” array that looks like the following.

Save the file and fire up vscode ‘Quick Open’ ( ctrl+shift+p ), select ‘Tasks: Run Task’ and you’ll see your newly created ‘run’ task. Once you’ve selected it, vscode ‘output’ panel should show something like

Debug

This will be the last thing we add and it is as easy as the other two with a small caveat.

Remember how I mentioned there were going to be two configuration files ? We’ll make use of the other one now. It order to debug, we will not be creating a task but a launch configuration. Automatically creating the configuration file is as simple as pressing F5  and selecting  .NET Core  as our environment. By default this will create the launch.json file with three default configurations, of which we’ll be only focusing on one for this article.

Right now, you might be tempted to re run debug (F5) because you created the configuration but you’ll quickly be prompted with an error message that reads something like

launch: launch.json must be configured. Change ‘program’ to the path to the executable file that you would like to debug

Don’t worry, we’ll sort it out in seconds.

Once you open up your launch.json, you’ll realize that while vscode created the configuration it hasn’t really specified which program it should debug and instead the path for the program contains two placeholders but because we’ve already built our project we can see what values it is expecting, so go ahead and replace <target-framework>  with netcoreapp1.1  and <project-name.dll>  with fsharp_tutorial.dll .

Your “.NET Core Launch (console)” should now look like this

All that is missing now is giving it a try, so just place a break point and hit debug (F5)

And we’re done! We’ve covered the basic setup to get your F# on linux journey started.

You can find the finished project here

This will be the second part of a series of 3 articles that will help you to get up and running to do F# development with .NET Core on Linux.

Ok, for this particular entry we’ll be talking about tools that’ll improve our development experience.

State of the art

Unfortunately, one of the downsides of not developing on Windows is not having access to the excellent Visual Studio IDE but fear not, we’ll be covering a setup that should make us feel at home. Today’s post will focus on Visual Studio Code (vscode), a fantastic open source code editor developed by Microsoft. Sometime in the future we’ll be covering alternative tools, such as the promising Jetbrains Rider IDE and VIM/Emacs.

Now head onto vscode’s download page and install the package corresponding to your favorite distro (both deb and rpm as well as 32 and 64 bits packages are provided).

If you’ve been following our previous entry, you should have a folder fsharp_tutorial , go ahead and open it.

Extensions

The vscode extensions ecosystem is huge and worth spending some time looking at what it has to offer. For the scope of this series, we’ll only be covering one: ionide-fsharp . This extension comes to us thanks to the people at ionide and on top of the one that we’ll be looking at, they provide two more excellent F# extensions that you should check out.

Go ahead and install it, you’ll be prompted to reload the current window to enable it. If you search for it again, you should see something like this

While the out of the box settings should be enough to get you started if you wanted to change something you can find the extension settings under ‘FSharp configuration’ or by searching ‘fsharp’ in the settings page.

Taking it for a ride

We’ll go over a few things now, so open up our Program.fs  file.

First thing we want to do is to add our add function that we used to test F# interactive on our previous post. Assuming things are working as intended, the first thing you should notice is the automatic function type signature displaying on top of our function.

The second thing now will be to test the integration with F# interactive. We can do this in several different way but for this post we’ll use the default ‘send line to fsi’ shortcut which is alt+/ .

Now your function is part of the interactive tool context and can be run.

You can find the rest of the options by opening up quick search ( ctrl+shift+p ) and searching for fsi .

On the next and final entry for the series, we’ll finish setting vscode for building, running and debugging our program.

This will be the first part of a series of 3 articles that will help you to get up and running to do F# development with .NET Core on Linux.

Installing .NET Core

The first thing we want to do is to install .NET core. Microsoft provides us with very easy to follow instructions for your favorite distro here.

Once the installation is over you can quickly check that it went well by running the following command.

Installing F#

At this stage we will be able to create, run and build projects but we still don’t have access to the language itself.

For that we will follow the instructions from the F# Foundation located here. One of the biggest benefits of doing so is to have access to the F# interactive tool, which we’ll use now to verify the installation went well by running the following command.

Taking it for a ride

F# Interactive

Let’s use it write a very simple function to see it in action.

Remember that in the context of F# interactive you need to terminate your instructions with  ;;

Dotnet CLI

The first time you fire up  dotnet it will take a few seconds while it bootstraps and prepares its cache.

We’ll create a new console app project which will be the basis for the series.

This will assume you’re running this command inside a folder called  fsharp_tutorial and that will be the name of our project as we won’t be specifying one.

You should now have 2 new files called  fsharp_tutorial.fsproj and  Program.fs .

Like with any other .NET core project type, we’ll need to restore its packages before can try to do anything useful.

Now we’re ready for the moment of truth as we’ll run our program for the first time.

If you see the above it means that your installation went as intended and we’re ready for our next step in this series which will be setting up our development environment.

Route Constraints can be a handy way to distinguish between similar route names, and in some cases, pre-filter out “junk” requests from actually hitting your actions and taking up resources. A route constraint can be as simple as enforcing that an ID that you expect in a URL is an integer, or as complicated as regex matching on strings.

An important thing to remember is that route constraints are not a way to “validate” input. Any server side validation you wish to occur should still happen regardless of any route constraints set up. Importantly, know that if a route constraint is not met than a 404 is returned, rather than a 400 bad request you would typically expect to see from a validation failure.

Type Constraints

Type constraints are a simple way to ensure that a parameter can be cast to a certain value type. Consider the following code :

At first glance you might assume that if you called “/api/controller/abc” that the route would not match – It would make sense since the id parameter is an integer. But infact what happens is that the route is matched and the id is bound as 0. This is where route constraints come in. Consider the following :

Now if the id in the URL is not able to be cast to an integer, the route is not matched.

You can do this type of constraints with int, float, decimal, double, long, guid, bool and datetime.

Size Constraints

There are two types of “size” constraints you can use in routes. The first is to do with strings and means you can set a minimum length, max length or even a range.

This sets a minimum length for the string value. You can also use maxlength to limit the length.

Alternatively, you can set how many characters a string can be within a range using the length property.

While that’s great for string variables, for integers you can use the min/max/range constraints in a similar fashion.

Regex Constraints

Regex constraints are a great way to limit a string input. By now most should know exactly what regex is so there isn’t much point doing a deep dive on how to format your regex, just throw it in as a constraint and away it goes.

It is worth noting there for whatever reason, the .NET core team added another handy “quick” way of doing alpha characters only instead of regex. There you can just use the constraint of “alpha”.

 

Culture in ASP.net has always been a bit finicky to get right. In ASP.net core there is no exception but with the addition of middleware, things are now configured a little differently. Lifting and shifting your standard ASP.net code may not always work in ASP.net core, and at the very least, it won’t be done in the new “ASP.net Core way”.

It should be noted that there are two “cultures” in the .net eco system. The first is labelled just “Culture”. This handles things like date formatting, money, how decimals are displayed etc. There is a second culture called “UICulture” in .net, this usually handles full language translations using resource files. For the purpose of this article, we will just be handling the former. All examples will be given using datetime strings that will change if you are in the USA (MM-dd-yyyy) or anywhere else in the world (dd-MM-yyyy).

Setting A Default Request Culture

If you are just looking for a way to hardcode a particular culture for all requests, this is pretty easy to do.

In the ConfigureServices method of your startup.cs, you can set the DefaultRequestCulture property of the RequestLocalizationOptions object.

In the Configure method of your app, you also need to set up the middleware that actually sets the culture. This should be placed atleast before your UseMvc call, and likely as one of the very first middlewares in your pipeline if you intend to use Culture anywhere else in your app.

I can write a simple API action like so :

When calling this action I can see the date is output as MM-dd-yyyy (I am from NZ so this is not the usual output!)

Default Request Culture Providers

When you use the request localization out of the box it comes with a few “providers” that you (Or a user) can use to override the default culture you set. This can be handy if your app expects these, otherwise it can actually be a hindrance if you expect your application to be displayed in a certain locale only.

The default providers are :

QueryStringRequestCultureProvider
This provider allows you to pass a query string to override the culture like so http://localhost:5000/api/home?culture=en-nz

CookieRequestCultureProvider
If the user has a cookie named “.AspNetCore.Culture” and the contents is in the format of “c=en-nz|uic=en-nz”, then it will override the culture.

AcceptLanguageHeaderRequestCultureProvider
Your browser by default actually sends through a culture that it wishes to use. A browser typically sends through your native language, but it will throw in a couple of “options”. So for example my browser currently ends through “en-GB and “en-US” (Even though I am in NZ).

This header in particular can become very problematic. If the default culture of your *server* matches the culture that a browser sends. Then by default it doesn’t matter what you set the “DefaultRequestCulture” to, this will override it.

There are two ways to keep this from happening. The first is to tell ASP.net core that the only supported cultures are the one that you want the default to be. You can do this in the ConfigureServices method of your startup.cs.

The second way is to remove the CultureProviders from the pipeline all together.

The second method should be done in anycase if you don’t intend to use them as this makes your pipeline much cleaner. It will no longer be running a bunch of code that you actually have no use for.

Supported Cultures List

If you do intend to allow the user to set their own culture in their browser, you intend to use a query string to define the culture, or you intend to do a custom request culture provider (outlined in the next section) to allow code to set a custom culture based on other parameters, then you need to provide a list of supported cultures.

Supported cultures is a list of cultures that your web app will be able to run under. By default this is set to a the culture of the machine. Even if you use a custom culture provider as outlined below to set a culture, it actually won’t be set unless the culture is in the supported list.

You can set the list as follows :

So in this example, I have set the default localization to “en-US”. But if a user comes through with a cultureprovider that wants to set them to en-NZ, the code will allow this. If for example a user came through with a culture of “en-GB”, this would not be allowed and they would be forced to use “en-US”.

Custom Request Culture Providers

Going beyond hard coding a particular culture, often you will want to set culture based on a particular user’s settings. In a global application for example, you may have saved into a database what datetime format a user wants. In this scenario, you can use a custom RequestCultureProvider class.

The code looks something like the following :

Inside your ConfigureServices method in startup.cs, you then need to add your new CultureProvider to the RequestCultureProviders list. In the below example I have cleared out all other providers as I don’t care about query strings, cookies or the accept language header.

However let’s say that you do care, and if your custom provider can’t sort out a culture you want it to try query strings, cookies and the accept header. Then the best way is to insert it at the start of the list. Remember that these are run in order, the first provider that returns a culture instead of null wins.

Remember! It doesn’t matter what your custom culture provider returns if the culture it tries to set is not in the supported culture list. This is extremely important and the cause of many headaches!

Pretty much any project that allows file uploads is going to utilize some cloud storage provider. It could be rackspace, it could be GCloud, it could be AWS S3, or in this post’s case, it’s going to be Azure Blob Storage.

Using Blob Storage in .net core really isn’t that different to using it in the full framework, but it’s worth quickly going through it with some quickfire examples.

Getting Required Azure Details

By this stage, you should already have an Azure account set up. Azure has a free tier for almost all products for the first year so you can usually get some small apps up and running completely free of charge. Blob Storage actually doesn’t have a free tier, but if you upload just a single file it’s literally cents to store a GB of data. Crazy. I should also note that if you have a MSDN subscription from your work, then you get $150 a month in Azure credits for the lifetime of your MSDN subscription.

Once you have your account setup, you need to head into the Azure portal and follow the instructions to create a storage account. Once created, inside your storage account settings you need to find your access keys.

The end screen should look like this (Minus the fact I’ve blurred out my keys) :

Write down your storage name and your keys, you will need these later to connect via code to your storage account.

Project/Nuget Setup

For this tutorial I’m just working inside a console application. That’s mostly because it’s easier to try and retry things when we are working on something new. And it means that we don’t have to fiddle around with other ASP.net boilerplate work. It’s just open our main and start writing code.

Inside your project, you need to run the following commands from your Nuget Package Manager.

This is all you need! It should be noted that the same package will be used if you are developing on full framework too.

Getting/Creating A Container

Containers are just like S3 Buckets in Amazon, they are a “bucket” or “collection” to throw your files into. You can create containers via the portal and some might argue this is definitely safer, but where is the fun in that! So let’s get going and create our own container through code.

First, we need to create the object to hold all our storage account details and then create a “client” to do our bidding. The code looks a bit like this :

When we create our storage credentials object, we pass it in the account name and account key we retrieved from the Azure portal. We then create a cloud storage account object – the second param in this constructor is whether we want to use HTTPS. Unless there is some specific reason you don’t… just put true here. And then we go ahead and create our client.

Next we actually want to create our container via code. It looks a bit like this :

That container object is going to be the keys to the world. Almost everything you do in blob storage will be run off that object.

So our full C# code for our console app that creates a container called “mycontainer” in our Azure Cloud Storage account looks like the following :

It’s important to note that every remote action in the storage library is async. Therefore I’ve had to do a quick wrap of an async method in our main entry point to get async working. Obviously when you are working inside ASP.net Core you won’t have this issue (And as a side note, from C# 7.1 you also won’t have an issue as they are adding async entry points to console applications to get around this wrapper).

Running this code, and viewing the overview of the storage account, we can see that our container has been created.

Uploading A File

Uploading a blob is incredibly simple. If you already have the file on disk, you can upload it simply by creating a reference to your blob (That doesn’t exist already), and uploading.

You can also upload direct from a stream (Great if you are doing a direct pass through of a file upload on the web), or even upload a raw string.

The important thing to remember is that in the cloud, a file is just a blob. While you can name your files in the cloud with file extensions, in the cloud it really doesn’t care about mimetypes or anything along those lines. It’s just a bucket to put whatever you want in.

Downloading A File

Downloading a file via C# code is just as easy.

Similar to uploading a file, you can download files to a string, stream or byte array also.

Leasing A File

Leasing is an interesting concept and one that has more uses than you might think. The original intent is that while a user has downloaded a file and is possibly editing it, you can ensure that no other thread/app can access that file for a set amount of time. This amount of time is a max of 1 minute, but the lease can be renewed indefinitely. This makes sense and it means if you are building some complex file management system, it is definitely handy.

But actually leasing has another great use and that is handling race conditions across apps that have been scaled out. You might typically see Redis used for this, but blob storage also works too.

Consider the following code :

When the second AcquireLease runs, an exception is thrown that a lease cannot be obtained – and can’t be obtained for another 30 seconds. A full rundown on using leasing is too much for this post, but it is not too much work to write code that can acquireleases on a blob, and if a lease cannot be obtained, do a spin wait until a lock can be obtained.