Script#: Taking care of ‘this’

Making sure ‘this’ points to exactly what you think it does in Javascript is one of the challenges that a new programmer to the language has to overcome. Script# makes this somewhat easy for us because it tries to make sure it points to exactly what we’d expect it to if we were writing a normal C# app.

Take this snippet, for example:

jQueryObject buttons = jQuery.Select(".homepageCreateButton");

buttons.MouseOver(delegate(jQueryEvent e)
{
	jQueryObject button = jQuery.This;
});

Here I’m selecting some buttons and applying a click handler. The generated code here is as you would expect, where jQuery. This clearly translates to $(this):

var buttons = $('.homepageCreateButton');

buttons.mouseover(function(e) {
    var button = $(this);
});

What happens though when I start using the C# keyword ‘this’ in my delegate?

jQueryObject buttons = jQuery.Select(".homepageCreateButton");

buttons.MouseOver(delegate(jQueryEvent e)
{
	jQueryObject button = jQuery.This;

	object a = this;
});

This gets compiled to:

var buttons = $('.homepageCreateButton');
buttons.mouseover(ss.Delegate.create(this, function(e) {
    var button = $(this);
    var a = this;
}));

.. which is not quite the same thing. As soon as the Script# compiler has detected that I am making use of the ‘this’ pointer it wraps the delegate call in a method and changes the context of the code inside the delegate so that ‘this’ points to the current instance of the class. This is of course the exact behaviour we would expect and love in C#, and for the most part this is also a good thing in Javascript. By the way, this transformation also happens if you implicitly access a class-level member without using the ‘this’ keyword.

However, look at what it has done to our jQuery selector; we expected ‘this’ to be the current element that we are handling the ‘mouseover’ event for, but now that has changed and we are effectively selecting the current instance of the class through a jQuery selector, which of course is nonsense.

To get around this and make sure that you’re accessing the actual object that you want inside the delegate, you should make use of the CurrentTarget property on jQueryEvent:

jQueryObject button = jQuery.FromElement(e.CurrentTarget)

Just be careful when you intend to use ‘this’ and ‘jQuery.This’ together in a delegate, as they will not behave as you would expect in this case.

Articles , , , ,

.Net Image Processor v1.2 released!

I’ve just put another release out for .Net Image Processor, my image processing and resizing code library for .Net and GDI, which includes a number of new filters, including:

  • Greyscale
  • Sepia
  • Invert
  • Image watermark
  • Text watermark

The first three also introduce a small framework for applying any sort of single pixel-based filter (as opposed to kernal-based filters) where you can simply create an implementation of PixelFilter and supply your own algorithm for manipulating a single pixel (a blog post is forthcoming on this soon).

You can grab the latest version from the project homepage, or you can update the Nuget package from within Visual Studio. To see how to use all of the available filters, have a scan of the documentation.

So what’s coming next?

I’m looking into using a couple of third-party libraries for a couple of prominent issues:

Both of these issues will be looked at for the 1.3 release.

Projects , , , , ,

.Net Image Processing library now available

This is a pet project which I’ve had around for a while now, which started off as a simple wrapper for GDI+ which allows you to create thumbnails from images. It’s turning into something a bit more than that, with an extensible filter framework where filters can be chained together. Also supports image conversion to/from Jpeg, PNG, TIFF, Bmp and GIF.

The idea is that over time I will be developing more and more filters which can be plugged in, with support coming for batch processing and asynchronous processing. Finally, the entire project is all open-source and free!

All the documentation for how to use it is all contained within the project homepage (there is more technical documentation to come), so without further ado here are all the links you need:

Nuget Support

What’s more, the project is also hosted on Nuget – so if you run Visual Studio 2010 with the excellent Nuget extension you can just install the project from there. The package name is Simplicode.ImageProcessor.

I would love to hear any feedback or issues you have if you use the library – you can get in touch with me directly or post a review on the project site!

Projects , , , ,

Problems with ResourceManager and neutral culture in Asp.Net MVC

I’ve been struggling with this for a couple of hours now and found a solution that I would like to share.

The problem is this: I added a resource file to my project as an Embedded Resource, configured the namespace as “Resources.Dialog” and set its Custom Tool property to “PublicResXFileCodeGenerator”. I then added some string resources to the file.

After inspection of the generated code file, everything looks normal. Next, I need to be able to access my resources dynamically, rather than simply using my Dialog resource class directly.

You would be tempted to do something like this:

ResourceManager dialogResources = new ResourceManager(typeof(Resources.Dialog));
string myString = dialogResources.GetString("MyString");

This would work in theory, but instead (for me at least) it throws this nasty exception on the call to GetString():

MissingManifestResourceException: Could not find any resources appropriate for the specified culture or the neutral culture

I might be expecting this exception if I hadn’t provided a neutral culture resource file (which are basically your ‘fallback’ resources if you’re not using a supported culture), or if I had defined the resource file in a different assembly, but I’m not. This is a simple neutral culture resource file, in the same assembly as where the resource is being used from.

I don’t know why its doing this, but I do know what I changed to finally fix it.

The class which is generated by the resource file exposes a static ResourceManager instance which is set up to manage itself – so the solution is to use this rather than create your own!

Therefore, the above code becomes:

ResourceManager dialogResources = Resources.Dialog.ResourceManager;
string myString = dialogResources.GetString("MyString");

.. and the exception goes away.

Snippets , ,

Adding a new Jquery UI theme to the default Asp.Net MVC 3 Project

The default project template for Asp.Net is pretty functional out of the box, but an interesting feature is that new templates install jQuery and jQuery UI out of the box! In fact, jQuery UI now comes pre-installed as a Nuget package if you’ve got the latest MVC3 Tools Update (April 2011). If you’re following this while sitting at a MVC3 project already in development, you can simply install the latest jQuery UI repository release using Nuget from within Visual Studio, and you will get the same thing.

In case you did not know, you can start working with jQuery UI pretty quickly and easily by just including the style sheet and script in your layout page like so (your actual file names may vary slightly):

<link href="@Url.Content("~/Content/themes/base/jquery.ui.all.css")" type="text/css" rel="stylesheet" />
<script src="@Url.Content("~/Scripts/jquery-ui-1.8.11.min.js")" type="text/javascript"></script>

This will get you working with a basic jQuery UI theme for all the components and controls which come with the framework. However, if you want to update the project with another jQuery theme to better suit your requirements, then you can do it like this.

First of all, find a theme using the jQuery UI theme roller that takes your fancy. For this example, I’ve chosen “Redmond” as it fits in nicely with the default Asp.Net MVC 3 theme, but you can chose any theme or construct your own. When you click download, it will ask you which components you want to download themes for – just leave it at the default, which is all of them – and click ‘Download’. After .zip archive has been downloaded, extract it to somewhere temporary, and explore its contents.

You will get a file structure which looks like this:

Everything you need is inside the “css” folder – if you open that now you will see a single folder which is named after the theme you just picked from the jQuery UI site. If you’ve created a custom theme, then it will be named “custom-theme” or something to that effect. You can also give it your own folder name if you change the options under ‘advanced theme options’ when you download the theme.

Right-click and copy this folder. Now, browse to the /content/themes folder of your MVC 3 application and paste the folder there. Now you should have two folders in that location – one called “base” and your new theme folder (see right).

All we need to do now is include this folder in your Visual Studio project. The easiest way to do this is to turn on “Show All Files” by clicking the little button at the top of the Solution Explorer tool window, then right-click on the theme folder (which will appear with a white folder icon) and select “Include in Project”.

Now, all that’s left is to include the theme’s style sheet into your layout, and you are done:

<link href="@Url.Content("~/Content/themes/redmond/jquery-ui-1.8.13.custom.css")" type="text/css" rel="stylesheet" />

Now your new theme will be automatically applied to any jQuery UI components you are using in your application. Here’s a shot of it working with jQuery UI Buttons:

You can apply the same process to any additional themes you want to install, just line up all your themes in the same folder and include the relevant style sheet on your pages.

Snippets , , , , , , ,

UK Techdays 2011 in London

I was able to get along to the UK Techdays event this year in Fulham (it’s a free event – if you can make the time, it’s worth the trip) to hear about the latest developments in the Windows Azure platform and also Windows Phone 7.

The first day concerned Azure, and it was interesting to hear from the Microsoft techies and evangelists (David Gristwood, Eric Nelson, Steve Plank and Keith Burns amongst others) , giving us the low-down on features and also running through some brief tutorials which showed us how to accomplish specific tasks, like deploying new web roles and administering our platform instances via the control panel. Steve Plank took us through some more interesting aspects like connecting your local Active Directory to your virtual network in the Cloud, and also spoke a bit about AppFabric and the various components which it concerns.

It was also interesting to hear from external businesses which have based their products on Azure, or had at least implemented a solution based on the technology. The general theme is that, if you can move your infrastructure to the Cloud and get rid of your existing hardware, it really is a no-brainer. If anyone is thinking of implementing a high-volume scalable solution, then they can use this technology at a fraction of the price. One of the speakers mentioned that they were able to turn their six-figure annual costs into a three-figure monthly payment!

Keith Burns later gave a talk on the Sql Azure platform, and the differences between it and Sql Server. To be honest, the differences are fairly small (no full-text indexing or non-clustered indexes yet) but the sizes and costs seem a little prohibitive to me. There’s a maximum of 50Gb per database (which is a LOT of storage anyway, but you still have that limit whereas the Table Storage and Blob Storage technologies are vastly larger) and there’s a cost of £6.06 per Gb of data. There are of course data transfer costs, but these only apply when your data leaves the data centre – having an Sql Azure database which is used by a Web Role (for example) located within the same data centre will not occur any costs.

The second and third days were completed engulfed by Windows Phone 7 announcements, demos and more case studies from external developers (including Cocktail Flow and Very Software). They demonstrated how their applications were put together, design decisions they made and also presented demos of their applications running.

Read more »

Articles ,

AjaxOnly actions and controllers in Asp.Net MVC

Currently as part of my work I find myself doing a lot of client-side work (using the excellent ScriptSharp I might add) and this does involve a lot of calls to the server for bits and pieces via an AJAX call. I’ve decided to dedicate an entire controller to serve such requests.

However, I want to be able to prevent actions on this controller being run from normal requests through the browser. Normally I would just make sure that such requests done through AJAX are through a POST request, but there is a better way.

Inside an action, you can inspect the current HttpContext.Request object and use the handy IsAjaxRequest() extension method to test whether the current request is being executed from an AJAX request or not. You can then just throw an exception if the request isn’t AJAX based when you expect it to be. Performing this in every action would become tiresome though if you have a lot of them. So – you can wrap it up inside a handy Action Filter!

[AttributeUsage(AttributeTargets.Class|AttributeTargets.Method)]
public class AjaxOnlyAttribute : ActionFilterAttribute
{
  public override void OnActionExecuting(ActionExecutingContext filterContext)
  {
    if (filterContext.HttpContext.Request.IsAjaxRequest())
    {
      base.OnActionExecuting(filterContext);
    }
    else
    {
      throw new InvalidOperationException("This operation can only be accessed via Ajax requests");
    }
  }
}

The code is very simple and really just wraps up code we would otherwise write in each action. Except now you can do this:

public partial class HomeController : Controller
{
  [AjaxOnly]
  public ActionResult SomeAjaxAction()
  {
    return Content("Hello!");
  }
}

Now, if you were to try accessing this action via the browser through the url /Home/SomeAjaxAction, you will hit the exception that is thrown from inside the filter. However, Ajax requests made through jQuery or some other client-side method will pass as normal. Notice how that it doesn’t break the normal GET/POST semantics; we can make Ajax actions which just return some data true Ajax GET requests without worrying about someone inadvertently linking to the action.

You can also mark the controller itself with this attribute so that all the contained actions inherit this behaviour if that is what is required.

Snippets , , , , ,

Top 3 jQuery Tools

While I wait for my shiny new download of Visual Studio 2010 SP1 to install, I just thought I’d share a couple of awesome frameworks and plugins I’ve been working with over this past week or so. Some of them might not be news to the masses but I have recently found them to be extremely useful.

Plupload
Demo/Download

This one blew me away. From the makers of the excellent TinyMCE rich-text editor comes Plupload – a free web-based multiple file upload utility that you can use within your sites to upload multiple files in an asynchronous fashion. The genius about it is that it detects the current browser capabilities and automatically chooses the best option for the user (based on the developer’s initial configuration). For example, it can be configured to use a Flash interface to do the upload in the first instance, but if Flash is not available then it will automatically fall back to another technology, including an Html5 or Google Gears implementation. The developer just has to configure the plugin with what technologies should be included based on their various capabilities and the rest is done for you.

What’s more it supports chunked transfer, so uploading massive files should be no problem.

I’m starting to use this in my home-brew projects now with great success and I will heartily recommend it over any licensed/paid products you might use! I plan to write a tutorial article in the near future showing how you can integrate this product into your Asp.Net MVC applications.

jQuery Context Menu plugin
Demo/Download

This plugin is great for showing context menus within your interface. You basically set up an unordered Html list which describes your menu, and then bind it to those items via a jQuery selector which should activate the menu when right-clicked. You then get notification about which item was clicked, which menu entry was selected and even where the mouse cursor was when you clicked it.

I’m not writing just about this plugin though. This site has all sorts of little bits and pieces on it which come in extremely handy. Just looking through their blog posts (it’s a shame these individual plugins aren’t more visible from the home page) I found these cool little plugins which have made my life easier:

And links to other plugins and utilities which I haven’t tried yet, including this gem: jCrop (in-browser image cropping tool).

It’s a great resource and is now on my list of blogs to regularly check for cool stuff!

jQuery-UI Sortables
Demo/Download

jQuery-UI itself is not news (if you’re not using this yet, you should be), and to be honest, neither is the Sortable module within. But the discovery I made was that it’s not just for sorting ordered lists – it can be used to create interesting portlet-type interfaces where people can drag content around and lay out pages exactly how they want (think Pageflakes or iGoogle). This kind of power is extremely easy to achieve and works great!

Snippets , ,

Ninject.MVC3 no longer on Nuget (or is it?)

It seems that within hours of posting my article on Dependency Injection: A Beginner’s Guide, some things had changed with the Ninject packages available on Nuget.

The article uses the package ‘Ninject.MVC3′ package, which also depends on Dave Ebbo’s WebActivator framework, allowing access to some really early initialisation for things such as dependency injection.

Today it seems as if the package includes Ninject 2.2 and has changed to ‘Ninject.Web.Mvc3′ (and I see they’ve also registered similar namespaces for MVC1 and MVC2), and this package no longer depends on WebActivator which means you don’t get the normal AppStart_NinjectMvc3.cs file in the root of your project. It also looks as though they’ve gotten rid of NinjectServiceLocator and now instead we have NinjectDependencyResolver.

However, WebActivator doesn’t seem strictly necessary. Taking these changes into account, I can just register all of my bindings in the Application_Start() method in global.asax.cs along with all my MVC routes and so on, and everything works as intended:

protected void Application_Start()
{
  IKernel kernel = new StandardKernel();
  kernel.Bind<ILogger>().To<Logger>();
  DependencyResolver.SetResolver(new Ninject.Web.Mvc.NinjectDependencyResolver(kernel));

  AreaRegistration.RegisterAllAreas();

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

Update

22nd Feb: And it looks as though everything is back to the way it was, with the Ninject.MCV3 package now available again. So pretty much everything in this post can be ignored but I’ll keep it up for historical archiving purposes!

Snippets , , ,

Dependency Injection: A Beginner’s Guide

This article intends to outline the concept of Dependency Injection and its uses within a software engineering project. From Wikipedia.org:

“it is a design pattern that separates behaviour from dependency resolution, thus decoupling highly dependent components”.

Later, I demonstrate the use of Dependency Injection within the context of an Asp.Net MVC 3 application.

Dependency Injection (or DI) allows us to provide implementations and services to other classes for consumption in a very loosely-coupled way. The key tenet is that such implementations can be swapped out for other implementations by changing a minimal amount of code, as the implementation and the consumer are linked by contract only.

In C#, this means that your service implementations should adhere to an interface, and when creating consumers for your services you should program against the interface and not the implementation, and require that the implementation is provided for you, or injected rather than having to create instances yourself. Doing this allows your classes to not worry about how dependencies are create nor where they come from; all that matters is the contract.

Read more »

Articles , , , , , , ,