<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><title><![CDATA[ObjectReference.net]]></title><description><![CDATA[ref this.object]]></description><link>http://objectreference.net/</link><generator>Ghost v0.4.0</generator><lastBuildDate>Tue, 14 Apr 2026 08:59:21 GMT</lastBuildDate><atom:link href="http://objectreference.net/rss/" rel="self" type="application/rss+xml"/><author><![CDATA[Nazmul Junaid]]></author><ttl>60</ttl><item><title><![CDATA[Apache Lucene.Net 4.8 beta is out]]></title><description><![CDATA[<p>Lucene is an awesome java library that provides ultra-fast search capabilities. </p>

<p>Unfortunately the .NET port Lucene.Net hasn't had any releases in over 4 years. This is partly due to there not being many volunteers and the 350,000 lines of executable code to port over to C#, no small feat.</p>

<p>Over a year ago I went to a .NET meetup in London presented by Itamar Syn-Hershko and was pretty excited to hear a new version of Lucene.Net was close to beta.</p>

<p>A few months later I eventually got around to taking it for a spin but quite quickly discovered many of my favourite features still missing. Remembering Itamar's plea for people to help the project, I downloaded the java Lucene source code and as an exercise, started porting the Lucene.Spatial code line by line into C#.</p>

<p>This was a huge learning experience for me as i'd not done anything like this before and have't had much experience with Java. After a lot of sweat and stackoverflow searching for java to C# equivalent code samples, I eventually raised a <a href='https://github.com/apache/lucenenet/pull/174' >pull request</a> and was pleasantly surprised that it was merged in.</p>

<p>The whole journey has made me realise just how much open source projects rely on community help to succeed. I'm pleased to hear the almost fully featured official beta is now released to the wild.</p>

<p>I'd like to thank everyone who's worked hard in making this happen and allowing me to contribute to the effort.</p>

<p>I'm now off to go play with <a href='https://www.nuget.org/packages/Lucene.Net/' >Lucene.Net 4.8</a>.</p>]]></description><link>http://objectreference.net/apache-lucene-net-4-8-beta-is-out/</link><guid isPermaLink="false">d60a941d-9428-4981-a6de-09c9fe04d99b</guid><dc:creator><![CDATA[Nazmul Junaid]]></dc:creator><pubDate>Sun, 25 Jun 2017 12:14:02 GMT</pubDate></item><item><title><![CDATA[Love The Sales ♥]]></title><description><![CDATA[<p><img src='http://objectreference.net/content/images/2014/Jan/love_the_sales.png'  alt="♥ All of the sales from all your favourite brands - follow top brands to never miss a sale." /></p>

<p>Some good friends have been working hard on new venture <a href='http://www.lovethesales.com/' >LoveTheSales.com</a> where you can find sales across multiple shopping sites such as Mothercare, House of Fraser, Currys etc covering a wide range of brands including Nike, Barbour, Monsoon.</p>

<p><img src='http://objectreference.net/content/images/2014/Jan/search.png'  alt="Love the sales search" /></p>

<p>The site is very clean, easy to use with a really fast search. The site runs on <a href='http://www.windowsazure.com/en-us/' >Azure</a> using <a href='http://lucene.apache.org/core/' >lucene.net</a> as their underlying search tech, for anyone that’s interested.</p>

<p>It's currently lacking setting price alerts for your favourite products, but I've been told this is in the pipeline.</p>

<p><a href='http://www.lovethesales.com/' >Check it out</a> and please do leave some feedback, they are very keen on hearing from users.</p>]]></description><link>http://objectreference.net/love-the-sales/</link><guid isPermaLink="false">4b5df120-1558-4316-8af5-0748baf9233c</guid><dc:creator><![CDATA[Nazmul Junaid]]></dc:creator><pubDate>Thu, 09 Jan 2014 12:01:51 GMT</pubDate></item><item><title><![CDATA[Organising apps in folders with a row per action]]></title><description><![CDATA[<p><img src='http://objectreference.net/content/images/2014/Jan/preview_apps_by_action.png'  alt="Organising apps using action rows" /></p>

<p>Folders in iOS are a great way to keep your large collection of iOS apps organised, but this has number of issues. Recently I starting organising my apps using an <strong>action per row</strong> approach and found it to be more efficient over iOS' default <strong>category-based</strong> naming system when it comes to launching apps.</p>

<p>Issues with folders:</p>

<ul>
<li>Requires you to tap multiple times to open an app, sometimes going through multiple folders to find an app, worse if you can't recall where you put it.</li>
<li>Need to remember what folder you put an app in. I keep getting brain farts where I am staring at my screen not remembering the app or folder I’m looking for.</li>
<li>Some categories e.g. Lifestyle can be a bit vague.</li>
<li>Hides away the attractive icons.</li>
</ul>

<p>You could just search, but that requires you to tap away even more and remember the name of the app. You could put the most used apps outside folders, maybe on the home screen. I find this messy and can be a bit confusing when you click on <strong>fitness</strong> and not find a app.</p>

<h2 id="verbbasedinterfaces">Verb based interfaces</h2>

<p><a href='http://smarterware.org/9324/good-tools-have-verb-based-interfaces' >Gina Trapani blogged about it a few years ago</a>. Essentially verb based interfaces are usually more user friendly as they require less thinking, our brains think in actions more easily.</p>

<p>I've taken Gina's idea one step further, with <strong>action rows</strong>.</p>

<p><img src='http://objectreference.net/content/images/2014/Jan/ios_apps.png'  alt="My apps organised using action rows" /></p>

<p>Action rows allow me to have 3 of my most used apps easily accessible alongside an <strong>action</strong> folder. You can then sort the rows based on popularity or similarity. I've ended up with a hybrid where my first screen is mostly full of productivity apps.</p>

<p>What's nice about this approach is that the folder acts as a sort of heading. As I use my phone mainly right handed, I keep the apps on the right, which makes them more accessible. Some <a href='http://lifehacker.com/465972344' #comments">prefer folders on the right</a>.</p>

<p>Try and think of the actions that usually go through your mind when you use your phone. It takes a bit of time tweaking and some apps will be hard to categorise, but once you get accustomed to it, it becomes a lot easier to recall and launch applications.</p>]]></description><link>http://objectreference.net/organising-apps-in-folders-with-a-row-per-action/</link><guid isPermaLink="false">d40384be-bbb5-43f8-9847-b44b223c994e</guid><category><![CDATA[iOS]]></category><category><![CDATA[User Experience]]></category><dc:creator><![CDATA[Nazmul Junaid]]></dc:creator><pubDate>Wed, 08 Jan 2014 12:00:00 GMT</pubDate></item><item><title><![CDATA[Installing Ghost Blog on Azure websites]]></title><description><![CDATA[<p><a href='https://ghost.org/features/' >Ghost</a> is a new free open source blogging platform, which recently gained lots of interest via the <a href='http://www.kickstarter.com/projects/johnonolan/ghost-just-a-blogging-platform' >kickstarter campain</a>. Most blogging platforms seem to evolve into complicated full-blown CMS's like Wordpress. What Ghost aims to do is bring simplicity to blogging and just blogging.</p>

<p>I tried to follow a few guides, (<a href='http://www.hanselman.com/blog/HowToInstallTheNodejsGhostBloggingSoftwareOnAzureWebsites.aspx' >Here</a>, <a href='https://github.com/TryGhost/Ghost/issues/830' >Here</a>) to get Ghost installed on Azure but kept failing. The following guide is the steps I took to get Ghost on Azure.</p>

<p>EDIT: You should be able to install Ghost from azure website gallery which maybe easier, i've not tried it yet. I have my own modified version of Ghost which i'm tweaking and deploying via git so this method still stands for me.</p>

<h2 id="installingghostonazure">Installing Ghost on Azure</h2>

<ol>
<li><p><a href='https://github.com/TryGhost/Ghost/releases' >Download Ghost</a></p></li>
<li><p>Rename <strong>config.example.js</strong> into <strong>config.js</strong>, open it up in your favourite editor, and start changing the settings for your desired environment.</p></li>
<li><p>Add a <strong>web.config</strong> file in the root folder. Copy the <a href='https://github.com/TryGhost/Ghost-Config/blob/master/azure/Ghost/web.config' >following content</a>.</p></li>
<li><p>Add a <strong>iisnode.yml</strong> file to the root folder. Copy the <a href='https://raw.github.com/TryGhost/Ghost-Config/master/azure/Ghost/iisnode.yml' >following content</a>. <em>Note: You should set loggingEnabled to false once your happy with you’re installation.</em></p></li>
<li><p><strong>Ghost 0.4.0+ can now skip this step.</strong> <del>Current release  of Ghost (0.3.3) has some issues with Azure due to a bug in the handlebars plugin. However the good news is that it has been fixed and you should be able to skip this step in Ghost 0.4+. In the meantime we can patch it ourselves easily by opening up <strong>package.json</strong> and updating the version numbers on the following dependencies.</del>  </p>

<ul><li><del>express to <em>3.4.6</em></del></li>
<li><del>express-hbs to <em>0.5.2</em> </del></li></ul></li>
<li><p>Create your website in Azure, if you don't already have one. I used the <a href='https://manage.windowsazure.com/' >web based interface</a>. Then deploy all the files to it. Done</p></li>
</ol>

<h3 id="note">Note</h3>

<p>The web.config method is preferred over the server.js include hack as it allows you also configure IIS to PassThrough errors to <strong>node</strong>, giving you pretty <a href='http://objectreference.net/404/' >Ghost error pages</a>.</p>

<p>Having a custom web.config also allows you to add <a href='http://www.iis.net/downloads/microsoft/url-rewrite' >UrlRewrite</a> rules. I've added some to migrate my old blogengine urls to the new posts and for canonicalizing www to non-www.</p>

<p>Here's a extract of my rewrite rules.</p>

<pre><code>&lt;rewrite&gt;
    &lt;rules&gt;
        &lt;rule name="Remove WWW" stopProcessing="false"&gt;
          &lt;match url="(.*)" /&gt;
          &lt;conditions logicalGrouping="MatchAll" trackAllCaptures="false"&gt;
            &lt;add input="{SERVER_NAME}" pattern="^(www\.)(.*)$" /&gt;
          &lt;/conditions&gt;
          &lt;action type="Redirect" url="http://{C:2}{REQUEST_URI}" redirectType="Permanent"/&gt;
        &lt;/rule&gt;

        &lt;!-- Redirect old Blogengine author &amp; category pages to homepage --&gt;
        &lt;rule name="Old pages redirect to homepage" stopProcessing="true"&gt;
            &lt;match url="\/author\/.*\.aspx|\/category\/.*\.aspx" ignoreCase="true" /&gt;
            &lt;conditions logicalGrouping="MatchAll" trackAllCaptures="false" /&gt;
            &lt;action type="Redirect" url="/" appendQueryString="false" redirectType="Permanent" /&gt;
        &lt;/rule&gt;                
        &lt;rule name="Redirect old posts" patternSyntax="Wildcard" stopProcessing="true"&gt;
            &lt;match url="post/*.aspx" ignoreCase="true" /&gt;
            &lt;conditions logicalGrouping="MatchAll" trackAllCaptures="false" /&gt;
            &lt;action type="Redirect" url="{ToLower:{R:1}}/" appendQueryString="false" redirectType="Permanent" /&gt;
        &lt;/rule&gt;

        &lt;!-- Node stuff --&gt;
        &lt;rule name="StaticContent"&gt;
          &lt;action type="Rewrite" url="public{REQUEST_URI}"/&gt;
        &lt;/rule&gt;
        &lt;rule name="DynamicContent"&gt;
          &lt;conditions&gt;
            &lt;add input="{REQUEST_FILENAME}" matchType="IsFile" negate="True"/&gt;
          &lt;/conditions&gt;
          &lt;action type="Rewrite" url="index.js"/&gt;
        &lt;/rule&gt;
    &lt;/rules&gt;
&lt;/rewrite&gt;
</code></pre>

<p>Happy blogging</p>]]></description><link>http://objectreference.net/installing-ghost-blog-on-azure-websites/</link><guid isPermaLink="false">0b00ff3e-36ec-42e3-a9c9-101cc29fc234</guid><category><![CDATA[Azure]]></category><category><![CDATA[Ghost]]></category><dc:creator><![CDATA[Nazmul Junaid]]></dc:creator><pubDate>Mon, 30 Dec 2013 12:00:00 GMT</pubDate></item><item><title><![CDATA[Welcome back]]></title><description><![CDATA[<p>Wow it's been over 4 years since <a href='http://objectreference.net/nhibernate-and-execution-plans/' >I last blogged</a>. I guess a lot has happened since then. No longer am I a wet eared junior developer but now lead my own crack team of developers. I'm a father to a one year old daughter, gained a passion for strength training and my experience and interests in development is no longer just limited to the .NET ecosystem. </p>

<p>This year I've decided to rekindle my interest of writing. This time I hope to write about my experiences in other topics not just limited to coding.</p>

<p>I don't want to make this a "new year's resolution" those usually fail after a few weeks. I'm going to make it a <a href='http://en.wikipedia.org/wiki/SMART_criteria' >SMART</a> goal. </p>

<blockquote>
  <p>I might write at least 12 posts by 2015.</p>
</blockquote>

<p>First step was migrating from blogengine into the beautifully clean and simple <a href='https://ghost.org/' >Ghost blogging platform</a>. I've only kept the popular articles and left all the spam filled comments behind they were actually harming SEO.</p>

<p>Getting Ghost working on azure was painful. I may do a post on how I got things working as it was hard to find guides that actually worked. Believe me I spend a whole day trying a number of them.</p>

<p>EDIT: Here's the post <a href='http://objectreference.net/installing-ghost-blog-on-azure-websites/' >Installing Ghost Blog on azure websites</a></p>

<p>Stay tuned, oh and happy New Year.</p>]]></description><link>http://objectreference.net/welcome-back/</link><guid isPermaLink="false">e889fadd-c800-45a7-89d2-112da2d3df3c</guid><dc:creator><![CDATA[Nazmul Junaid]]></dc:creator><pubDate>Sun, 29 Dec 2013 12:00:00 GMT</pubDate></item><item><title><![CDATA[NHibernate and Execution Plans]]></title><description><![CDATA[<p>Lately we have been investigating ORM’s (Object Relational Mapping) frameworks for use on a large enterprise level website which we been given the rare opportunity to rebuild from the ground up in Microsoft MVC. </p>

<p>I’ve used Subsonic in the past while working with dashCommerce and more recently on my latest project based on the wonderful Subsonic 3.0. We decided we needed something more robust and proven with a large enterprise level system like ours which currently comprises with hundreds of tables and store procedures all managed by a team of professional DBA’s who do a pretty good job at optimising and tuning the Microsoft SQL 2005 database. </p>

<p>After much deliberation we managed to convince the DBAs and Developer Head to give NHibernate a shot. It seemed to be the most mature fully featured ORM for .NET and rated highly whitin the .NET community as is apparent by the huge number of blog posts about it, so we felt more secure choosing it over the premature Entity Framework. </p>

<p>NHibernate and MVC brought us to reconsider our architecture and after finally getting my head around to the S#harp Architecture I managed to convince the team it was the way to go and gave us a good foundation to build our application on. </p>

<p>After a few weeks we got a really good prototype working. We mapped some of our core tables using FluentNhibernate, wrote some simple LinqToNHibernate queries, religiously followed Test Driven Development and Domain Driven Design until we stumbled across our first major issue. </p>

<p>Queries run by NHibernate were not re-using SQL Server execution plans This was causing us some major performance issues since some queries were taking a few seconds just to generate a plan. We quickly managed to figure out the problem caused viewing the queries using SQL Profiler. NHibernate was passing parameter sizes dynamically based on the length of the value rather than from the mapping which was causing SQL Server to create new execution plans for each unique query. </p>

<p>We found a <a href='http://testdrivendevelopment.wordpress.com/2009/03/10/nhibernate-queries-sql-server-execution-plans/' >good explanation and “fix”</a> setting prepare_sql to true in the NHibernate config. </p>

<p>This seemed to fix the parameter size issue but now the queries were being sent using exec sp_prepexec which even had the DBA’s scratching their heads over as it’s documented as a system procedure used to facilitate cursors within SQL Server. The DBAs later informed us that running queries like this causes the execution plans to only be re-used per open connection so for every connection it would still have to create new execution plans. </p>

<p>Carsten Hess wrote a <a href='http://ayende.com/blog/3991/nhibernate-the-database-query-cache-and-parameter-sizes' #30894">good comment</a> on Ayende’s Blog explaning the issue to which no follow up was made but helped us find and fix the issue. I’ve attached the file for those interested in the fix as to why this isn’t the default behaviour of NHibernate has us perplexed. I've just commenting out an if statement in \Driver\SQLClientDriver.cs found in NHibernate source code thus forcing it to call SetParameterSizes() all the time regardless of the prepare_sql setting alowing us to set it to false so queries are sent normally and excecution plans being issued and re-used correctly. </p>

<p>The whole experience left us feeling weary, had we not discovered the issue beforehand it almost certainly would have brought down our application if we went live with NHibernate. In the end we decided to hold off on implementing the ORM to give it more investigation. </p>

<p>Our journey wasn’t a waste of time as it has brought us to learn about many new skills along the way that has already had an affect on our programming. Test Driven Development, Dependency Injection, Inversion of Control, Domain Driven Design all of which has given us an understanding of some techniques we can use to better develop our system. </p>

<p>EDIT: Andrei Volkov has posted a good followup in which he explains the history of this issue and an alternative fix to create your own driver. <a href='http://zvolkov.com/clog/2009/10/28?s=NHibernate+parameter+sizes+controversy' >NHibernate parameter sizes controversy</a></p>

<p><strong>Please note this article was written in 2009 based on NHibernate 2.1.0 with SQL Server 2005 and may not be an issue anymore.</strong></p>]]></description><link>http://objectreference.net/nhibernate-and-execution-plans/</link><guid isPermaLink="false">241055df-6305-4ce0-85b1-b9955dd76cd0</guid><category><![CDATA[nHibernate]]></category><category><![CDATA[Coding]]></category><dc:creator><![CDATA[Nazmul Junaid]]></dc:creator><pubDate>Mon, 26 Oct 2009 12:00:00 GMT</pubDate></item><item><title><![CDATA[Construct a comma delimited list from table column with SQL]]></title><description><![CDATA[<p>How many times have you had to create a comma delimited list from a table column? Do you ever remember how to do it? I don’t. Here is a little snippet I find useful:</p>

<pre><code>-- this will be a comma delimited list of location ids
DECLARE @LocationIds Varchar(Max)
-- set it to an empty string to start with
SET @LocationIds = ''

--add commas 
SELECT @LocationIds = COALESCE(@LocationIds + ',','') + CAST(Location_ID AS VARCHAR) FROM Locations_Table
--get rid of the comma at the front of the string
SELECT SUBSTRING(@LocationIds, 2, Len(@LocationIds))
</code></pre>

<p>Result: 1234,3445,6778,6789,… </p>]]></description><link>http://objectreference.net/construct-a-comma-delimited-list-from-table-column-with-sql/</link><guid isPermaLink="false">02d5d492-7d8c-4e20-b380-3f340ee6d6a5</guid><category><![CDATA[SQL]]></category><category><![CDATA[Coding]]></category><dc:creator><![CDATA[Nazmul Junaid]]></dc:creator><pubDate>Thu, 15 Jan 2009 12:00:00 GMT</pubDate></item><item><title><![CDATA[SQL: Find last week date range]]></title><description><![CDATA[<p>The other day we needed to write a report on online sales for the last week. SQL doesn’t offer developers many predefined functions to work with date ranges unlike the C# programming language. Here is a little example how to query SQL for some data between the dates for the last week. </p>

<p>By default the first day of the week is set to Sunday (default value 7), so if you need it to be Monday run the following command:</p>

<pre><code>SET DATEFIRST 1    
</code></pre>

<p><img src='http://objectreference.net/content/images/2013/Dec/last_week_date.jpg'  alt="" /></p>

<pre><code>SQL Last Week Date Range
DECLARE @TodayDayOfWeek INT
DECLARE @EndOfPrevWeek DateTime
DECLARE @StartOfPrevWeek DateTime

--get number of a current day (1-Monday, 2-Tuesday... 7-Sunday)
SET @TodayDayOfWeek = datepart(dw, GetDate())
--get the last day of the previous week (last Sunday)
SET @EndOfPrevWeek = DATEADD(dd, -@TodayDayOfWeek, GetDate())
--get the first day of the previous week (the Monday before last)
SET @StartOfPrevWeek = DATEADD(dd, -(@TodayDayOfWeek+6), GetDate())
</code></pre>

<p>Now we can use above expressions in our query:</p>

<pre><code>SELECT …. FROM… WHERE Sale_Date BETWEEN 
CONVERT(VARCHAR, @StartOfPrevWeek,7)
AND
CONVERT(VARCHAR, @EndOfPrevWeek+1,7)
</code></pre>

<p>Note that we had to convert dates in order to reset minutes/hours/seconds to 00:00:00, but it also means that if we want to include the whole Sunday into our week report we need to set the dates BETWEEN Monday AND Monday 00:00:00. </p>]]></description><link>http://objectreference.net/sql-find-last-week-date-range/</link><guid isPermaLink="false">8414f1cc-9d74-4bcb-88c2-1922ac1cd2b0</guid><category><![CDATA[SQL]]></category><category><![CDATA[Coding]]></category><dc:creator><![CDATA[Nazmul Junaid]]></dc:creator><pubDate>Mon, 24 Nov 2008 12:00:00 GMT</pubDate></item><item><title><![CDATA[enum to friendly string extension method]]></title><description><![CDATA[<p>We use enums quite extensively in our application as they are great for representing integral values in a strongly typed way using symbolic names eg. </p>

<pre><code>if (Status == UserStatus.NotLoggedInAYear)
    ArchiveRecord();
</code></pre>

<p>is a lot more clearer and meaningful making it easier to maintain than</p>

<pre><code>if (Status == 3)
    ArchiveRecord()
</code></pre>

<p>The enum names are not very friendly to the user here's a solution creating friendly strings for enum values without using reflection which can be costly.</p>

<pre><code>public enum RemovalType
{
    None,
    ManAndVan,
    FullRemoval,
    FullRemovalsAndPacking
}

public static class RemovalTypeEnum
{
    /// &lt;summary&gt;
    /// Returns a friendly enum name
    /// &lt;/summary&gt;
    public static string ToFriendlyString(this RemovalType removalType)
    {
        switch (removalType)
        {
            case RemovalType.ManAndVan:
                return "Man &amp; Van Service";
            case RemovalType.FullRemoval:
                return "Standerd removals service";
            case RemovalType.FullRemovalsAndPacking:
                return "Full removals and packing service";
            default:
                return removalType.ToString();
        }
    }
}
</code></pre>

<p>Usage:</p>

<pre><code>RemovalType removalType = RemovalType.ManAndVan;
removalType.ToFriendlyString()
</code></pre>

<p>This implementation creates an extension method on the actual enum "RemovalType" which then allows you to call a ToFriendlyString() on the instance of all enums of that type I think this a more fluid implementation and also means better performance compared to the other implementations as it doesn't need to use reflection. </p>

<p>You will notive i've decided to leave the default return value to call ToString() on the enum value which means you only need to implement the values that need to be made friendlier.</p>

<p>You can also call it easily inside databinded controls in the aspx page. </p>

<pre><code>&lt;%# ((RemovalType)Eval("ServiceType")).ToFriendlyString() %&gt;
</code></pre>

<p>Or in razor with the necessary usings.</p>

<pre><code>@Model.ServiceType.ToFriendlyString();
</code></pre>]]></description><link>http://objectreference.net/enum-to-friendly-string-extension-method/</link><guid isPermaLink="false">d5033710-d224-4eb5-b800-4fe4c0b85ea5</guid><category><![CDATA[Coding]]></category><dc:creator><![CDATA[Nazmul Junaid]]></dc:creator><pubDate>Sat, 28 Jun 2008 11:00:00 GMT</pubDate></item><item><title><![CDATA[Object reference not set to an instance of an object]]></title><description><![CDATA[<p>“Object reference not set to an instance of an object” is probably the most common run-time exception message spat-out by the .Net framework, and most programmers will probably encounter this more often than any other framework exception type. </p>

<p>This exception, or more specifically a “System.NullReferenceException” is always caused when code tries to access an instance of any object, when the object has not yet been created and/or returned via a constructor, or some method.</p>

<h2 id="backtobasics">Back to basics.</h2>

<p>Object oriented programming is a form of programming wherein things called “Objects” are given “responsibility” for data, and for various operations. Each Object has a kind of blueprint, called a “Class”, as shown in the following code:</p>

<pre><code>public class Chair
{
    public Chair() { }
    public void Sit() { }
}
</code></pre>

<p>In order to use this object, you must create an “instance” of it, so to do that with the above class:</p>

<pre><code>Chair myChair;
myChair = new Chair();
myChair.Sit();
</code></pre>

<ol>
<li><p>Memory Allocation</p>

<pre><code>Chair myChair;
</code></pre>

<p>This line of code designates some memory to be used by your program for holding a “Chair” object. Think of this line, like setting aside some wood and nails to build a real chair.</p></li>
<li><p>Constructing your object</p>

<pre><code>myChair = new Chair();
</code></pre>

<p>This line of code creates an “Instance” of a “Chair” class, and assigns it to the variable “myChair” so that we may use it. To continue the above analogy, this is akin to looking at the blueprints for a chair, and using the assigned resources of wood &amp; nails (Memory, in the case of our program) and actually creating the Chair.</p></li>
<li><p>Using the Object</p>

<pre><code>myChair.Sit();
</code></pre>

<p>Now that we have an actual chair object, we can sit on it. If, however, you forget to include the line:</p>

<pre><code>myChair = new Chair();
</code></pre>

<p>Or, somehow your “myChair” object gets set to null before the myChair.Sit(); method-call, then a System.NullReferenceException will be thrown. </p></li>
</ol>

<p>If your object is unassigned (or null) you’re essentially tying to “Sit()” on nothing, and your program will fall on its arse. </p>]]></description><link>http://objectreference.net/object-reference-not-set-to-an-instance-of-an-object/</link><guid isPermaLink="false">e4fd6ee7-2256-4688-a6fe-9a6acab4c557</guid><category><![CDATA[Coding]]></category><dc:creator><![CDATA[Nazmul Junaid]]></dc:creator><pubDate>Wed, 28 May 2008 11:00:00 GMT</pubDate></item><item><title><![CDATA[SCOPE_IDENTITY() return the id from the database on insert]]></title><description><![CDATA[<p>As a .NET programmer most of my time is spent coding in C# and I try to avoid writing SQL where possible, which is great as we have dba's that can help with the more complicated queries. Why is it so complicated to write a loop without turning the database upside down? I'm not saying it's not possible it's just the language can me annoying at times.</p>

<p>Anyways, Recently I had to write an insert stored procedure and needed to return the ID of the row I was inserting. While writing my usual bad SQL I came across a fascinating function I’ve never used before, <code>SCOPE_IDENTITY()</code>. </p>

<p>Here's short example of how you can use the <code>SCOPE_IDENTITY()</code> function while doing an SQL INSERT to return the identity value of the row just inserted. </p>

<p>In this example I’m inserting a new customer record using a stored procedure and have declared a output parameter which I'd like to return to my application. </p>

<pre><code>CREATE PROCEDURE [dbo].[Customer_Insert]
  @Name VARCHAR(255),
  @Email VARCHAR(255),
  @Phone VARCHAR(255),
  @CustomerID INT OUTPUT
  AS
BEGIN
    INSERT INTO dbo.Customer ([Name], Email, Phone)
    VALUES (@Name,@Email,@Phone)

    SET @CustomerID = SELECT CustomerID 
              FROM dbo.Customer 
                  WHERE [Name] = @Name 
              AND Email = @Email 
              AND Phone = @Phone
END
</code></pre>

<p>What I’ve done wrong here is after inserting run a select to try and SET the <code>@CustomerID</code>. This is a bit risky as it could return more than 1 record, or it return an of completely different record. </p>

<p>SQL's <code>SCOPE_IDENTITY()</code> function can return the last identity value inserted into an identity column in the same scope e.g. a stored procedure, trigger, function, or batch. Alternativly you can also use the @@IDENTITY function to return the last identity value inserted into an identity column regardless of the scope. </p>

<p>Now lets improve my stored procedure using SCOPE_IDENTITY(). </p>

<pre><code>CREATE PROCEDURE [dbo].[Customer_Insert]
    @Name VARCHAR(255),
    @Email VARCHAR(255),
    @Phone VARCHAR(255),
    @CustomerID INT OUTPUT
AS
BEGIN
    INSERT INTO dbo.Customer ([Name], Email, Phone)
    VALUES (@Name,@Email,@Phone)

    SET @CustomerID = CAST(SCOPE_IDENTITY() AS INT)
END
</code></pre>

<p>I've casted the value returned by <code>SCOPE_IDENTITY()</code> to make sure the confirms to the return parametor <code>@CustomerID</code> INT OUTPUT.</p>]]></description><link>http://objectreference.net/scope_identity-return-the-id-from-the-database-on-insert/</link><guid isPermaLink="false">d2f43b9b-6368-4f40-8caf-fab7132e025f</guid><category><![CDATA[SQL]]></category><category><![CDATA[Coding]]></category><dc:creator><![CDATA[Nazmul Junaid]]></dc:creator><pubDate>Thu, 22 May 2008 11:00:00 GMT</pubDate></item><item><title><![CDATA[Select Text or Value From DropDownList Extension Method]]></title><description><![CDATA[<p>Here is a cool way to select an item from the DropDownList using it's value.</p>

<pre><code>ddlCountries.Items.FindByValue(value).Selected = true;
</code></pre>

<p>However I keep forgetting how to do it and end up spending ages searching for it, so here is a very usefull extension method that allows you to select an item from a DropDownList using the text or value of the item without needing to know the index of the item.</p>

<pre><code>using System;
using System.Runtime.Serialization;
using System.Web.UI.WebControls;

namespace Core.ExtensionMethods
{
    public class GenericDropDownListException : Exception, ISerializable
    {
        public GenericDropDownListException(string type, string value) : 
            base(string.Format("Unable to set  \"{0}\" to {1}", type, value)) { }
    }

    public static class DropDownListExt
    {
        public static void SelectValue(this DropDownList bob, string value)
        {
            try
            {
                if (bob.SelectedIndex &gt;= 0)
                    bob.Items[bob.SelectedIndex].Selected = false;
                bob.Items.FindByValue(value).Selected = true;
            }
            catch
            {
                throw new GenericDropDownListException("value", value);
            }
        }

        public static void SelectText(this DropDownList bob, string text)
        {
            try
            {
                if (bob.SelectedIndex &gt;= 0)
                    bob.Items[bob.SelectedIndex].Selected = false;
                bob.Items.FindByText(text).Selected = true;
            }
            catch
            {
                throw new GenericDropDownListException("value", text);
            }
        }
    }
}
</code></pre>

<p>Now all you need to do to select an item from the DropDownList is: </p>

<pre><code>ddlCountries.SelectText("UK");
</code></pre>]]></description><link>http://objectreference.net/select-text-or-value-from-dropdownlist-extension-method/</link><guid isPermaLink="false">f2eca503-c611-4eb2-9dab-3b360452b06b</guid><category><![CDATA[webforms ]]></category><category><![CDATA[Coding]]></category><dc:creator><![CDATA[Nazmul Junaid]]></dc:creator><pubDate>Fri, 25 Apr 2008 11:00:00 GMT</pubDate></item><item><title><![CDATA[Enum TryParse Extension Method]]></title><description><![CDATA[<p>TryParse method is very helpful if you need to convert string representation of a value to a value itself. TryParse is better than Parse method because it doesn’t throw any exceptions and just returns a Boolean value to indicate weather the parsing was successful. Surprisingly there is no TryParse method available to use for Enum and this is where extension method can be extremely useful.</p>

<pre><code>public static bool TryParse&lt;T&gt;(this Enum theEnum, string valueToParse, out T returnValue)
{
    returnValue = default(T);
    int intEnumValue;
    if (Int32.TryParse(valueToParse, out intEnumValue))
    {
        if (Enum.IsDefined(typeof(T), intEnumValue))
        {
            returnValue = (T)(object)intEnumValue;
            return true;
        }
    }
    return false;
}
</code></pre>

<p>Now it’s time to test our extension method! Here I have a simple UserType Enumeration</p>

<pre><code>public enum UserType
{
    None = 0,
    Administrator = 1,
    Manager = 2,
    Consultant = 3
}
</code></pre>

<p>Usage:</p>

<pre><code>currentUserType.TryParse(Request.QueryString["usertype"], out currentUserType);
</code></pre>]]></description><link>http://objectreference.net/enum-tryparse-extension-method/</link><guid isPermaLink="false">fec8c68b-ab2f-4d36-a8e7-07ada65d71e7</guid><category><![CDATA[Coding]]></category><dc:creator><![CDATA[Nazmul Junaid]]></dc:creator><pubDate>Mon, 21 Apr 2008 11:00:00 GMT</pubDate></item></channel></rss>