Book Image

Instant Nancy Web Development

By : Christian Horsdal
Book Image

Instant Nancy Web Development

By: Christian Horsdal

Overview of this book

Nancy is a C# web framework which aims to provide you ,the application developer, with an easy path to follow, where things will naturally fall into place and work. Nancy is a powerful, flexible, and lightweight web framework that allows you to get on with your job. Instant Nancy Web Development will give Readers practical introduction to building, testing, and deploying web applications with Nancy. You will learn how to take full advantage of Nancy to build clean application code, and will see how this code lends itself nicely to test driven development. You will also learn how to hook into Nancy to easily extend the framework. Instant Nancy Web Development offers you an in-depth exploration of all the major features of the Nancy web framework, from basic routing to deployment in the Cloud, and from model binding to automated tests. You will learn how to build web applications with Nancy and explore how to build web sites using Razor views. Next, you will learn how to build web based APIs suitable for JavaScript clients, mobile clients, and even desktop applications. In fact, you will learn how to easily combine the two into one. Finally, you will learn how to leverage Nancy to write clean and maintainable web applications quickly.
Table of Contents (7 chapters)

Preface

Welcome to Instant Nancy Web Development. I would like to start off by giving you a few motivations for using Nancy and touch upon the types of applications where I think Nancy really shines. These are personal opinions and others may not agree to it. That's OK. The point is, knowing that these are the motivations I have for using Nancy and that these are the situations where I'd use it, give you better context for reading this book.

The Nancy web framework (http://nancyfx.org/) was founded by Andreas Håkansson, who, along with Steven Robbins, maintains the project. Nancy was originally inspired by the Sinatra Ruby web frameworks, but is by no means a port.

Style matters

Before I get to the motivations for using Nancy, I want to digress for a bit. In this seemingly (or wannabe) rational realm of technology, we tend to focus a lot on the concrete and measurable things when we choose between one technology and the other, such as how do the features lists compare, how well does each cope with high volumes of load, and what is the total cost of ownership for each. We may end up with a chart or spreadsheet scoring each technology on multiple axis and calculating a final aggregate score which the answer to the choice. I think we too often miss an important component in these decisions, namely the style Why? Because style, in my experience, has a tremendous effect on the happiness of the developers working with the technology. Why does that matter? Well, apart from the basic good of people being happy, they are also more productive and more creative when they are happy. This is not too far from saying that a happier developer can save the development time and/or lead to a better product. That is quite tangible, and I argue that it has the potential benefit of choosing the more stylish or more aesthetically pleasing technology.

What is style then? It's a lot of small things, such as how the code looks line by line, how the framework makes you structure the code, and how terse versus explicit the code is.

As it turns out, Nancy's style really clicks for me. I find it fun and refreshing to work with. I hope the recipes in this book will make you feel the same way.

The super duper happy path

Nancy's declared ethos is to provide the super duper happy path; that is, it is a goal for Nancy to make anything you would want to do in a web application easy. To do this, Nancy employs a range of techniques and principles, such as:

  • Small embedded Domain Specific Language (DSL) that makes your application code very short and very explicit at the same time.

  • The other principle is convention over configuration. There are lots of things in Nancy applications that we don't need to be explicit about, because Nancy, out of the box, has sensible defaults. For instance, you don't have to configure all your Nancy modules (introduced in the recipes Building and running your first Nancy application (Simple), Nancy testing – your first Nancy tests (Intermediate), and Routes and model binding (Intermediate)); instead, by convention, any Nancy module in your application code is automatically picked up by the framework.

  • Everything, including the core pieces of the framework, can be extended with your custom extension or even swapped out completely, if needed. We will see examples of this in the recipes Routes and model binding (Intermediate) and Content negotiation and more model binding (Advanced).

  • Everything is highly testable. This is not a Test Driven Development (TDD) book, but I will say that I very much prefer to use TDD for the vast majority of my code, which means that for me, testability is a huge deal. Nancy allows a very nice TDD flow.

  • Nancy is not tied to any particular platform beyond the client profile, Base Class Library (BCL). This means that Nancy runs on IIS, in a command-line application, in a WPF application, on Azure, and on Mono, just to name a few.

The result of the super duper happy path is that Nancy, for the most part, does exactly what I expected and wanted without much code. This gives Nancy applications a nice, lightweight feeling.

Sweet spot

The question remains, when to use Nancy? The short answer is that Nancy is suitable for all the .NET based web development. A slightly longer answer is that I find Nancy making the most sense for web applications with multiple clients. An example of this is a web application, where the main desktop UI is a single page JavaScript application (SPA), and which also has native apps for iOS, Android, and Windows Phone, a mobile version of the SPA, and may be, even a simple HTML UI for people who turn off JavaScript in their browsers. Such an application calls for an architecture where the backend exposes a common API over HTTP that all the clients use. The nice embedded HTTP DSL and the content negotiation features make Nancy a perfect fit for building an HTTP based API.

The running example used in the book is a simple to-do application with two clients, an SPA and a very simple server-side generated HTML UI. The Nancy to-do application will be ready to support other clients, for example, mobiles. The focus, though, will be on building the backend part with Nancy, using TDD. The client-side pieces of software are mainly out of scope of this book. Therefore the SPA client, we will use, is the well-known Backbone TodoMVC application (http://todomvc.com/architecture-examples/backbone/). The details of the code of the Backbone TodoMVC application and of any mobile clients are out of scope.

What this book covers

Building and running your first Nancy application (Simple) shows you how to get from zero to hello world with Nancy in no time. At the same time, you will see an example of the part of Nancy you will probably be using the most in real applications.

Nancy testing – your first Nancy tests (Intermediate) gets you started down the path of sound-test-driven development with Nancy. The emphasis is not on TDD, but on Nancy, and along the way, you will see how Nancy treats tests as first-class citizens.

Routes and model binding (Intermediate) walks you through how to easily receive data from client side code in your routes. You will also dig a level deeper into how to set up the routes with Nancy.

Taking a dependency – introducing the bootstrapper (Intermediate) shows you how Nancy lets you handle configuration in code with the bootstrapper. This recipe will also show you just how easy Nancy makes it to inject the dependencies into your application code without giving up any control or any testability.

Content negotiation and more model binding (Advanced) takes you a level deeper into model binding, and furthermore, delves into the concept of content negotiation. You will see how you give client-side code a great amount of flexibility while maintaining a nice separation of concerns on the server side.

Adding views (Intermediate) shows you how to add server-side-rendered Razor views to your Nancy application, and how to configure Nancy to use a variety of other view engines.

Adding static content (Intermediate) shows you how to serve static content easily, following Nancy's default conventions, and how to augment those conventions to suit your own needs.

Hosting Nancy on the Cloud (Intermediate) shows you how to deploy your Nancy application to the AppHarbor PaaS cloud service, and discusses how to deploy Windows Azure. In both the cases, very little work needs to be done.

Handling cross-cutting concerns – Before, After, and Error hooks (Intermediate) shows you how to easily hook into Nancy's request and error handling pipelines in order to add your own custom steps.

Authenticating users (Intermediate) shows how to add Twitter and other third-party authentication to your Nancy application with only a little bit of work. Furthermore, you will be introduced to how Nancy helps you do authorization on a module or route basis.

Separating applications and hosting (Advanced) explains the notion of hosting in a Nancy application and shows you how to easily set up your application such that it can be run under several different types of hosting.

Using async handlers (Advanced) shows you how to turn existing synchronous request handlers into async request handlers. Doing this involves just a few easy steps and can potentially improve your application's scalabilty.

What you need for this book

All you will need to code along with the recipes is a Windows box with Visual Studio 2012 Express for Web (or a "bigger") edition, a working knowledge of C#, and of the Web.

Who this book is for

The book is for any curious .NET developer who is keen to find out what all the fuss concerning Nancy, Sinatra, and other lightweight web frameworks is about.

Conventions

In this book, you will find a number of styles of text that distinguish between different kinds of information. Here are some examples of these styles, and an explanation of their meaning.

Code words in text are shown as follows: "We can set up a route by use of the Get property."

A block of code is set as follows:

public class Hello : NancyModule
{
  public Hello()
  {
    Get["/"] = _ => "Hello!";
  }
}

When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:

      Get["/"] = _ =>
        Negotiate
        .WithModel(todoStore.GetAll().Where(todo => todo.userName == Context.CurrentUser.UserName).ToArray())
        .WithView("Todos");

Any command-line input or output is written as follows:

PS > Install-Package Nancy

New terms and important words are shown in bold. Words that you see on the screen, in menus or dialog boxes for example, appear in the text like this: "click on add you get an Internal Server Error ".

Note

Warnings or important notes appear in a box like this.

Tip

Tips and tricks appear like this.

Reader feedback

Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or may have disliked. Reader feedback is important for us to develop titles that you really get the most out of.

To send us general feedback, simply send an e-mail to , and mention the book title via the subject of your message.

If there is a book that you need and would like to see us publish, please send us a note in the SUGGEST A TITLE form on www.packtpub.com or e-mail .

If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide on www.packtpub.com/authors.

Customer support

Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.

Downloading the example code

You can download the example code files for all Packt books you have purchased from your account at http://www.PacktPub.com. If you purchased this book elsewhere, you can visit http://www.PacktPub.com/support and register to have the files e-mailed directly to you.

Errata

Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in the text or the code—we would be grateful if you would report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/support, selecting your book, clicking on the errata submission form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded on our website, or added to any list of existing errata, under the Errata section of that title. Any existing errata can be viewed by selecting your title from http://www.packtpub.com/support.

Piracy

Piracy of copyright material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works, in any form, on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.

Please contact us at with a link to the suspected pirated material.

We appreciate your help in protecting our authors, and our ability to bring you valuable content.

Questions

You can contact us at if you are having a problem with any aspect of the book, and we will do our best to address it.