NetBash Updated – Formatting Helpers Added

NetBash (drop in command line for asp.net web applications) was first released late last year with little to no response from the community. No big deal – I built it to scratch my own itch so it was at least going to be useful to me. Then, like clockwork I go on holidays for a week and a bit and it is featured on Asp.net and tweeted by close to 100 people. I have used the past few days to catch up with the bugs people have found (thanks heaps to those who forked and fixed bugs themselves) and get a new release out on NuGet.

Bug Fixes

  • NetBash is now compatible with older versions of JQuery (1.5 at least). This was causing some issues with people using a fresh file –> new project mvc app to test it out.
  • Console now auto scrolls to bottom when opened.
  • Now more compatible with older versions of IE.

Formatting Extensions

A couple of classes have been included in the NetBash.Formatting namespace to help make the output of your commands a bit prettier. The most useful is the TableExtensions class contributed by Damian Karzon. This class includes a couple of extension methods on IEnumerable<T> that take a list of objects and using reflection output them into a nice consoley table. Here is an example:

public string Process(string[] args)
{
    var tempData = new List<GridData>
    {
        new GridData
        {
            RowId = 1,
            SomeName = "NUMBER1",
            Longtext = "12345678901234567890",
            SomeDate = DateTime.Today
        },
        new GridData
        {
            RowId = 2,
            SomeName = "sup bro",
            Longtext = "I AM THE GREATEST",
            SomeDate = DateTime.Now.AddDays(21)
        },
        new GridData
        {
            RowId = 5,
            SomeName = "GridCommand",
            Longtext = "longish",
            SomeDate = DateTime.Now.AddDays(-3)
        }
    };

    return tempData.ToConsoleTable();
}

Output:

gridyo

Pretty neat I think. It works with most things I’ve thrown at it including anonymous classes but not dynamic.

The other class is called SparkExtensions. This class is a C# port of this cool little shell script. The Spark() methods are extension methods on various IEnumerable collections (int, decimal, string, etc) they take the list and turn it into a cool little spark line graph similar to this: ▁▂▃▅▂▇. Here is a basic example:

public string Process(string[] args)
{
    var list = new List<int>() { 5, 7, 3, 8, 9, 2, 12, 7, 6 };

    return list.Spark();
}

Hopefully these additions make building commands a little more painless. If you are using NetBash or better still have built some open source commands I’d love to hear from you. NetBash source can be found on Github and downloaded using NuGet.

NetBash – An Alternative to Endless Admin Pages in Asp.Net Web Applications

One thing that always annoys me when working on a web app is having to write those inevitable pages full of admin functions some of which are just a single button. When hacking up one such page I had a thought – a plug in library providing a command line for your web app might save me a lot of time. NetBash is what I came up with.

netbash

As you can see from the screenshot NetBash is basically a miniature command line complete with that sweet lime green on black theme that lives in your web app. It can be expanded, minimised and hidden with keyboard shortcuts (keymaster ftw) and remembers recent command history using localStorage. NetBash works in a similar way to the MVC Mini Profiler meaning that it can be installed with minimal effort on your part (just a NuGet package) and follows you around your site. This is the setup:

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

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

    NetBash.Init();

    //this is optional, allows you to decide who sees netbash
    NetBash.Settings.Authorize = (request) =>
        {
            return request.IsLocal;
        };
}

The call to Init inserts a couple of routes for the handler, css and js files. You also need to somewhere in your _Layout.cshtml / MasterPage add the RenderIncludes function to write the css and script tags to the page.

NetBash.RenderIncludes()

The way it works is by searching your application using reflection for classes implementing IWebCommand with a WebCommand attribute. The WebCommand attribute defines a name for the command which is used to invoke it as well as a description displayed on help. The IWebCommand interface has a method called Process which passes in a string array of arguments in the same manor that a .NET console application’s main method would. When a command is entered on the front end an ajax request is made to the NetBash handler. The handler grabs the first word of the request text and matches it to a WebCommand with the same name then invokes Process and returns the result. Here is a very simple example command that returns the length of the arguments passed in:

[WebCommand("length", "Returns number of characters in given arguments")]
public class LengthCommand : IWebCommand
{
    public bool ReturnHtml
    {
        get { return false; }
    }

    public string Process(string[] args)
    {
        return string.Join(" ", args).Length.ToString();
    }
}

Hopefully defining commands this way makes it both dead easy to implement while allowing flexibility to do something more complex (perhaps parsing the arguments with nDesk.Options).

It is pretty early days for the code so I probably wouldn’t recommend using it in a production situation at the moment. NetBash is available as a NuGet package and the source on GitHub at lukencode/netbash. I’d love to hear people opinions on the api (nothing is set in stone) as well as the UI which could use some work. I have some ideas for some useful commands (some mad stats with a .net version of spark) also Ben Cull promises me he will write an asp.net membership command pack.

Windows Phone (Mango) Contact Chooser Task

When creating the amazing, incredible and life changing app for managing money you borrow and lend Metrowe I was pretty annoyed to discover that in the Mango SDK there are choosers for selecting emails: EmailAddressChooserTask and phone numbers: PhoneNumberChooserTask but not just plain selecting a contact. The problem with the other choosers is the email address will exclude contacts without an email and similarly the phone number chooser and phone numbers. After much complaining decided to develop my own contact chooser (quite closely based off this french one) matching the OS version as closely as possible. This is what it ended up looking like:

contact-chooser

Seamless huh? I’ve managed to get the calling code for this down to something nice a simple which pretty much matches the built in choosers:

private void button1_Click(object sender, RoutedEventArgs e)
{
    var contactChooser = new ContactChooserTask();
    contactChooser.OnSelected += new EventHandler<ContactChooserEventArgs>(contactChooser_OnSelected);
    contactChooser.Show();
}

void contactChooser_OnSelected(object sender, ContactChooserEventArgs e)
{
    MessageBox.Show(e.Contact.DisplayName);
}

Under the covers it is a bit of a different story. The display relies on the Silverlight Toolkit’s LongListSelector (which is awesome) and uses code pretty similar to that described by my good friend Benjii in his post: How to Use the Long List Selector for Windows Phone Mango. The code to encapsulate the page is kind of a mish mash of code adapted(/stolen) from the source of the Coding4Fun toolkit (also awesome). That said it seems to work well in my app and in my very limited testing.

The code for the library lives on github at lukencode/ContactChooser and is free and open source fork it, try it out, tell me how I suck then submit a pull request fixing the aforementioned suck! A couple of things that would be cool to see added would be some nice transition animations in and out and some more control over how the chooser looks.

Behind the XAML of the Windows Phone Silverlight Game – Numbertap

Numbertap is a Windows Phone game built by me and a few mates (@benjii22, @d1k_is and @fishkopter). It is alive and well in the marketplace right now in the games section. When people ask this is what we tell people Numbertap is:

“NumberTap pits you and your mad math skills against the rest of the world in a fast paced number tapping math frenzy!”

What that actually means is Numbertap is a maths based game where you answer maths questions online organised into 2 minute rounds. At any one time everyone playing the game is playing the same round, at the end scores are tallied and you are placed in your rightful place as king of the maths world on the online leader board. Its kinda like times tables meets guitar hero scoring meets global leader boards. Here is a shot of the game in action:

GameScreen

This post is a collection of the libraries and techniques we found useful in both the windows phone app and the asp.net mvc server side.

The App

Like all good Windows Phone apps we focused on a few key ideas – simply and beautiful design, fluid movement and animation and speedy performance. Listed in no particular order is the technology we used to (hopefully) achieve this.

Silverlight over XNA for a game?!
If I were to guess I would say the vast majority of windows phone games are XNA based (and with good reason!) but we had a couple of reasons to roll with Silverlight:

  1. We know Silverlight. This one is the most obvious 3/4 developers had built reasonably successful apps using Silverlight while 0/4 of us had built anything at all in XNA.
  2. We wanted a kick ass metro design. Building apps with expression blend in Silverlight almost feels like cheating in terms of design. All the styles, colours, buttons and fonts are right there ready to go all the [crap at design] developer has to do is follow Jeff Wilcox’s excellent metro design guideto metro UI heaven (just don’t let Jeff catch you missing a 12px margin). Since the gameplay we had in mind was pretty simple and Silverlight animations are actually pretty powerful we didn’t give up too much on the XNA front.
  3. There is no 3.

Awesome Open Source Control Libraries
This is one are where windows phone is really starting to shine, nearly any control you would want UI wise that isn’t in the base SDK exists in a well documented and supported open source library. The two we like best are the official Silverlight Toolkit and the Coding4Fun Toolkit both are available on NuGet.

Silverlight toolkit is more or less a must have in every windows phone app. The most useful thing it brings to the table is really nice and super simple to implement page transitions. Here is an example of some XAML form the Numbertap about page to do turnstile transitions in and out:


    
        
            
        
        
            
        
    


    
        
            
        
        
            
        
    

The other Silverlight Toolkit feature I really like is the tilt effect, it really helps bring an application to life when elements react to touch. You can automatically add a “tilt” to all eligible controls (buttons, list items, etc) on a page by just adding this to your PhoneApplicationPage xaml.

toolkit:TiltEffect.IsTiltEnabled="True"

Coding4Fun is the other toolkit we make heavy use of. It has a couple of good controls but the ones we really like are the prompts. The input prompt was clean way to prompt players on registration, as with all the Coding4Fun prompts the code is really simple.

var msg = new InputPrompt();
msg.Title = "Create Player";
msg.Message = "Please enter a player name";

msg.Show();

That code (plus a tiny bit extra to add the buttons) gives this result:

input-prompt

These are other prompts we use are the regular message prompt and the toast prompt (that one looks awesome, slides in and out). They use really similar and really simple code to display so I won’t show it again (but if you want to see let me know).

message-box-resizetoast-resize

Web Services with RestSharp
I’ve already posted about how much I love RestSharp for communicating with web services in windows phone apps but screw it I will say it again: USE RESTSHARP its fast, simple and reliable.

Prompt Users to Review with AppEvents
With mobile apps getting a good review is pretty much gold. As a user I am very unlikely to try any app with a sub 3/5 star rating. We wanted to give Numbertap the best chance we could at a decent rating by asking users (nicely) to rate the app. We didn’t just want to annoy any user either, we wanted to hit them up when we KNOW they are enjoying the game and they are at a point where they can jump out and give us a good score.

To achieved this lofty goal we used a little library @d1k_is open sourced – AppEvents. The syntax is a little funky so you should probably check out dk’s blog post for a full intro but essentially what we are doing here is running the method AskToRate() when the “games-played” event has been fired 5 or more times and the “rated” event has not occurred.

//in app.xaml.cs set up the rule
AppEventsClient.New(Rule.When("rate-app",
                el => el.Any(e => e.Name == "games-played" && e.Occurrrences.Count >= 5) && !el.Any(e => e.Name == "rated"))
                .Do(r => DispatcherHelper.SafeDispatch(() => AskToRate()))
            );

//when a game has played fire the event
AppEventsClient.Current.Fire("games-played");

This little piece of code has helped us gain 170+ reviews with an average of about 4.5 / 5 so far (hopefully having a cool game helped).

The Icon
When you live in an app store (sorry marketplace… don’t sue me) you basically have two ways to attract any customers that may be passing by. One is to have a good review and the other is a slick icon. Given that no one ever has or (or ever will) describe my artistic skills as “slick” we jumped on the crowd sourcing bandwagon and cruised over to 99designs to get ourselves an icon on the cheap ($140ish). We think it turned out pretty good:

The Server

Like the App we wanted the server side of Numbertap to be fast and simple, this is what we used.

The Framework
We know ASP.NET MVC so just like the Silverlight decision we rolled with what we knew. Turns out combining RestSharp, mvc and a shared class library for the API models makes REST based API’s really easy. Because both our app and server shares a class library for RestSharp models it means that we can easily update our web service responses and have that data available in the app. We return json over xml because json rules – this is how you do it from an MVC controller, this action returns some info on player rank and the current number of players in game:

[HttpPost]
public ActionResult GameStats(LoginRequest loginRequest)
{
    var player = DB.Queries.Player.GetPlayer(loginRequest.ID, loginRequest.PlatformID, loginRequest.GameID, null);

    var response = new GameStatsResponse();

    response.PlayerStats = DB.Queries.Player.GetPlayerStats(loginRequest.GameID, player.PlayerID);
    response.PlayerStats.PlayerRank = DB.Queries.Player.WeeklyRank(player.PlayerID, loginRequest.GameID);

    return Json(response, JsonRequestBehavior.AllowGet);
}

The Platform
Being a multiplayer game Numbertap needed a server side component and where better to look for a server than the cloud? I bet you are thinking I’m going to talk about how awesome azure is right? WRONG! Bottom line is I looked at azure and I looked at the azure pricing table and quickly shut my browser and unplugged my computer before my head exploded. Azure is too hard for a simple developer like me, we wanted easy cloud and found it with App Harbour. App Harbour in their own words is “Azure done right”. Deployment is super simple – pushing to a git repo will build your project, run your tests and deploy. We went with the $10 a month shared Sql Server DB and have the option to add instances to scale at any time BALLIN’.

Hopefully from this rambling post you can pick up a tip or two you can use in your own app. If anyone (ha! like anyone reads my blog) would like some more information on something I have posted here hit my up in the comments and I might do a blog post on it or maybe just send you some code.

Phonealytics “Mango” Update Preview

I have been talking up some substantial updates to the live tiles used in my Windows Phone Google Analytics app Phonealytics for some time now. Over the weekend I finally got round to getting started implementing them. The result is a button you can press on your site’s profile page (the first page you get to when you press a site) to pin a live tile of that site to your home screen.

fullviewPhonealytics Live Tiles

You can pin as many tiles as you like (although I think the background process might struggle with 5+) with the tiles taking the settings for date range (day, week, month, year) of Phonealytics when pinned. The tiles themselves show a bit more data than the current ones with the front of the tile showing visits and % change, the tile will occasionally flip to reveal the bounce rate and time on site. Pressing a tile from the home screen will take you directly the the details of that site in Phonealytics.

Pin Tile

These new live tiles are updated entirely from your phone so should be much more reliable than the current tile. The update will be submitted as soon as Microsoft allows mango app updates and hopefully should be ready to go as your phone is updated to mango. The new tiles will definitely be available on the paid version of Phonealytics and possibly will come to the free version eventually now that I don’t need to run a server for them. I am planning on making them a bit more interesting visually to stand out a tad from the sea of [“PhoneAccent”] on everybody’s home screen, any suggestions for the look of the tiles (or anything else) would be awesome.

For those of you who haven’t got the app you can pick it up from the zune marketplace or grab the free version.

Windows Phone 7 App Phonealytics – Sales and Download Numbers

Phonealytics is my Windows Phone 7 Google Analytics client. Phonealytics is currently selling for $0.99 in the marketplace with a free trial. Its major features include a live tile updating with a single sites stats, good performance and simple to use “metro” interface. Here I will be giving a rough and rundown of how it has performed along with the changes I have made and am planning. Due to my poor records keeping and Microsoft’s limited app hub reporting the numbers might be off here and there but should be close enough.

Total Numbers

Here are the raw numbers as of 30-MAR-2011:

278
paid
+
514
trial
=
792
total

This gives me a conversion rate of about 35% which I am pretty pleased about. The app is sitting on around a 4 star rating (depending which country you are from) and has close to 30 reviews. I get a ton of feedback via email most of it encouraging with some excellent ideas for features. Seeing as though people generally enjoy using the app I am a little disappointed in the sales numbers so far.

Downloads Over Time

Since first launching in the marketplace Phonealytics has been update 5 times. Major changes included adding a trial version of the app on 13-DEC-2010. Due to some pretty solid competing apps I also dropped the price of Phonealytics from $2.99 to $0.99 on 30-JAN-2011. Here is the downloads (trial and paid)  per day from the day the app went on sale 25-NOV-2010 to 30-MAR-2011.

day

In the cumulative graph that Phonealytics has been downloaded at a fairly steady rate since hitting the marketplace.

cumulative

As you can see the downloads have remained fairly stable throughout the life of the app. I’d like to think that this means the app is pretty good and as new people are introduced to Windows Phone 7 the sales will continue to grow. Spikes in downloads generally coincided with me putting some effort into promoting updates. The free trial has been kept the downloads pretty steady and has a good conversion rate to the paid app. The price drop however hasn’t had a great effect.

Estimated Moneys

119
at $2.99
+
159
at $0.99
*
0.7
Microsoft’s Cut
=
$358.56
total

I probably shouldn’t quit my day job any time soon.

Future Plans

  • As you may have noticed, the app hub reporting tools are very limited. First change I am making is implementing some decent analytics through Localytics to get a better idea of how many active users Phonealytics has and how they use the app.
  • I am going to try prompting repeat users to rate and review the app using a library like app events. My plan is to track users who have accessed the core functionality a certain number of times (and not experienced any crashes) and prompt them to review the app. Hopefully by targeting people with a positive experience I can get the average score up over 4.
  • Adding a separate ad supported free version. This one is a bit of a gamble, the free version will essentially be the same as the paid version minus the live tile functionality. I will track users on the trial version using a similar method to get reviews and ask them if they would like to try the free version instead.
  • Lowering the price of the app to $0.99 made little difference in terms of sales so I will be upping the price to $1.99 – less than the original price but still an increase.
  • Continued updating of the app’s functionality. Though Phonealytics hasn’t been a financial success I have really enjoyed making it. I am planning some cool features around the Mango update API – most significant being multiple live tiles with more information on them.

My Tips

  • Encourage feedback from your users, I use a real simple section on my settings page with a button that fires of an EmailComposeTask sent to me with Phonealytics as the subject.feedback
  • People like the “metro” style. If you are not a designer (like myself) keep to its guidelines and you should end up with something decent looking. Don’t be afraid to add some colour though, you don’t want to look like a hello world sample. Basically follow everything Jeff Wilcox suggests in his Metro Design Guide.
  • If you have a paid app be sure to include a trial. Make the trial is of some use and remind users a paid version exists. One thing I found to work well is showing the user an example of the functionality they are missing from the full version with a button linking to the marketplace to purchase it.trial

Fluent Email Now Supporting Razor Syntax For Templates

A while back I wrote Fluent Email, a little .NET wrapper for sending emails with System.Net.Mail using a fluent interface. After relentless requests (there was at least 2) to publish the library on NuGet.org I eventually caved in. You can add Fluent Email to your project using Nuget’s built in library package manager or the following package console command.

PM> Install-Package fluent-email

The library is pretty simple buts makes the code for sending emails easy to use and read.

var email = Email
            .From("john@email.com")
            .To("bob@email.com", "bob")
            .Subject("hows it going bob")
            .Body("yo dawg, sup?");

//send normally
email.Send();

//send asynchronously
email.SendAsync((sender, e) =>
{
    Console.WriteLine("Email Sent");
});

There are a few other methods not shown here that work in a similar way for adding the usual email suspects such as CC, BCC  and ReplyTo.

I had also been playing around with some form of templating when I came across RazorEngine. RazorEngine is an awesome library that brings the razor syntax (from MVC3) to other applications. In Fluent Email we use RazorEngine to make email templates as simple as this:

var template = "Dear @Model.Name, You are totally @Model.Compliment.";

var email = Email
            .From("bob@hotmail.com")
            .To("somedude@gmail.com")
            .Subject("woo nuget")
            .UsingTemplate(template, new { Name = "Luke", Compliment = "Awesome" });

This will set the body of the email to the rendered template “Dear Luke, You are totally Awesome." and can be sent the same way as the first example. The UsingTemplate method uses generics so you can pass in a specific type or just use an anonymous object like in the example. If you prefer to use a seperate file for your template there is a method called UsingTemplateFromFile to handle that. Since RazorEngine supports everything you would expect from the Razor view engine so does Fluent Email!

If you want to take a look at the code it is hosted on Github at lukencode/fluentemail otherwise just grab the NuGet package.

Windows Phone 7 Charts

One of the big features of my Windows Phone 7 Google Analytics Client – Phonealytics is the nice (I think) looking graphs. After briefly considering porting an existing Silverlight solution to wp7 I stumbled upon Quick Charts by amCharts. Quick Charts is a lightweight and more importantly free chart control for Windows phone 7. It’s a bit light on options but very easy to get working and looks good.

The xaml for a line chart is pretty straightforward. You can see I am using the phone’s inbuilt styles partially because it looks awesome and partially because I am a terrible designer. The things to note here are setting the CategoryValueMemberPath to the name of the property in your model you want the graph to use as the label and in the LineGraph section setting the ValueMemberPath to the property you want to chart. The title property of the LineGraph renders on a small legend. One tip I have is setting IsEnabled to false when the graph is loading (or just in general) I got an exception tapping the graph before any data has been bound.



    
        
    

    
        
    

    
        
    

    
        
     

    
        
            
                
            
        
        

I use an ObservableCollection of the super simple ChartDataPoint class below, with just the top properties I set on the chart xaml above.

public class ChartDataPoint
{
    public string Label { get; set; }
    public double Value { get; set; }
}

Here is a screen of the resulting graph with a dark / blue theme.

Quick charts also allows for some pretty delicious pie charts. Here is one I prepared earlier:


    
        
        
        
        
        
        
    
    
        
    

Again I am using the default phone colours, this time I set a few brushes with different opacities. These will be used depending on the number of slices in your pie. Speaking of pie, here is what it looks like.

Phonealytics – Google Analytics App for Windows Phone 7

99x99Phonealytics, as you may have guessed, is a Google Analytics client for Windows Phone 7. Phonealytics focuses on speed, getting information at a glance and blending in with your phone’s OS and style.  The app is priced at $2.99 USD and is available (almost) worldwide. Get the Phonealytics app from the Zune marketplace here.

 

fav pie profile sites

The Official Line

Phonealytics is a Google Analytics Client. With Phonealytics you get all the important traffic stats for your website available in your pocket.

Phonealytics focuses on providing information at a glance and in line with your phones theme key features include:

- Pin favourite sites to the app homepage for quick stats and access
- Configure an automatically updating live tile for your phones home screen
- Phonealytics follows your phones theme settings, no matter how white and pink you make them
- Fancy charts!

Future Features

These are the features I’ve got planned for future releases, I look forward to getting feedback and implementing some of the features you guys want from analytics on the go.

  • Keywords / Search engine reports
  • More in-depth sources and referrers report
  • Visitors report showing country, city, browser, etc

wp7_English_480x80_blue2

Writing AJAX web applications in Asp.Net MVC

Asp.Net MVC and jQuery have made it much easier to build awesome Gmail like ajax powered applications. I am going to run through the technique I used to do the ajax web services, call them in javascript and display the html through a template.

What Do I Need?

  1. An Asp.Net MVC web application
  2. jQuery
  3. jQax – a wrapper around jQuery ajax
  4. jQote – a simple lightweight jQuery templating engine

What Do I Do?

Lets start at the web application because you probably already have something there. Pick a nice simple controller action you wish was ajaxy – say displaying some gig (also know as concert) info?

You probably have a view model you hand to your concert details page. Here is a simplified version of what I use:

public class GigViewModel
{
	public int GigID { get; set; }
	public string StartDate { get; set; }
	public string Name { get; set; }
}   

I am using a string to represent the date to make the eventual javascript I have to write simpler.

//
// GET: /Gig/Details/5

public ActionResult Details(int id)
{
	var gigSession = new GigSession();
	var gig = gigSession.Single(g =>; g.GigID == id);

	if (Request.IsAjaxRequest())
	{
		return Json(new GigViewModel(gig), JsonRequestBehavior.AllowGet);
	}

	return View("GigDetails", new GigViewModel(gig));
}


I have here a pretty standard controller action it grabs some data from the database (the session stuff) dumps it into a view model and returns it to a view. What I’ve added is the Request.IsAjaxRequest() statement. This statement checks the headers of the incoming request for “XMLHttpRequest” meaning the request originated in javascript. If we have an ajax request I use the MVC method Json() to return a json representation of my view model instead of a view. The JsonRequestbehavior parameter allows this control to return json on a Get request.

Now that the backend is set up to give us our json we need to write some javascript to request it. I am using jQax to make this a bit simpler but you could go vanilla jQuery if that floats your boat.

var ajax = $.jQax();

ajax.Get("/gig/1"", null, function (data) {
	alert("woo a json gig - " + data)
});

This bit of javascript uses jQax to make a get request to the url “/gig/1” to get the very first gig in my database. That null parameter is used to set query string parameters which I didn’t need in this case. jQax also has a few other pretty cool options that you can check out on benjii’s blog, for now we will keep it simple.

So now that we have our json gig what should we do with it? You coooouuuld manually set some html up and inject it into a container or you could do what the cool kids are doing and use a template engine. A template engine basically allows you to set up a sort of javascript view which renders the model (a json object) you pass to it. I am using jQote (what’s with the stupid names?) which under the covers uses John Resig’s micro templating code which in turn invokes black voodoo magic to do it’s bidding (its quite complicated).

Before I show you the template this little bit is important to us asp.net developers. By default jQote will want to use tags like: <%= %>. Asp,Net doesn’t like that so we change jQote’s tag character to be something else, I like #.

$.jqotetag"#");

It is easiest to do this once on document load before you attempt to do any templates.

jQote templates look pretty similar to MVC views using javascript rather than C#. They also work best when they live in a script tag like so:

<script type="text/x-jqote-template" id="GigDetailsTemplate">
	<div class="gigDetails">
		<h2><#= this.Name #></h2>
		<span class="date"><#= this.StartDate #></span>
	</div>
</script>

The “this” in the template refers to the json object you pass it. This example is pretty simple but jQote allows you do easily work with lists, conditions and pretty much any other javascript – the doco page has some pretty good examples.

Now all the pieces are in place it is just a matter of giving the gig json to the GigDetailsTemplate and putting the resulting html somewhere on the page. jQote has a few different methods depending if you want to replace, append, prepend or just get the raw html. This example alters the code used to get the gig json to use the jqotesub method which will replace whatever you had in the target dom element with the rendered template html:

var ajax = $.jQax();

ajax.Get("/gig/1", null, function (data) {
	$("#gigWrapper").jqotesub("#GigDetailsTemplate", data);
});

First we use jQuery to select the container we want the html in. Next we call jqotesub with the selector for the template we created above and the gig json data returned from the ajax call. BAM! The template is filled out with the values of the gig and displayed on the page.

Helpful Tips

  • I found to keep things organized creating templates as Partial Views in MVC and then rendering them on the pages they are required worked well.
  • In your view models try to avoid DateTime – its pretty annoying trying to display javascript dates how you like.