Monthly Archives: August 2017

An Introduction to ASP.NET Core

ASP.NET Core uses .NET Core, and is the next generation of ASP.NET, having first been released only last year (2016).

ASP.NET itself uses the full .NET Framework, and has been around since .NET’s first release back in 2002.

In this article, I’ll provide a quick introduction to ASP.NET Core. If you already know about ASP.NET MVC, you won’t learn anything new here!

Note that I’ll use the term ‘web application’ rather than ‘website’, because web applications can be websites or web APIs, running either on the internet or on a private intranet. (A web API, if you’re unaware, can be considered a set of functions accessed across the internet or other network.)

Why .NET Core?

.NET Core – used by ASP.NET Core, naturally – is the next generation of the .NET Framework. It’s open source, cross-platform (Windows, Linux, Mac), highly performant, and getting better with every release. There’s virtually nothing bad anybody can say about it!

An Overview of MVC

You’ve almost certainly heard of MVC. In web development, it’s everywhere, and it’s not specific to ASP.NET, ASP.NET Core, or any other web technology.

Model-View-Controller (MVC) is an architectural pattern that splits an application into discrete parts according to their role. It’s not new, it’s been around for a long time, but it gained popularity particularly in the development of web applications.

Models

Models represent data. In an MVC application, there are two types of model: the model that represents data stored in database tables; and ‘view models’, which are used to transfer data to and from web pages.

Views

Views represent web pages, and web pages make up a web application. Users interact with views. Data (in the form of a view model) is passed to a view before it’s returned to the user’s browser, and passed back when the user submits a form.

Controllers

Controllers represent the logic behind a web application. When a user requests a web page, a controller picks up the request. The controller might perform some validation, processing, or other tasks, but ends by passing data (in the form of a view model) to a view. The view is then returned to the user’s browser.

Interaction

Here’s the obligatory diagram that shows the interaction between the parts of an MVC application:

MVC Architecture Diagram

It’s grossly simplified and high-level, but that’s the beauty of the MVC architecture: it is conceptually simple. If you’re coming from a Web Forms background, then MVC is radically different and adheres nicely to the separation of concerns (SoC) principle.

MVC Operations

Here’s a quick overview of how data is passed around in an MVC application.

Passing data to a view

The controller can trigger the rendering of a view by returning the result of calling the View() method. Any object can be passed to the view, and that object becomes the view model that the view uses to help render the HTML page.

public IActionResult Index()
{
    return View(new IndexViewModel
    {
        Name = "Dave"
    });
}

In this case the view model is actually a POCO (a class with no methods) defined as follows:

public class IndexViewModel
{
    public string Name { get; set; }
}

When a user navigates to the index page of the controller – e.g. http://example.com/controller/index or just http://example.com/controller – the controller’s Index() method is executed. This returns a View object (by default, it’ll return a view of the same name as the method; Index in this example). Optionally, a view model can be attached to the view, and the view (implemented using a .cshtml file) can use the data provided by the view model as simply as this:

Hello @Model.Name

At the head of the view (the .cshtml file) the view model must be referenced:

@model WebApplication1.Models.IndexViewModel

Sending data to a controller

There are (at least) two ways in which a page can send data to the page’s controller.

Forms

Typically, the user enters some text into an input control, then clicks a button which submits a form. The data is passed to the controller in the form of a view model.

<form action="/Home/Submit">
    <label>Your name is:</label> <input name="Name" type="text" />
    <button type="submit">Submit</button>
</form>

A method is added to the controller to handle the form submission:

public IActionResult Submit(IndexViewModel viewModel)
{
    return View(viewModel);
}

Remember that View() will cause a view (with the same name as the method unless specified) to be rendered.

Submit.cshtml must reference the view model at the top:

@model WebApplication1.Models.IndexViewModel

and the view model can be used:

Hello @Model.Name

(This is just the same as the Index view above!)

So the user enters their name in the text box, then presses Submit. The form’s action determines the controller (Home) and the page (Submit). So the HomeController’s Submit() method is called, with a view model created (from the contents of the form) and passed to the method. All our method does is return the view model, so that the Submit view can say hello.

There’s a lot going on here, and we’ve only just scratched the surface.

JavaScript

Another way in which data can be sent to a controller is by using JavaScript. But that’s beyond the scope of this short intro to ASP.NET Core. Maybe next time.

Sources of Information

There’s a lot of information on the internet, and finding good quality information can be hard.

So here’s a short list of websites, podcasts, and books that I frequently refer to. It’s not comprehensive, because it’s not meant to be!

Blogs/News

https://blogs.msdn.microsoft.com/dotnet
Everything .NET: new and upcoming releases, updates, and other useful articles.

https://blogs.msdn.microsoft.com/webdev
Web development using ASP.NET.

https://blogs.msdn.microsoft.com/visualstudio
New and upcoming releases of Visual Studio, plus details of patches, new features, and other useful articles.

https://code.visualstudio.com/blogs
News about Visual Studio Code.

https://www.smashingmagazine.com
Lots of good articles for web development and design.

https://www.reddit.com/r/webdev
Occasional links to useful articles and questions. It’s Reddit, what more can I say?

Podcasts

https://dotnetrocks.com
The original podcast for software developers, long before the word ‘podcast’ even existed. They talk everything .NET- and web-related, and a whole lot more. Lots of useful, good quality information.

https://hanselminutes.com
I’ve only recently started listening to this, but already I’m impressed by the quality of the information and the wide range of software development topics.

https://simpleprogrammer.com/2016/10/29/ultimate-list-developer-podcasts
As the link says, this is the ultimate list of developer podcasts. If you don’t like either of the above, you’ll certainly find something here.

Reference/Documentation

https://docs.microsoft.com/en-us/dotnet/core
Microsoft’s documentation for .NET Core. Written from scratch, bare in places, but getting better all the time.

https://docs.microsoft.com/en-us/aspnet
Microsoft’s documentation for ASP.NET Core. Includes guides and tutorials on getting started, and comprehensive references.

https://developer.mozilla.org/en-US/docs/Web
Mozilla’s comprehensive reference for everything web-related.

https://www.w3schools.com
An easy-to-use reference for everything web-related. Not as comprehensive as Mozilla, but provides info on everything that’s important.

Help

https://stackoverflow.com
The ultimate site for software developers. If you’ve got a problem, it’s pretty much guaranteed that somebody’s already encountered the same problem. Go here to find the solution!

https://answers.microsoft.com
Microsoft’s community for getting help with all sorts of problems with Microsoft’s technologies.

Training/Learning

https://www.pluralsight.com
Thousands of courses across a wide range of software development topics languages and technologies and other IT-related topics.

Books

Any self-respecting software developer should have a collection of books, whether they’re traditional paper books or modern e-books. Here’s a few selected books concerned with web development:

JavaScript: The Good Parts by Douglas Crockford (Yahoo Press / O’Reilly)
Essential reading, from the author of JavaScript! Tells you what’s good about JavaScript, and what to avoid.

JavaScript Patterns by Stoyan Stefanov (Yahoo Press / O’Reilly)
Shows you how to use JavaScript properly.

Responsive Web Design with HTML5 and CSS3 by Ben Frain (Packt)
How to layout modern web applications.

Pro ASP.NET Core MVC by Adam Freeman (Apress)
A good, albeit hefty book for developing web applications with .NET Core. If you’re new to the MVC pattern (model-view-controller) this does a good job at teaching the concept.

.NET Core on Linux

Introduction

Just a few years ago, Microsoft was decidedly anti-Linux.

Mono – the cross-platform, open-source version of the .NET Framework – had been around since 2004. But it was independent of Microsoft, was always playing catchup, and not widely accepted.

So in 2014, Microsoft surprised everyone by announcing a new, cross-platform .NET!

.NET Core runs on Windows, Linux, and macOS. It’s a fairly large subset of the full .NET Framework, provides excellent performance, and is very much geared towards web applications using ASP.NET Core.

What We’ll Be Doing

On a Linux machine (Ubuntu 16.04) we’ll be installing .NET Core, and creating and running an ASP.NET Core web application.

Then we’ll install Visual Studio Code, a freely available source code editor (*) from Microsoft, and use it to build and debug a .NET Core web application.

(*) Visual Studio – which has been in existence since the 1990s – is Windows only, and paid software. Visual Studio Code, on the other hand, has only been around since 2015, and is cross-platform.

Right, let’s go…

.NET Core

Installation

Open up a terminal, and enter these four commands:


sudo sh -c 'echo "deb [arch=amd64] https://apt-mo.trafficmanager.net/repos/dotnet-release/ xenial main" > /etc/apt/sources.list.d/dotnetdev.list'

sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys B02C46DF417A0893

sudo apt-get update

sudo apt-get install dotnet-dev-1.0.4

Refer to https://www.microsoft.com/net/core#linuxubuntu for full details.

Creating a .NET Core Project

In the terminal, enter:


cd

mkdir dev

cd dev

dotnet new mvc --name webapp1

The dotnet command will take a minute or so while it creates a local cache “to improve restore speed and enable offline access”.

Now enter:


cd webapp1

dotnet restore

dotnet build

dotnet run

This will output text similar to the following:

Hosting environment: Production
Content root path: /home/grahamb/dev/webapp1
Now listening on: http://localhost:5000
Application started. Press Ctrl+C to shut down.

Open up a browser, and navigate to http://localhost:5000:

dotnetcore success

Success!

Return to the terminal, and press Ctrl+C to terminate the process.

Visual Studio Code

Installation

Go to https://code.visualstudio.com/Download and click the .deb box below Tux (the Linux penguin) to download the package.

In the terminal, enter:


sudo dpkg --install ~/Downloads/code_1.14.2-1500506907_amd64.deb

and wait for the installation to complete (note that the version number in the filename might be different for your download!).

Create a .NET Core Project

Return to the terminal, and enter:


cd ~/dev

dotnet new mvc --name webapp2

cd webapp2

code .

This opens Visual Studio Code in the current directory (~/dev/webapp2):

vscode 1 first launch

A new web browser window will also be opened, showing a Getting Started page for Visual Studio Code. Feel free to browse this documentation.

Double-click Program.cs or Startup.cs. You’ll see an information bar at the top; click Show Recommendations:

vscode 2 missing C# extension

Locate the C# extension in the list, click Install, wait a few seconds, click Reload, click Reload Window.

The Output pane will automatically open, and the C# dependencies will be updated.

Click Yes and Restore in response to the two messages:

vscode 3 restarting after installing C# extension

Wait for the NuGet (*) packages to be restored:

(*) What’s NuGet, some of you might ask? It’s a package manager originally created for Visual Studio, similar to npm (Node.js) and pip (Python).

vscode 4 after restoring packages

Now click the Debug icon on the left:

vscode 5 click debug icon

Click the dropdown beside the green debug icon at the top, and select “.NET Core Launch (web)”:

vscode 6 select configuration

Now click the green debug icon (or press F5). Debugging will start and a browser window will automatically open:

vscode 6 success

Success!

Return to Visual Studio Code and click the red stop icon in the toolbar.

As an exercise, I’ll let you experiment with debugging and stepping through the source code. With the cursor on a line – try the actions in HomeController.cs – press F9 to set a breakpoint. When you navigate to the page in the web browser, program execution will halt at the breakpoint. Press F10 to execute the current statement, or F5 to continue execution. If you’re a Visual Studio user, you’ll already be familiar with these keyboard shortcuts!

First Steps with Visual Studio

Introduction

If you’re an experienced software developer, there’s a good chance you’ve already used Visual Studio. If so, then you can skip this post; you won’t learn anything new here.

But you might be an experienced developer who’s never used Visual Studio. You might be wanting to move into web development with C# and ASP.NET  after years of writing Java, C++, or VB6 code.

You might be an experienced PHP developer who’s never even seen Visual Studio.

Or you might be a student or a hobbyist, looking for your first software development position.

Whatever your reasons for being here are, we’ll start at the beginning.

An Overview of Visual Studio

Visual Studio is an IDE (Integrated Development Environment) from Microsoft. It’s been in existence since the 1990s, and is very widely used by professional – and hobbyist – software developers around the world. It’s mostly focused on C#, Visual Basic .NET, F#, and C++ development, but also includes support for other languages and technologies including Python, JavaScript, Xamarin, and Android.

And don’t confuse it with Visual Studio Code which – whilst getting better all the time – has only been around since 2015. This is essentially a free cross-platform text editor, also from Microsoft, but with support for projects, building, debugging, and is highly extensible; a scaled down Visual Studio, if you like.

What We’ll Be Doing

We’ll be installing Visual Studio Community 2017, and creating a .NET Core web application.

The Community edition is free and intended for students and individual developers rather than the enterprise. It’s fully functional, but lacks more advanced features.

We’ll be creating a .NET Core web application because, frankly, .NET Core is all the rage right now. If you don’t know anything about it, it’s the new cross-platform edition of .NET that currently runs on Windows, Linux, and Mac, has been written from the ground up, and provides a lean subset of the full .NET Framework. If you don’t know anything about the original .NET Framework itself, check out Microsoft’s overview.

Installing Visual Studio

Downloading

First, you’ll need to download Visual Studio Community. Go to https://www.visualstudio.com/vs/community, then click “Download VS Community 2017”.

Installing

Run the downloaded executable file. After accepting the UAC prompt and clicking Continue on the first Visual Studio window, you’ll soon be presented with this page:

vs install 1 - workloads 1

vs install 2 - workloads 2

Check (tick) these four workloads:

  • .NET desktop development;
  • ASP.NET and web development;
  • Asure development;
  • .NET Core cross-platform development (scroll down for this one).

There’s no need to check anything else, but feel free to do so should you wish to look at other areas (such as game or mobile development).

Click Install. The Workloads page disappears, showing this:

vs install 3 - progress

You’ll need to wait a little while as the installation proceeds. How long depends on the workloads and components you selected, and how performant your machine is.

Eventually – assuming there were no hiccups – you’ll see this:

vs install 4 - complete

Click “Launch”. Then – on the following window – click “Not now, maybe later” (or – if you have a Microsoft account – you can sign in instead).

vs install 5 - after clicking launch

This is what you’ll normally see whenever you run Visual Studio:

vs install 7 - after clicking start visual studio

To prove this, close Visual Studio, then find it in the Start Menu. Why would I lie?

Creating a New Project

Now it’s time to create a project. Click “Create new project…” underneath “New project” (near the middle of the window).

vs install 8 - create new project

In the list of Installed Templates on the left, find and select .NET Core. Now select ASP.NET Core Web Application (.NET Core). I never use the default location (it’s too long and easy to forget!) so change it to somewhere more convenient – C:\Dev or C:\Projects are good suggestions. You can leave the name of the project as is.

Now click OK, and you’ll see…

vs install 9 - after clicking ok

Nothing should need changing; just ensure that Web Application is highlighted and that Authentication is set to No Authentication.

Click OK. The project has been created:

vs install 10 - project created

Press Ctrl+F5 to build and run the web application. After a short delay a web browser (*) should open, running the web application that Visual Studio just created for you:

vs install 11 - after running

(*) No flaming me for using Edge! I simply installed Visual Studio on a clean virtual machine.

That was easy, wasn’t it? Of course, it’s a default template so the website doesn’t really do much. But it’s a decent starting point, and you’ll probably use this a lot while you’re finding your feet.

Hopefully you won’t have any problems, but sometimes they happen. In which case, the Microsoft Community and Stack Overflow are good places to find help.