Object Reference .NET

ref this.Object

Object reference not set to an instance of an object

clock May 28, 2008 15:25 by author DaveTheKnave

This article is intended for amateur programmers, and/or people new to Object Oriented programming.

“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.

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.

Back to basics.

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:

public class Chair
{
    public Chair() { }
    public void Sit() { }
}  


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

Chair myChair;
myChair = new Chair();
myChair.Sit();


1) Memory Allocation

Chair myChair;

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.

2) Constructing your object

myChair = new Chair();

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 & nails (Memory, in the case of our program) and actually creating the Chair.

3) Using the Object

myChair.Sit();


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

myChair = new Chair();


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

If your object is unassigned (or null) you’re essentially tying to “Sit()” on nothing, and your program will fall on its arse.

kick it on DotNetKicks.com



We made it to asp.net front page!

clock May 23, 2008 08:00 by author Naz

Daves article on Implementing Generic Caching hit asp.net front page as article of the day for a week!



SCOPE_IDENTITY() return the id from the database on insert

clock May 22, 2008 20:15 by author Naz

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.

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, SCOPE_IDENTITY().
Here's short example of how you can use the SCOPE_IDENTITY() function while doing an SQL INSERT to return the identity value of the row just inserted.

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.

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



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

SQL's SCOPE_IDENTITY() 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.

Now lets improve my stored procedure using SCOPE_IDENTITY().

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


I've casted the value returned by SCOPE_IDENTITY() to make sure the confirms to the return parametor @CustomerID INT OUTPUT.

kick it on DotNetKicks.com



the LinqToSQL is a lie

clock May 8, 2008 21:18 by author Admin

LinqToSql is amazing! I've been working with it for the past week and loving every moment. However i've noticed somethig weird, it lies to me about the SQL it's generating. Here is my example...

Updated with better example

IEnumerable<QuoteLINQ> quote = from q in db.QuoteLINQs
                               where q.QuoteID.Equals(10)
                               select q;
 
lvQuoteDetails.DataSource = quote;
lvQuoteDetails.DataBind();


<asp:ListView ID="lvQuoteDetails" runat="server">
    <LayoutTemplate>
        <h2>Booking Details</h2>
        <asp:PlaceHolder runat="server" id="itemPlaceholder" />
    </LayoutTemplate>
    <ItemTemplate>
        Booking ID: <%# Eval("QuoteID") %><br />
        Booking Date: <%# Eval("BookingDate") %><br />
        Customer ID: <%# Eval("CustomerLINQ.CustomerID") %><br />
    </ItemTemplate>
</asp:ListView>


Linq allows you to see while you're debugging the SQL it's generating by hovering over the object. For the above code it tells me this is the generated SQL

{SELECT [t0].[QuoteID], [t0].[CustomerID], [t0].[BookingDate], [t0].[ServiceTypeID], [t0].[Comments], 
[t0].[Referer], [t0].[QuoteTypeID], [t0].[GUID]
FROM [dbo].[Quote] AS [t0]
WHERE [t0].[QuoteID] = @p0
}


Now most people will think everything's hunky dorey it's just a simple un-taxing query, but hold on... now how is it possible that in my Quote object I now have access to the customer object with all the customer details in it??

The LinqToSQL is a lie

So the generated Linq to SQL is a lie! Now my simple query as not so simple at all. What Linq actually does is fire of extra queries on request of the data. If you run SQL profiler you can see exactly what it's running. You need to be carefull accessing internal objects as Linq will go right ahead and get the information you request in another query, it's a lot safer to get everything in the initial Linq query go explicitly.

Atleast the cake is not a lie.

the cake is not a lie

kick it on DotNetKicks.com



Why can't you have handlers with multiple paths in web.config?

clock May 6, 2008 17:29 by author Naz

I have created IIS7 asset handler for my application which deals with images and stylesheets by serving them from a CMS database. For some reason the new IIS7 handlers section doesn't allow multiple paths for a handler, so you have to map each path like so..

<handlers>
    <add name="AssetHandlerGif" path="*.gif" verb="GET" type="CMS.AssetHandler" />
    <add name="AssetHandlerJpg" path="*.jpg" verb="GET" type="CMS.AssetHandler" />
    <add name="AssetHandlerPng" path="*.png" verb="GET" type="CMS.AssetHandler" />
    <add name="AssetHandlerCss" path="*.css" verb="GET" type="CMS.AssetHandler" />
<handlers>


This seems a bit odd since with the older httpHandler you were do this in one line

<httpHandlers> 
    <add verb="GET" path="*.jpg,*.gif,*.png,*.css" type="CMS.AssetHandler" validate="false"/>
</httpHandlers>


So can someone tell my why this does not work..am i doing something wrong here?

<handlers>
    <add name="AssetHandler" path="*.jpg,*.gif,*.png,*.css" verb="GET" type="CMS.AssetHandler" />
<handlers>


kick it on DotNetKicks.com



Simpleton Gaming

clock May 3, 2008 12:49 by author brew

Game developers have come together and decided to bring out a new range of games aimed at the not-so-bright ones among us. Games for the simpletons who have trouble turning their TV's on, let alone figuring a typical Metal Gear Solid dilemma. This range has an all-star cast of games including the following.

FIFA 2008 SE (Simpleton edition)
You start the game with just one team to avoid the confusion of navigating through all those hundreds of clubs. Within this one team you only get to control one player, thus saving the immense skill of actually changing player every time you wish to kick the ball. Pressing directional buttons will suggest to your player which way you want to go, and he will decide whether to obey you or not depending on whether you are asking him to do something sensible. When your player actually has the ball, control is simplified so that he will control himself until he is no longer in possession of it. Free kicks and penalties are also made easier as you just have to press a button and your player will take a decent kick wherever he likes, but still leaving ultimate power to you as you get to choose when he kicks it. Also included are post-match interviews with Beckham to make dim players feel intelligent.

Colin McRae Rally 4 SE
Since the normal version required a good deal of driving skill to master, certain driving aids have been introduced to help out the 'less-gifted'. The first change is invisible cushions along all the tracks that stop your car from leaving the track but actively pull opponents off. As well as auto-braking at corners, there is an additional option for auto-turning where the car steers itself round the corners. Also the AI cars don't exceed 30 mph, and they regularly explode and get flat tires without obvious cause. As an added measure, to ensure that players don't get distracted and worried too easily, the original plan to model the driver as a true likeness of Colin has been canned.

Unreal Tournament 3 SE
In a bold move, UT developers have made the shock decision to allow the player to control ALL directional movements. This is swiftly countered by the changeover to become a 2D platformer, and the auto-aim facility, which will automatically aim your crosshair at the nearest enemy player, be he in sight or not. The weapons have also been simplified, so you'll now be able to wield the likes of a rolling pin, knife and fork, cucumber, and nuclear bomb.

Final Fantasy XI SE
The main character who you control is Fred, the original names for FFX are too hard to read and pronounce and so have been cut in favour of smaller and simpler names. To obviate the obvious need to solve the hard puzzles throughout the game, you actually watch a pre-rendered video sequence of the game's characters completing the missions. To make players really think they are having an input into the game, lights flash and the controller vibrates.

These games should exploit a previously untapped niche in the market, and cater for the gaming needs of all the total idiots around today. They're still too advanced for the techno-illiterate oldies of yesteryear, but just perfect for Joe Bloggs next door who still uses tip-ex on his computer monitor.

The future's bright. The future's simpleton.



A C# Operator I would like to see.

clock April 30, 2008 19:14 by author DaveTheKnave

You could argue there are too many operators in C# as it is; however, I feel having an acute knowledge of the available operators is like knowing CTRL + B will bold the selected text in most word processing software.

To put it simply, it hurts no-one, whilst providing shortcuts to advanced users.

Consider the following:

if (MyObject != null)
{
    return MyObject;
}
else
{
    return SomeOtherObject;
}


In C# 2.0, the kind people at Microsoft provided the ?? operator to make this a much more sucinct:

return MyObject ?? SomeOtherObject;


One thing that I find ugly and boring in code is that of checking for nulls in nested object properties, so for a moderately extreme example:

Staff.Manager.PersonalDetails.Address.Location.Postcode


In order for me to be sure that I can access the “Postcode” part of this chain correctly (with the caviet that each of these proerty objects might be null) I’d have to write something like the following:

if (Staff != null && Staff.Manager != null && 
    Staff.Manager.PersonalDetails != null && 
    Staff.Manager.PersonalDetails.Address != null && .....
{


I’m sure you’ll agree the above is pretty ugly, especially if you don’t really care which property is null, just if any of them are.

So, I propose a new operator, the “Is anything in this chain null” operator, to be used something like so:

return ??{Staff.Manager.PersonalDetails.Address.Location.Postcode} : “No Postcode”


The actual syntax of this operator isn’t important, just the functionality.

I’d be interested to hear feedback on this.

Dave

kick it on DotNetKicks.com



Implementing Generic Caching

clock April 28, 2008 18:40 by author DaveTheKnave

I develop for a large, high-availability website, with hundreds of thousands of daily users. As such, we need to cache a lot of data in our web-server memory (which is cheap) to save numerous hits to our main database cluster (which is very expensive). I would imagine the desire to improve performance by saving on database hits is common across many web applications – and caching frequently used data is often seen as one of the best ways to solve this problem.

There are two further specific problems I face in every-day life, and these are:

  1. We have lots of silly little objects and lists of objects we wish to cache to improve performance
  2. Populating the cache (on request) needs to be thread-locked


Why thread locked?

When the loading of a particular cached item is particularly expensive, say, a fifteen-second database query, there is the possibility that multiple requests can try to populate the cache at the same time – so for example, if ten people simultaneously request a resource, with something like below – you can run into problems due to the required null check:

public List<int> CachedWidgetIds
{
    get
    {
        if (Cache["CachedWidgetIds"] == null)
        {
            Cache["CachedWidgetIds"] = SomeProvider.GetWidgetIds();
        }
        return (List<int>)Cache["CachedWidgetIds"];
    }
}


If this property is accessed more than once quickly, and if SomeProvider.GetWidgetIds(); takes a few seconds to complete – there is every possiblity that multiple requests will attempt to populate this cached object at the same time, until at least one of these completes and assigns a value to the cache.

At a database level, this could potentially cause row-locking and deadlocks if multiple requests are all needlessly running the same expensive query, meaning the query could fail thus making the problem much worse.

In order to solve these problems, and standardize or cache access, we have implemented a generic class as follows:

public interface ICachable
{
    string GetUniqueCacheName();
    int GetCacheTime();
    void FillSelf();
}
 
public static class SafeCache<T> where T : ICachable
{
    private static T singletonObject;
    private static object classLock = new object();
 
    public static T Object
    {
        get { return singletonObject == null ? CacheMethod() : singletonObject; }
    }
 
    public static T CacheMethod()
    {
        if (HttpContext.Current == null)
        {
            // if the current httpcontext is null then we are in a non-web app and can't use web caching
            if (singletonObject == null)
            {
                singletonObject = Activator.CreateInstance<T>();
                singletonObject.FillSelf();
            }
            return singletonObject;
        }
        else
        {
            //Create an instance of a generic type T for a reference type. 
            //Using default(T) will return null
            T cachedObject = Activator.CreateInstance<T>();
 
            if (HttpContext.Current.Cache[cachedObject.GetUniqueCacheName()] != null)
            {
                cachedObject = (T)HttpContext.Current.Cache[cachedObject.GetUniqueCacheName()];
            }
            else
            {
                lock (classLock)
                {
                    //Why check if the cache is null for a second time?
                    //If person #1 enters this statement, they will lock "classLock" and start 
                    //to run cachedObject.FillSelf(); - the lock will mean any requests that take 
                    //place during the time it takes to exectue cachedObject.FillSelf() operation 
                    //will wait at the line "lock (classLock)" - then, once Person #1 releases the lock, 
                    //they'll all come pouring into this satement - and we dont want them to run FillSelf() again!
                    if (HttpContext.Current.Cache[cachedObject.GetUniqueCacheName()] != null)
                    {
                        cachedObject = (T)HttpContext.Current.Cache[cachedObject.GetUniqueCacheName()];
                    }
                    else
                    {
                        cachedObject.FillSelf();
                        HttpContext.Current.Cache.Insert(cachedObject.GetUniqueCacheName(), cachedObject, null,
                            DateTime.Now.AddHours(cachedObject.GetCacheTime()), TimeSpan.Zero);
                    }
                }
            }
            return cachedObject;
        }
    }
}


This class can be used with any object that implements the simple interface “ICacheable” (decalred above) to provide a standard way of populating itself with data. So, to make a long story short, this can be used like:

DropDownList1.DataSource = SafeCache<Widgets>.Object.WidgetIds;
DropDownList1.DataBind();


As you can see, this removes all the workings of the cache from the calling resource, and provides a clean and thread-safe way for it to be accessed.


[Edit: This code sample has been updated with ideas from www.DotNetKicks.com to make it slightly more efficient, also implementing a singleton version]

kick it on DotNetKicks.com



Select Text or Value From DropDownList Extension Method

clock April 25, 2008 17:22 by author Naz

Here is a cool way to select an item from the DropDownList using it's value.

ddlCountries.Items.FindByValue(value).Selected = true;


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.

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 >= 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 >= 0)
                    bob.Items[bob.SelectedIndex].Selected = false;
                bob.Items.FindByText(text).Selected = true;
            }
            catch
            {
                throw new GenericDropDownListException("value", text);
            }
        }
    }
}


Now all you need to do to select an item from the DropDownList is:

ddlCountries.SelectText("UK");


kick it on DotNetKicks.com



Being a “nice” programmer

clock April 22, 2008 01:46 by author DaveTheKnave

Being a C# developer by trade, I naturally spend a lot of my working life programming computers. Whilst I by no-means profess to be a “guru” of any kind, I do notice that there is one aspect of software development that is often neglected from discussion, and most programmers will hopefully agree with me as I explain.

Programming is often described as an “art” – and whilst I agree with that statement, it is probably for different reasons than most programmers would assume. I believe one of the most important (and inherently artistic) elements of programming, to be that of simple document formatting.

With the majority of application development shifting to the ‘net, maintenance-programming is arguably becoming more important. As such, I myself would much rather attempt to maintain something complicated that was formatted and factored sensibly and aesthetically, than something programmatically simple, but with poor formatting, naming and structure.

Take the following made-up Page_Load example:

protected void Page_Load(object sender, EventArgs e)
{
    CreateDefaultWidgetProperties();
    if (WidgetProperties == null)
    {
          divMain.Visible = true;
     }
     
     HideWidgetTable(false, "customers", null);
     //The keyword Search Keyword = tbSearch.Text.Trim();
    lblMessage.Text = string.Empty;
    lblMessage.Visible = false;
    int PersonID = Int32.MinValue;
 
    if (!Page.IsPostBack)
    {
        if (Session[SessionKeys.ManageWidget.ContinueAction] != null 
                              && Person.Details.IsSomething == false)
        {
            string action = (string)Session[SessionKeys.ManageWidget.ContinueAction];
            ContinueAction(action, true);
        }
       
        SetupColumnHeaders();
       
        switch (ManageWidget.SearchType)
        {
            case ManageWidget.SearchTypes.DateSearch:
                LoadFromDateSearch();
                break;
            case ManageWidget.SearchTypes.RefSearch:
                LoadFromRefSearch();
               break;
            case ManageWidget.SearchTypes.StdSearch:
                LoadFromStandardSearch();
                break;
            default:
                SetupPage(WidgetProperties);
                BindRepeater(WidgetCollection);
                break;
             }
        }
       
        if (divOtherUsers.Visible == false || ddlPeople.SelectedValue == Person.ID.ToString())
            personId = Person.ID;
        else
            personId = int.Parse(ddlPeople.SelectedValue);
       
        if (personId > 0) Session.Add("CurrentPerson", personId);
}


As a rule of thumb, especially when dealing with program entry-points (such as .Net page-loads) I strongly believe that they should contain as little “code” as possible (if you have over a page in a method, you’re probably doing something wrong) – but more-so, they should contain an “code-index”.

When writing a page of code, consider you are writing it as you would an instruction manual, wherein having everything listed in one big chunk could potentially be hard to follow. Using the example of a VCR, if you only wanted to know how to fix a blinking VCR clock, you would go straight to the section in the instructions “How to set your VCR’s time”.

It should be the same with code. If I have to fix a bug in my imaginary “Widget Search”, I’ll know straight-off that it’s very likely to be in the ProcessWidgetSearch() method, meaning my maintainence will probably be faster, and my head will hurt less.

So, for example:

protected void Page_Load(object sender, EventArgs e)
{
    CreateDefaultWidgetProperties();
    divMain.Visible = WidgetProperties == null;
    HideWidgetTable(false, "customers", null);
    ProcessKeywordSearch();
 
    if (!Page.IsPostBack)
    {
        if (this.ContinueAction != null && !Person.Details.IsSomething)
        {
            ContinueAction(this.ContinueAction, true);
        }
        SetupColumnHeaders();
        ProcessWidgetSearchType();
    }
 
    SetCurrentPerson();
}


Another positive that should naturally fall-out of such an approach will be that of code re-use. If I wish to make a call to process my widget search-types again, I have already wrapped this logic in a method, meaning I’m less likley to copy / paste the same block of code (which would add to further maintainence).

The ‘art’ of this process is choosing which code-elemets are abstractly linked – however if you take the time to write code as if you were formatting it for someone else to read, not a computer, you will notice this will point your abstraction in the right direction, and everyone will say:

“What a nice programmer”

kick it on DotNetKicks.com



Advertisment


RecentComments

Comment RSS

Sign in