Tag Archives: ASP.Net

Getting Started with ASP.Net 5 Nightly Builds on Windows

ASP.Net 5 is more than an update to ASP.Net, it is a dramatic rethinking of the .Net web stack. By dropping some of the baggage that has been with the framework since classic ASP, Microsoft has been able to greatly reduce the footprint of an ASP.Net application and created a more modular runtime that can be deployed to Windows, Mac, and Linux.

If you’d like to read a more complete breakdown of new features, Scott Guthrie’s excellent post announcing ASP.Net 5 is a good starting place.

As of April 2015, ASP.Net 5 is still in the beta. The easiest way to use it is to install the latest Visual Studio 2015 Community Technology Preview. But if you want to get features as the come available the best option is to install the new cross platform command line tools. These are the instructions for installing the latest ASP.Net tooling on Windows.

Installing dnvm

Because Visual Studio doesn’t run on Mac or Linux, a new set of tools needed to be created to use ASP.Net on those platforms. The ASP.Net team have been building a set of command line applications that lets users build ASP.Net projects with any editor.

ASP.Net 5 includes a new execution environment is called DNX. DNX bootstraps and runs your application, however it is not the CLR itself.

To install DNX you will need DNVM, the Dot Net Version Manager. You can download DNVM from the aspnet/home GitHub repo. This repo contains tools and samples to get you started, though some of the instructions don’t necessarily reflect the latest rapidly changes to the framework.

You will install DNVM by running the following in a command prompt.

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

This script will create a new .dnx directory under your %USERPROFILE%. It will contain a bin directory with the dnvm command.

Note: Originally the new ASP.Net runtime was code-named Project-K, so you may see references to tools that begin with the letter k (k, kvm, kpm). Those tools have been replaced by their DNX counterparts.

Adding DNX Nightly Builds NuGet Feed

You now have DNVM installed, but if you can’t yet install the latest nightly builds. The DNX is delivered as NuGet packages, and the nightly builds are served from a custom NuGet feed, https://www.myget.org/F/aspnetvnext/api/v2/. To add this feed to NuGet open %AppData%/NuGet/NuGet.config and change the contents to the following.

<?xml version="1.0" encoding="utf-8"?>
    <add key="AspNetVNext" value="https://www.myget.org/F/aspnetvnext/api/v2/" />
    <add key="nuget.org" value="https://www.nuget.org/api/v2/" />
  <disabledPackageSources />
    <add key="nuget.org" value="https://www.nuget.org/api/v2/" />

Installing the .Net Execution Environment (DNX)

Now that you have DNVM and you’ve configured NuGet you can install the DNX. To install the latest version open PowerShell or a command prompt and run:

dnvm upgrade

This will install a new runtime under %USERPROFILE%/.dnx/runtimes/ and add the bin directory of the new runtime to your PATH. The bin directory has two important commands

  • dnx – used run a .Net application under the DNX
  • dnu – Dot Net Utility used to perform tasks like building, installing packages, and more

Running a Sample Project

You should now be ready to run a sample project. New project scaffolding isn’t functional with DNX at the moment, so the best way to run an ASP.Net 5 project is to clone an existing project. The aspnet/home repo mentioned above has sample projects using the latest runtime, just make sure you’re looking in the dev branch.

The critial component to look for is the supported frameworks in the project.json file. The supported frameworks should be dnx451 and dnxcore50.

"frameworks": {
"dnx451": { },
"dnxcore50": { }

If you see aspnet50 or aspnetcore50 you’re looking at an old version from before the DNX rename.

So, clone the dev branch of the aspnet/home repo.Then, at the command line move to the HelloMvc folder and run the following command.

dnu restore

This is equivalent to restoring packages for a solution with NuGet in Visual Studio. In fact, under the covers it’s simply using the newest version of NuGet!

Now you’re ready to run the project. Still at the root of the HelloMvc folder simply run dnx . web and your project will begin running at http://localhost:5001 (as defined in the project.json).

D:\dev\aspnet-home\samples\HelloMvc> dnx . web

The output for the web command is pretty underwhelming. If you’d like to see a little more output upgrade Microsoft.AspNet.Server.WebListener in project.json to 1.0.0-beta5* and you’ll see something like the following.

D:\dev\uavdb\src> dnx . web
info : [Microsoft.Framework.DependencyInjection.DataProtectionServices] Userprofile is available. Using 'C:\Users\pnewhook\AppData\Local\ASP.NET\DataProtec
ion-Keys' as key repository and Windows DPAPI to encrypt keys at rest.
info : [Microsoft.Net.Http.Server.WebListener] Start
info : [Microsoft.Net.Http.Server.WebListener] Listening on prefix: http://lcalhost:5001/


It’s an exciting time to be an .Net developer. The latest version of ASP.Net framework is open source and it’s possible to follow the team’s development live. While you could install the latest Visual Studio 2015 CTP, you won’t be able to try new features as they’re released. There will likely be a big announcement at Build on April 29th. The command line tools are probably the way to go for now, and they have the added bonus of working cross platform.

There are three commands you’ll run into:

  • dnvm – the .Net Version Mananger for installing the DNX
  • dnu – the .Net Utility for managing projects and packages
  • dnx – the Execution Environment executable for running your projects

A core tenent of the DNX is to make everything a NuGet package. While the framework is under development, and potentially beyond, nightly builds are served through a MyGet feed that needs to be configured in your NuGet install.

After you’ve taken these steps you’ll be ready to experiment with ASP.Net 5 feature hot off the press.

Background Tasks in ASP.Net with HostingEnvironment.QueueBackgroundWorkItem

.Net 4.5.2 was released on May 5th, you can read all about it on the .Net Framework Blog or MSDN Library release notes. It includes HostingEnvironment.QueueBackgroundWorkItem, which lets you queue background threads from within an ASP.Net web application. This is useful for long running tasks that don’t need to complete before returning a response to the user.


ASP.Net MVC SelectList, SelectedValue, and DropDownListFor

Unintuitive framework features usually end up as highly rated questions on StackOverflow because everyone is running into the same problem with a commonly used feature. This question on about drop-down lists in ASP.Net MVC with  59 votes, 38 favourites and numerous partially correct answers should prove that the lowly drop-down list is one of the most baffling features in ASP.Net MVC. This article will be an overview of how to use drop-down lists, setting a selected item, and issues you’ll run into on a strongly typed view. The following code applies to the Razor view engine and have been written for MVC 4.

Sample Model

For the sake of this article, assume we have two classes, Movie and Director. In our application we want to add new movies, and select directors from a drop-down list. The classes are structured as follows.

    public class Movie
        public int Id { get; set; }
        public string Title { get; set; }
        public virtual Director Director { get; set; }
        public virtual int DirectorId { get; set; }
    public class Director
        public int Id { get; set; }
        public string Name { get; set; }

Html.DropDownList vs Html.DropDownListFor

To add the drop-down markup to your .cshtml page you could of course simply write out a select element by hand, but then you lose out on validation. MVC provides HTML helpers for generating common HTML elements. For an HTML select element you have two choices: Html.DropDownList and Html.DropDownListFor. The difference is the way they reference the name attribute of the resulting HTML element. DropDownList takes as it’s first argument a string that will be turned into the form field. So the call

@Html.DropDownList("director", directorList) //assume directorList is an IEnumerable of SelectListItem to create options from

Will result in an html element that looks like this.

<select id="director" name="director">...</select>

The problem with this approach is if you change the name of the property on your model from ‘director’ to ‘auteur’ you won’t get compile time checking and your form will no longer work with model binding. Html.DropDownListFor was introduced in MVC 2 and allows binding to strongly typed views. The first argument should be a lambda function that returns the model property you want the control to bind to. So in our case if the view-model includes a property DirectorId we can create a drop-down list with the code

@Html.DropDownListFor(viewModel => viewModel.DirectorId, directorList)

Which generates the following html

<select id="DirectorId" name="DirectorId">

Now if we change the name of the Director property our build will break because the lambda expression will be invalid.Note that we’re using DirectorId instead of a Director object because we likely want to store the id in a foreign key.

Populating Drop-Down List Options

To populate a drop-down we need to pass the HTML helper an IEnumerable. This is easily created by making a SelectList object in your controller, and passing it in via a view-model.

        public ActionResult Index()
            var directors = new Collection
                    new Director {Id = 1, Name = "David O. Russell"},
                    new Director {Id = 2, Name = "Steven Spielberg"},
                    new Director {Id = 3, Name = "Ben Affleck"}
            var selectList = new SelectList(directors, "Id", "Name");
            var vm = new ViewModel {DirectorSelectList = selectList};
            return View(vm);

I’ve created a collection of directors and passed it into the SelectList constructor. This collection could have been queried from a database, this sample was simply for demonstration. I’ve also supplied which fields should be the drop-down value (Id) and display text (Name). If I omitted those additional parameters the ToString method would be called on the each object to generate the item.
My drop-down list now looks like this.
Populated drop-down list.
If you don’t like passing in a SelectList as part of your model you could pass in the IEnumerable and construct the SelectList in the view, but I prefer putting as little code in the view as possible.

Setting a Default Value of the Drop-Down

And here is where things start falling apart. The aforementioned StackOverflow question highlighted how hard it is to set a default value on a drop-down. The problem stems from poor documentation for DropDownListFor. There is an overload that takes a fourth parameter called selectedValue which is an object to set the value. Theoretically I should be able to have the following the default to the option with an id of 3

var selectList = new SelectList(directors, "Id", "Name", new {id = 3});

However the first value, David O. Russell, is still selected in the view. And as good a job as he did in Silver Linings Playbook, I want to default to Ben Affleck. The problem is by using a strongly typed view, MVC is trying to bind my DirectorId field to the DirectorId property of my model. And because I didn’t populate the DirectorId field of my view-model, MVC is defaulting the drop-down to the first value.

My solution is to set the DirectorId property of the viewmodel to the value I want defaulted as follows.

var vm = new ViewModel {DirectorSelectList = selectList, DirectorId = 3};

Then when my view is templated the correct option is selected.
Default value selected in a drop-down