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!

One of the easiest ways to publish your application to Azure App Service is straight from Visual Studio. While not an ideal solution long term or for any team over the size of one, it’s a great way for a solo developer to quickly get something up and running. Most of all, it doesn’t rely on any special configuration, scripts or external services.

Publish via Login

If the Azure account you are publishing to is the same one you use for your Visual Studio account or you have the username/password combination of the Azure account you are publishing to, you can publish direct from Visual Studio.

Inside solution explorer, right click your project and select “Publish”. You want to select “Azure App Service” on the next screen and “Select Existing”. The “Create New” option can be used if you don’t already have an App Service instance already (Rather than creating via the portal) – but we won’t do this this time around.

Click “Publish”. On the next screen you can select your Account, App Service and Deployment Slot to push to. Click “OK” and… that’s it. Really. You should see your project start building, publishing (via Web Deploy), and then Visual Studio will open your browser at the App Service URL.

Publish via Publish Profile

A publish profile is a settings file that holds all information for deploying your code direct to Visual Studio. The only real difference is that the publish profile can be given to you without you having any Azure login credentials yourself. Other than that, the actual deployment is largely the same.

To get a publish profile from the Azure Portal, head over to the dashboard of your App Service. Along the top you should see an option to “Get Publish Profile”.

With this file you are now able to deploy direct from Visual Studio. It’s important that this file is not just left lying around somewhere. With it, anyone can push code to your app service. So while it’s not quite the keys to the kingdom as much as a user/pass combination is, it’s pretty damn close.

Inside Solution Explorer, Right click your project, select Publish. Select “Import Profile” (You may have to scroll to the right to see this option).

Hit Publish! Immediately your project will build, publish and then open your browser at the App Service URL.

Obvious Issues

I touched on it earlier, but I feel the need to point it out further. Publishing from Visual Studio is not a long term strategy. Publishing from Visual Studio cuts out any CI/CD process you have running (If any), it creates possible inconsistencies with what you are deploying (Think “Did you get latest before you published?) and it creates a single point of failure of one developer doing all deployments in teams of more than 1.

That last point is important, while documentation can get some way around this, a single developer being the “release” guy usually creates some “magic” process where only that person can push code.

Again, with a single developer, especially when it’s just a hobby project, it’s less of an issue.

 

Deploying to the Azure App Service through Github is a simple but effective way to deploy websites that don’t require too much ceremony. Because many projects use Github for hosting their Git repositories, it’s a pretty seamless deployment process that is more around point and clicking in the Azure portal rather than having to write complicated deployment scripts.

It should be noted while this post references Github throughout, the exact same process can be used to setup Bitbucket to automatically deploy on a push.

Setting Up Github Deployment In Azure Portal

Setting up a Github Deployment for an Azure Web App Service is nothing more than a point and click process. Inside your App Service on the Azure Portal, select Deployment Options from under the Deployment category.

Select “Setup” on the online menu, and then select your source. In our case either Github or Bitbucket. You should now be able to click “Authorize” and use OAuth to connect your Github/Bitbucket account to Azure. Note that this account will be available for all other Azure App Services, not just this one.

Select your project and branch from the options. Typically your branch can just be master, but if this is a development instance you may want to use your develop branch, or you can even select a particular release branch if you are just using this deployment method as an easy way to push code rather than a continuous deployment strategy.

After connecting, wait 5 minutes for your project to sync up. Note that sometimes you need to go to a different blade in the portal and then head back to see updates (Not the greatest, but it works eventually!)

A great feature is that the deployment engine behind this will only sync files that are changed (Since it can see what has changed inside GIT). This makes deployments much faster than a FTP transfer or similar because it’s only uploading what it needs.

Any pushes to your selected branch will be deployed automatically within seconds, but if you get impatient, you can click the Sync button inside the Deployment Options blade and you should get a deployment going within seconds.

Rollback A Deployment

The Github CD Process allows you to roll back any deployment right from inside the Azure portal. Head to the Deployment Options screen inside your Azure App Service and select the deployment you wish to roll back to.

Select the option to “Redeploy” along the top menu and your previous deployment will be redeployed to production.

Linux App Service

If you are attempting to use Azure App Service with Linux (And now is a good time to be doing so, it’s 50% off!), unfortunately I couldn’t get Continuous Deployment working. Using the exact same Github repository but with a Linux App Service, the deployment failed. I have a sneaky suspicion that is related to the Docker Settings on App Service, but I wasn’t able to get things up and running. Feel free to drop a comment below if you have got it up and running!

With Azure App Service currently being 50% off for Linux, people are taking advantage and halving their .NET core hosting bill. And why wouldn’t you!? Because Azure App Service is fully PaaS, the underlying OS doesn’t make too much of a difference both from a deployment and management perspective.

Most deployment guides floating around the web center on deploying to a Windows App Service, which really isn’t too different to the Linux version, except for one important step. If you have deployed your ASP.net Core code and are not seeing anything when you visit your website in a browser, read on.

Docker Startup File

Linux App Service actually runs Docker under the hood. To get everything starting correctly you actually need to set a “startup file”. This is essentially the entry point for your app.

Inside the Azure Portal, inside your App Service, under the Settings category, find the option for “Docker Container”. Here is where you can set the runtime stack, but more importantly, your startup details.

For a dotnet project, the startup file line should read :  dotnet /home/site/wwwroot/{yourdllhere}

Where yourdllhere is the DLL of your main web project in your deployment. In practice it should end up looking a bit like this :

Once saved, you should head back to the app service dashboard and restart your service. It does take a while to boot up first time, so wait 5 minutes and give it a spin!

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.

A quick and easy way to get your code up and running on Azure App Service is to upload your code using FTP. FTP can be as simple as a drag and drop process from your desktop, or as complicated as having your CI/CD pipeline run an FTP client for you. While it’s not an ideal scenario for large scale deployments due to the individual uploading of files one at a time, it’s a good starting point if you are just looking to have a play with Azure without too much fuss.

Setting Up FTP In Azure Portal

After creating your App Service, FTP may not be immediately available if you have never used it to deploy applications before. Deployment credentials, while they are viewable under a particular app service plan, are actually for the entire Azure account. So if you have *ever* used FTP or GIT to deploy apps before, the credentials will already be set and you should use those same ones. Resetting the credentials, even if you only do it within one app service, will reset them account wide.

Thankfully this is easy to check. Head over to your app service overview screen, if on this page you have an FTP deployment username showing, then you or someone else has already set up credentials.

If you don’t see anything here, then you will need to scroll down to the Deployment section, you should see an option for “Deployment credentials”.

Enter in a username/password combination you would like to use for FTP. Again, I cannot stress enough that this will be used on all FTP deployments for the entire account, not just this one app service plan.

Publishing Your ASP.net Core Web Project

Because App Service in Azure has a runtime installed, publishing your app is a one line job.

Open a command prompt in your project directory and run the following :

Heading to “bin\Release” you should see your published project for your .net core runtime (netcore1.0 or netcore1.1).

Uploading Your ASP.net Site

Back on your App Service overview, you should have a FTP hostname to connect to using your favourite client (I use Filezilla). After connecting, make your way to /site/wwwroot.

Upload your entire published app to the wwwroot.

Docker Settings For Linux App Services

Linux App Service plans are currently 50% of the Windows price right now, and given it’s a PaaS service, it really doesn’t make a huge difference what the underlying OS is. If you are using Linux, you will need one extra step to get going.

On the app service menu, under the Settings category, there should be an option for “Docker Container”. Here you can select your runtime stack but more importantly, you set the “entry” DLL for dotnet. Set the startup file to “dotnet /home/site/wwwroot/{yourdllhere}”.

Head back to the app service dashboard and restart the service. Wait 5 minutes and hit your URL and you should be up and running!