Javascript Sandbox for ASP.NET MVC 3

October 21st, 2011 by Gareth / Comments

I’ve started reading more about Javascript this year. My home project is coming up to the point where I’m making some important client side decisions and I want to make sure I’m making the best choices.

As anyone who has looked beyond the surface will tell you, Javascript is deceptively complex and capable. I have four books helping me out at the moment :

I recommend all four. I started reading Javascript Web Applications by Alex MacCaw because I wanted to understand how Javascript frameworks like KnockoutJS, BackboneJS and JavascriptMVC are constructed rather than just use them and this book is exactly for that purpose. For me it quickly proved to be a bit too “in at the deep end” so I’ve switched to Javascript Enlightenment by Cody Lindley to get a solid and deep understanding of Javascript.

All these books have code examples and I learn best by following, experimenting and pushing the samples with questions that pop up. So how does an ASP.NET MVC developer play around with Javacsript?

  • You could have a folder full of HTML files and chuck your javascript in there, and run them individually
  • You could use JS Fiddle
  • You could spend three hours creating a modest little sandbox framework built as an ASP.NET MVC app

I did the last one. At one point I abandoned it and switched to JS Fiddle, but then I went back to it. I prefer messing about in my own environment sometimes.

I’ll call your individual Javascript fiddles a sandcastle because I’m looking left and right and can’t see anyone telling me not to (although I am alone in my upstairs office). A Javascript sandcastle is created as a view like this :

  1. Description : Optional description of what your javascript is testing
  2. Javascript_Setup : Stick your setup code in here
  3. Javascript_Test : The code that runs against the Javascript_Setup code

Then edit the Home/Index view to add a link to your new test. As you can see from the screenshot in the link I’ve added the html helper @Html.SandboxLink(sandboxViewName,description) to simplify generating links to your Javascript tests. I want to automate this at some point in the future so you only need to create the views.

The advantage you will notice at this point is that you get Intellisense in your sandcastle because it’s all in an ASP.NET MVC view in Visual Studio. The other advantage comes from how the _SandboxLayout.cshtml  page presents the results. Here’s what you see when you’ve run a test :

Your sandcastle is presented nicely and formatted using the terrific Syntax Highlighter by Alex Gorbatchev. There is a generous 500ms pause while I wait for the formatting to complete then I run your test code. In your JavaScript you can call the helper log() function which outputs to the Log area at the bottom thus completing your test and showing you what happened. Logging helps to see the flow of the code which isn’t always obvious with Javascript, look at a slightly more complex example to see what I mean.

When I’ve grokked the good parts of Javscript the next step on my client side journey is Javascript unit testing. When I mention “test” in this blog post I’m not talking about unit testing an application’s code, I’m talking about isolated tests that’ll help you figure out some code – a tiny bit like how we use LinqPad (but that’s in a different league of course).

You can download this project from my Javascript Sandbox For ASP.NET MVC 3 Github page (I’m really enjoying using it to learn Javascript) or you could use JSFiddle and wonder with bemusement why I spent 3 hours putting this project together, 2 hours writing this blog post and 15 minutes messing about with Git when I could have finished the book by now and be back working on my home project.

My home project is such a long way off because every little step of the way I’m going down all these rabbit holes and discovering that rabbit droppings taste good.

ASP.NET MVC, Javascript, jQuery

Comments

Added MVC Mini Profiler to PetaPoco – A simple web app

August 8th, 2011 by Gareth / Comments

I saw a question on Stack Overflow asking how to setup Sam Saffron’s MVC Mini Profiler to work with PetaPoco and realised it would be a good idea to implement the mini profiler into my PetaPoco example app.

The latest release of PetaPoco included a change that made it very easy to integrate the profiler with PetaPoco if you want to. Prior to the latest version you had to hack the PetaPoco.cs file a little bit or implement your own db provider factory. Pleasingly there is now a virtual function called OnConnectionOpened(), which is invoked by PetaPoco when the database connection object is first created. Being a virtual function you can override it in a derived class and return the connection object wrapped in the MVC Mini Profiler’s ProfiledDbConnection class. Like this :

	public class DatabaseWithMVCMiniProfiler : PetaPoco.Database
{
   public DatabaseWithMVCMiniProfiler(IDbConnection connection) : base(connection) { }
   public DatabaseWithMVCMiniProfiler(string connectionStringName) : base(connectionStringName) { }
   public DatabaseWithMVCMiniProfiler(string connectionString, string providerName) : base(connectionString, providerName) { }
   public DatabaseWithMVCMiniProfiler(string connectionString, DbProviderFactory dbProviderFactory) : base(connectionString, dbProviderFactory) { }
 
   public override IDbConnection OnConnectionOpened(
      IDbConnection connection)
   {
      // wrap the connection with a profiling connection that tracks timings
      return MvcMiniProfiler.Data.ProfiledDbConnection.Get( connection as DbConnection, MiniProfiler.Current);
   }
}
	

I didn’t want to lose the existing Glimpse profiling I had in place so I made my class derive from DatabaseWithGlimpseProfiling, which is already in my project’s codebase, so you get both methods of profiling in one app.

	public class DatabaseWithMVCMiniProfilerAndGlimpse : DatabaseWithGlimpseProfiling
	

This is turning into a profile demonstration app with a bit of PetaPoco chucked in :

You can download PetaPoco – A Simple Web App from my GitHub repository.

ASP.NET MVC, Data, Petapoco

Comments

PetaPoco – A simple web app

June 12th, 2011 by Gareth / Comments

I’ve put together a basic web app using PetaPoco to manage a one-to-many relationship between authors and their articles.

The author poco contains just the author’s name, id and a list of articles the author has written :

	public class Author
{
    public int Id {get; set;}
    public string Name {get; set;}
 
    [ResultColumn]
    public List<Article> Articles {get; set;}
 
    public Author()
    {
        Articles = new List<Article>();
    }
}
	

The Author.Articles list is a [ResultColumn] meaning that PetaPoco won’t try and persist it automatically, it’s ignored during inserts and updates. The Article poco has more properties :

	public class Article
{
    public int? Id {get; set;}
    public string Title {get; set;}
    public string Body {get; set;}
 
    [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode=true)]
    public DateTime Date {get; set;}
 
    [ResultColumn]
    public Author Author {get; set;}
 
    [Column( "author_id")]
    [DisplayName( "Author")]
    public int? AuthorId {get; set;}
 
    public Article()
    {
        Date = DateTime.Now;
    }
}
	

The Date property has a date format attribute so that in the \Article\Edit.cshtml view @Html.EditorFor(model => model.Article.Date) will display the date how I want it. The Author property is another ResultColumn only used when displaying the Article, not when updating it. In the ArticleRepository I use the MulltiPoco functionality in PetaPoco to populate the Author when the Article record is retrieved.

Setup

By default the app uses the tempdb at .\SQLEXPRESS. This is defined in the web.config :

	<add name="PetaPocoWebTest" connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=tempdb;Integrated Security=True" providerName="System.Data.SqlClient" />
	

The tempdb is always present in SQL Server and is recreated when the database is stopped and started. You can change this to suit your environment. The app will auto generate the tables for you if they don’t exist. In theory if you have SQL Express running you don’t need to do anything to get started

A few details

There are two repository classes; AuthorRepository and ArticleRepository. These classes are where the PetaPoco work lives. As well as loading the Author the AuthorRepository class also loads in the list of articles by that author. I use a relationship relator callback class as demonstrated in the recent PetaPoco object relationship mapping blog post. I made a slight tweak to handle objects that have no child objects at all otherwise there was always a new() version of Article in the list. The fix is simple :

	if( article.Id != int.MinValue)
{
    // Only add this article if the details aren't blank
    _currentAuthor.Articles.Add( article);
}
	

I tried to get this working with an int? Id, but had type conversion problems in PetaPoco. I’ll investigate that later as it would be useful to have int? Id to indicate a blank record

I’ve used the Glimpse PetaPoco plugin by Schotime (Adam Schroder). Because the Glimpse plugin uses HttpContext.Current.Items all the SQL statements are lost when RedirectToAction() is called from a controller. I got around this by copying the PetaPoco Glimpse data into TempData before a redirect, and from TempData back into the Items collection before the controller executes.

This means you still see update/insert/delete SQL. It is definitely a requirement to perform a RedirectToAction() after such database calls so that it isn’t possible to refresh the screen and re-execute the commands (ie; cause havoc). If the user did refresh the screen (or otherwise repeat the last request) they’d just get the redirect to action and not the request that fired the database action.

I expect this to be a common pattern with Glimpse plugins that use response redirects.

UPDATE
Many thanks to Schotime who showed me that the Remote tab in Glimpse shows you the last 5 requests. All the SQL is there in Glimpse if you look for it. I didn’t realise this when I added the TempData solution :) but at least using TempData the SQL commands prior to a redirect are visible right on the PetaPoco tab without having to drill down to the previous request, which I kinda like as it’s more intuitive and effortless.

Hope this is useful to someone. You can download the source at GitHub. This is my first project using git so if there are any problems please let me know.

Finally, I’ve cut my finger and I’m angry with my cat.

ASP.NET MVC, Data, Petapoco

Comments

My Micro-SAAS Journey

Get the inside story as I work out how to create a micro-SAAS