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>
    <section>
        <h2>My heading</h2>
        @RenderBody()
    </section>
</div>
...
<!-- 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)
            $(this).show();
    }
    img.src = src;
    $("#banner").append(img);
    $(img).hide();
});
</script>

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 Public Holidays

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)
{
    try
    {
        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()))
Next

Selecting the current month

cboExpiryMonth.ClearSelection()
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>
    </div>
</div>
<style type="text/stylesheet">
    .hidden {display:none;}
</style>

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 {
        $.colorbox.close();
    }
}

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);
}

Usage

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">
    <Columns>
        <asp:TemplateField>
            <ItemTemplate>
                <asp:HyperLink ID="hypDelete" runat="server" Text="Delete"></asp:HyperLink>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:BoundField HeaderText="Name" DataField="Key" />
        <asp:BoundField HeaderText="Description" DataField="Value" />
    </Columns>
</asp:GridView>
<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" />
</div>
<script type="text/javascript">
    function confirmDeleteFruit(id, name) {
        showQuestion('Confirm Delete', 'Are you sure you want to delete this fruit (' + name + ')?', $("#pConfirmDeleteFruitButtons"));
        $('input[id$="hFruitID"]').val(id);
    }
    function deleteFruit() {
        var id = $('input[id$="hFruitID"]').val();
        showSuccess("Successful", "This fruit was successfully deleted.", undefined);
        $("tr[fruit='" + id + "']").hide();
    }
</script>

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.

Ingredients:

  • 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 http://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?');
    </script>

    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
    Page.Header.Controls.Add(embeddScript)

    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;}
    </style>

    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
    Page.Header.Controls.Add(embeddedCss)

    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
    Page.Header.Controls.Add(referencedScript)

    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")
    Page.Header.Controls.Add(css)

    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

    Attaching a Stream object to an e-mail


    Recently I came across a simple conundrum, I need to do something that I have not done before and wasn’t really equipped with all the knowledge to do it. All I needed to do was attach a generated file to an e-mail. This sounds simple enough only my file gets generated on-the-fly through an ASPX page and is never saved to the server. Examples of such a generated file can be a PDF, XML, document, spreadsheet, vCard, barcode, image or even a custom file which is most likely personalised.

    I started by checking out what is available to me through the System.Net.Mail.Attachment class in System.Net.Mail as (logically) that is where I will need to add my attachment. I noticed that one particular constructor allows me to pass an System.IO.Stream object through. This was a good starting point!

    I analysed what I need to do dynamically:

    1. Make a call to my ASPX page (personalised through query string parameters)
    2. Execute the page
    3. Get its generated contents
    4. Add it as an attachment

    Luckily this is made simple with the System.Net.WebRequest class.  Using the code below I am able to create a request to any URL on the Wicked Webby World!

    Note: my sample scripts are done inVB.NET but are VERY close to C#. If you need help, there are good converters out there for free such as http://converter.telerik.com/

    WebRequest.Create("http://kleinkiecode.wordpress.com")

    It is not enough to simply create a request and not process it. In order to process it, I will need to work with the response sent from the server.

    WebRequest.Create("http:// kleinkiecode.wordpress.com").GetResponse()

    The System.Net.Mail.Attachment class does not have a constructor allowing me to send a System.Net.WebResponse so I need to somehow convert the response that I have gotten into a stream (System.IO.Stream).

    WebRequest.Create("http:// kleinkiecode.wordpress.com").GetResponse().GetResponseStream()

    That was done simply enough! Now all I need to do is adjust my URL to the URL that returns my response and add the stream to the attachment.

    Dim mail As New System.Net.Mail.MailMessage() 'Create mail object
    ... 
    Dim url As String = "http://kleinkicode.wordpress.com/generator.aspx?post=" & Request.QueryString("post")  'Define the personalised url to be requested
    'NOTE: You cannot create a relative request such as "~/generator.aspx"
    Dim filename As String = "POST_" & Request.QueryString("post") & ".doc" 'The file name can be generated if necessary
    'Attach the stream from the response of the created webrequest using the specified URL. Also provide a file name for display in the e-mail client
    Dim attach As New Attachment(WebRequest.Create(url).GetResponse().GetResponseStream(), filename) 
    mail.Attachments.Add(attach) 'Attach the attachment

    I hope that this post helps!

    Set up local secure certificate


    If you need to set up a local secure server certificate in order to mimic a secure (HTTPS) and non-secure (HTTP) website, follow the steps below for IIS 7+.
    1. Open IIS (Windows > Run > inetmgr)
    2. In the connections panel, click on the top-most tree node (A)
    3. In the main panel ensure you are in Features View (B), and double click on Server Certificates (C)
    4. In the actions panel, click on Create Self-Signed Certificate link and follow the prompts
    5. In the connections panel, click on the Default Web Site node (directly under Sites if you expand top- most tree node (A))
    6. In actions panel, click on Bindings link
    7. In Add Site Binding dialog, change Type to https and SSL certificate to the certificate you have just created
    8. Click OK and Close