Object Reference .NET

ref this.Object

Web developers. You suck.

clock July 15, 2008 16:54 by author DaveTheKnave
Well, JavaScript developers, specifically.

In order to aid in development of my own websites, I enabled JavaScript debugging in Internet Explorer a few weeks back.

To my horror, I have quickly experienced what seems to be complete disregard for serving syntactically correct JavaScript on the open internet.

No, I’m not just talking about a few niche websites, run by amateur programmers. I am talking about industry-leading nerd-friendly powerhouse websites that should know better.

To list a few examples of websites coated with syntax errors (at the time of writing):

  1. http://slashdot.org/. Slashdot for god’s sake!! On the homepage!
  2. http://digg.com/. Try posting a new dig article with a thumbnail.
  3. http://www.computerworld.com/ come on.
  4. http://www.somethingawful.com/
  5. http://www.pcmag.com/
  6. http://www.washingtonpost.com

The list really does go on. With script debugging enabled, the internet becomes an almost unusable, frustrating place. Especially if you couple this with a delightful bug in Internet Explorer, that causes it to freeze if two of your open and loading tabs both have a modal JavaScript error box waiting for a response.

Anyone who writes production JavaScript should always have script debugging enabled. If not just to help catch your own mistakes - but also to see how infuriating it can be to simply use the internet while being forced to close millions of error dialogs.
This alone should convince you to write better JavaScript.

To enable script debugging:

Tools/Internet Options/Advanced/ - Un-check "Disable Script Debugging"



When disabled, this will cause a small error box to show if there is a syntax (or execution) error in any JavaScript code.


Slashdot: 15 July 2008

If you wish, you can click the “Debug” option, and this will offer you the option of opening visual studio, letting you step through the broken code.

I’m sure you’ll all agree that correct JavaScript should not be a lofty goal to aim for.

Dave

kick it on DotNetKicks.com


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


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


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


The Briny Deep - Suggest cartoon ideas!

clock April 4, 2008 20:24 by author DaveTheKnave

Be sure to visit http://www.thebrinydeep.com/ – here, you can add a cartoon suggestion, in the form of a crazy activity (or just vote on the existing suggestions).
After a day or so, a winner will be chosen and drawn!


Check it out!



Search

Sign in