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!

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!