Upgrading vNext MVC6 Apps From Beta4 to Beta5

It’s been a while, but my last few sprints have been focused on working with ASP.NET 5 MVC6, namely evaluating what is going on in order to protoype an app front-end. Working with Beta versions is definitely challenging – there are plenty of moving parts and a lack of documentation. Fortunately, the term “community” is one we can apply more to what is going on with Microsoft’s iniciative. I’ve been pretty much googling stuff, deducing concepts, and hogging the Jabber #AspNetvNext chat room, where, fortunately, I’m getting answers I need.

I started developing the prototype in Beta4, and decided to migrate to Beta5 before starting to add even more parts to the project. Unfortunately, upgrading isn’t the easiest thing in the world, but it is possible.

1. Upgrade your DNVM and DNU

Your runtime environment should be one that can support Beta5 correctly. At this time, the latest is Beta6-10383. To upgrade, you can run in the command line window:

@powershell -NoProfile -ExecutionPolicy unrestricted -Command "&{$Branch='dev';iex ((new-object net.webclient).DownloadString('https://raw.githubusercontent.com/aspnet/Home/dev/dnvminstall.ps1'))}"

This will update dnvm itself, if you are still in Beta4. As of the beta5 or 6 version, a self-update command is available.

With dnvm updated, you should upgrade the dnu versions.

dnvm upgrade

should pull and install the most recent stable dnu. You can indicate a specific version also:

dnvm install 1.0.0-beta5-11904


dnvm install 1.0.0-beta5-11904 -r coreclr

if you want to choose/specify the clr type. You can also pull the most recente beta build available using

dnvm upgrade -Unstable

2- Update your global.json

In your solution’s global.json, update the sdk version value:

"sdk": {
"version": "1.0.0-beta5-11904"

3- Update packages in the projects

At this time, you can update package refs in your projects to Beta5 versions. One thing to consider, though, is that from Beta4 to Beta5, a lot of changes have occurred, especially in the namespaces for some class. For instance, pretty much every package set now has an *.Abstractions package with base classes and interfaces, separated from their implementations. I would at this point recommend excluding as many projects as it would make sense to and to update gradually, traversing the dependency chain. This is simply to reduce the amount of focus required to analyse output errors.

The main NuGet feed contains a large set of packages, but if you want to try using the latest and greatest, you can pull from the myGet feed. In order to do so, at the same level as your global.json and .sln file, add a .nuget/ folder and a NuGet.config file (similar to previous solution types). Add the following :

<?xml version="1.0" encoding="utf-8"?>
<!-- Add this repository to the list of available repositories -->
<add key="AspNet MyGet" value="https://www.myget.org/F/aspnetvnext/" />
<add key="nuget.org" value="https://www.nuget.org/api/v2/" />

I prefer having this in the solution, and committed to source control, as the entire team can share this definition in the solution context AND you won’t have to manually configure VS to use the repository (which would make it available to every solution you use, which you may or may not want).

3.1 Abstractions

Alot of things are changing, so some car is required, and code will require updates. The most common change that affected me were namespace changes (as mentioned in https://github.com/aspnet/Announcements/issues/14). Pretty much all of the repos have some Abstractions namespace associated to it, now. That’s actually a pretty good thing , in my opinion. If you are not tied to a specific implementation of abstract class or interface, the only reference you are required to have in class libs is the abstractions package. That makes use of DI more straight foward in the application project, which would be where the actual implementation is referenced. Other than there, you can always program against the abstraction and Mock as you wish in tests.

Some common abstraction refs I required where:


Microsoft.Framework.Caching.Abstractions Microsoft.Framework.Caching IExperationTrigger
Microsoft.Framework.FileProviders.Abstractions Microsoft.Framework.FileProviders IFileInfo, IDirectoryContents
Microsoft.Framework.DependencyInjection.Abstractions Microsoft.Framework.DependencyInjection IServiceCollection
Microsoft.Framework.Runtime.Abstractions Microsoft.Framework.Runtime ILibraryManager
Microsoft.AspNet.Http.Abstractions Microsoft.AspNet.Http IApplicationBuilder

3.2 – Configuration

Configuration classes have changes also (https://github.com/aspnet/Announcements/issues/25 , https://github.com/aspnet/Announcements/issues/26). There is a preference towards using ConfigurationModel classes / packages, to tie into the OptionsModel, instead of the previous Configuration (though configuration builder is in Configuration). Configuration can be loaded into IOption objects in DI by using the following code:

var applicationEnvironment = services.BuildServiceProvider().GetRequiredService<IApplicationEnvironment>();
var configurationPath = Path.Combine(applicationEnvironment.ApplicationBasePath, "config.json");

var configBuilder = new ConfigurationBuilder()
var configuration = configBuilder.Build();

The path to the config file should now be an absolute path as mentioned in https://github.com/aspnet/Announcements/issues/13

3.3 – _GlobalImport.cshtml

If you use _GlobalImport.cshtml for your views, the file name convention has changed to search for _ViewImports.cshtml (plural) as mentioned in https://github.com/aspnet/Announcements/issues/27 . That file should therefore be renamed.

3.4 – Configure()

For some unexplained reason, I was having trouble using Use* extension methods on IApplicationBuilder such as UseStaticFiles and UseCookieAuthentication. For some odd reason, the runtime shouldn’t load the UseMiddleware<>() method those extensions use.

Método não encontrado: 'Microsoft.AspNet.Http.Authentication.SignInContext Microsoft.AspNet.Authentication.AuthenticationHandler.get_SignInContext()'.



For some reason some packages were not playing nice. The workarounds I used:

For UseStaticFiles(), I just used what the extension actually does:

app.UseMiddleware<StaticFileMiddleware>(new StaticFileOptions());

For UseCookieAuthentication(), using Beta6 packages for Microsoft.AspNet.Authentication and Microsoft.AspNet.Authentication.Cookies solved the problem.

SemVer, Team Development and Visual Studio Solutions

Controlling dependency chains between libraries and services in complex software projects isn’t easy, though you can, to a certain point, get away with very simple solutions. I guess most teams end up applying some sort of versioning strategy to the software they develop, even if it’s saying that it’s a 1.0 at deployment time and stick with that. Like I said, you can get away with a lot, depending on your context. A lot of the projects I have worked in my career where single client and single installation applications. That pretty much meant the version of the software installed was whatever was built based on some source control revision. Match the deployed package to whatever revision it was created with and you had your version. This generally meant a single version across components that integrated the software.

As simple as this method is, it works and takes a load off in terms of the amount of things a small team has to focus on to release software. Still, not all projects can live with such a simple solution. I’d say that you can live with this solution as long as you can contain the whole installation as a single package or build result. Once you start mixing and matching and thinking about plugable architectures, or have large package dependency graphs with more than a couple nodes, things can get complicated…. and break easy due to incompatibility.

Continue reading

Wiring up an event-message handling service

Recently, in a project I’m working on, I needed to create a service that would allow me to monitor what was going on in the application. In this case, log file info wasn’t rich enough for the type of analysis required. We wanted a contextualized view of what was going on at any moment within this application, but also to measure key aspects of its use. In a sense, it would be an implementation of some of the control patterns referred to in Architecting Enterprise Solutions: Patterns for High-capability Internet-based Systems (Wiley Software Patterns Series)
, such as the System Monitor.

Lately I’ve been looking at and quite interested in CQRS. I like the concept and what it offers, especially when used with event sourcing. Unfortunately, I haven’t been able to apply it for many reasons, namely lack of experience with it and time to focus on learning how to do it, especially considering the need for features in a time constrained production application. For this particular case, though, I considered I could use some of the concepts to get to a solution that’ll do what I want.

Continue reading

Passwords “insonsas”

Um dos pontos fulcrais na segurança de um site é a gestão de passwords dos utilizadores.Sempre que nós como programadores implementamos um sistema de autenticação que recorre a nome de utilizador e password, temos de ter cuidados especiais. Vulnerabilidades que desconhecemos nos nossos sistemas podem comprometer a base de dados e tornar o seu conteúdo acessível.

Se considerar-mos os hábitos de utilizadores, nomeadamente a reutilização frequente de palavras passe, a descoberta de uma palavra passe num local poderá facilitar o acesso a dados do utilizador noutros locais e sistemas. Agentes maliciosos utilizam ataques para obter este tipo de informação devido ao seu valor. Ainda recentemente houve o ataque ao Linkedin, e a publicação da informação de passwords dos utilizadores. É portanto necessário tomar medidas, não só para preservar a segurança dos dados, mas garantir que o acesso a elas não crie novas vulnerabilidades.

Continue reading

Beginner’s Guide to PostgreSQL

Acabei de publicar um novo curso de iniciação às bases de dados relacionais em PostgreSQL no Udemy, um site de formação on-line. O curso está dividido em 3 módulos – introdução, criação e manipulação das estruturas de dados, e SQL. Actualmente, tem 18 lições em vídeo disponíveis, e muitas em produção.

O curso está em inglês, e espero que venha a ser bastante útil a muita gente de modo a entrar no mundo desta excelente base de dados.


I just finished publishing a new beginner’s course on PostgreSQL at Udemy, an online platform for learning. The course has 3 modules – an introduction to relational databases, data structures and manipulation finally SQL. Currently, the course has 18 vídeo lessons and the missing ones are currently in production.

The course is in english, and I hope it becomes very usefull to anyone wanting to enter the world of this amazing database system.

Conferência SerFreelancer

Dia 2 de Abril vou ter o prazer de participar como orador na “Conferência – Ser Freelancer em Portugal”, no IPJ de Aveiro. vai ser certamente um dia muito interessante em que vamos reunir freelancers de diversas áreas, especialmente quem está a começar, para falar dos vários aspectos inerentes ao trabalho como freelancer.

Vou estar na conferência a representar área da programação web e desenvolvimento de software. Tem piada que vem numa altura em que preparo-me para dar o salto do freelancing para a estrutura de empresa. De qualquer forma, não deixarei de partilhar os diversos aspectos da minha experiência como tal. Há sempre muito para dizer, e muitas questões a responder. Até lá, tenho que recuperar a voz!

Espero ver muito pessoal por lá. Se houver tópicos que alguem gostaria que abordasse em especial, deixa um comment!

Mais info em http://freelancerportugal.com/

FATAL: could not reattach to shared memory (key=…, addr=…): 487

FATAL: could not reattach to shared memory (key=276, addr=01F20000): 487

Este é um erro que aparenta aparecer em algumas instalações PostgreSQL em Windows, em especial depois de existir algum update do OS. Uma instalação minha teve este problema, com o erro a ser registado periodicamente nos logs do PostgreSQL. Infelizmente o erro é problemático para aplicações dependentes da base de dados, uma vez que ele interrompe conecções entre a aplicação e a base de dados. É causador de um tipico erro de .NET com mensagem pouco esclarecedora:

[SocketException (0x2746): An existing connection was forcibly closed by the remote host]
System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size) +232

Poderia ser de uma coneção externa, mas o pilha de chamadas tinha claramente a biblioteca NpgSQL – o provider PostgreSQL para .NET na lista. Não era uma conecção entre cliente e servidor, mas sim entre a aplicação e o serviço de base de dados (que é efectuado sobre TCP, mesmo estando na mesma máquina).

A solução é a actualização da instalação do serviço de base de dados – este caso passei do 8.4.0 para o 8.4.6. (a correcção deve ter sido introduzido no 8.4.1). Esta versão terá o patch para a correcção deste erro. A actualização é simples: para o serviço e correr o instalador mantendo os dados e configurações intactas (poderá ser necessário recolocar o serviço a arrancar pelo sistema utilizador LOCAL SYSTEM, se necessário).

Info sobre o erro ou patch: