<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Technology Resource Blog &#187; Sam Critchley</title>
	<atom:link href="http://www.shivam.com.au/blog/index.php/author/sam/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.shivam.com.au/blog</link>
	<description>Information Technology Resourses</description>
	<lastBuildDate>Fri, 27 Jan 2012 04:22:07 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Bool Format Provider</title>
		<link>http://www.shivam.com.au/blog/software-development/bool-format-provider/</link>
		<comments>http://www.shivam.com.au/blog/software-development/bool-format-provider/#comments</comments>
		<pubDate>Mon, 08 Mar 2010 06:04:16 +0000</pubDate>
		<dc:creator>Sam Critchley</dc:creator>
				<category><![CDATA[Dot Net Tips]]></category>
		<category><![CDATA[Software Development]]></category>
		<category><![CDATA[bool format]]></category>
		<category><![CDATA[formatting boolean]]></category>

		<guid isPermaLink="false">http://www.shivam.com.au/blog/?p=271</guid>
		<description><![CDATA[I did a quick bit of research a while ago into how .Net converts a Boolean value to a string (via System.Bool.ToString). It does not make use of the current culture format provider so as such there is no way to easily tap in and override this methods behaviour.]]></description>
			<content:encoded><![CDATA[<h2>A non-localised solution to formatting Booleans to “Yes” or “No”</h2>
<p><span style="color: #000000;">I did a quick bit of research a while ago into how .Net converts a Boolean value to a string (via System.Bool.ToString). It does not make use of the current culture format provider so as such there is no way to easily tap in and override this methods behaviour.</span></p>
<p><strong>See this reflected code from System.Boolean.ToString:</strong></p>
<pre><span style="color: #0000ff;">public override string ToString()
{
    if (!this)
    {
        return "False";
    }
    return "True";
}</span></pre>
<p><strong><span style="color: #ff6600;">Appendix 1</span></strong></p>
<p><span style="color: #000000;">A common scenario is when a developer needs to display the value of a Boolean item inside your aspx/ascx code possibly from within a repeater. Like so:</span></p>
<pre><span style="color: #0000ff;">&lt;%# (bool)Eval(Container.DataItem, "IsActive") ? "Yes" : "No" %&gt;</span></pre>
<p><span style="color: #ff6600;"><strong>Appendix 2</strong></span></p>
<p><span style="color: #000000;">A VB.Net approach would probably use the IF ternary operator. There a number of different ways to solve this. You could have a utility function that accepts Booleans (or even objects and attempt to cast them to bool) and call that from your code. However, I wanted a solution that I could easier easily make c easily make accessible from my entire application. I also wanted to be able to extend the behaviour of the conversion. I may want “Yes” or “No” most of the time but sometimes I may want old fashioned “True”/”False” or even something more obscure like “On”/”Off”, “Active”/”Inactive” etc.</span></p>
<p><span style="color: #000000;">So, after a bit of looking around I decided that creating my own implementation of IFormatProvider would be the best approach to take. Coupled with the extension method I could make a new System.Bool.ToString method that would format Booleans how I wanted.<br />
To begin with I created my new BoolFormatProvider:</span></p>
<pre><span style="color: #0000ff;"><span style="color: #000000;">p</span>ublic class BoolFormatProvider : IFormatProvider, ICustomFormatter
{
    #region ICustomFormatter Members

    public string Format(string format, object arg, IFormatProvider formatProvider)
    {
        bool value = (bool)arg;
        format = (format == null ? null : format.Trim().ToLower());

        switch (format)
        {
            case "yn":
                return value ? "Yes" : "No";
            default:
                if (arg is IFormattable)
                    return ((IFormattable)arg).ToString(format, formatProvider);
                else
                    return arg.ToString();
        }
    }

    #endregion

    #region IFormatProvider Members

    public object GetFormat(Type formatType)
    {
        if (formatType == typeof(ICustomFormatter))
            return this;
        else
            return null;
    }

    #endregion
}</span></pre>
<p><span style="color: #ff6600;"><strong>Appendix 3</strong></span></p>
<p><span style="color: #000000;">So, in BoolFormatProvider I have a switch statement that identifies all the format strings I want to provide for. In this case I have only implemented a single format string for “Yes” &amp; “No” conversions. In the event that an unrecognised format string is provided the default ToString implementation for the value is used.<br />
To use the IFormatProvider only a few methods accept one to format the value. I don’t want a solution that has me manually instantiating a BoolFormatProvider every time I want to use it. So,with the help of an extension method:</span></p>
<pre><span style="color: #0000ff;">namespace MyExtensions
{
    public static class BooleanExtensions
    {
        public static string ToString(this bool value, string format)
        {
            return string.Format(new BoolFormatProvider(), "{0:" + format + "}", value);
        }
    }
}</span></pre>
<p><span style="color: #ff6600;"><strong>Appendix 4</strong></span></p>
<p><span style="color: #000000;">With this method created any code that is referencing the MyExtensions namespace can also call this method of an instance of System.Boolean. For use in aspx/ascx pages you can globally include a namespace via the web.config.</span></p>
<p><span style="color: #0000ff;">&lt;namespaces&gt;<br />
&lt;add namespace=&#8221;MyExtensions&#8221;/&gt;<br />
&lt;/namespaces&gt;</span></p>
<p><span style="color: #ff6600;"><strong>Appendix 5</strong></span></p>
<p><span style="color: #000000;">This should be placed under system.web/pages/. You can now use this from any aspx/ascx page in your website like this: </span></p>
<pre><span style="color: #0000ff;">&lt;%= Convert.ToBoolean("false").ToString("YN") %&gt;</span></pre>
<p><span style="color: #000000;">Or</span></p>
<pre><span style="color: #0000ff;">&lt;%# ((bool)Eval(Container.DataItem, "IsActive").ToString("YN") %&gt;</span></pre>
<p><span style="color: #000000;">Which makes boolean conversions to Yes/No or any other text representative of a boolean state very easy to implement all across your site from code or aspx/ascx alike.</span></p>
]]></content:encoded>
			<wfw:commentRss>http://www.shivam.com.au/blog/software-development/bool-format-provider/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Managing Exceptions &amp; SQL Transactions</title>
		<link>http://www.shivam.com.au/blog/software-development/managing-exceptions-sql-transactions/</link>
		<comments>http://www.shivam.com.au/blog/software-development/managing-exceptions-sql-transactions/#comments</comments>
		<pubDate>Wed, 03 Mar 2010 11:54:03 +0000</pubDate>
		<dc:creator>Sam Critchley</dc:creator>
				<category><![CDATA[Dot Net Tips]]></category>
		<category><![CDATA[Software Development]]></category>
		<category><![CDATA[managing exceptions]]></category>
		<category><![CDATA[sql transaction]]></category>

		<guid isPermaLink="false">http://www.shivam.com.au/blog/?p=260</guid>
		<description><![CDATA[A very common approach to managing exceptions that occur while a database transaction is in progress is to simply wrap it in a try catch block and if an exception occurs call Rollback on the transaction.]]></description>
			<content:encoded><![CDATA[<h3><span style="text-decoration: underline;"><span style="color: #000000;">A better try&#8230;<del datetime="2010-03-03T11:38:15+00:00">catch</del>&#8230;finally pattern</span></span></h3>
<p><span style="color: #000000;">A very common approach to managing exceptions that occur while a database transaction is in progress is to simply wrap it in a try catch block and if an exception occurs call Rollback on the transaction. This approach would typically appear like the example below:</span></p>
<pre><span style="color: #0000ff;">using (SqlConnection conn = new SqlConnection())
{
    conn.Open();
    using (var tran = conn.BeginTransaction())
    {
        try
        {
            DoOperation();//Exception may occur
            tran.Commit();
        }
        catch
        {
            tran.Rollback();
            throw;
        }
    }
}</span></pre>
<p><span style="color: #ff6600;"><strong>Appendix 1</strong></span></p>
<p><span style="color: #000000;">One of the issues with this approach is you are catching an exception that you are not handling. The exception handler doesn’t alter the execution of the program at all it just rolls back the transaction then throws the exception again to either be handled or not somewhere up the execution stack.</span></p>
<p><span style="color: #000000;">The second issue is a bit more obscure but I have run into it on more than a few occasions. Lets alter our example a little bit by adding in our own bit of validation that, when failed, throws our own exception.</span></p>
<pre><span style="color: #0000ff;">using (SqlConnection conn = new SqlConnection())
{
    conn.Open();
    using (var tran = conn.BeginTransaction())
    {
        try
        {
            bool result = DoOperation();//Exception may occur
            if (!result)
                throw new Exception("The operation failed!");

            tran.Commit();
        }
        catch
        {
            tran.Rollback();
            throw;
        }
    }
}</span></pre>
<p><span style="color: #ff6600;"><strong>Appendix 2</strong></span></p>
<p><span style="color: #000000;">This executes much as you might expect. If the result is false the exception is thrown, caught, the transaction is rolled back and the exception is rethrown. However, there is one problem. In the stack the line number reported for the source of the exception is the line of our “throw;” statement. Not the “throw new Exception(&#8220;The operation failed!&#8221;);” statement. This oddity only occurs if the exception is thrown from within our try block on the same frame of the stack (meaning it wasn’t thrown from a method called from within our try block, but directly from a statement inside the try block itself).</span></p>
<p><span style="color: #000000;">When I first encountered this I believed it to be a bug in the .Net runtime. Here is what <strong>Mike Magruder</strong> (who was introduced to me as the “architect in charge of the CLR’s exception handling system.”) had to say about it.<br />
<em><br />
This is by design. This has been odd ever since v1. We have a stack trace here, with one entry per stack frame, and we have a choice about what line to show for a method with a catch/rethrow. We could show the original throw point in the method, or we could show the rethrow point. Both can make sense, and you might be happier with one or the other depending on the scenario.</em></span></p>
<p><span style="color: #000000;"><em>I can’t honestly say why they chose that one, but I could speculate, and that speculation would start with the observation that a “catch { work(); throw;}” is often better represented by “finally {work();}”, and perhaps they believed that they would help more people by marking the point of rethrow as those might be more complicated scenarios.</em></span></p>
<p><span style="color: #000000;">I’ve always regarded “finally” as a somewhat useless feature so this was a bit of a revelation for me. I wondered for a while how my finally block could know if an exception occurred or not. The solution as it turns out was very simple.</span></p>
<pre><span style="color: #0000ff;">using (SqlConnection conn = new SqlConnection())
{
    conn.Open();
    bool fail = true;

    using (var tran = conn.BeginTransaction())
    {
        try
        {
            bool result = DoOperation();//Exception may occur
            if (!result)
                throw new Exception("The operation failed!");

            tran.Commit();
            fail = false;
        }
        finally{
            if (fail)
                tran.Rollback();
        }
    }
}</span></pre>
<p><span style="color: #ff6600;"><strong>Appendix 3</strong></span></p>
<p><span style="color: #000000;">Like I said, it’s very simple. Just include a flag variable that indicates if the code has executed successfully. The caveat is you do end up having this additional variable, you do have to manually set it and you do have to test its value. However, that is a small price to pay for optimal code (that doesn’t produce odd/wrong stack traces). After working with this approach for a month or so ,(my actual implementation look s a bit different as I don’t deal with ADO.Net classes directly) I have grown to like it.</span></p>
<p><span style="color: #000000;">One colleague asked me what to do if I, as a developer, wanted to log the exception. I think in this case if you want to catch and log the exception and display a nice error message to user as part of the normal page operation you could do that (it would/should probably happen further down the stack). Otherwise, you could show the user an error page using the inbuilt mechanisms of ASP.Net and also bind to the Application Error event which will fire for any unhandled exception, that would be a good place to log the exception and you are free of any catch/throw concerns at the point.</span></p>
]]></content:encoded>
			<wfw:commentRss>http://www.shivam.com.au/blog/software-development/managing-exceptions-sql-transactions/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Writing a Watermark jQuery Plugin</title>
		<link>http://www.shivam.com.au/blog/software-development/writing-a-watermark-jquery-plugin/</link>
		<comments>http://www.shivam.com.au/blog/software-development/writing-a-watermark-jquery-plugin/#comments</comments>
		<pubDate>Mon, 15 Feb 2010 04:08:08 +0000</pubDate>
		<dc:creator>Sam Critchley</dc:creator>
				<category><![CDATA[Dot Net Tips]]></category>
		<category><![CDATA[Software Development]]></category>
		<category><![CDATA[Dotnet Tips]]></category>
		<category><![CDATA[jQuery Tips]]></category>

		<guid isPermaLink="false">http://www.shivam.com.au/blog/?p=238</guid>
		<description><![CDATA[This article shows how to create a watermark plugin which can be used on textboxes or text areas. The watermark effect allows the developer to specify some brief instructive text inside the textbox without having to interfere with the use of the textbox.]]></description>
			<content:encoded><![CDATA[<h3><span style="color: #000000;">Introduction</span></h3>
<p>This article shows how to create a watermark plugin which can be used on textboxes or text areas. The watermark effect allows the developer to specify some brief instructive text inside the textbox without having to interfere with the use of the textbox.</p>
<p>For example, a search form will contain a textbox for the user to enter their search query; you can use the watermark effect on the textbox so that it always displays ‘Enter search query’ unless the user has already entered something.</p>
<p>I have read several articles on how to achieve this watermark effect and thought it would be a good idea to take that approach and put it in reusable, portable jquery plugin.</p>
<p><strong>Note</strong><strong>:</strong> This plugin requires jQuery 1.4x.</p>
<h3><span style="color: #000000;">The plugin pattern</span></h3>
<p>There are a few very scant, very simplified examples of how to author a jQuery plugin. The most popular of which is this: <a href="http://docs.jquery.com/Plugins/Authoring">http://docs.jquery.com/Plugins/Authoring</a> from the jQuery doc’s site.</p>
<p>However, the examples there are too simplistic to apply to anything of real complexity in which most developers work in. With a bit of hard work, I have learnt some techniques by reading the source code of Jörn Zaefferer’s (<a href="http://bassistance.de/">http://bassistance.de/</a>) plugins. In the field of jQuery, he is a master.</p>
<h3><span style="color: #000000;">Options</span></h3>
<p>This plugin will have two options, both with defaults. They are:</p>
<ul>
<li>waterClass – the name of the css class that will apply the visual effects . The default is “watermark”. (greyed text etc.)</li>
<li>valueAttribute – the attribute to read from the target field element. That value of the attribute is used as the water mark text. <em>Title</em> is the recommended default.</li>
</ul>
<h3><span style="color: #000000;">The foundation</span></h3>
<p>We will start by laying out our script foundation on which to build our functionality on.</p>
<pre><span style="color: #0000ff;">jQuery(function() {
    jQuery.waterMark = {
        defaults: {
            waterClass: 'watermark',
            valueAttribute: 'title'
        }
    };
});</span></pre>
<p><span style="color: #ff6600;"><strong>Appendix 1</strong></span></p>
<p>What this object stores are defaults and these may be accessed by curious developers like so: jQuery.waterMark.defaults.waterClass. Developers can easily override the defaults if they so desire.</p>
<p>Now, we shall define our initialisation method. This is the method users will actual call to kick things off.  The first thing to do is cache the settings and apply any settings were passed in over the top of the defaults:</p>
<p>This is then followed by adding the jQuery.waterMark definition.</p>
<pre><span style="color: #0000ff;">jQuery.fn.extend({
        waterMark: function(settings) {
            settings = jQuery.extend({}, jQuery.waterMark.defaults, settings);
            return this.each(function(i, item) {
                jQuery.data(item, 'settings', settings);
            });
        }
    });</span></pre>
<p><span style="color: #ff6600;"><strong>Appendix 2</strong></span></p>
<p>When a user calls our plugin (e.g.: $(‘#txt1’).waterMark()) this is what is executed. We call extend to extend a blank object with first the defaults and then what was passed to the plugin, overwriting the defaults if applicable. If what was passed in is null, then the defaults stay unchanged.</p>
<p>Secondly, we call this.each. In this case the keyword ‘this’ is pointing to whatever objects wherein the element set that waterM ark was called on (‘#txt1’ – a single element in this example). For each matched item we cache the settings in ‘data’ cache. We then return <em>this</em> as it is recommended practice for all public plugin methods to return the matched element set so users can easily chain method calls. (e.g. $(‘#txt1’).waterMark().hide ();)</p>
<p>We’ll be adding to this <em>loop</em> soon but first we need to define our event handlers. The events we are concerned with are the focus and blur events of the text fields and the submit event of the field’s form.</p>
<p>But just before we do that;</p>
<h3><span style="color: #000000;">Accessing Settings</span></h3>
<p>We’ll add this handy settings method that allows us to simply and consistently access the field’s settings:</p>
<pre><span style="color: #0000ff;">function settings(element) {
        return element.data('settings');
}</span></pre>
<p><span style="color: #ff6600;"><strong>Appendix 3</strong></span></p>
<h3><span style="color: #000000;">The Events</span></h3>
<pre><span style="color: #0000ff;">function focus() {
        var item = $(this);
        if (item.hasClass(settings(item).waterClass)) {
            item.val('');
            item.removeClass(settings(item).waterClass);
        }
    }</span></pre>
<p><span style="color: #ff6600;"><strong>Appendix 4</strong></span></p>
<p>When our textbox receives focus, we check if the element currently has the water mark effect applied and if it does we reset the value of the field so the user can begin typing. We also remove the css visual effect for the water mark.</p>
<pre><span style="color: #0000ff;">function blur() {
        var item = $(this);
        if (!item.val().length) {
            item.addClass(settings(item).waterClass);
            item.val(item.attr(settings(item).valueAttribute));
        }
    }</span></pre>
<p><span style="color: #ff6600;"><strong>Appendix 5</strong></span></p>
<p>When the user shifts focus away from the textbox, we need to check if they have entered anything. If they have, we do nothing, but if they have not, we need to turn the watermark visual effect back on and set the value of the field back to the water mark message text.</p>
<pre><span style="color: #0000ff;">function submit() {
        var item = $(this);
        if (item.val() == item.attr(settings(item).valueAttribute))
            item.val('');
    }</span></pre>
<p><span style="color: #ff6600;"><strong>Appendix 6</strong></span></p>
<p>Finally we need to handle what happens when the user submits the form. Currently all our watermarked text fields have default values that we do not want to send back the server. So, when the form submits we need to strip these defaults values out before the form sends the data to the server.</p>
<h3><span style="color: #000000;">Wiring the events</span></h3>
<p>Okay, let us attach our events now and handle the state of the textboxes when the plugin is first attached. We need to modify the code in Appendix 2. We need to change each loop (actually, technically speaking this is not a loop).</p>
<pre><span style="color: #0000ff;">return this.each(function(i, item) {
                jQuery.data(item, 'settings', settings);
                $(item.form).submit(jQuery.proxy(submit, item));
                item = jQuery(item);
                if (item.val().length &amp;&amp; item.val() != item.attr(settings.valueAttribute))
                    item.removeClass(settings.waterClass);
                else {
                    item.val(item.attr(settings.valueAttribute));
                    item.addClass(settings.waterClass);
                }
            }).focus(focus).blur(blur);</span></pre>
<p>We have just added quite a few lines now. Let us go through them. Firstly, we need to bind to the form’s submit event. To make things a bit simpler in the submit handler method, I do not want the <em>this</em> keyword to map to the form. I want it to map to the specific form field in question.</p>
<p>This was pretty simple to do already but jQuery 1.4 has introduced the <em>proxy </em>method (<a href="http://api.jquery.com/jQuery.proxy/">http://api.jquery.com/jQuery.proxy/</a>) which allows you to specify what object the <em>this </em>keyword references in the target event handler method (simply).</p>
<p>Next, our “if” statement checks what state the text field is currently in. Does it already have a value? Does that value match the water mark text? Depending on the state the plugin will switch on the css style and set the value of the field to the water mark text, otherwise it will remove the style if it is already applied.</p>
<p>At the end of the <em>each</em> method call, we are chaining on another two event binding methods to catch the focus and blur events.</p>
<h3><span style="color: #000000;">Using the plugin</span></h3>
<p>Reference the plugin code either as an external script file or an inline script block.</p>
<p>A textbox could be defined like the following:</p>
<p><span style="color: #0000ff;">&lt;input type=&#8221;text&#8221; title=&#8221;Type your text here&#8221; id=&#8221;txt1&#8243; name=&#8221;txt1&#8243; /&gt;</span></p>
<p>You then initialise it like this:</p>
<p><span style="color: #0000ff;">&lt;script&gt;$(function() {$(&#8216;#txt1&#8242;).waterMark();});&lt;/script&gt;</span></p>
<p>Or if you wish, to specify the css class to use:</p>
<p><span style="color: #0000ff;">&lt;script&gt;$(function() {$(&#8216;#txt1&#8242;).waterMark({waterClass: &#8216;customclass&#8217;});});&lt;/script&gt;</span></p>
<p>Which is very easy to implement.</p>
<p>I hope you found this article useful and thanks for reading it.  The full source code of our plugin can be found below:</p>
<pre><span style="color: #ff6600;">//Shivam Technologies
//Author: Sam Critchley
//Watermark - jQuery plugin</span>
<span style="color: #0000ff;">jQuery(function() {
    jQuery.waterMark = {
        defaults: {
            waterClass: 'watermark',
            valueAttribute: 'title'
        }
    };

    jQuery.fn.extend({
        waterMark: function(settings) {
            settings = jQuery.extend({}, jQuery.waterMark.defaults, settings);

            return this.each(function(i, item) {
                jQuery.data(item, 'settings', settings);
                $(item.form).submit(jQuery.proxy(submit, item));

                item = jQuery(item);
                if (item.val().length &amp;&amp; item.val() != item.attr(settings.valueAttribute))
                    item.removeClass(settings.waterClass);
                else {
                    item.val(item.attr(settings.valueAttribute));
                    item.addClass(settings.waterClass);
                }
            }).focus(focus).blur(blur);
        }
    });

    function submit() {
        var item = $(this);
        if (item.val() == item.attr(settings(item).valueAttribute))
            item.val('');
    }

    function focus() {
        var item = $(this);
        if (item.hasClass(settings(item).waterClass)) {
            item.val('');
            item.removeClass(settings(item).waterClass);
        }
    }

    function blur() {
        var item = $(this);

        if (!item.val().length) {
            item.addClass(settings(item).waterClass);
            item.val(item.attr(settings(item).valueAttribute));
        }
    }

    function settings(element) {
        return element.data('settings');
    }
});</span></pre>
]]></content:encoded>
			<wfw:commentRss>http://www.shivam.com.au/blog/software-development/writing-a-watermark-jquery-plugin/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>

