ninja star Using RavenDB with ASP.NET MVC

by Michael Ceranski, posted on November 08 2010

imageTraditionally when you think about a database you think of tables, views, indexes and stored procedures. If you have made a career out of developing database centric applications like I have, then chances are that you have spent a great deal of time dealing with issues around referential integrity, normalization and performance.

Unless you have been living underneath a rock, then you have probably heard of the newest database trend named NoSQL. NoSQL refers to non relational document databases that help address issues like performance and scalability which are often hard to achieve when using traditional database systems such as SQL or Oracle.  NoSQL replaces the old “scale up” mantra of database management  with a new one: “scale out.” Instead of adding bigger servers to handle more data load, a NoSQL database allows a company to distribute the load across multiple hosts as the load increases. In case you are wondering many successful companies such as Amazon, the BBC, Facebook and Google already rely on NoSQL DBs for day to day operations.

If you do a quick search on the web you will discover that there are many document databases to choose from. Some of the most popular options today are MongoDB, CouchDB and RavenDB. For whatever reason I was attracted to RavenDB because I knew it would seamlessly integrate with the .NET/windows platform. As always, the best way to learn something is to jump in head first. So the following article is a step-by-step tutorial on how I built an MVC 2 web app using RavenDB as the backend.

 

Installing RavenDB

  • Download the latest bits from the RavenDB website. In order to keep things simple extract the files to C:\Raven
  • In my example I configured RavenDB as an IIS application. Here are the steps which I have taken directly from the RavenDB website:
    • Extract the distribution zip.
    • In IIS Manager, create a new Web Site and point its physical path to the "/Web" folder in the extracted folder.
    • Set the Application Pool to "ASP.Net v4.0" (or create a new Application Pool set to .NET 4.0 Integrated Pipeline)
    • Set port and host, if you need them.
    • Make sure that the user you set for the site has write access to the physical database location.
  • Finally, make sure that you have read/write access to the “c:\Raven\Web\Data folder”.

Once everything is configured you should be able to open a browser and view the RavenDB console:

image

Using RavenDB with ASP.NET MVC

After you create your ASP.NET MVC web app, the first thing you need to do is add a reference to the C:\Raven\Client\Raven.Client.Lightweight.dll assembly.

Second, you need to initialize the client. According to the documentation the DocumentStore object should only be created once per application. So I setup my document store in the Application_Start event of my MVC application:

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

    RegisterRoutes(RouteTable.Routes);

    var documentStore = new Raven.Client.Document.DocumentStore { Url = "http://localhost:8080" };
    documentStore.Initialize();
    Application["DocumentStore"] = documentStore;
    
    ControllerBuilder.Current.SetControllerFactory(typeof(CustomControllerFactory));
}

At this point you have an initialized client and you could start accessing the data. However, I decided to wrap my calls in a repository class. My repository class implements an interface so I can easily create a “fake” repository for unit testing purposes.  As a good practice, I typically create a base controller which takes an IRepository object as a parameter. This is a simple form of Dependency Injection that comes in handy when creating unit tests later on. Anyways, the repository code that I came up with is very simple and straightforward. The Raven API utilizes LINQ so as a .NET developer you should feel right at home. As you will see below, the constructor of the RavenRepository class takes a DocumentStore which was created during the Application_Start event. Here is the code:

public class RavenRepository : IRepository
{        
    private DocumentStore _store;
    private IDocumentSession _session;

    public RavenRepository(DocumentStore store)
    {
        _store = store;
        _session = _store.OpenSession();
    }        

    public T SingleOrDefault<T>(Func<T, bool> predicate) where T : IModel
    {
        return _session.Query<T>().SingleOrDefault(predicate);           
    }

    public IEnumerable<T> All<T>() where T : IModel
    {
        return _session.Query<T>();
    }

    public void Add<T>(T item) where T : IModel
    {
        _session.Store(item);
    }

    public void Delete<T>(T item) where T : IModel
    {
        _session.Delete(item);
    }

    public void Save()
    {
        _session.SaveChanges();
    }
}

Now, that the repository is created we need to create some models to use with it. Here is a simple Person class. I also added a few data annotations to make validation and formatting easier in MVC.

public class Person : IModel
{
    public string Id { get; set; }

    [DisplayName("First Name")]
    [Required(ErrorMessage="*")]
    public string FirstName { get; set; }
    
    [DisplayName("Last Name")]
    [Required(ErrorMessage = "*")]
    public string LastName { get; set; }

    [Required(ErrorMessage = "*")]       
    [DataType(DataType.EmailAddress)]
    public string Email { get; set; }
}

In order to understand how the repository works, lets take a look at the Create and Edit methods that I created in the PersonController. The create action is very simple, you instantiate a new person, add it to the repository and then save your changes:

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

[HttpPost]
public ActionResult Create( PersonViewModel input )
{
    var person = new Person
    {
        FirstName = input.Person.FirstName,
        LastName = input.Person.LastName,
        Email = input.Person.Email
    };

    _repository.Add(person);
    _repository.Save();
    TempData["Message"] = "Person created successfully";
    return RedirectToAction("Index");
}

Editing is just as easy, you retrieve the record from the repository, update the properties and save:

public ActionResult Edit(string id)
{            
    var model = new PersonViewModel(_repository,id);
    
    if (model.Person == null) return View("NotFound");

    return View(model);
}

[HttpPost]
public ActionResult Edit(string id, PersonViewModel input)
{
    var person = _repository.SingleOrDefault<Person>(x => x.Id == id);
    person.FirstName = input.Person.FirstName;
    person.LastName = input.Person.LastName;
    person.Email = input.Person.Email;
    _repository.Save();

    TempData["Message"] = "Person updated successfully";
    return RedirectToAction("Index");
}

Conclusion

Document databases are extremely easy to use, setup and develop against. The fact that you can create an object and stuff it into the database without having to fool around with an object to table mapping is absolutely fantastic! The demo project is attached.

RavenDbDemo.zip (114.69 kb)

Tags:

ninja star Charting with JavaScript

by Michael Ceranski, posted on October 24 2010

Last week a co-worker of mine sent me a link for the gRaphaël charting library. gRaphaël is a full fledged charting library written entirely in JavaScript. Normally when I need to do charting on a website I resort to using the Microsoft Chart Controls. Unfortunately the MS Chart Controls run on the server side, rely on IIS and tend to a require a slight learning curve before you can become efficient with them. Since the gRaphaël library is written in JavaScript it is lightweight, easy to use and it will run in almost any browser. Since seeing is believing, here is a walkthrough on how to create your first pie chart with gRaphaël:

 

Step One - add a script reference to the raphael.js and g.raphael.js. These two files are required no matter what type of chart you are trying to render.

<script src="http://raphaeljs.com/raphael.js" type="text/javascript" charset="utf-8"></script> 
<script src="http://g.raphaeljs.com/g.raphael.js" type="text/javascript" charset="utf-8"></script> 

Step Two - Once you determine what type of chart you are trying to draw you will need to include additional files. For example if you are drawing a pie chart you will also want to include the g.pie.js file:

<script src="http://g.raphaeljs.com/g.pie.js" type="text/javascript" charset="utf-8"></script>

Step Three – Add a div to your page that you will use as a place holder for the rendered chart. The id attribute on the div tag will be referenced in the document.ready event to wire up the control.

<div id="pieDemo"></div> 

Step Four – Wire up the JavaScript and render the chart. I am going to build a pie chart which displays the market share for the top 3 browsers. According to a post I found on softpedia on October 6th, IE leads the race with 59.65, followed by Firefox with 22.96 and Chrome with 7.98. The pie chart will have a legend and display the percentages. The legend will be positioned on the left hand side. Here is the code:

$(document).ready( function() {
    var r = Raphael("pieDemo");
    r.g.txtattr.font = "12px 'Fontin Sans', Fontin-Sans, sans-serif";
    r.g.text(320, 70, "Top 3 Browser Usage").attr({"font-size": 20});
    var pie = r.g.piechart(320, 240, 100, [59.65, 22.96, 7.98], {legend: ["IE - %%.%%", "Firefox - %%.%% ", "Chrome - %%.%%" ], legendpos: "west", href: ["http://raphaeljs.com", "http://g.raphaeljs.com"]});
});

 

And here are the results...

image

You have to admit that building this pie chart was extremely simple. A few script references, a div tag and a little bit of JavaScript and you are done. Much simpler than the steps that I had to go through in order to use the MS Chart Controls in ASP.NET MVC.

Anyway, I hope you find this control as useful as I did. If so, then please make a donation to the author Dmitry Baranovskiy. Thanks Dmitry!

Tags: ,

ninja star Five Must Have Tools for MVC Developers

by Michael Ceranski, posted on September 27 2010

Zippy-236x300 Chirpy Zippy – A Visual Studio add-in that Mashes, minifies, and validates your JavaScript, Stylesheet, and dotless files. Chirpy can also auto-update T4MVC and other T4 templates.

In the past, I  typically would run all of my script and CSS files through a compressor before deploying them to a production web server. However, with Chirpy installed, your CSS and script files will be automatically compressed based on their  name. For example, if you have a script file named myscript.js that you want compressed, you would rename the script to myscript.yui.js and your file will automatically be minified using the YUI compressor. The minified file shows up as a child item in solution explorer so you still have your non-minified, human-readable scripts for debugging purposes.

T4MVC - I blogged about T4MVC before but its always worth mentioning again. T4MVC is a T4 template for ASP.NET MVC apps that creates strongly typed helpers that eliminate the use of literal strings when referring the controllers, actions and views. It helps make your MVC code much more maintainable, and gives you intellisense where you normally would not have any.

MVC Contrib – T4MVC is a small part of the MVC Contrib library which contains various utilities for the realm of ASP.NET MVC development. I recently wrote a post about the Grid HTML Helper which I am using in a few of my personal projects. However, MVC Contrib contains many features and libraries which you may find useful in your day to day development.

ASP.NET Sprite and Image Optimization Framework – One of the best ways to boost the performance of your website is to reduce the number of HTTP requests required to render a page. One way to reduce the amount of requests is to use CSS sprites or inline images.

For example, say you have a toolbar on your websites which contains twelve 32 pixel by 32 pixel icons. When the page loads 12 HTTP requests need to be made, one for each image. A CSS sprite can reduce the number of requests to one by stitching all of the images together and using CSS styles to define the boundaries of each image.

Unfortunately, the process of creating sprites can be time consuming and tedious. You basically need to merge all the images and then declare the x and y boundaries for each image in your stylesheet. Wouldn’t it be nice if the merged image and CSS could be automatically generated? Well…they can, the ASP.NET Sprite and Image Optimization Framework does exactly that.

ELMAH– If you are not using ELMAH than you should be. ELMAH is the ultimate tool for logging errors in your MVC application. It requires very little setup but delivers a boat load of features. Here is a quick list:

  • Logging of nearly all unhandled exceptions.
  • A web page to remotely view the entire log of recoded exceptions.
  • A web page to remotely view the full details of any one logged exception.
  • In many cases, you can review the original yellow screen of death that ASP.NET generated for a given exception, even with customErrors mode turned off.
  • An e-mail notification of each error at the time it occurs.
  • An RSS feed of the last 15 errors from the log
Tags: ,

ninja star Automatic Resource File Translation via Google Translate

by Michael Ceranski, posted on September 15 2010

One of the features that I support in WeBlog is localization. That means that all the labels, buttons and text within the application are stored in a resource file. So if you switch from English to Spanish, the text will be automatically displayed in the right language. For more information about how this magic happens, read this article.

Since I am only fluent in English I depend on Google translator to make the translations for me. After about 10 minutes of manually translating a spanish resource file, I decided that I needed a way to automate the process. I did a quick Google search and discovered that the translator service utilizes a JSON based API. A little more searching and I found a class library written by Alex Meyer-Gleaves which takes care of making the service calls to the translator API and parsing the results. So the only work I had to do was read the resource file, invoke the translator via Alex’s C# library and save the translated data to a new resource file.

Turns out that reading a resource file is extremely easy in C#. You just use the ResXResourceReader class, get an enumerator and iterate over the file. I put my results in a dictionary so it would be easy to iterate over the values later on.

private Dictionary<string, string> ReadResourceValues(string filename)
{
    var results = new Dictionary<string, string>();
    // Create a ResXResourceReader for the file items.resx.
    ResXResourceReader rsxr = new ResXResourceReader(filename);

    // Create an IDictionaryEnumerator to iterate through the resources.
    IDictionaryEnumerator id = rsxr.GetEnumerator();

    // Iterate through the resources and display the contents
    foreach (DictionaryEntry d in rsxr)
    {
        results.Add(d.Key.ToString(), d.Value.ToString());
    }

    return results;
}

Now that the resource file has been read I just need to translate the values. Again, thanks to Alex, The translation service calls are extremely simple. Here is the code that I used to invoke the translator service and add the results to a data table. Just for your information, the Translate method generates an Http request, de-serializes the results (a JSON object ) and populates an object so we can easily consume the results:

DataTable table = new DataTable();
table.Columns.Add("Source Key");
table.Columns.Add("Source Value");
table.Columns.Add("Translation");

var resource = ReadResourceValues(txtResourceFile.Text);

foreach (string key in resource.Keys){
    var row = table.NewRow();
    row[0] = key;
    row[1] = resource[key];

    try{
        TranslationResponse response = Google.Translate(resource[key], Language.Unknown,
                                                        cbDestLang.SelectedValue.ToString(),
                                                        TextFormat.Text);
        row[2] = response.ResponseData.TranslatedText;
    }
    catch {
        row[2] = "?";
    }                        
    table.Rows.Add(row);
}

grid.DataSource = table;


Anyway, here is the end result. If you are fluent in Spanish then you will probably not completely agree with all of the translations shown in the screenshot below. In any case, this utility is a quick way to get the translation started. For English only speaking geeks like me, this utility is a life saver.

image

Download the Source Code - GoogleTranslator.zip (499.94 kb)

Tags:

ninja star Simple Dependency Injection using a Custom MVC Controller Factory

by Michael Ceranski, posted on August 30 2010

Whenever I develop an MVC application there is always some degree of data access required. As a best practice, I usually define a interface that my repository objects will adhere to. Creating an interface is generally a requirement for Dependency Injection (DI). DI is a very important pattern if you plan on doing any unit testing later on. For the purpose of this demo, I am going to keep things simple and only create a fake repository.  Here is the code:

public interface IRepository
{
    Person GetPerson( int id ); 
}

public class FakeRepository : IRepository
{        
    public Person GetPerson( int id )
    {
        return new Person { Id = id, FirstName = "Mike", LastName = "Ceranski" };
    }
}

Obviously, in a real-world application you would probably utilize the Entity Framework or LINQ to SQL in order to implement the IRepository interface. However, for the purposes of this demo the FakeRepository illustrates the point. Moving on, the next step is to create a base controller class which all of the other controllers in the application will derive from. The BaseController class has a IRepository property which gets set by the constructor. By having this constructor we can easily “inject” our repository objects.

public class BaseController : Controller
{        
    public IRepository Repository { get; private set; }

    public BaseController(IRepository repository)
    {
        Repository = repository;
    }
}

So now its time to create the "Person" controller which inherits from the BaseController class. We also add a single action named "Details" which will get return a Person model from the repository:

public class PersonController : BaseController
{
    public PersonController(IRepository repository) : base(repository) { }

    public ActionResult Details( int id = 1)
    {
        return View( Repository.GetPerson(id) );
    }
}

So at this point you may think your work is done, right? Well, if you were to run the application at this point and try to view the Details for the person with the ID 1 (“/Person/Details/1”) you would get an error stating that “No parameterless constructor is defined for this object”. That’s because the default controller factory used in MVC always uses the default constructor to create a controller. Since our PersonController does not have a parameterless constuctor defined, the application throws an error. Obviously, we will need to do a little more work in order to make MVC use our DI friendly constructor. Luckily this is easily accomplished by creating and registering our own custom controller factory. Here is the code:

public class CustomControllerFactory : DefaultControllerFactory
{
    protected override IController GetControllerInstance(System.Web.Routing.RequestContext requestContext, Type controllerType)
    {
        return Activator.CreateInstance(controllerType, new FakeRepository()) as IController;
    }
}

The code above overrides the CreateController method. It uses the Activator.CreateInstance method to create the controller using our custom constructor and passes in a new instance of the FakeRepository class. So now the final step is to register the CustomControllerFactory in the Global.asax:

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

    RegisterRoutes(RouteTable.Routes);

    ControllerBuilder.Current.SetControllerFactory(typeof(CustomControllerFactory));
}

Now, when I run my application and access the URL "/Person/Details/1" I get the following results:

image

The end result is a MVC application which allows you to easily inject repository objects for testing purposes!  The sample code is attached.

DI_MVC_Example.zip (252.38 kb)

About the author

MikeMichael Ceranski is a developer specializing in the .NET stack. I have spent time as a DBA, Web Developer and even a network engineer. Up til now most of my career has revolved around the .NET stack but I have recently taken an interest in microcontrollers which has forced me to get acquainted with lower level languages such as C, and C++.

View my resume

Sponsors