Deploy ASP.NET 5 Apps to Docker on Azure

NOTE: This post is part 4 of a series on developing and deploying cross-platform web apps with ASP.NET 5:

  1. Develop and Deploy ASP.NET 5 Apps on Mac OS X
  2. Develop and Deploy ASP.NET 5 Apps on Linux
  3. Deploy ASP.NET 5 Apps to Docker on Linux
  4. Deploy ASP.NET 5 Apps to Docker on Azure (this post)

Download instructions and code for this post here: https://github.com/tonysneed/Deploy-AspNet5-Azure-Docker.

Over the past few years, a phenomenon known as “the Cloud” has appeared.  While the term is rather nebulous and can mean a number of different things, with regard to business applications it generally refers to a deployment model where apps run on servers provided by a third party that rents out computational resources, such as CPU cycles, memory and storage, on a pay-as-you-go basis.  There are different service models for cloud computing, including infrastructure (IaaS), platform (PaaS) and software (Saas).  In this post I’ll focus on the first option, infrastructure, which allows you set up Linux virtual machines where you can deploy Docker images with your ASP.NET 5 apps and all their dependencies.  There are a number of players in the IaaS market, including Amazon Elastic Compute Cloud (EC2), Google Compute Engine (GCE) and Microsoft Azure, but I’ll show you how to deploy a Dockerized ASP.NET 5 app to Azure using Docker Hub, GitHub and the Docker Client for Windows.

Azure-logo

So let’s start out with GitHub.  The reason we’re starting here is that you can set up Docker Hub to link to a GitHub repository that contains a Dockerfile.  When you push a commit to the GitHub repo, Docker Hub will build a new image for your app.  What makes this a nice approach is that you get automated builds with continuous integration, and it’s easy to pull images from Docker Hub and run them on the Linux VM on Azure.

To demonstrate this I’ve created two repositories on GitHub.  The first one is a simple console app: https://github.com/tonysneed/AspNet5-ConsoleApp.  It contains three files: project.json, program.cs, and a Dockerfile.

FROM microsoft/aspnet:1.0.0-beta4

COPY . /app

WORKDIR /app

RUN ["dnu", "restore"]

ENTRYPOINT ["dnx", ".", "run"]

The second is a simple web app: https://github.com/tonysneed/AspNet5-WebApp.  It also contains three files: project.json, startup.cs and a Dockerfile.

FROM microsoft/aspnet:1.0.0-beta4

COPY . /app

WORKDIR /app

RUN ["dnu", "restore"]

EXPOSE 5004

ENTRYPOINT ["dnx", ".", "kestrel"]

Next, you’re going to need to set up an account on Docker Hub.  It’s free, and you can log in using your GitHub credentials.  Then add an “Automated Build” which links to a GitHub repo.

dockerhub-auto-build

By far the easiest way to create a new Docker virtual machine in Azure is to use the Visual Studio 2015 Tools for Docker.  Otherwise, you’re going to need to create the certificates manually and upload them to the Azure portal when adding the VM Extension for Docker.  When I attempted this on the Azure portal, installing the Docker extension hung.  But I didn’t experience a problem using the VS Docker Tools to create a Docker VM on Azure.

You’ll have to go through a few steps in Visual Studio before you can create the VM on Azure.  First create a new Web Project, selecting one of the ASP.NET 5 templates.  For our purposes, an empty web project will do just fine.

vs-new-proj-empty

Then right-click on the generated project and select “Publish” from the context menu.  Under Profile, select Docker Containers, at which point you’ll be presented with a list of existing Azure Docker virtual machines.  Simply click the New button to create a new Linux VM with Docker installed.

vs-docker-vms

Enter a unique DNS name, together with an admin user name and password.  You can check the option to auto-generate Docker certificates, and the wizard will create the required certificates, configure Docker on the VM to use them, and copy the certificate and key files into the “.docker” folder under your user profile, so that you can use the same certificates to create additional virtual machines on Azure or elsewhere.

create-docker-vm-azure

I highly encourage you to check out the video series on Docker for .NET Developers, where you can learn more about the VS Docker tools, which can also generate a Dockerfile and build scripts for publishing an app to a Docker container on the VM you created on Azure.

What’s cool is that installing the tools will also give you the docker client for Windows, which you can use from a command prompt to build and run Docker images on the remote VM.  You can start with the following command to display basic information, supplying the host name and port number specified when you created the VM.

docker --tls -H tcp://linux-docker.cloudapp.net:2376 info

docker-info

To keep from having to include the remote host address with every command, you can set the DOCKER_HOST environment variable.

set docker_host=tcp://linux-docker.cloudapp.net:2376

You can now use the docker client on the command line to run packages.  If the package is not already installed locally, it will be pulled from Docker Hub.  The following, for example, will simply print “Hello from Docker” to the console, along with a few other bits of information.

docker --tls run -t hello-world

You can also run Docker images which you have pulled into Docker Hub from GitHub.  The following command will run an ASP.NET 5 console app that prints “Hello World” to the console.

docker --tls run -t tonysneed/aspnet5-consoleapp

If you want to get the latest version of the image from Docker Hub, simply execute a pull command.

docker --tls pull tonysneed/aspnet5-consoleapp

The following command will run a daemonized web app, mapping port 80 on the VM to port 5004 on the container.

docker --tls run -t -d -p 80:5004 tonysneed/aspnet5-webapp

This command will return a big long number, which you can use to output the container logs.  The following will display “Started” if successful, otherwise it will list runtime exceptions.

docker --tls logs f2de092f14b67590ae4dc08cd3a453a28271de0a8f27e6d80ec356cbc5151d43

To list running processes, execute the ps command, which will list all the running containers.

docker --tls ps

docker-ps

Now you can just open a browser with a URL that contains the fully qualified DNS name for the VM in Azure: http://linux-docker.cloudapp.net.

ie-webapp-azure

Congratulations!  You have successfully deployed an ASP.NET 5 web app to a Docker container running on a Linux virtual machine in Azure.  More importantly, you have configured Docker Hub to re-build the image whenever a commit is pushed to a linked GitHub repo, and you know how to pull that Docker image into the VM on Azure from the command line using the Docker Client for Windows.  The Visual Studio Tools for Docker make it easy to create the Linux VM on Azure and generate certificates which you can use to create other Docker VM’s and which you can copy to other machines (both Windows and non-Windows) so that you can run Docker commands from there.  All in all, a sweet story indeed.

Posted in Technical | Tagged , , , , , | Leave a comment

Deploy ASP.NET 5 Apps to Docker on Linux

NOTE: This post is part 3 of a series on developing and deploying cross-platform web apps with ASP.NET 5:

  1. Develop and Deploy ASP.NET 5 Apps on Mac OS X
  2. Develop and Deploy ASP.NET 5 Apps on Linux
  3. Deploy ASP.NET 5 Apps to Docker on Linux (this post)
  4. Deploy ASP.NET 5 Apps to Docker on Azure

Download instructions and code for this post here: https://github.com/tonysneed/Deploy-AspNet5-Docker.

Docker is a technology for Linux that enables you to deploy applications inside of containers, which are analogous to virtual machines, but which are much more lightweight because multiple containers on a VM all share the same operating system and kernel.

docker

While lightweight containers are a cool idea, what makes Docker a killer app is that docker images are built from a simple script, called a DockerFile, that can be layered on top of other definitions and which lists all the components needed to run your application.  Images based on a Dockerfile can be pushed to an online repository called Docker Hub, where they can be built automatically whenever commits are pushed to a linked repository on GitHub.  And it’s super easy to pull images from Docker Hub and run them on a Linux virtual machine, either locally or in the cloud.

In this post I’ll describe how to deploy an ASP.NET 5 app to a docker container running on a local virtual machine with Linux Ubuntu.  Note that you’re not actually going to install ASP.NET 5 directly on the virtual machine.  Instead, you’ll build a docker image that already comes with ASP.NET 5.  Virtualization software, such as Parallels, allows you to create a number of snapshots, so that you can easily revert the VM to an earlier state.

ubuntu-snapshots

First you’ll need to install Docker on your Ubuntu VM.  We’ll install it from its own package source.  Just open a Terminal and paste the following commands, one by one.

sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys 36A1D7869245C8950F966E92D8576A8BA88D21E9
sudo sh -c "echo deb https://get.docker.com/ubuntu docker main > /etc/apt/sources.list.d/docker.list"
sudo apt-get update
sudo apt-get install lxc-docker

 

To verify the Docker installation, enter: docker –version. You should see the Docker version and build number.

docker-version

For convenience you’ll want to set things up so you don’t have to prefix docker commands with sudo for elevated privileges.

sudo groupadd docker
sudo gpasswd -a parallels docker
sudo service docker restart
newgrp docker

To verify docker root privileges enter: docker run –help.  Then just to be sure all is well, you can run the docker hello-world image, which will pull down and run a basic image from Docker Hub.

docker run hello-world

You should see the following output in the Terminal.

docker-hello-world

You can then “dockerize” the Hello World ASP.NET 5 console app.  Start by creating a ConsoleApp directory and placing there two file from the AspNet Console sample repo on GitHub: project.json and program.cs.  In this same directory, create a file called DockerFile, with the following content:

FROM microsoft/aspnet:1.0.0-beta4
COPY . /app
WORKDIR /app
RUN ["dnu", "restore"]

ENTRYPOINT ["dnx", ".", "run"]

This will create a new Docker image based on the AspNet 1.0.0-beta4 image on Docker Hub, which will copy files in the current folder to an app folder in the container.  When the container is built, the dnu restore command will download required dependencies.  The entry point is defined as dnx . run, which will invoke the code in Program.Main when the container is run.

Open a Terminal at the ConsoleApp directory and execute the following command (remember to include the trailing dot):

docker build -t consoleapp .

You can verify that the container exists by entering: docker images.

docker-images

Lastly, run the container.  You should see “Hello World” printed to the Terminal window.

docker run -t consoleapp
 

Console apps are well-suited for running tasks on a server, but more often you’ll use ASP.NET 5 to run web apps. The AspNet repo on GitHub has a HelloWeb sample, where you can grab two files: project.json and startup.cs.

Create a directory called WebApp containing these two files, as well as an empty directory called wwwroot, then add a file called Dockerfile with the following content:

FROM microsoft/aspnet:1.0.0-beta4
COPY . /app
WORKDIR /app
RUN ["dnu", "restore"]

EXPOSE 5004
ENTRYPOINT ["dnx", ".", "kestrel"]

Open a terminal at the WebApp directory and build the docker image.

docker build -t webapp .
 

Then run the container, indicating with the –d switch that you want a daemonized app running in the background that does not interact with the Terminal.  You’re also mapping the VM’s port 5004 to that of the container.

docker run -t -d -p 5004:5004 webapp

This will execute the container entry point, which is to start the Kestrel web server on the indicated port.  You’ll get back a container id, a big long number which you can use to see the log output.  This will display log messages, including runtime error information.  You can also verify that the container successfully started by entering docker ps, which lists running containers.

docker-web-run

Open a browser and enter the address: http://localhost:5004.

linux-web-welcome[4]

And that is how you can deploy ASP.NET 5 apps to docker containers on a Linux virtual machine.  For the next part of this series, I’ll show you how you can push your image to Docker Hub, where it can be pulled into a Linux virtual machine you’ve provisioned on Microsoft Azure.

Posted in Technical | Tagged , , , , | Leave a comment

Develop and Deploy ASP.NET 5 Apps on Linux

NOTE: This post is part 2 of a series on developing and deploying cross-platform web apps with ASP.NET 5:

  1. Develop and Deploy ASP.NET 5 Apps on Mac OS X
  2. Develop and Deploy ASP.NET 5 Apps on Linux (this post)
  3. Deploy ASP.NET 5 Apps to Docker on Linux
  4. Deploy ASP.NET 5 Apps to Docker on Azure

Download instructions and code for this post here: https://github.com/tonysneed/VsCode-AspNet5-Linux.

It is now possible to develop and deploy an ASP.NET application on Linux.  In case you haven’t heard, Microsoft’s CEO, Satya Nadella, has proclaimed, “Microsoft loves Linux.”

Microsoft-Hearts-Linux

The reason is simple: Linux is vital to Microsoft’s cloud service, Azure.  But more important, in embracing cross-platform initiatives, such as Core CLR, there is an acknowledgement that we no longer live in a world with a single dominant platform, and that developers not only need to write code that runs on multiple platforms, but that they should be comfortable writing apps with an IDE that will run on multiple platforms. For most of us, that IDE will be Visual Studio Code.

In this blog post I’ll show you how to set up a Linux virtual machine to run VS Code, so that you can both develop and deploy ASP.NET 5 applications.  If you’re on a Mac with Parallels, creating a virtual machine running Ubuntu Linux is just a few clicks away.

parallels-linux-vm

Once you’ve stood up your shiny new Linux VM, follow these instructions to install VS Code.  I found it convenient to create a VSCode folder under Home and extract the contents of VSCode-linux-x64.zip there.  Then you can create a link that will launch VS Code from the Terminal, so that you can type code . to start editing files in VS Code at that location.

sudo ln -s /home/parallels/VSCode/Code /usr/local/bin/code

Next you’ll need to follow these instructions to install ASP.NET 5 on Linux.  The first step is to install Mono.

sudo apt-key adv --keyserver keyserver.ubuntu.com --recv-keys 3FA7E0328081BFF6A14DA29AA6A19B38D3D831EF
echo "deb http://download.mono-project.com/repo/debian wheezy main" | sudo tee /etc/apt/sources.list.d/mono-xamarin.list
sudo apt-get update
sudo apt-get install Mono-Complete

Second, you’ll need to install libuv, which is used by Kestrel for hosting ASP.NET 5 apps on Linux.

sudo apt-get install automake libtool curl
curl -sSL https://github.com/libuv/libuv/archive/v1.4.2.tar.gz | sudo tar zxfv - -C /usr/local/src
cd /usr/local/src/libuv-1.4.2
sudo sh autogen.sh
sudo ./configure
sudo make
sudo make install
sudo rm -rf /usr/local/src/libuv-1.4.2 && cd ~/
sudo ldconfig

Lastly, you’ll need to install the DotNet Version Manager, which is used to select and configure versions of the .NET runtime for hosting ASP.NET 5 apps.

curl -sSL https://raw.githubusercontent.com/aspnet/Home/dev/dnvminstall.sh | DNX_BRANCH=dev sh && source ~/.dnx/dnvm/dnvm.s
source /home/parallels/.dnx/dnvm/dnvm.sh
dnvm
dnvm upgrade

Entering dnvm will then bring up the version manager, which allows you to select and configure different versions of the ASP.NET 5 runtime.

dnvm-linux

To see which versions are installed, enter: dnvm list.

dnvm-list-linux

Next, you’ll create a directory and fire up VS Code to create your first ASP.NET 5 app.  We’ll start with a Hello World console app! The quickest approach is to grab two files from the ConsoleApp folder for the AspNet Samples Repo: project.json and program.cs.

Here is project.json for the console app, which lists the dependencies you’ll bring in.

{
    "dependencies": {

    },
    "commands": {
        "ConsoleApp": "ConsoleApp"
    },
    "frameworks": {
        "dnx451": { },
        "dnxcore50": {
            "dependencies": {
                "System.Console": "4.0.0-beta-*"
            }
        }
    }
}

And here is program.cs, which simply prints “Hello World” to the console.

using System;

public class Program
{
    public static void Main()
    {
        Console.WriteLine("Hello World");
    }
}

Editing program.cs in Visual Studio Code looks like this:

vscode-console-linux

To launch the app, open a Terminal at the ConsoleApp directory, then restore the dependencies and execute the program.

dnu restore
dnx . run

You should see “Hello World” printed to the Terminal window.

linux-console-helloworld

Console apps are well-suited for running tasks on a server, but more often you’ll use ASP.NET 5 to run web apps. The AspNet repo on GitHub has a HelloWeb sample, where you can grab two files: project.json and startup.cs.

Here is the project.json file for the web app.  Notice the “kestrel” command for starting an HTTP listener on Mac OS X and Linux.

{
    "version": "1.0.0-*",
    "dependencies": {
        "Kestrel": "1.0.0-*",
        "Microsoft.AspNet.Diagnostics": "1.0.0-*",
    },
    "commands": {
        "kestrel": "Microsoft.AspNet.Hosting --server Kestrel --server.urls http://localhost:5004"
    },
    "frameworks": {
        "dnx451": { },
        "dnxcore50": { }
    }
}

Here is the startup.cs file, which configures the pipeline with an endpoint for displaying a welcome page.

using Microsoft.AspNet.Builder;

namespace HelloWeb
{
    public class Startup
    {
        public void Configure(IApplicationBuilder app)
        {
            app.UseWelcomePage();
        }
    }
}

To start the web server, restore dependencies and then enter the kestrel command.  VS Code also allows you to execute commands from the command palette, but this doesn’t yet work on Linux.

dnu restore
dnx . kestrel

Then open a browser and enter the address: http://localhost:5004. You’ll see a message in the Terminal stating the web server has started. To end it, press Enter.

linux-web-welcome

Aside from running the console and web Hello World samples, you’re going to want to develop your own applications based on templates you’d find in Visual Studio on Windows.  To get a similar experience, you can install Yeoman, which scaffolds various kinds of ASP.NET 5 apps, such as MVC 6 or Web API (which is technically now part of MVC 6). To install Yeoman you’ll need the Node Package Manager, which you can download and install using the apt-get command.

sudo apt-get install nodejs-legacy npm

Once you have Node installed, you can use it to install Yeoman, the asp.net generator, grunt and bower – all in one fell swoop.

sudo npm install -g yo grunt-cli generator-aspnet bower

Having installed Yeoman, you can then navigate to a directory in Terminal where you’d like to create your new app.  Then execute:

yo aspnet

This brings up a number of choices.  For example, you can select Web API Application, which then scaffolds the standard Web API app with a ValuesController. If you run dnu restore and dnx . kestrel, as you did with the sample web app, you can browse to the following URL to get back JSON values: http://localhost:5001/api/values.

And that is how you can both develop and deploy ASP.NET 5 apps on Linux.  For the next part of this series, I’ll show you how to deploy an ASP.NET 5 app to a Docker container on Linux.

Posted in Technical | Tagged , , , | 8 Comments

Develop and Deploy ASP.NET 5 Apps on Mac OS X

NOTE: This post is part 1 of a series on developing and deploying cross-platform web apps with ASP.NET 5:

  1. Develop and Deploy ASP.NET 5 Apps on Mac OS X (this post)
  2. Develop and Deploy ASP.NET 5 Apps on Linux
  3. Deploy ASP.NET 5 Apps to Docker on Linux
  4. Deploy ASP.NET 5 Apps to Docker on Azure

Download instructions and code for this post here: https://github.com/tonysneed/VsCode-AspNet5-OsX.

The day has arrived when you can both develop and deploy an ASP.NET application on an Apple Mac.  Notice I said, develop, not just deploy.  For that you’re going to need either a souped up text editor (such as Sublime Text, Brackets, Atom, Emacs or Vim) together with OmniSharp for intellisense, or you’ll want to use Visual Studio Code, the new cross-platform IDE from Microsoft that uses OmniSharp with Roslyn and provides Git integration for version control, plus limited debugging support.  To get started setting up and using VS Code, check out the docs.

So why would you want to forsake full-blown Visual Studio running on Windows for a stripped down version running on OS X?

I’m not saying you should.  VS Code is still in preview and, at the time of this writing, lacks support for debugging ASP.NET 5 apps (although it’s promised soon).  And Microsoft offers the Community Edition of Visual Studio for free.  It’s more a matter of getting out of your comfort zone and trying something different.  It’s also about using different tools for different things.  I happen to use a MacBook Air, mainly because of the amazing hardware, and I like how iCloud syncs everything with my iPhone and iPad.  And while I have no problem running Windows in a virtual machine on my Mac using Parallels, it’s nice to hack together a web app for ASP.NET 5 on my Mac without having to fire up Win 8 and load Visual Studio, both of which gobble up a chunk of RAM. Note that while you’ll need to own a Mac, if you’re running Parallels you can create a virtual machine that runs OS X, which will allow you to create snapshots in time, so that you can easily revert to an earlier state.

osx-snapshots

To develop ASP.NET 5 apps on a Mac, we’ll start with these instructions for installing VS Code. (By the way, VS Code can also be used for TypeScript and Node.js development.) In order to launch VS Code from a Terminal window, you’ll want to add some entries to your .bash_profile file.  You can check to see if the file already exists by changing to your root directory with cd ~/, and then entering ls –a, to list all files, including hidden ones (those are the ones with names starting with a dot).  If .bash_profile does not exist, enter: touch .bash_profile.  Otherwise if it does exist, enter open -e .bash_profile, and it will open in TextEdit.  Then add the following text to the file:

code () {
if [[ $# = 0 ]]
then
open -a "Visual Studio Code"
else
[[ $1 = /* ]] && F="$1" || F="$PWD/${1#./}"
open -a "Visual Studio Code" --args "$F"
fi
}
export PATH="~/npm-global/bin:$PATH"
source dnvm.sh

This will allow you to launch VS Code at any folder from the terminal window simply by typing code ., so that you can start editing files contained in that folder.  It also sets up the Node package manager to install Yeoman and makes the DotNet Version Manager for every Terminal session (see below).

Next, you’ll want to install ASP.NET 5 on Mac OS X, so that you can deploy web apps on a Mac.  The docs list instructions for installing ASP.NET 5 on Mac OS X, which can be summarized as follows:

  • Install Homebrew with the command line developer tools
  • Tap the ASP.NET 5 repo from Homebrew
  • Install the DotNet Version Manager

ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
brew tap aspnet/dnx
brew install dnvm

dnvm upgrade
source dnvm.sh

After this, entering dnvm will bring up the version manager, which allows you to select and configure different versions of the ASP.NET 5 runtime.

dnvm-launch

To see which versions are installed, enter: dnvm list.

dnvm-list

Next, you’ll create a directory and fire up VS Code to create your first ASP.NET 5 app.  We’ll start with a Hello World console app! The quickest approach is to grab two files from the ConsoleApp folder for the AspNet Samples Repo: project.json and program.cs.

Here is project.json for the console app, which lists the dependencies you’ll bring in.

{
"dependencies": {

},
"commands": {
"ConsoleApp": "ConsoleApp"
},
"frameworks": {
"dnx451": { },
"dnxcore50": {
"dependencies": {
"System.Console": "4.0.0-beta-*"
}
}
}
}

And here is program.cs, which simply prints “Hello World” to the console.

using System;

public class Program
{
public static void Main()
{
Console.WriteLine("Hello World");
}
}

Editing program.cs in Visual Studio Code looks like this:

vscode-console

To launch the app, open Terminal at the ConsoleApp directory, then restore the dependencies and execute the program.

dnu restore
dnx . run

You should see “Hello World” printed to the Terminal window.

mac-console-hello-world

Console apps are well-suited for running tasks on a server, but more often you’ll use ASP.NET 5 to run web apps. The AspNet repo on GitHub has a HelloWeb sample, where you can grab two files: project.json and startup.cs.

Here is the project.json file for the web app.  Notice the “kestrel” command for starting an HTTP listener on Mac OS X and Linux.

{
"version": "1.0.0-*",
"dependencies": {
"Kestrel": "1.0.0-*",
"Microsoft.AspNet.Diagnostics": "1.0.0-*",
},
"commands": {
"kestrel": "Microsoft.AspNet.Hosting --server Kestrel --server.urls http://localhost:5004"
},
"frameworks": {
"dnx451": { },
"dnxcore50": { }
}
}

Here is the startup.cs file, which configures the pipeline with an endpoint for displaying a welcome page.

using Microsoft.AspNet.Builder;

namespace HelloWeb
{
public class Startup
{
public void Configure(IApplicationBuilder app)
{
app.UseWelcomePage();
}
}
}

To start the web server, restore dependencies and then enter the kestrel command.

dnu restore
dnx . kestrel

VS Code also allows you to execute commands from the command palette, which you can bring up by typing ⇧⌘P.  From there enter a command listed in the “commands” section of project.json, for example, “kestrel”.

vscode-command-kestrel

Then open a browser and enter the address: http://localhost:5004. You’ll see a message stating the web server has started. To end it, press Enter.  If it does not stop, open another terminal to kill the process: ps {To see a list of PIDS} kill -9 {PID #}.

mac-web-welcome

Aside from running the console and web Hello World samples, you’re going to want to develop your own applications based on templates you’d find in Visual Studio on Windows.  To get a similar experience, you can install Yeoman, which scaffolds various kinds of ASP.NET 5 apps, such as MVC 6 or Web API (which is technically now part of MVC 6). To install Yeoman you’ll need the Node Package Manager, which you can download and install from here.  Once you have Node installed, you can use it to install Yeoman, the asp.net generator, grunt and bower – all in one fell swoop.

sudo npm install -g yo grunt-cli generator-aspnet bower

Having installed Yeoman, you can then navigate to a directory in Terminal where you’d like to create your new app in a child directory.  Then execute:

yo aspnet

This brings up a number of choices.  For example, you can select Web API Application, which then scaffolds the standard Web API app with a ValuesController. If you run dnu restore and dnx . kestrel, as you did with the sample web app, you can browse to the following URL to get back JSON values: http://localhost:5001/api/values.

And that is how you can both develop and deploy ASP.NET 5 apps on Mac OS X.  For the next part of this series, I’ll show you how to do the same on Linux.

Posted in Technical | Tagged , , , | 3 Comments

Remember RIA Services? Trackable Entities Can Fill the Void

Anyone remember WCF RIA Services?  It was a great idea: simplify n-tier development with a combination of libraries and tooling. Take something which is inherently difficult, namely data-centric web services consumed by rich clients, and make it easier.  Provide a client library that performs change-tracking without dependence on Entity Framework, and a service library that can persist batch updates.  But more importantly, provide an extension to Visual Studio that generates entities based on a data model and templates for scaffolding query and update operations on the server.

Ah, but the devil is in the details.  The fatal flaw was coupling it to Silverlight.  When Silverlight bit the dust, so did RIA Services.  And it was also coupled to Windows Communication Foundation, which has declined in popularity since the arrival of ASP.NET Web API.  Another problem was the implementation, which had a lot of magic glue that was not well documented (for example, project linking and code projection).

What troubles me, however, is not that RIA Services landed in the dustbin of history – which happens all the time in the world of technology – but that it wasn’t replaced by something new and better.  We should be learning from the mistakes of the past to forge a new and better future.

So what to do about it?  Gone are the days when we can sit back and complain.  This is an era when open source has come into its own, when the infrastructure and tools are in place for developers all over the world to join together to make stuff happen.  And that’s what Trackable Entities is all about.  It’s a community effort to reduce the needless pain required to build n-tier applications with RESTful services using Entity Framework, which target any .NET client (including iOS and Android via Xamarin) and implement repository and unit of work patterns with dependency injection.

And so it is with great pleasure that I’m announcing that the Trackable Entities project has moved, from its former home on CodePlex, over to GitHub.  Why GitHub?  Suffice it to say that Microsoft has moved its important projects over to GitHub (such as ASP.NET, Core CLR, TypeScript and Roslyn).  It’s where all the cool kids are doing open source, and it has amazing tools for distributed version control and collaboration. Oh, and there’s support for Git in Visual Studio 2013 and GitHub integration for Visual Studio 2015.

GitHub also makes it easy to build online documentation.  So I’ve created a home page for Trackable Entities on GitHub which includes getting started tutorials and how-to videos (hosted on YouTube), as well as tips for debugging and ways you can contribute to the project.  Here is the URL for the Trackable Entities documentation:

http://tonysneed.github.io/trackable-entities

So what makes Trackable Entities a viable successor to RIA Services?

To sum it up: Trackable Entities gives you just the right amount of help, without too much hand-holding or behind the scenes magic.  The client library is decoupled from the service, because all it does is set a state property: Unchanged, Added, Modified, Deleted.  That’s it really, aside from a few other helper methods.  The service library does one thing: read the state property and tell Entity Framework about it.

Secondly, there is entity code-generation based on customizable T4 templates.  These templates are used by other tools, such as the Add Entity Data Model wizard or the EF Power Tools.  But you can tweak them to your heart’s content.  There are templates for separate client / server entities, as well as shared entities, which target either .NET 4.5 or greater, or Portable Class Libraries, for compatibility across desktop and mobile platforms.

select-entities-page1

select-entities-page2

Thirdly, the Visual Studio extension for Trackable Entities provides a set of multi-project templates for creating a Visual Studio solution that includes projects for services (WCF or Web API, Repository and Unit of Work), entities (client, service or shared) and a console client (there is also a sample app which includes a WPF client using the MVVM pattern).

This is a HUGE time saver. All of the NuGet packages are installed by the template, and all the cross-project references have been set. And there is also a set of Visual Studio item templates for adding WCF services, Web API controllers, and all the classes you need to implement Repository and Unit of Work patterns.

Can’t wait to get started?  Check out these how-to videos, in which you can see me use Trackable Entities to create an n-tier application from scratch in less than 15 minutes!

One of the goals I’ve had for Trackable Entities is for it to serve as a learning tool. N-tier development is just plain hard.  But mainly it’s hard to avoid certain pitfalls in your implementation, like sending unchanged entities across the wire, failing to handle cyclical references, or not making proper use of async and await in your services.  The nice thing about the generated projects is that you can see how n-tier is done right, and you can use it to learn a set of best practices for building services that perform queries and updates in a disconnected, scalable fashion.

If you’d like to contribute to the project, check out the page in the online documentation on Contributing.  There you’ll find links to video tutorials on both Git and GitHub, as well as tips on reporting bugs and submitting good pull requests.

Happy coding!

Posted in Technical | Tagged , , , | Leave a comment

Software Development Guidelines to Live By

Not too long ago I posted a tweet that immediately went viral. (OK, it’s all relative – to me 66 retweets and 120 favorites is viral.)  It referred to Microsoft’s Engineering Guidelines for contributing to its open-source repository on GitHub for the next version of its web development platform, ASP.NET 5.

eng-guidelines

You may be familiar with other C# Coding Guidelines.  And generally I’m a huge fan of picking a set of guidelines, making necessary adjustments, and sticking to them as a team.  But what I appreciate about the ASP.NET 5 guidelines is that they not only cover coding guidelines, but also include other vital aspects of software development, such as source code management, product planning and issue tracking.

One of the first things listed is the guidelines for submitting pull requests and a description of how they are reviewed and approved (using an emoticon!).  Their Git branching strategy is also described, as well as the solution and project folder structure and the assembly naming pattern.  It’s notable that xUnit is used for all testing and is indicative that xUnit has now supplanted both MSTest and NUnit as the preeminent testing platform.  (In other words, just use it.)  It’s also worth noting that to use xUnit you no longer need to install a Visual Studio extension – adding the xUnit NuGet package is all you need to do for tests to show up in the Visual Studio Test Explorer.  And ReSharper has its own xUnit plugin, which you can install to use the R# test runner with xUnit tests.  Lastly, you’ll want to pay close attention to the naming guidelines for test assemblies, classes and methods, as well as appropriate unit test structure, and taking into account exception messages in your tests.

The actual coding guidelines section is rather lightweight, probably because ReSharper enforces most generally accepted rules.  (You are using ReSharper, aren’t you?!)  If you’re a company, the commercial license is well worth the price, but if you’re an individual developer and price is a concern, see if you can qualify for a free license as the author of an open source project.  One interesting thing to call out is the use of the [NotNull] parameter attribute for argument null checking, which results in null-checking code injected into the method at compile-time.  You’ll need to use it on all public methods, including constructors and property setters.

Another thing to note is the restricted use of internal types and members.  You’ll almost always want to shy away from the use of internal and instead place those types in a namespace which indicates they are primarily for internal use.  It’s not a hard and fast rule, but it’s how most modern frameworks are built.  This makes the use of the [InternalsVisibleTo] attribute unnecessary, which is good because it prevents you from having to modify a core assembly when all you want to do is add a test assembly for it.

The most controversial part of the coding guidelines is the recommendation to use the var keyword whenever possible for local type inference.  I have mixed feelings on this one, because nowadays you’re often looking at code in GitHub, or with a Git client, where you can’t just mouse over var for the return of a method call to see what the type really is.  On the other hand, there are arguments for using var whenever allowed by the compiler.  For this one, it’s really a matter of what your team prefers.

Note that guidelines are only as effective as their enforcement.  For this reason, you’ll need something like StyleCop, which has been implemented as a ReSharper extension.  First install it by selecting Extensions Manager from the ReSharper menu in Visual Studio.

resharper-stylecop-ext

Then go to ReSharper, Options, Tools, and select StyleCop.  If you see a compatibility warning message, click the the button that says, “Reset C# Code Style Options.”

resharper-stylecop-opt

After this, you’ll see StyleCop rules pop up when you’ve violated standard conventions, such as the ordering of using directives. In the example below, selecting the first option will reorder the usings appropriately.

resharper-code-cleanup

There are also facilities which allow you to select a Settings.StyleCop file, and to enable the  insertion of file headers during cleanup.

The last thing I’ll mention is that there is an unwritten rule regarding line length: lines of code should not be so long as to cause the scroll bar to appear in GitHub.  I found this to happen when exceeding 118 characters, but you may wish to limit your code to a shorter width.  Whatever length you decide on, you need a visual cue for when your code has exceeded it.  The best way I know if is to install the Visual Studio Productivity Power Tools, and insert a registry entry so that a vertical guideline will appear showing where to insert a line break.

The AspNet guidelines are a step in the right direction, but there are a bunch of other things developer should keep in mind when writing code.  In particular, when refactoring one should avoid code smells as much as possible.  These coding standards provide a nice summary, and they mention the principles of SOLID, KISS, YAGNI and DRY, as well as common design patterns.

The important thing is not to take these guidelines as written in stone, but as a starting point for formulating your own set of guidelines, which work for you, your project and your team.

Posted in Technical | Tagged , | Leave a comment

Cmder: Making the Command Line Your Best Friend

Now that I’ve jumped fully on board the Git and GitHub bandwagon, I’m spending a lot more time at the command line.  In fact, I find myself working with both Visual Studio and the command prompt simultaneously, constantly switching back and forth between the two.  The main reason is that, while Visual Studio 2013 makes a great Git client and tools such as TortoiseGit are a great help, there are some Git commands, like stash and rebase, that either aren’t supported well by the tools or are just easier to perform at the command line.  Besides, most of the online Git tutorials list Git commands.

cmder-main

DOWNLOAD Cmder here: http://bliker.github.io/cmder.

Another reason why I find myself more on the command line is that I’m working with ASP.NET 5, which requires the use of a command prompt for managing versions of the runtime and generally embraces command line tools as a first class citizen.  Finally, there’s Chocolatey, for easily installing tools at the command line, and, of course, PowerShell for automating actions with scripts.

As my need to work at the command line has increased, so has my frustration with the standard windows command prompt. Thankfully, I’ve run across a very nice command prompt replacement called Cmder, which combines the console emulator, ConEmu, with cmd enhancements from Clink and Git support from msysgit.  In short, it’s the one command prompt you’ll ever want to use.

If for no other reason, Cmder will win you over with its support for ^C and ^V for Copy and Paste. A list of basic commands can be found here, and you can execute a command to add file explorer integration, so that you can right-click on a directory to see “Cmder Here” in the context menu (open an administrator prompt at the Cmder installation directory and execute .\cmder.exe /REGISTER ALL).

I much prefer using Cmder for all my git command-line tasks rather than opening a Git Bash prompt, because all the standard cmd.exe commands are there, and it shows both the repo location and current branch.  Here you can see I’m at a local Git repo on the master branch, then I list all the branches and checkout the develop branch.

cmder-git

And here you can see an example of executing ASP.NET 5 commands, such as dotnetsdk (aka kvm).

cmder-asp

There are some fancy things you can do with Cmder, including basic unix commands (such as ls, mv, cp, grep, cat) and aliases, which are shortcuts you can define in a text file (located in config\aliases) for common tasks. For example, there’s a built-in alias for the Windows file explorer. Simply type .e, and an explorer window opens at your current location.

Besides its versatility, what I especially like about Cmder is the ConEmu goodness that comes with it.  It’s easy to set up predefined tasks that open additional tabs in the same Cmder window so you can switch between them by pressing Ctrl+Tab and Ctrl+Shift+Tab.  You can also assign each task a hot key. To set up tasks, just click on the dropdown arrow to the right of the green plus icon in the lower right-hand corner.

cmder-setup-tasks

Selecting “Setup tasks…” from the menu will display a dialog for configuring ConEmu settings.  From here you can click “Add default tasks,” then tweak the commands that were inserted.  This will allow you to open new tabs for an administrator prompt, PowerShell, Chocolatey and Git Bash, among others.

cmder-tasks

Another thing you can do at this dialog is to assign a different palette (color scheme) for different commands.  For example, it would be nice for the Admin prompt to show up with a slightly different color scheme to give you a visual queue as to which console you’re on, and it would be just as nice for the PowerShell console to light up with the standard PS colors.  To do that, you can select Features / App distinct, then add application distinct settings which override the default color palette.

cmder-app-distinct

Executing the PowerShell Admin task will, for example, open a new elevated Cmder tab colored in the same way as the standard PS prompt.

cmder-ps

Lastly, after making these customizations you’ll want to export the settings file.  If you want to use the settings file I created for my own use, you can get it here.  Better yet, you can copy the entire cmder folder to a USB stick or a cloud service, such as DropBox, where you can use it from any connected machine.  Enjoy!

Posted in Technical | Tagged , | Leave a comment