SyntaxHighlighter Evolved and Chrome

While performing some housekeeping on this blog today I couldn’t help but be slightly frustrated by the unsightly vertical scrollbars which appear on the code snippets that I post. A quick search sorted this one out.

If you run a WordPress blog and are using the excellent Syntax Highlighter Evolved plugin, and you’re using Google’s Chrome browser, then you can quickly sort this out by editing the shCore.css file and changing the overflow style.

FTP into your webspace and find this file:

/wp-content/plugins/syntaxhighlighter/syntaxhighlighter3/styles/shCore.css

Then look for this line (which should be on around line 60 in the .syntaxhighlighter style:

overflow: auto !important;

Change it to:

overflow-y: hidden !important;

This should cause the vertical scrolls to disappear and will hopefully look a bit better.

Snippets , ,

Redirecting to an action with an anchor with Asp.Net MVC

There are those times when you want to redirect to a route from inside your Asp.Net MVC controller and tag an anchor name (#myanchor) on the end, whilst still utilising the power of the route table. I accomplished this by creating a new class inheriting from RedirectToRouteResult and implementing the appropriate code to generate a url and then attach the required anchor.

If you’ve ever seen the source code for the standard Controller class, the code is not really anything new, but the only way it seems to extend this functionality is to almost copy the code out and mix your little extensions in there; no real hook points exist aside from that.

You use the class like so when returning an ActionResult from your controller action:

return new RedirectToActionAnchor("index", "home",
    "myanchor",
    new { id = 12 });

..which will hopefully give you a url like /home/index/12#myanchor.

Download RedirectToActionAnchor.cs

Snippets , , , ,

Asp.Net MVC 3 Areas and _ViewStart.cshtml Scope

I came across a problem today (or should I say misunderstanding) with MVC 3 (RC) and the _ViewStart.cshtml file.

In case you haven’t used these yet, the _ViewStart.cshtml is there to make it easy (and DRY) to apply the same layout file across all your views. The problem is that when you start to use areas, you might find your layout is not applied to the views inside your areas. You could copy your view start file into the view directories for your areas, but that’s not very DRY is it? It’ll become unmaintainable after a while.

The key thing to note is that, in fact, _viewstart.cshtml files have scope, and they affect all the views which are in the same directory or below the location of the file. By default, and in all the tutorials, blog posts and examples that I’ve seen, _viewstart.cshtml is always created in the Views folder in the root of the site, thus having an impact on the views inside that file.

If you want a wider scope so that it affects your area views as well, simply move _viewstart.cshtml into the root of your site, and the problem will be solved.

Similarly if you want to apply a different layout to all of your areas, but maintain the default one for non-area views, create another _viewstart.cshtml file inside the root of your /areas directory, and all your area views will maintain that layout.

Snippets , , ,

Data Caching with .Net 4.0 and Asp.Net MVC – part 3

Welcome to part 3 of this short data caching series. In the previous parts we had a look at how we can employ smart in-memory data caching to avoid round-trips back to the database when using Sql Server and the Entity Framework, set in an Asp.Net MVC context. I showed you how you can seamlessly query from cached or non-cached data, how to update cache items on inserts and updates, and wrapped this up in an extensible framework to keep everything nice and clean. In case you missed those parts, you can view them here:

I received some emails and comments asking a couple of different questions. How can this concept be applied to Sql Server without using EF? How can we create a dependency between Sql Server and our framework? This article is an attempt at answering these two questions, and as it turns out is also a great showcase for just how extensible our little framework is.. because I’m just about to hack it to bits. This article starts from where part 2 left off, so I strongly recommend you download the code from part 2 if you haven’t coded it to that point yourself.

Download source code from part 2

How can this concept be applied to Sql Server without using the Entity Framework?

In case you haven’t guessed by now, the answer to this is fairly simple – essentially we just create a new implementation of IVehicleRepository and utilise the normal Ado.Net objects to interact with our database. My solution in this article deals with the following:

  • Refactoring VehicleRepository and moving some common code and methods into an abstract base class so that we can utilise some common bits and pieces in our new repository class
  • Creating a new repository class SqlVehicleRepository, which uses Ado.Net to retrieve data from the database
  • A crude Unit of Work implementation with transaction support

So, to being with lets set about refactoring our current repository class into a common base class. The main reason for doing this is because the code surrounding the cache and opting to do a database read is fairly common to any repository. Since we’ve already abstracted away the actual implementation of our cache, this refactoring is a fairly simple affair.

Read more »

Articles , , , , , , ,

Script#, System.dll and build errors

Having discovered the excellent ScriptSharp project just a few weeks ago, I began to encounter errors with the project in that sometimes it would cease to build successfully. If you ever encounter the situation where the project would fail to build, but you would receive no build errors in the error log, make sure System.dll has not been added as a project reference.

This reference can be added by Visual Studio automatically (I’m using 2010 here) when you:

  • Add a new class by selecting Add > Class.. from the project context menu
  • Import an existing class from another (non-Script#?) project

.. and there are probably a few more situations, but these are the only ones I encountered.

Initially,I thought the only way to get my project back to a working state was to copy the files out, remove and re-create the project then add all my items back in. However, the real solution is simple; just remove the reference to System.dll and your project should start compiling again.

By the way – if you’re a C# programmer who also plays with Javascript, I highly recommend using Script#. It’s just so top-drawer.

Snippets , , , , ,

Blog Code Formatter Visual Studio Extension

Just a quick note to say that I just published a new Visual Studio 2010 Extension, which makes it easy to format your source code/css/SQL/Html etc, ready for pasting into a blog post.

Currently the formatting tags only support Syntax Highlighter, but I will shortly be adding support for WordPress hosted and self-hosted tags in the next version.

Quick run-down of the features in version 1:

  • Formats your selection, removing leading tabs and replacing them with double spaces.
  • Removes consecutive blank lines
  • Optionally applies Html encoding
  • ‘Copy’ button for quick copy to clipboard
  • Constructs <pre> tags for Syntax Highlighter, using new or old style format
  • Option to remove <pre> tag formatting
  • Auto-detection of file types

If you use VS2010, and you blog about your work, why not give it a try? You can download the extension through the VS2010 Extension Manager, or directly from the online Extension Gallery.

If you have any bugs/suggestions, please feel free to comment! Also, if you like the extension, please feel free to post a tiny review or give it a rating.

Tools , ,

Asp.Net and Colorbox: Creating a ‘delete’ confirmation dialog

This article was inspired by a friend of mine who wanted to implement a delete confirmation dialog in his website, and I thought it might be a useful little tutorial to write about.

These days, I like to use the excellent Colorbox for this sort of thing. In case you haven’t heard of it or used it before, it’s simply a brilliant jack-of-all-trades Javascript pop-up library based on the even more awesome jQuery. It can display anything in a pop-up, from arbitrary Html content, flash video and an image gallery depending on how you set it up. In the past I’ve used Thickbox for this sort of thing, but as it’s not maintained any more (not to mention Colorbox looks a lot nicer) I prefer this.

For this tutorial, imagine the following scenario:

  • You have some sort of form you use to add/edit some data
  • This form has the usual ‘Save’, ‘Cancel’ and ‘Delete’ buttons hanging off the bottom of it
  • When the user clicks ‘Delete’, you want to show them a dialog asking the user if the really want to delete

For the delete confirmation you could just redirect the user to another page and show the confirmation there, but this method is cooler, not to mention ludicrously easy. Best of all, it doesn’t interfere too much with the .Net code you would have had to write anyway. So let’s get going.

Read more »

Articles , , , ,

Testing for a jQuery object in Javascript

I’ve just spent an inordinate amount of time trying to figure out how to test if an object in Javascript has actually been extended using jQuery or not. Ok, not actually that long; but probably longer than it really should have taken, and I had to dig deep into the bowels of the internet to find the answer.

Furthermore, the answer is pretty simple really:

if(obj instanceof jQuery)
{
}

It does what it says on the tin – if the object is an instance of jQuery, i.e. you are dealing with a jQuery-enhanced object, then do something. This can be useful if you have a function which expects a jQuery object and want to make sure that the object has been jQuery-ified. Or, conversely as in my case and the reason for this post, you want to ensure that you’re dealing with a plain Html node:

if(myElement instanceof jQuery)
{
    myElement = myElement[0];
}
// .. continue
Snippets , ,

Machine-specific Asp.Net configuration settings

One of the first things we noticed when we began to use version control to manage our source code is that configuration settings across multiple machines became unmanageable. For starters, different people checked out projects to different locations on their hard-drives, had different connection string settings depending on whether or not they were in the office or at home, and other people wanted different email settings than other developers, amongst a few other things.

What we needed was a per-machine configuration solution which could allow different settings for different developers, which should fall-back to reading the standard web.config if a setting wasn’t available in the custom file. This would effectively allow the developer to override settings as they see fit without affecting other developers. The following class to handle this is what we came up with. Most developers have the proverbial “toolbox” of code which they will utilise in most projects, and this is a good one for your collection.

The requirements that we would like to fulfil with our implementation are:

  • Allows the developer to request an application setting or connection string by key
  • Should try to read the setting from an XML file from the root of the website. The file name should include the local machine name.
  • If the setting or connection string cannot be found, the class should attempt to read it from the web.config using the standard ConfigurationManager framework.
  • Because the machine-specific settings and connection strings should override the common settings from the web.config, an exception should be thrown if a setting which is defined in the host settings file does not also exist in the common settings file.
  • For performance reasons, the settings file should be cached in memory to keep from reading from disk every time a setting is read.

Download the source code to accompany this article

For starters then, I’ve called my implementation the ConfigSettingsProxy. Here’s the model we’ll end up with by the time we’ve finished this article:

ConfigSettingsProxy model

Let’s just go through each of the objects and define their purpose.

Read more »

Articles , , , ,

Data Caching with .Net 4.0 and Asp.Net MVC – part 2

This is the second article in a series about using the .Net 4.0 Caching objects in Asp.Net MVC – catch up first with part 1 of the series, in case you missed it.

In this post I’m going to cover how we can invalidate our repository cache in a more fine-grained, efficient way; instead of simply dropping and re-creating the cache every time something is written to the database, we’re essentially going to replace updated items directly into the cache just after we write them to the database. This will involved hooking into Entity Framework’s change-set and picking out the entities we’re interested in. I’m not going to cover the use of SqlDependancy here and the new wrappers within .Net 4.0.

If you download the sample project now, you can follow along with the article. The sample project (and this article) continue on from where part 1 in this series left off.

Over the course of this article, we’re going to do the following:

  • Retrieve the objects which are being inserted, modified or deleted whenever we save changes
  • Use the changeset to identify entities which need to be added, updated or removed from the cache
  • Create a form to add and edit entities from the UI

So this means we’re basically doing our own invalidation, and the only way the cache will be updated is to update entities through our UI. Any changes made to the data outside of the UI (for example, in Management Studio) will not be picked up unless the cache is explicitly invalidated.

Lets start by making the changes to our IVehicleRepository class.

Read more »

Articles , , , , , ,