CRUD Operations in NancyFx Using ASP.Net and FluentNHibernate by Repository Pattern

Introduction

These days Rapid Application Development (RAD) is growing quickly. There are numerous frameworks available to develop Web Applications or Web Projects. We can use either ASP.Net or ASP.Net MVC from Microsoft or any other framework. Although NancyFx has its own support for View Engines for example Super Simple View Engine or Razor View Engine. Also, anyone can define their own custom view engine. In this article we will use NancyFx to build a restful service using ASP.Net and FluentNHibernate and understand how it works step-by-step.

NancyFx

In simple and shorter words NancyFx is a lightweight web framework for .Net. In these days, this tool is the most popular among C# developers for web development. NancyFx is inspired by ruby's Sinatra. I have never worked on Ruby, so I can't compare Sinatra and NancyFX. NancyFX has builtin support for all requests (GET, PUT, POST, DELETE and so on).

Why To Use NancyFx

There are numerous reasons to adopt NancyFX for your web development. Here are my views (we are not discussing these points in this article):

  • Less costlier.
  • Builtin IoC container (TinyIOC).
  • Easy to test (just like ASP.Net MVC).
  • Not limited to, or biased toward, any UI framework (viz. MVM, MVC and so on).
  • Providing customization (built-in feature to replace any part as required).
  • Runs on Mono.
  • No configuration required to setup NancyFx.
  • Free from Design Framework.
  • Can run anywhere (IIS, WCF, can embed within an EXE, as a Window Service and so on).

Let's Start Creation of a Sample Project

We need to setup NancyFx and FluentNHibenrate support for our project.

Prerequites

To implement and play with the source code, one should have:

  • Visual Studio 2013 express or later
  • ASP.Net
  • Basic knowledge of RestFul services
  • Basic knowledge of FluentNHibernate
Create Skeleton/Empty ASP.Net project

To start we are using a simple empty ASP.Net project:
  • Start Visual Studio and select "File" -> "New" -> "Project..." (or type Ctrl + Shift + N).

    new web application

    Note: do not confuse that with the installed Nancy template (we will discuss it in the next article).

  • In the Template dialog select Empty template as in the following:

    empty website
    (P.S.: Alternatively you can host this on cloud; we are not discussing this topic here.)

Adding NancyFx and FluentNHibernate support

We can add NancyFx and FluentNHibernate in many ways, here we are using a Nugget package:

  1. Open the Nugget Package Manager and search for "Nancy" and select it as shown in the following image:

    Nancy

  2. Alternatively, go to the Package Manager Console and enter the following command.

    Package Manager Console

  3. To install FluentNHibernate go to Package Manager Console and enter the following command.

    FluentNHibernate

    (P.S. We installed the stable release, currently there is a pre-release available you can use if want to try a pre-release).

We are ready with a template of our app. Now, let's start writing simple CRUD Operations.

  1. Add a new class file and name it "ServerDataModule.cs".

    ServerDataModule

  2. Add the following code to your class (this is just to test that your NancyFx has been set up).

    cs code

  3. Let's check our NancyFx resources. Run your application (Hit F5) from Visual Studio.

    output

    If you see the output in your browser, it means you have successfully set up the required things.

  4. Now, let's set up our model classes and Repository.

    1. Add a new folder named Models from Solution Explorer and add the following classes:

      1. ServerData.cs

        ServerData

      2. ServerDataMap.cs

        ServerDataMap

        P.S. Do not forget to add:

        FluentNHibernate mapping

    2. Add a new folder named Persistent beneath the Models from the Solution Explorer and add an Interface IServerDataRepository:

      IServerDataRepository

  5. For our project we have created a helper class that supports our repository Pattern of NHibenrate. Just add a new folder named Helper using Solution Explorer and add a class NHibernateHelper.

    At this point, we are done with the core preparation of our project. Now, we just need to implement our repositories in the flavor of NancyFX.

    Let's revisit our NancyModule class ServerDataModule and modify it.

    NancyModule

    Here, we are passing an int type parameter and returning a JSON object. One most exciting thing of NancyFx is that it will automatically recognize the parameters [parameters are defined within {} braces], we call this dynamic parameterization of resources.

    NancyFx

    Here, we are using the Post resource and this.Bind<ServerData>() is automatically bound in the incoming request to our ServerData model.

Add Database

Creating DataBase

The complete SqlScript is attached. The following is the SQL of our table:

  1. CREATE TABLE [dbo].[ServerData](  
  2.     [Id] [int] IDENTITY(1,1) NOT NULL,  
  3.     [InitialDate] [datetime] NULL,  
  4.     [EndDate] [datetime] NULL,  
  5.     [OrderNumber] [intNULL,  
  6.     [IsDirty] [bitNULL,  
  7.     [IP] [nvarchar](15) NOT NULL,  
  8.     [Type] [intNULL,  
  9.     [RecordIdentifier] [intNULL,  
  10. PRIMARY KEY CLUSTERED   
  11. (  
  12.     [Id] ASC  
  13. )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ONON [PRIMARY]  
  14. )  
Adding Bootstrap and Custom Exceptions to our project

As of now we are using a builtin exception and let's now move forward and implement the custom exceptions and Bootstrap things.

Adding Bootstrap

We will use a "Structure Map". There are many other IoC frameworks available but I picked SM for make our demo easier.

Go to the Nugget Package Manager and install Nancy.BottStrappers.StructureMap as shown below:

BottStrappers

Add a new class named BootStarpper.cs as shown below:

Container and BootStrapper

Now, add two more important files, Container and BootStrapper.

Container

BootStrapper file

Adding Custom Exception

We are now near to adding a custom exception to our project. For this we need to add to our application.

Add a new class named ErrorPipeline (here we simply defined one custom exception for demo purposes).

add new class

Here is what we implemented:

error pipeline

In the above you can see we are just attaching our customization to the OnError hook, there are many more ways and here we took the preceding only for demo purposes.

Revisiting Module Code

Let's revise the ServerDataModule of our code as below:

responce as json

We are not going to explain refactoring in details.

Testing NancyFx

We have already created our CRUD operations using NancyFx, since we are planning to deploy this project as services on a server that is a separate from client servers (note that the client may be a console app, web app or from any other source that can consume NancyFx services), we need to ensure that our services are working properly and providing desired results.

Create New Test Project

Create a new project named CrudsWithNancyFx.Test. We will use NUnit with Moq framework for our project. Add a new class and name it ServerDataTest.cs.

test project

Adding Testing support to NancyFx project

Open the Nuget Package Manager and install Nancy.Testing as shown in the following image:

Adding Testing support

Adding Nunit and Moq Framework

Open the Nuget Package Manager and add a Nunit and Moq framework as shown below:

Adding Nunit

Moq Framework

Add Simple Test

We added a simple test to verify (we are not going to explain each and every test in details).

Add Simple Test

We are using Resharper, so it easy to run tests from within Visual Studio as in the following:

Resharper

Conclusion

This article showed how to get started with NancyFx with FluentNHibernate and Repository Pattern. We covered Nancy Testing.

Up Next
    Ebook Download
    View all
    Learn
    View all