My Development Blog

My Development experiences

Archive for the ‘Uncategorized’ Category

Kentico – Inline Data Binding

Posted by ipwright83 on November 12, 2013

My first Kentico page resulted in a bit of a mess. It involved lots of WebPartZones, and then each zone had a WebPart in that would then be bound to the CMSContext.CurrentDocument.SomeField. This allowed me to bind the name, description, image etc…

Unfortunately it quickly looks a mess in CMSDesk, is quite time consuming and it just a bit of a pain working in CMSDesk for all this content. I asked around and my team pointed out that I could do in-line data binding like so:

<div class="imageInfo">
   <h1><%= CMSContext.CurrentDocument.GetStringValue("Title", "{Title}") %></h1>
   <p><%= CMSContext.CurrentDocument.GetStringValue("Description", String.Empty) %></p>

The problem is at this point things like the Designer view in CMSDesk will frequently complain with the error:

The Controls collection cannot be modified because the control contains code blocks

This is rather annoying, and consequently developers have either used the approach of adding lots of WebParts (the norm) or sometimes assigning values in the code behind. What I find easier however is to change the syntax slightly to use data binding:

<div class="imageInfo">
   <h1><%# CMSContext.CurrentDocument.GetStringValue("Title", "{Title}") %></h1>
   <p><%# CMSContext.CurrentDocument.GetStringValue("Description", String.Empty) %></p>

Now this won’t work either directly, because your page probably hasn’t been data bound. The easy way to fix this is to ensure you call DataBind(). In my case I wanted to put this in the masterpage, but the masterpage from Kentico didn’t feature a code behind file that I could easily modify so I simply changed the master page inherits it like so:

<%@ Control Language="C#" Inherits="MasterPageLayout" %>

Now in page load I can call DataBind:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using CMS.PortalControls;

namespace NetC.BurtonRoofing
    /// <summary>
    /// Code behind for the Master Page
    /// <remarks>Allows the use of markup in the ascx such as </remarks>
    /// </summary>
    public class MasterPageLayout : CMSAbstractLayout
        /// <summary>
        /// Raises the <see cref="E:Load" /> event.
        /// </summary>
        /// <remarks>Calls the DataBind method for the page</remarks>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        protected override void OnLoad(EventArgs e)


This makes data binding nice and simple, keeping your binding in your designer code without needing to mess around with WebPartZones.

Posted in Uncategorized | 2 Comments »

MVC Part1 – Routing

Posted by ipwright83 on June 14, 2013

I’ve been spending some time watching videos to learn ASP.NET and decided to blog the useful nuggets of information that I’ve learnt to try and help myself remember them, and share them with anyone interested.


So what’s routing? Routing is what MVC uses to determine where an HTTP request should go. When you make a request such as http:\\localhost\home\about this gets split up into sections and determines which controller and method should be visited.

Routing is setup in the global.ascx file with the following line:


So lets take a look at the RouteTable class:

public class RouteConfig
    public static void RegisterRoutes(RouteCollection routes)

            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }

The first line to note is the routes.IgnoreRoute. This prevents .axd files from being included in the routing system as these are handled by MVC specifically. Following that a single route is setup which matches a particular pattern of {controller}/{action}/{id}, and a default is set. This means when we visit /Home/About we can see that it will use the Home controller, and the About action (aka Method).

We could create our own route, for example to define a system for controlling the language, so whenever /language/ is used it will direct to our controller. It should be noted that the default matches {controller} first which is essentially a variable parameter, making it very greedy. Therefore we need to place our custom route before it:

routes.MapRoute("Language", "language/{name}",
				new { controller = "Language", action = "Search", name=""});

At this point we’ll get a 404 or ‘Page not Found’ error if we try to navigate to /language/english. The reason for this is because we don’t yet have an appropriate controller. If we create a new LanguageController and rename the ‘Index’ method to ‘Search’ then we should be able to test the system.

public class LanguageController : Controller
    // GET: /Language/
    public ActionResult Search(string name)
    	string message = Server.HtmlEncode(name);
        return Content(message);

Notice here that the name property has been passed in as a parameter. This is because the Controller will automatically search through the routing data, querystrings etc. and fill it in for us. Also remember to protect your strings against potential attacks, the Razor engine introduced later will do this for us, but for custom Actions we need to do this ourselves manually using helper methods such as Server.HtmlEncode().

What is interesting is that this information can be interrogated later on within your controller, for example:

public ActionResult Index()
	var controller = RouteData.Values["controller"];
	var action = RouteData.Values["action"];
	var id = RouteData.Values["id"];

	string message = controller + "::" + action + " " + id; 
	ViewBag.Message = message;

You can then test this by running your application and going to /Home/Index/49833345.

There are some other useful things to note, when dealing with URL’s you should generally use tilde ~ which means from the ‘root’, this means you don’t have to try and figure out complex web locations and they can instead all be relative. An example: Server.MapPath(“~/Content/site.css”) which would turn this into a real URL.

When you add a method to a controller, by default it’s name will be used as the Action, however using the ActionAttribute it is possible to change this behavior to use a different name, in this example to use the action named Modify:

public ActionResult Index()

You can also specify verbs which ensures the action is only called for a specific HTTP requests (e.g. Get, Post, Put). This method also allows two action methods to have the same name. You can do this using attributes again:

public ActionResult Index()

Finally it is also possible to apply action filters to commands, for example to ensure only people with certain permissions have access to an action.

public ActionResult Search() {}	
public ActionResult Edit(string departmentName) {}

Posted in Uncategorized | Leave a Comment »

Windows based Git Client

Posted by ipwright83 on March 14, 2013

I find myself increasingly having to grab code from Github or similar sources with the project I’m working on. It’s relatively straight forward to hit the ‘ZIP’ button in GitHub:



The problem is it’s awkward and clunky to keep on doing this to get changes, extracting over old locations. Also, what if you want to contribute to a project? I’ve tried setting up Git on a windows machine, creating all the various SSH keys and found it hard work… I want my source control to be simple.

GitHub have released a new windows client which I’ve actually not yet tried, the reason being I believe you can only set it up to point to one location (e.g. GitHub) and then choose repositories to fork. As an alternative Atlassian have started a beta programme for their conversion of SourceTree, there popular MAC source control software. You can sign up to the private beta here which currently allows connecting to GitHub, BitBucket and Stash.

I’ve already received one update to the software and they’re receptive to bugs and feature requests. Best of all it’s free (and I believe will be remaining free just like the MAC version). It’s currently a little sluggish I find due to the live ‘Diff’ pane that works for each file you’ve got selected, but it’s generally a nice clear system to use. They’ve gone for a simple clean UI at the moment which is a great improvement over trying to use something like TortoiseGit and find the right options in the right menus:


Posted in Uncategorized | Leave a Comment »

WPF – RateBar

Posted by ipwright83 on June 5, 2012

As per my previous post, I have been working on a WPF based progress bar. This is supposed to be similar to the  Windows 8 file transfer progress bar, I’ve named it a ‘RateBar’ as it seems appropriate. Well I’ve finished the initial version of this project and based on the popularity of the question on StackOverflow I imagine there are some other people who would benefit from the control.

I’ve not got any automated tests for it (I’ll try to add some at some point) and I don’t know if it works with WPF styles (mainly because I don’t know how they work), but it all seems to work so far and matches quite nicely based on my initial intention. To get a true windows 8 style it’ll probably need combining with an ‘expansion’ arrow which switches between a progress bar and a rate bar.

Some basic instructions to get you started. You’ll need to do the following (I hope most of which are fairly obvious):

  • Add a reference to RateBar.dll within your WPF project.
  • Add the RateBar namespace within your WPF window/control that you wish to include it on:
  • Add an instance of the RateGraph, recommended size is 380×88:
            <my:RateGraph x:Name="rateGraph1" Height="88" Width="380" />
  • Update Value (the progress), Rate (the current rate) and Caption (the rate info above the black line) on a regular basis.
Note: The Progress needs to change before the Rate is updated, otherwise you’ll end up with a vertical line on your graph, as the rate get’s added based on the current progress location to the graph.

I’ve included the source and release binaries in a zip file accessible from here. If you like this and would like to contribute in some way then please feel free to sign up for Dropbox if you’re not already on (free multi location file storage with cloud synchronization) using my referral link. This will give me more space for hosting source code, binaries and useful tools for the community.

The license for the code is that you may use it in any project and modify it as much as you need. Please reference me somewhere if you have a readme and if you’d like to use it for commercial use feel free to do so as long as you leave a comment so I know how many people are using it (and whether I should invest more time improving it!).

Posted in Uncategorized | 4 Comments »

Visual Studio – File Navigation Extension

Posted by ipwright83 on May 30, 2012

One of the most frustrating things I found when I upgraded to Visual Studio 2010 was the navigation. I work with a fairly large solution with hundreds of files, many of which I can’t locate via the solution explorer as I just can’t remember where they are. To make this harder, sometimes the file names don’t match the class names and other times the name is the compound of several words that I can’t quite remember the combination of.

Within Visual Studio 2008 I used to use Resharper, and I almost exclusively used this for the file searching capabilties. It was quick and supported camel case searching. I’d previously used other solutions but found them to be slower and not as lightweight. Once I upgraded to VS2010 however I found that the search had been disabled in the express version.

Not wanting to sacrifice the brilliant searching I decided to write my own Visual Studio addin (I found this much harder than I anticipated, hence the extension doesn’t get many updates). It does exactly what I wanted, in a performant way and is avaliable to anyone who wants it. It allows searching by name or camel case and supports wildcards, with filtering as you type and highlighting of the matching criteria, bumping the best matches to the top of the list.


You can find the shortcut under the ‘Edit->Find and Replace->VS File Nav’ option and can re-bind the shortcut using Edit.VSFileNav.

Feel free to have a play and leave some feedback.

Visual Studio Gallery – VSFileNav

Posted in Uncategorized | Tagged: , , | Leave a Comment »

Memory Leak within XmlSerializer

Posted by ipwright83 on May 3, 2012

Within the product I work on we used XML based serialization for some of our classes, the original aim was to provide a way of storing settings that was human readable to make debugging and upgrades easier in the future, while avoid the deprecated SOAP serialization. Unfortunately XML serialization brings about it’s own problems, most recently of which we discovered was leaking memory.

I discovered the memory ramping via Process Explorer, if you don’t have this tool I recommend downloading it for free from the SysInternals suite.

This lead down a road to our XML serialization helper class. By commenting out parts of the code eventually the problem was isolated to a section of code along the following line:

private XmlSerializer GetSerializer(Type type, XmlRootAttribute root)
   return new XmlSerializer(type, root);

When you construct a new XmlSerializer it will generate a temporary assembly on the disk (not however if you generate the xml serialization assemblies when you build via SGen). Normally these assemblies are loaded up into the AppDomain and then cached, however not in the case of this specific constructor call. It never caches the assembly, instead it’s re-created every time and therefore leaks memory.

The solution is fairly simple, create your own cache, in our case we made the cache based upon the Type name, and the name of the XmlRootAttribute:

private readonly Dictionary cache = new Dictionary();

private XmlSerializer GetSerializer(Type type, XmlRootAttribute root)
    String key = type.AssemblyQualifiedName + "|" + root.ElementName;
    XmlSerializer result;

    if (cache.TryGetValue(key, out result))
        return result;

    result =  new XmlSerializer(type, root);
    cache.Add(key, result);
    return result;

Note that the code above isn’t threadsafe, you’d need some form of locking if you were to call this over multiple threads. This however solved our problem and gave us a nice flat memory profiler for de serialization.

Some useful links I discovered on my way:

Microsoft’s Tess Ferrandez – .NET Memory Leak: XmlSerializing your way to a Memory Leak
Microsoft Support – Memory usage is high when you create several XmlSerializer objects in ASP.NET
Microsoft Connect – XmlSerializer memory leak

A little later I’ll be discussing Binary serialization, why I’d like to move to it instead of XML serialization and how we can work around the issue of human readability.

Posted in Uncategorized | Tagged: , , , | Leave a Comment »

Reflector context menu in Windows Explorer

Posted by ipwright83 on May 1, 2012

I often find myself using Reflector to open up DLL’s, sometimes to double check they contain the code I think they do (match the expected build version) or othertimes just to browse other assemblies. However I always find myself jumping to my desktop to find the shortcut and dragging my DLL on. I wondered to myself why I was doing this today when I can easily just extended the Explorer shell.


Unfortunately in their bid to make Windows easier to use for the majority, they make it more difficult for the power users. The ‘File Types’ section that used to be avalaiable via the Tools menu in Windows Explorer has gone. This was actually just a handy way of modifying the registry. A quick bit of googling led me to the correct set of keys to add a custom context menu.

Windows Registry Editor Version 5.00

@=”Reflector.exe %1″


Placing the above in a .reg file and running it, or adding the keys manually and setting the default value will add a ‘Reflect’ option to your .dll context menu and make things that little bit easier. Happy reflecting.


[Reflect] can be modified to change the title of the context menu item.
[Reflector.exe] needs to be modified to point to the actual location of Reflector.

Posted in Uncategorized | Tagged: , | Leave a Comment »