Object Reference .NET

ref this.Object

BlogEngine Flaws

clock July 27, 2008 21:46 by author Naz
Get Blog Engine I'm part of the small open source team for dashCommerce an .NET shopping cart system so please don't get me wrong this article isn't about dissing the hard work and time developers have put into BlogEngine it is just to highlight some of the the design flaws I've encountered which we should help to improve on in future versions. I will still continue to use blogengine as it's still the best out there but it can be better...

This site is currently distributed across multiple web servers sometimes referred to as “Cloud Hosting”. Many large popular websites work of this kind of architecture to keep up with demand of resources required to process user requests. I’ve read somewhere Facebook currently has around 200 distributed web servers for hosting their site at various parts of the world.

BlogEngine runs of a singleton caching model where it caches posts and comments into an static object and then reads and writes that object to either an XML or Database when required. A common problem with this design is each server does not have direct access to the in memory object. Due to this when a comment is posted on server 1 gets saved to database, server 2 doesn't know that there has been change so you wont see the update until server 2 updates itself. However there are some work-rounds the simplest is just using the standard .NET caching model instead of singleton caching as you can specify an expiration times and also set-up things like cache dependency enabling your servers can get back to sync.

Recently I’ve been having problems as the site has gotten more popular I’ve had comments and even posts disappearing randomly, sometimes re-appearing you might have experienced this yourself either on my site or in your own so after divulging into the code to see what was happening found something I thought was shocking. When you add a comment, or Rating, Approving and Remove Comments this is what BlogEngine DbBlogProvider actually does...

  1. UPDATE The post
  2. DELETE All Tags for that post
  3. INSERT All Tags for that post
  4. DELETE All Posts Categories
  5. INSERT All Posts Categories
  6. DELETE All existing comments for that post
  7. INSERT All comments back in including the new comment
  8. DELETE All post notifications
  9. INSERT All post notifications

Remember all this when all it needed to do is INSERT into Comments table the new Comment!

From what I can see (I could be wrong) it is doing it without an SqlTransaction so if something where to go wrong it wont rollback changes. This can also cause concurrancy issues say if two people are adding comments at the same time i'm not sure if it will lock it. So instead of just getting delayed updates my web servers are actually in constant battle with each other overwriting each others changes when they save content every time someone post's a comment or rates an article.

I hacked a workaround so Add Comment just does what it needs to by adding new Abstract Methods to BlogProvider but this meant I had to write the same methods for XMLProvider but XML's and relational databases are completely different so I just stubbed them out.

I hope the developers take note about this for future versions there might have been a reason for this the only thing I can think of is they tried to reduce the number of methods a BlogProvider requires.

kick it on DotNetKicks.com


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


Lightbox images for dashCommerce

clock July 1, 2008 21:20 by author Naz
lightbox

As of revision 142 of dashCommerce i've added a new feature on product pages to now display images using lightboxes.

As it did not make the 3.0.1 release i've made available the patch to allow you to add it if you wish to do so.

It's based on the jQuery lightbox library.

Demo -> Test Site

Patch -> Lightbox_Patch.patch (83.97 kb)

Files -->  dashCommerce_Lightbox.zip (37.13 kb)

Check in note.

"ADDED: Lightbox for product images.
1. You can now view images if js is disabled it just opens them in a new window makes it more accessible.
2. If you have large images it wont break the design on the product page like it did before.
3. You can cycle through all the images in the product using next and back links and it also displays the title for each one.
4. Don't need tiny thumbnails any more as it uses the same size one as the category page.
5. It looks really cool ;)

TODO: Remove tiny thumbnails.
"

Please report any bugs or issues here


Get Checked Repeater Items Extension Method

clock June 16, 2008 17:24 by author Magz
Imagine you have a list of some items and checkboxes next to each item providing the ability for a user to make multiple choices and submit a result in one go. Weather you are implementing a news groups subscription, user survey or online products catalogue - the code behind is the same: we bind some object list to a data control like Repeater, add a checkbox to every item, set checkbox value to item ID.

Here is an example with list of books available for order

Repeater with checkboxes
<table>
    <asp:Repeater ID="rptBooks" runat="server"> 
        <ItemTemplate>
            <tr>     
                <td><input type="checkbox" runat="server" value='<%# Eval("BookID")%>' ID="chkBox" /></td>
                <td><%# Eval("Title")%></td>
                <td><%# Eval("Author")%> </td>
            </tr>
        </ItemTemplate>  
    </asp:Repeater>
</table>
<asp:Button ID="btnOrder" OnClick="btnOrder_Click" runat="server" Text="Order" />

When “Order” button is clicked we need get all selected book IDs (we store them in a value field of each checkbox). I suggest that we create an extension method that will do all the work and when we need to get selected items in any repeater in our code we will have to call only one method GetSelectedItems

public static class RepeaterExt
{
    /// <summary>
    /// Returns selected items array list in a repeater rpt
    /// </summary>
    /// <param name="chkBoxId">ID of a checkbox used in repeater to store the value of each item</param>
    public static ArrayList GetSelectedItems(this Repeater rpt, string chkBoxId)
    {
        var selectedValues = new ArrayList();
        for (int i = 0; i < rpt.Items.Count; i++)
        {
            var chkBox = rpt.Items[i].FindControl(chkBoxId) as HtmlInputCheckBox;
 
            if (chkBox != null && chkBox.Checked)
                selectedValues.Add(chkBox.Value);
        }
        return selectedValues;
    }
}

Now if we go back to our page with books catalog we can right the following:

protected void btnOrder_Click(object sender, EventArgs e)
{
using extenstion method to get checked items
selectedValues array will contain BookIDs that were ordered and you can store them in the database or process as required by your code.

Note that this example assumes that you need to use <input runat=”server”…  to be able to pre-polulate checked values or keep the state of the checkboxes after the postback. If none of this functionality is needed, the simplest way to get selected values is to use standard html

<input type="checkbox" value='<%# Eval("BookID")%>' name="chkBox" />

When the “Order” button is clicked Request["chkBox"] will return comma delimited list of selected BookIDs.

kick it on DotNetKicks.com


enum to friendly string extension method

clock June 3, 2008 12:05 by author Naz
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.

if (Status == UserStatus.NotLoggedInAYear)
    ArchiveRecord();

is a lot more clearer and meaningful making it easier to maintain than

if (Status == 3)
    ArchiveRecord()

The enum names are not very friendly to the user and I recently read a some good articles creating user friendly strings for enum values and Enum description values which tried to solve this problem.

I think i've found a better solution to this problem using extension methods.

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

RemovalType removalType = RemovalType.ManAndVan;
removalType.ToFriendlyString()

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.

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.

You can also call it easily inside databinded controls in the aspx page.

<%# ((RemovalType)Eval("ServiceType")).ToFriendlyString() %>


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


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 Naz

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



Search

Sign in