Host your RavendDB based MVC app on Appharbor

RavenDBIn this blog post I will walk through how to host an MVC application which uses RavenDB as the back-end document database hosted up on Appharbor, Appharbor now allows us to host RavenDB in the cloud.

In the blog post I am going to make several assumptions, the post itself is more to do with getting an application deployed and running up on AppHarbor using RavenDB as the document database.

I am assuming you have you have a github account and know how to get your code up onto github, an Appharbor account and know how to deploy your code to github to Appharbor.

If you need some help with doing this then check here.

Ok lets create a brand new MVC Web application project, I used MVC 3 application

Raven2

And then I chose the internet template.

Raven3

You can either download RavenDB from RavenDB.net or use Nuget to get RavenDB. For the demo I just installed it using Nuget
as follows, within Visual Studio goto Tools, Library Package Manager and then select Package Manager Console and then type:-

Raven

RavenDB is now downloaded using NuGet and you will find it within the packages folder in the same location on disk as your project solution files, to start RavenDB locat the packages folder and then go to the RavenDB.1.0.616 folder and then the Server folder and double click on Raven.Server.exe as below:-

Raven4

By default RavenDb runs on http://localhost:8080, once started you can view the Raven Studio from within a browser, and you should see something like this:- (if it says Create Sample Data then click on the button to create sample data)

Raven10

Moving back to our MVC Application we now need to wire a couple of things up to use RavenDB as below:-

In the global.asax add in the following in the Application_Start event:-

 
protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();

    RegisterGlobalFilters(GlobalFilters.Filters);
    RegisterRoutes(RouteTable.Routes);

    var parser = ConnectionStringParser<RavenConnectionStringOptions>.FromConnectionStringName("RavenDB");
    parser.Parse();

    Store = new DocumentStore
    {
        ApiKey = parser.ConnectionStringOptions.ApiKey,
        Url = parser.ConnectionStringOptions.Url,
    }.Initialize();
}

Add in a connection string in your web.config as follows:-

 
<connectionStrings>
    <add name="RavenDB" connectionString="Url=http://localhost:8080" />
  </connectionStrings>

All new Controllers will inherit from RavenController which is below:-

 
public class RavenController : Controller
{
    public IDocumentSession RavenSession { get; private set; }

    protected override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        if (filterContext.IsChildAction)
            return;
        RavenSession = MvcApplication.Store.OpenSession();
        base.OnActionExecuting(filterContext);
    }

    protected override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        if (filterContext.IsChildAction)
            return;
         using (RavenSession)
         {
             if (filterContext.Exception != null)
             return;

             if (RavenSession != null)
             RavenSession.SaveChanges();
         }
     }
}

Below is some example code for some basic CRUD.

 
public class AlbumController : RavenController
    {
        public ActionResult Index()
        {
            var model = this.RavenSession.Query<Album>().ToList();
            return View(model);
        }

        public ActionResult Create()
        {
            var model = new Category();
            return View(model);
        }

        [HttpPost]
        public ActionResult Create(Album album)
        {
            this.RavenSession.Store(album);
            return RedirectToAction("Index");
        }

        public ActionResult Edit(string id)
        {
            var model = this.RavenSession.Load<Album>(id);
            return View(model);
        }

        [HttpPost]
        public ActionResult Edit(Album album)
        {
            this.RavenSession.Store(album);
            return RedirectToAction("Index");
        }

        public ViewResult Details(string id)
        {
            var model = this.RavenSession.Load<Album>(id);
            return View(model);
        }

        public ActionResult Delete(string id)
        {
            var model = this.RavenSession.Load<Album>(id);
            return View(model);
        }

        [HttpPost, ActionName("Delete")]
        public ActionResult DeleteConfirmed(string id)
        {
            this.RavenSession.Advanced.DatabaseCommands.Delete(id, null);
            return RedirectToAction("Index");
        }
    }

Within Appharbor choose RavenDB as an add-on, appharbor will provision you with a connection string if you choose
RavenDB as an add-on, wait a couple of seconds and you will be supplied with a connection string for your RavenDB instance in the cloud.

Step 1

Step1

Step 2

Step 2

Step 3

Step 3

Step 4
Step 4

Step 5
Step 5

This setting is the one you will change to within your web.config, for testing locally use http://localhost:8080 but for deploying to the cloud use the connection string setting supplied to us by Appharbor.

Getting RavenDB from NuGet means quite a large download, we dont want to have to upload all of this content to github so we can do a nice little thign within our solution, roght click on the entire solution within Visual Studio and choose:-

Package Restore

This means our github repository doesnt have to contain all of the Nuget packages and will pull them down for us when building.

Once your code is building and running locally send it up to github and use the service hook to deploy to Appharbor.

If you come across any build errors then you may have to turn customerrors=”Off” in your web.config as well as checking the build log on Appharbor to see what went wrong.

At this point we should have a working MVC application which is using RavenDB as the back-end document database – sweet.

If I missed anything or anyone has any questions or comments please tweet me @gsuttie or leave a comment.

Book Review:- Dependency Injection in .Net

Dependency Injection in .Net written by Mark Seesman @ploeh on twitter

This book is one of the best books I have read regarding .Net development due to its style – it covers misconceptions, what not to do, and then shows you step by step what to do and why. If you’re looking for the definitive guide to dependency injection as a subject matter within the .net world then buy this book – don’t bother with anything else.

My main reason for reading this book was to basically make sure my understanding of the subject matter wasnt distorted from what dependency injection and IoC is. It’s quite easy to good articles on the subject but I wanted a point of reference I can pick up or go to when I need to refresh my memory on the subject.

I am willing to bet there are a lot of developers who don’t actually understand what dependency injection is used for and what it brings to the table.

Part 1 Putting Dependency injection on he map

  • Chapter 1 – Covers misconceptions about dependency injection and what its purpose and the benefits if it are.
  • Chapter 2 – Explores a comprehensive example, starting by showing you not to do and then discussing why not and then shows you how it should be done properly.
  • Chapter 3 – Explores Dependency Injection containers and DI containers.

Part 2 DI Catalog

  • Chapter 4 – DI Patterns, including constructor injection, property injection, method injection and ambient context, of which I really only understood one before reading this part of the book. Each is taken in turn and described, has a code example, and discusses the advantages and disadvantages of each.
  • Chapter 5 – DI AntiPatterns, covers all the different wrong ways to do dependency injection some of them named by Mark who admits to having done all of them, having read through this chapter I recognised a few.
  • Chapter 6 – DI Refactorings, how to spot issues and basically ways to fix the code so that its using proper dependency injection methods.

Part 3 DIY DI

  • Chapter 7 – Object Composition, how to correctly use and setup object composition in different types of .net applications.
  • Chapter 8 – Object Lifetime, managing dependency lifetime disposable dependencies and more.
  • Chapter 9 – Interception, cross cutting concerns, AOP and dynamic interceptions.

Part 4 DI Containers

  • Chapter 10 – Covers Castle Windsor.
  • Chapter 11 – Covers StructureMap.
  • Chapter 12 – Covers Spring.Net.
  • Chapter 13 – Covers Autofac.
  • Chapter 14 – Covers Unity.
  • Chapter 15 – Covers MEF.

This book was enjoyable to read and is all you need to know about DI in once place – go get it now.

RavenDB Useful Tools

Here I will list all of the useful tools I come across when using RavenDB.

So here is the list:-

  • RavenDB add on for Glimpse Glimpse RavenDB.
  • RavenDB Mini Profiler – more info can be found here and here.
  • LinqPad which can be found here is a great tool which you can use to query RavenDB using Linq statements – if you have the correct third party driver installed.

    To learn how to get Linqpad to query RavenDB you will find all you need to do here.

  • Rest-Client which can be found here is extremely handy for testing Restful webservices which RavenDB is.

    RestClient

    Click the downloads tab and then select the following:-

    RestClient

    Once selected rest-client will fire up, it’s very straight forward to use, put in the url to your database where RavenDB is running and then you can use the POST, GET and so on as below:-

    RestClient3

  • Fiddler 2 which can be found here

    Fiddler is a Web Debugging Proxy which logs all HTTP(S) traffic between your computer and the Internet. Fiddler allows you to inspect traffic, set breakpoints, and “fiddle” with incoming or outgoing data. Fiddler includes a powerful event-based scripting subsystem, and can be extended using any .NET language

    We can use Fiddler to monitor what is going on when we work with RavenDB as well as use it to inject documents on the fly which is shown in the Tekpub video series.

  • If anyone has any other useful tools for working with RavenDB then please let me know and I will add to this list.

RavenDB Video Tutorials

RavenDB is fast becoming pretty popular and 2 of the best resources I find for learning is TekPub and Pluralsight, these sites are for developer training and require you to pay for them.

Both sites offer subscriptions but Tekpub also offers the ability to pay for a single course such as the RavenDB course, which is a nice addition.

  • Tekpub Course Details:- Tekpub RavenDB course

    In this production, Oren Eini walks Rob through the various aspects of RavenDB – from the basics through to advanced Administrative Tasks. Along the way you’ll learn how to query with the core Lucene engine, how to index your documents for searches, backups, sharding, replication to SQL Server, and how to plug all of this in to an ASP.NET MVC application.

    This series is In Production which means we are actively recording and producing content for it. Currently we have 10-12 episodes planned.”

  • Pluralsight Course Details:- Pluralsight RavenDB course

I have watched both courses and they are both superb and I encourage you to check them both out.

Adding RavenDB to an MVC application

Adding RavenDB to an MVC 3 application is very straightforward – in this post I will add RavenDB via Nuget and it will run RavenDB in embedded mode.

  1. Start Visual Studio 2010 and Add a new MVC 3 Application, choose Internet Application from the project template option. This will create our new app ready to add RavenDB to.
  2. Ok now to Add RavenDB into your application lets use Nuget to add in the RavenDB Embedded package, go to the Tools Menu and then select Library Package Manager and then Manage Nuget Packages – search for RavenDB Embedded as seen below:-

    RavenDB via Nuget

    Click install and wait a little, it’s a larger package compared to most, also accept the license agreement.

  3. That’s it RavenDB has been added to our MVC 3 application, in the next blog post we will make use of RavenDB in our application.

I feel fortunate where I work

I moved jobs a little under 3 months ago and I know work for Maclean Electrical as a developer in a small team.

At Maclean’s I work in an Agile development team working on a number of projects which we use to drive the business forward and make the company more productive.

Maclean Electrical

Our code base is a made of a number of different projects including some windows service projects, some MVC web apps, a Windows Forms application and even an ASP.NET 2 web app.

The development team strive for a number of goals a couple of which are below as below:-

  • Test Driven Development – write a failing test, write the code tp make the test pass, refactor your code.
  • Code Coverage – the code you write should meet a high level of test code coverage, each project had individual levels but should be around 70% as a minimum.
  • Refactor where possible – refactoring the code you come across so that you always leave it better than you found it where possible.
  • If you break the build, its your responsibility to fix it, yeah it’s normally me I know.

We have a very nice setup at work using TeamCity as our build server and we have ported over a few things as Nuget packages to make life easier going forward – I can push a deployment of the code which runs all the unit tests from the build server to deployment or the test environment in one click.

At work we are about to start looking at using RavenDB and the developers are all being sent on a course in London for training on a 2 day course.

Working for a company who listens to their developers and has fantastic communication with everyone in the team is always good in my book. The developer’s in the team often chat about what technologies are new and who’s looking at what and what they have thought about it. We don’t stick with what we know and are always looking at new technology as a way of sharpening our skills which I love to do anyway.

I guess we have a team of passionate developers who communicate well and who really enjoy their jobs – if you enjoy your job it makes a huge difference. If you want a book on a particular subject then it’s ordered, if you come across a tool that you find helpful its bought.

Do you enjoy your job as much as I do? – I do hope so.

Host your MVC app in the Cloud with AppHarbor

Deploy your MVC 3 application to the cloud and have it hosted for free, you can even get 20MB SQL Server for free should your app use a SQL database backend.

If your unfamiliar with Appharbor let me introduce you.

AppHarbor

“AppHarbor is a fully hosted .NET Platform as a Service. Appharbor can deploy and scale any standard .NET application.”

Deploy and host host your application for free using GitHub to publish the content to Appharbor – couldnt be easier and ultra fast, and did I mention its free?

GitHub

Basically build your application locally – put it up onto Github, setup the Github service hook ( cut and paste 2 lines) and job done – AppHarbor will build your code and deploy it and host it in the cloud for you!

The following are the steps to deploying a blank MVC 3 project to Appharbor using Git and Github, if your unfamiliar with Git and Github then its worth spending some time reading up on both, Git is very straight forward to get going and GitHub is the site to host your git content.

I will assume you have git installed and setup a local repository on your machine – let’s get started.

  1. Open Up Visual Studio 2010 and create an empty MVC 3 Application, I chose an Internet Application and didn’t select to add a Unit Test Project.
  2. I changed the text on the main page that will do for now. Then I copied the contents of the solution and the folder to my Github local repository folder.
  3. Go to Github and create yourself an account – this is free and allows you to put up your code – very useful for open source projects or you can use it to publish to Appharbor like we are about to do.
  4. Create a new Repository on GitHub as below and GitHub will show you the steps to adding the code to your repository on GitHub, similar to the screen shot below.

    Github Repo

    Go ahead and follow these steps to add your content onto GitHub.

  5. Now we want to add a .gitignore file into the git repository so that when we deploy to AppHarbor it builds without any issues. Create a .gitignore file and add this into your repository – the contents of my .gitignore file was as follows:-

    [Bb]in
    [Oo]bj
    *.suo
    *.user

  6. At this point our source code is up on GitHub and now we want to deploy it from GitHub to AppHarbor – this step is very easy indeed and makes everything worthwhile and definitely worth any effort in having to learn git and setup accounts on both GitHub and AppHarbor.
  7. Log onto your AppHarbor Account and then create a new application as below:-

    AppHarbor

  8. Now click on the Build URL link on the blue part of the screen shot below:-

    AppHarbor

    This copies the url you need to paste into GitHub in order for it to deploy your code to AppHarbor, firstly paste this link from your clipboard into notepad.

  9. Here is the url for a potential app:-

    AppHarbor Build URL

  10. Ok now go back to GitHub and go to the admin link once you are on the page displaying your GitHub repository.

    GitHub Admin Link

  11. Click on Service Hooks on the left hand side and then select AppHarbor – this is where you need to be careful to paste in the Slug from the notepad link we have and then paste in the authorization code into the correct part within GitHub as below:-

    AppHarbor Details

  12. Back to AppHarbor and we should see something like the screenshot below, AppHarbor has built my code and deployed it, clicking on the ‘Go To Your Application’ link will show you the app deployed to the url for your site hosted on AppHarbor – free.

    View App

Conclusion
AppHarbor is really cool and very handy indeed, after deploying your first app you can deploy straight from GitHub just by pushing up file changes. Its superb, also comes with a host of add-ons, please go check it out now.

Glencoe Scotland – road trip

Today I went for a run and having never been to Glencoe in Scotland I decided to go for a drive and see the stunning scenery for myself – unfortunately my pics don’t do the place justice, but here are a few of the ones that turned out some what ok. If you ever get the chance to visit then you should take a run up there its awesome – Scotland has some stunning scenery.

Pic1
Pic2
Pic3
Pic4
Pic5
Pic6

In 2012 I plan to see more of the beautiful country I live in – hope you enjoy.

Real World MVC 3 Development

During the last couple of months I have been working with MVC 3 daily and I have used Nuget packages and tools which have helped in a number of areas, in this post I will give a shout out to these tools which help make MVC 3 a pleasure to work with. For the most part Nuget packages can be found for these tools so you can add them very easily and get going quickly.

Routing

    • Attribute routing for MVC – Remove any routing concerns/issues and start using this now.
    • T4MVC helps make your MVC code much more maintainable, enough said.

Page Performace

      • Chirpy is an open source Visual Studio Add In For Handling JavaScript, Css, DotLess, and T4 Files, which in essence improves page performance.
      • Cassette – Cassette automatically sorts, concatenates, minifies, caches and versions all your JavaScript, CoffeeScript, CSS, LESS and HTML templates.

Profiling

      • Mvc Mini Profiler – A simple but effective mini-profiler for ASP.NET MVC and ASP.NET.
      • Glimpse – What Firebug is for the client, Glimpse does for the server… in other words, a client side Glimpse into whats going on in your server.

Error Logging

      • ELMAH – ELMAH (Error Logging Modules and Handlers) is an application wide error logging facility that is completely pluggable. It can be dynamically added to a running ASP.NET web application, or even all ASP.NET web applications on a machine, without any need for re-compilation or re-deployment

All MVC posts

        • All of my MVC blog posts can be found here.

Conclusion

MVC is great to work with on its own but these tools can only enhance the development process. Please leave feedback or comments, and also let me know if I have missed out on any tools which I can add to this list.

Follow

Get every new post delivered to your Inbox.