2
votes

Okay, so I'm following this example in a book by Cristian Darie called Beginning ASP.NET in E-Commerce. The example builds an online shop called BalloonShop. I'm crusing along till around chapter 17 when my site no longer launches due to this error:

Object reference not set to an instance of an object

Line 27:             HttpContext context = HttpContext.Current;
Line 28:             // try to retrieve the cart ID from the user cookie
Line 29:             string cartId = context.Request.Cookies["BalloonShop_CartID"].Value;
Line 30:             // if the cart ID isn't in the cookie...
Line 31:             {

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.

My stack trace is as follows:

[NullReferenceException: Object reference not set to an instance of an object.] ShoppingCartAccess.get_shoppingCartId() in f:\TheGate\App_Code\ShoppingCartAccess.cs:29 ShoppingCartAccess.GetItems() in f:\TheGate\App_Code\ShoppingCartAccess.cs:188 UserControls_CartSummary.PopulateControls() in f:\TheGate\UserControls\CartSummary.ascx.cs:25 UserControls_CartSummary.Page_PreRender(Object sender, EventArgs e) in f:\TheGate\UserControls\CartSummary.ascx.cs:18 System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, >EventArgs e) +14 System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +35 System.Web.UI.Control.OnPreRender(EventArgs e) +8998946 System.Web.UI.Control.PreRenderRecursiveInternal() +103 System.Web.UI.Control.PreRenderRecursiveInternal() +175 System.Web.UI.Control.PreRenderRecursiveInternal() +175 System.Web.UI.Control.PreRenderRecursiveInternal() +175 System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +2496

My code seems to okay to my limited knowledge (as follows, from my ShoppingCartAccess.cs class):

    private static string shoppingCartId
{
    get
    {

        // get the current HttpContext
        HttpContext context = HttpContext.Current;
        // try to retrieve the cart ID from the user cookie
        string cartId = context.Request.Cookies["BalloonShop_CartID"].Value;
        // if the cart ID isn't in the cookie...
        {
            // check if the cart ID exists as a cookie
            if (context.Request.Cookies["BalloonShop_CartID"] != null)
            {
                // return the id
                return cartId;
            }
            else
            // if the cart ID doesn't exist in the cookie as well, generate a new ID
            {
                // generate a new GUID
                cartId = Guid.NewGuid().ToString();
                // create the cookie object and set its value
                HttpCookie cookie = new HttpCookie("BalloonShop_CartID", cartId);
                // set the cookie's expiration date
                int howManyDays = TheGateConfiguration.CartPersistDays;
                DateTime currentDate = DateTime.Now;
                TimeSpan timeSpan = new TimeSpan(howManyDays, 0, 0, 0);
                DateTime expirationDate = currentDate.Add(timeSpan);
                cookie.Expires = expirationDate;
                // set the cookie on the client's browser
                context.Response.Cookies.Add(cookie);
                // return the CartID
                return cartId.ToString();
            }
        }
    }
}

I'm pretty helpless at this stage in my programming learning. Near as I can tell, my program is looking for a cookie, if it doesn't see one it creates one, but somehow it's all tripping up, now. I was doing fine till Chapter 16, but now I'm kinda screwed as I don't know how to fix it. Any ideas? Thanks!!

2
I believe there are more problems with your code than the null reference exception you're receiving. I rewrote that method getShoppingCartId and put it below - hopefully it helps!99823

2 Answers

3
votes

Since line 29 is this:

string cartId = context.Request.Cookies["BalloonShop_CartID"].Value;

Based on the error, the only things that it could be are:

  • The HTTP context is not available (since you are in a user control, that's highly unlikely).
  • The HTTP request or cookies collection is null (not possible the way you are getting the HTTP context)
  • Cookies["BalloonShop_CartID"] returns null, and this blows up when you access .Value (most likely)

Those are the only possible reasons for Object Reference exception, and is most likely the last item, the cookie returns null. In looking at the entire code sample, it's odd that it checks for the cookie, then does a null check to see if the cookie is not null; it should do the following (remove line 29).

HttpContext context = HttpContext.Current;
 // check if the cart ID exists as a cookie
if (context.Request.Cookies["BalloonShop_CartID"] != null)
{
     // return the id
      return context.Request.Cookies["BalloonShop_CartID"].Value;
}
else
// if the cart ID doesn't exist in the cookie as well, generate a new ID
{
     .
     .
0
votes

You could also do something like this...

string cartId = context.Request.Cookies["BalloonShop_CartID"] != null 
    ? context.Request.Cookies["BalloonShop_CartID"].Value
    : "";

Also, I just noticed your code is kinda messsed up, I rewrote it here, I can't really test it but hopefully it gets you closer to your answer:

private static string GetShoppingCartId() {

    HttpContext context = HttpContext.Current;
    string cartId = context.Request.Cookies["BalloonShop_CartID"] != null 
        ? context.Request.Cookies["BalloonShop_CartID"].Value 
        : "";

    if (cartId == "")
    {
            // generate a new GUID
            cartId = Guid.NewGuid().ToString();
            int cartPersistDays = TheGateConfiguration.CartPersistDays;
            // create the cookie object and set its value
            context.Response.Cookies.Add(new HttpCookie("BalloonShop_CartID", cartId) {
                Expires = DateTime.Now.AddDays(cartPersistDays)
            });
     }

     return cartId;
 }