Dynamically load a personalised image (client-side)

I wanted to dynamically load an image that was specific to a user who was recognised by the system via the client-side. If the image did not exist for the user, the image must be hidden.

<div id="body">
    <div id="my-image"></div>
        <h2>My heading</h2>
<!-- The rendered body is to contain an element called my-variable and the images are saved as a standard "my-picture_" + my-variable + ".jpg" <script type="text/javascript">
$(function () {
    var id = $('#my-variable').val();
    if (id == '') id = 'Generic';
    var src = "http://www.myurl.com/imgs/my-picture_" + id + ".jpg";

    // If an image does not exist for this user (height = 0), instead of showing a missing image in the UI, hide the image
    var img = new Image();
    img.onload = function () {
        if (this.height > 0)
    img.src = src;

Public Holidays

What is le-problem?

I need to create and access a repository for all South African Public Holidays. This is needed for business logic for some applications. To solve this problem I need to create a simple repository and a means to access it (or use someone elses’ service / API).

Some holidays occur on the same day each year where others are based on the ecclesiastical approximation of the March equinox (Good Friday and Family Day). Also according to South Africa’s Public Holidays Act (Act No 36 of 1994), a public holiday falling on a Sunday, requires that the following Monday shall also be a public holiday. Continue reading

Keep it DRY with StringExtentions

Extension methods enable developers to add custom functionality to data types that are already defined without creating a new derived type. Extension methods make it possible to write a method that can be called as if it were an instance method of the existing type.Extension Methods (Visual Basic) – MSDN or StringExtensions Class – MSDN

Reuse rocks my socks! I simply love minimalism so when my code looks clutter free I find it super sexy! Sexy code keeps me happy. Win! StringExtensions really do help with making code look super sexy and I have found that some of the extensions listed below really help with some of my projects especially when it comes to saving and loading objects.

Starting with my star function, convert an empty or null string to a default value of your choice. Yippeee!

/// <summary>
/// Converts the null or empty value of this instance to a specified default value.
/// </summary>
/// <param name="value"></param>
/// <param name="defaultValue"></param>
public static string ToDefault(this string value, string defaultValue)
    if (String.IsNullOrEmpty(value))
        value = defaultValue;
    return value;

Convert a nullable boolean to a Yes or No string.

/// <summary>
/// Converts the value of this instance to its equivalent string representation of Yes / No values.
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static string ToYesNo(this bool? value)
    if (value == null) value = false;
    if (value == true) return "Yes";
    return "No";

The function below will simply try to convert the string value to a double.

/// <summary>
/// Converts the value of this instance to its equivalent double representation of a string value. Empty or invalid values are returned as 0D.
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static double ToDouble(this string value)
        return Convert.ToDouble(value.ToDefault("0"));
    catch (Exception) { }
    return 0D;

Seeing these beauties in action

bool? choice = true;
Console.WriteLine(choice.ToYesNo()); // Writes Yes

string option = "";
Console.WriteLine(option.ToString("There is no option")); // Writes There is no option

string cost = "150.50";
Console.WriteLine(cost.ToDouble() + 10D); // Writes 160.50

Named months in a drop down list

Adding months to a drop down list

Dim months() As String = {"January", "February", "March", "April", "Map", "June", "July", "August", "September", "October", "November", "December"}
For i As Integer = 0 To months.GetUpperBound(0)
    cboExpiryMonth.Items.Add(New ListItem(months(i), IIf((i + 1) < 10, "0", "").ToString() & (i + 1).ToString()))

Selecting the current month

Dim li As ListItem = cboExpiryMonth.Items.FindByValue(IIf(DateTime.Now.Month < 10, "0", "").ToString() & DateTime.Now.Month.ToString())
If li IsNot Nothing Then
     li.Selected = True
End If

ColorBox Modals

It is always important that a Delete button asks the user to confirm that the delete should take place or not. It is furthermore important that the delete button visually works as the user expects it to and doesn’t accidently delete everything in the grid. But we digress…

Displaying a message to the user can simply be done by utilising the JavaScript confirm or alert boxs… eek! I believe that this method is lazy and is frowned upon by users, although I have definitely used this method countless times before. It is also simply not retina friendly which is the current web trend to conform to.

To overcome this obstacle, I have decided to implement prettified modals with the help of ColorBox and jQuery and so far it is working quite nicely. My solution allows me to display pretty looking modals with HTML messages, a UI icon to visually depict the modal type as well as provide the ability to inject ASP.NET or HTML buttons which allows me to write server-side or client-side code for the logic required.

Confirm Model Box

An example of a confirmation modal. If the user clicks Yes the page can post back and execute the click event of the server control button although I have implemented jQuery Ajax calls throughout my applications.

Source Code

You can access my project source code by right-clicking on the Source Code link and saving it to your hard drive. Please rename the file from PDF to ZIP as WordPress has limitations with the file types that can be uploaded. Source Code (Website Solution – created in Visual Studio 2012).

The Implementation

First you need to download the jQuery and ColorBox files and copy them to your website. Note: I used Example 1 of the ColorBox demo.
Once you have referenced the jQuery and ColorBox JavaScript files as well as the ColorBox StyleSheet, you are ready to rock ‘n roll!

I am going to start with the modal UI structure. If you have a look at the example figure above, you will notice a heading, icon, message and buttons. This structure is created in HTML on the master page and is hidden for standard browsing. When the ColorBox is called, the div’s HTML will be updated with the necessary values and the resulting HTML will be injected into the ColorBox to give us the final result. Note: this step can be skipped if you would prefer the HTML can be created on the fly when calling the modal.

<div class="hidden">
    <div id="msg" class="modal">
        <h5><span id="heading"></span></h5>
        <span id="icon" class="error"></span>
        <span id="message"></span>
        <div id="buttons"></div>
<style type="text/stylesheet">
    .hidden {display:none;}

If you preview the ColorBox demo that I used (Example 1), you will notice that the close button is at the bottom right corner of the modal by default. I decided to follow a lifelong Microsoft standard where the close button is on the top right corner of the box. To do so I had to alter the #cboxClose ID in the ColorBox stylesheet. I changed the bottom to top as indicated below.

#cboxClose{position:absolute; top:0; right:0; background:url(images/controls.png) no-repeat -25px 0; width:25px; height:25px; text-indent:-9999px;}

In order for your #msg div to be visually appealing within the modal, you will need to style it. I created modals for alerterror, question and successful messages each with their own icons which I downloaded through IconFinder. The CSS I used to style my modal is provided below:

#msg { padding: 0px 10px; padding-bottom: 0px; margin-bottom: 0px; }
    #msg #heading { margin: 0px; font-size: 1.5em; }
    #msg #icon { display: inline-block; float: left; width: 48px; height: 48px; margin-right: 10px; margin-bottom: 10px; }
        #msg #icon.icon-alert { background-image: url(../img/modal_alert.png); }
        #msg #icon.icon-error { background-image: url(../img/modal_error.png); }
        #msg #icon.icon-question { background-image: url(./img/modal_question.png); }
        #msg #icon.icon-success { background-image: url(../img/modal_success.png); }
    #msg #buttons { clear: both; text-align: center; margin-top: 20px; margin-bottom: 10px; }
    #msg #buttons input { padding: 3px 20px; }

To show the modal a showMsg function is created which requires the heading (eg. Confirm Delete), message, icon (the style of the icon eg. icon-alert) and buttons to be passed through. For the modal to work effectively (allowing the Yes button in a confirmation box to be able to execute server-side or client-side (ajax) code) it needs a div.hidden (resides on the calling page and wraps the buttons that needs to display in the modal) to be passed through. If the user sends through undefined or a blank string, the modal will display a button labeled Okay which will close the modal.

function showMsg(heading, msg, icon, buttons) {
    $("#msg #heading").text(heading);
    $("#msg #icon").removeClass().addClass(icon);
    $("#msg #message").html(msg);
    if (buttons == undefined || buttons == '') {
        $("#msg #buttons").html("<input type='button' value='Okay' onclick='$.colorbox.close();' />")
    } else {
        if ($(buttons).html() == "") {
            $("#msg #buttons").html(buttons);
        } else {
            $("#msg #buttons").html($(buttons).html());
    if (!$("#msg").is(":visible")) {
        $.colorbox({ html: $("#msg").parent().html(), width: "450px" });
    } else {

To simplify the modal calls, I created 4 JavaScript functions which I would use throughout my application to call the modal I required. This way I could also minimise the repetition of the icon-style which needs to be passed to showMsg.

function showAlert(heading, msg, buttons) {
    showMsg(heading, msg, "icon-alert", buttons);

function showQuestion(heading, msg, buttons) {
    showMsg(heading, msg, "icon-question", buttons);

function showSuccess(heading, msg, buttons) {
    showMsg(heading, msg, "icon-success", buttons);

function showError(heading, msg, buttons) {
    showMsg(heading, msg, "icon-error", buttons);


Now that the scripts and styles are implemented, it is ready for use within our ASPX pages. Below I have created a simple grid with a delete button template field, a #pConfirmDeleteFruitButtons.hidden containing the buttons to be injected (I used client-side but you can use <asp:Button /> or simply add runat=”server” and implement the code-behind logic for server-side functionality). The confirmDeleteFruit function displays the confirm modal which will inject the #pConfirmDeleteFruitButtons div HTML. When the user clicks on the Yes button another function is fired. Note: This function can either be client or server-side depending on the application requirement.

<asp:GridView ID="gvFruit" runat="server" AutoGenerateColumns="false" DataKeyNames="Key">
                <asp:HyperLink ID="hypDelete" runat="server" Text="Delete"></asp:HyperLink>
        <asp:BoundField HeaderText="Name" DataField="Key" />
        <asp:BoundField HeaderText="Description" DataField="Value" />
<div id="pConfirmDeleteFruitButtons" class="hidden">
    <input type="button" value="Yes" onclick="deleteFruit();" />
    <input type="button" value="No" onclick="$.colorbox.close();" />
    <asp:HiddenField ID="hFruitID" runat="server" />
<script type="text/javascript">
    function confirmDeleteFruit(id, name) {
        showQuestion('Confirm Delete', 'Are you sure you want to delete this fruit (' + name + ')?', $("#pConfirmDeleteFruitButtons"));
    function deleteFruit() {
        var id = $('input[id$="hFruitID"]').val();
        showSuccess("Successful", "This fruit was successfully deleted.", undefined);
        $("tr[fruit='" + id + "']").hide();

The VB.NET Code
I have bound the onclick and href attributes on the RowDataBound event of the GridView as indicated below.

Protected Sub gvFruit_RowDataBound(sender As Object, e As GridViewRowEventArgs) Handles gvFruit.RowDataBound
    If e.Row.RowType = DataControlRowType.DataRow Then
        'Set the row to contain a key attribute with value
        e.Row.Attributes.Add("fruit", gvFruit.DataKeys()(e.Row.RowIndex)("Key").ToString())
        Select Case e.Row.RowState
            Case DataControlRowState.Normal, DataControlRowState.Alternate
                'Configure the delete button
                CType(e.Row.FindControl("hypDelete"), HyperLink).NavigateUrl = "javascript:void(0);"
                CType(e.Row.FindControl("hypDelete"), HyperLink).Attributes.Add("onclick", String.Format("confirmDeleteFruit('{0}','{0}'); return false;", gvFruit.DataKeys()(e.Row.RowIndex)("Key").ToString()))
               'Remember to check the string for any JavaScript unsafe characters that may break the generated script like a single '
           End Select
      End If
End Sub

Writing your own tiny URL

This post shows you just how easy it is to transform a very long url into something small like http://s.ly?13X. You see it everywhere online especially on Twitter and now you can make your own.


  • A registered domain name that is relatively small in length like http://sl.y
  • A datasouce: table or flat file to contain the data
  • A web page that will read from and/or write to the datasource
  • Essentially all you need to do is map a query string value (which must be unique of course) to a URL. The link https://kleinkiecode.wordpress.com/myposts/the-post-i-wrote-way-back-when can be mapped as http://tiny.com?X1is09. When I access the URL, the code on the page will check the query string in the datasource and redirect me to its URL mapping.

    Fields: PKID, Code/Key, URL. Note: The code/key can be the PK because it is unique, it is up to you and the structure of your table of course.

    This ingeniously simple concept has taken the web by storm and has helped keep URLs tiny enough to use in restricted text fields like on Twitter. One major drawback however is that you are clicking in the dark as you won’t know its destination until you’ve clicked on it although you can never really trust a URL name regardless of what it says.

    Dynamically inject embedded & external JS / CSS

    I went rogue recently by consciously choosing to avoid ASP.NET Themes and create my own mechanism, not to be smart but to have full control and simplicity for my solution. This obviously resulted in me having to dynamically embed and reference certain CSS and javascript.

    I decided to share my knowledge gained from this approach for any beginners as well as more developed developers to use as a reference because some of us just don’t usually muck about in the brain of the html document on a day-to-day basis.

    *My sample code is in Javascript, CSS and VB.NET

    How to embed JS

    Embedded javascript looks like this:

    <script type="text/javascript">
        alert('what up, ninja?');

    Well, in its simplest form at least. Obviously the stuff (or more technically the code/script) between the script tags will be dynamic otherwise this excise is useless.

    Now that we know how our script should generate, we can create the code generation process in the code behind. For the purpose of my post, my code in this document can be placed in the Page Load Event.

    Dim script As String = "<script type='text/javascript'>alert('what up, ninja? ');</script>"
    Dim embeddScript As New System.Web.UI.WebControls.Literal
    embeddScript.Text = script

    The above code creates a String object which will be used to handle the generation of the script. A literal control is created, set accordingly and added to the head tag of the html document via the Page.Header.Controls.Add sub. I chose to use a literal control because it doesn’t generate any additional html other than the html you have explicitly defined.

    **NOTE: When concatenating strings, you should use the System.Text.StringBuilder. To find out why, check out TIP: Concatenating Strings below.

    Now you can run your website and check out the source of your page to ensure you are happy with the injection.

    How to embed CSS

    Embedded CSS looks like this:

    <style type="text/css">
        body {background-color:steelblue;}

    To generate the above programmatically, we will follow the same approach as before except the generation of the script/code is different.

    Dim css As String = "<style type='text/css' rel='stylesheet'>body {background-color:steelblue; } </style>"
    Dim embeddedCss As New System.Web.UI.WebControls.Literal
    embeddedCss.Text = css

    How to reference an external JS file

    Referenced javascript file looks like this:

    <script src="js/script.js" type="text/javascript"></script>

    To reference a javascript file, you should use the same approach before. Your only concern is to ensure that the correct path is resolved for the injection process, otherwise your file could not be correctly referenced. To do so, you could use Page.ResolveClientUrl(“~/js/script.js”)

    Dim script As String = String.Format("<script type='text/javascript' src='{0}'></script>", Page.ResolveClientUrl("~/js/script.js"))
    Dim referencedScript As New System.Web.UI.WebControls.Literal
    referencedScript.Text = script

    How to reference an external CSS file

    Referenced CSS file looks like this:

    <link href="css/style.css" rel="stylesheet" type="text/css" />

    To reference a css file, you could use the same approach as before or you could make use of the System.Web.UI.HtmlControls.HtmlLink control and programmatically set the necessary attributes as done below.

    Dim css As New System.Web.UI.HtmlControls.HtmlLink
    css.Attributes.Add("rel", "stylesheet")
    css.Attributes.Add("type", "text/css")
    css.Attributes.Add("href", Page.ResolveClientUrl("~/css/style.css"))
    css.Attributes.Add("media", "Screen, projection")

    TIP: Using String.Format

    With Javascript and CSS we often have to make use of curly braces. To avoid getting the inevitable input string was not in a correct format error message, try the following:

    Dim myString As String = "body \{ background-color:{2}; \}".Replace("\{", "{0}").Replace("\}", "{1}")
    myString = String.Format(myString, "{", "}", "blue")

    I have escaped all curly braces that are part of the string by prefixing each one with a back slash. I have then simply replaced the \{ with {0} and \} with {1} and ensured my variable index in the string will always start from {2}.  In my String.Format function, I first merge the curly braces {, } and then my variable(s). This way the String.Format cannot get confused with any rogue curlies.

    TIP: Concatenating Strings

    The below is an abstract from Using the StringBuilder Class from MSDN:

    “The String object is immutable. Every time you use one of the methods in the System.String class, you create a new string object in memory, which requires a new allocation of space for that new object. In situations where you need to perform repeated modifications to a string, the overhead associated with creating a new String object can be costly. The System.Text.StringBuilder class can be used when you want to modify a string without creating a new object. For example, using the StringBuilder class can boost performance when concatenating many strings together in a loop.”

    To find out more about the StringBuilder class, check out: http://msdn.microsoft.com/en-us/library/2839d5h5(v=vs.71).aspx