Wrox Programmer Forums
|
BOOK: Beginning ASP.NET 3.5 : in C# and VB BOOK ISBN: 978-0-470-18759-3
This is the forum to discuss the Wrox book Beginning ASP.NET 3.5: In C# and VB by Imar Spaanjaars; ISBN: 9780470187593
Welcome to the p2p.wrox.com Forums.

You are currently viewing the BOOK: Beginning ASP.NET 3.5 : in C# and VB BOOK ISBN: 978-0-470-18759-3 section of the Wrox Programmer to Programmer discussions. This is a community of software programmers and website developers including Wrox book authors and readers. New member registration was closed in 2019. New posts were shut off and the site was archived into this static format as of October 1, 2020. If you require technical support for a Wrox book please contact http://hub.wiley.com
 
Old September 18th, 2010, 02:36 AM
Authorized User
 
Join Date: Oct 2009
Posts: 40
Thanks: 4
Thanked 0 Times in 0 Posts
Default page 456, chapter 13.

Ive been working through the book playing about with pages making similar ones practising making my own site and getting used to .net's features.

Im on page 456, chapter 13 and Ive created an aspx page that is practically identical to NewPhotoAlbum.aspx which i called AdvertiseABookNight.aspx. This page compiles, when i click insert on this page, which in NewPhotoAlbum.aspx would then take you to ManagePhotoAlbum.aspx?PhotoAlbumId=......, i get the following error when it tries to go to my page YourBookNightDetails.aspx?.......

I have followed the exact same logic and my code is identical except for the name changes:

Server Error in '/' Application.
--------------------------------------------------------------------------------

Object reference not set to an instance of an object.
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.

Source Error:

The source code that generated this unhandled exception can only be shown when compiled in debug mode. To enable this, please follow one of the below steps, then request the URL:


1. Add a "Debug=true" directive at the top of the file that generated the error. Example:

<%@ Page Language="C#" Debug="true" %>

or:

2) Add the following section to the configuration file of your application:

<configuration>
<system.web>
<compilation debug="true"/>
</system.web>
</configuration>

Note that this second technique will cause all files within a given application to be compiled in debug mode. The first technique will cause only that particular file to be compiled in debug mode.

Important: Running applications in debug mode does incur a memory/performance overhead. You should make sure that an application has debugging disabled before deploying into production scenario.

Stack Trace:


[NullReferenceException: Object reference not set to an instance of an object.]
Events_AdvertiseABookNight.LinqDataSource1_Inserte d(Object sender, LinqDataSourceStatusEventArgs e) +57
System.Web.UI.WebControls.LinqDataSourceView.OnIns erted(LinqDataSourceStatusEventArgs e) +105
System.Web.UI.WebControls.LinqDataSourceView.Execu teInsert(IDictionary values) +372
System.Web.UI.DataSourceView.Insert(IDictionary values, DataSourceViewOperationCallback callback) +86
System.Web.UI.WebControls.DetailsView.HandleInsert (String commandArg, Boolean causesValidation) +274
System.Web.UI.WebControls.DetailsView.HandleEvent( EventArgs e, Boolean causesValidation, String validationGroup) +676
System.Web.UI.WebControls.DetailsView.OnBubbleEven t(Object source, EventArgs e) +95
System.Web.UI.Control.RaiseBubbleEvent(Object source, EventArgs args) +37
System.Web.UI.WebControls.DetailsViewRow.OnBubbleE vent(Object source, EventArgs e) +113
System.Web.UI.Control.RaiseBubbleEvent(Object source, EventArgs args) +37
System.Web.UI.WebControls.LinkButton.OnCommand(Com mandEventArgs e) +118
System.Web.UI.WebControls.LinkButton.RaisePostBack Event(String eventArgument) +135
System.Web.UI.WebControls.LinkButton.System.Web.UI .IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +10
System.Web.UI.Page.RaisePostBackEvent(IPostBackEve ntHandler sourceControl, String eventArgument) +13
System.Web.UI.Page.RaisePostBackEvent(NameValueCol lection postData) +175
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1565


Here is my code, YourBookNightDetails.aspx:
Code:
<%@ Page Language="C#" MasterPageFile="~/MasterPages/MasterPage.master" AutoEventWireup="true" CodeFile="YourBookNightDetails.aspx.cs" Inherits="Events_YourBookNightDetails" Title="Your Event Details" %>

<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
    <asp:ListView ID="ListView1" runat="server" DataKeyNames="Id" 
        DataSourceID="LinqDataSource1" InsertItemPosition="LastItem" 
        onselectedindexchanged="ListView1_SelectedIndexChanged">
        <ItemTemplate>
            <li style="">
                
                ImageUrl:
                <asp:Label ID="ImageUrlLabel" runat="server" Text='<%# Eval("ImageUrl") %>' />
                <br />
              
               
               
                Event:
                <asp:Label ID="EventLabel" runat="server" Text='<%# Eval("Event") %>' />
                <br />
                <asp:Button ID="DeleteButton" runat="server" CommandName="Delete" 
                    Text="Delete" />
            </li>
        </ItemTemplate>
        
 
        <InsertItemTemplate>
            <li style="">
                ImageUrl:
                <asp:TextBox ID="ImageUrlTextBox" runat="server" 
                    Text='<%# Bind("ImageUrl") %>' />
                <br />
                
               
                Event:
                <asp:TextBox ID="EventTextBox" runat="server" Text='<%# Bind("Event") %>' />
                <br />
                <asp:Button ID="InsertButton" runat="server" CommandName="Insert" 
                    Text="Insert" />
                <asp:Button ID="CancelButton" runat="server" CommandName="Cancel" 
                    Text="Clear" />
            </li>
        </InsertItemTemplate>
        <LayoutTemplate>
            <ul class="itemContainer">
            <li id="itemPlaceHolder" runat="server" />
            </ul>
            </LayoutTemplate>
            
            
            
        </asp:ListView>
        <asp:LinqDataSource ID="LinqDataSource1" runat="server" 
            ContextTypeName="SalfordStudentBooksDataContext" EnableDelete="True" 
            EnableInsert="True" TableName="Pictures" Where="EventId == @EventId" 
            oninserting="LinqDataSource1_Inserting">
            <WhereParameters>
                <asp:QueryStringParameter DefaultValue="-1" Name="EventId" 
                    QueryStringField="EventId" Type="Int32" />
            </WhereParameters>
        </asp:LinqDataSource>
</asp:Content>
Code Behind:
Code:
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

public partial class Events_YourBookNightDetails : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void LinqDataSource1_Inserting(object sender, LinqDataSourceInsertEventArgs e)
    {
        Picture myPicture = (Picture)e.NewObject;
        myPicture.EventId = Convert.ToInt32(Request.QueryString.Get("EventId"));
    }
    protected void ListView1_SelectedIndexChanged(object sender, EventArgs e)
    {

    }
}
AdvertiseABookNight.aspx:
Code:
<%@ Page Language="C#" MasterPageFile="~/MasterPages/MasterPage.master" AutoEventWireup="true" CodeFile="AdvertiseABookNight.aspx.cs" Inherits="Events_AdvertiseABookNight" Title="Untitled Page" %>

<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
Tell us about any Book Sale Auctions or Book Club Nights your planning on having at your local University here.
Below insert the name of your Book Sale Auction, Book Night or Event you would like to advertise here.
<br /><br />
    <asp:DetailsView ID="DetailsView1" runat="server" AutoGenerateRows="False" 
        DataKeyNames="Id" DataSourceID="LinqDataSource1" DefaultMode="Insert" 
        Height="50px" Width="125px">
        <Fields>
            <asp:BoundField DataField="Id" HeaderText="Id" InsertVisible="False" 
                ReadOnly="True" SortExpression="Id" />
            <asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" />
            <asp:CommandField ShowInsertButton="True" />
        </Fields>
    </asp:DetailsView>
    <asp:LinqDataSource ID="LinqDataSource1" runat="server" 
        ContextTypeName="SalfordStudentBooksDataContext" EnableInsert="True" 
        oninserted="LinqDataSource1_Inserted" TableName="Events">
    </asp:LinqDataSource>
</asp:Content>
CodeBehind:
Code:
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

public partial class Events_AdvertiseABookNight : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void LinqDataSource1_Inserted(object sender, LinqDataSourceStatusEventArgs e)
    {
        Event myEvent = (Event)e.Result;
        Response.Redirect(string.Format("YourBookNightDetails.aspx?EventId={0}",
            myEvent.Id.ToString()));
    }
}
Ive been sat for a while trying to decipher the error message. I think its trying to say that one of my objects has a null reference or something is set to null in my code but ive played around with it and i still get the error message. I have created an event class in the database, as well as the picture class that i already added as per the book. Ive put some records in these classes as i thought perhaps it meant i have no instances(ie no records) but still the same error.

Any recommendation Imar?

Kind Regards

Lee

Last edited by leemark2k3; September 18th, 2010 at 02:39 AM..
 
Old September 18th, 2010, 02:47 AM
Imar's Avatar
Wrox Author
 
Join Date: Jun 2003
Posts: 17,089
Thanks: 80
Thanked 1,576 Times in 1,552 Posts
Default

Hi there,

Try debugging the LinqDataSource1_Inserted event handler (see chapter 17 for tips on debuggging).

My guess is that after this line

Event myEvent = (Event)e.Result;

myEvent is null. Can you check in the debugger if that's the case?

Imar
__________________
Imar Spaanjaars
http://Imar.Spaanjaars.Com
Follow me on Twitter

Author of Beginning ASP.NET 4.5 : in C# and VB, Beginning ASP.NET Web Pages with WebMatrix
and Beginning ASP.NET 4 : in C# and VB.
Did this post help you? Click the button below this post to show your appreciation!
 
Old September 18th, 2010, 07:00 PM
Authorized User
 
Join Date: Oct 2009
Posts: 40
Thanks: 4
Thanked 0 Times in 0 Posts
Default

Hi Imar. Ive reread the debugging chapter today and have stepped into the method that you explained, and indeed as you presumed, when hovering over myEvent in debug mode it confirms that it is null.

What should i do now to get this working now i know myEvent is null.

Thanks.

Lee
 
Old September 19th, 2010, 06:51 AM
Imar's Avatar
Wrox Author
 
Join Date: Jun 2003
Posts: 17,089
Thanks: 80
Thanked 1,576 Times in 1,552 Posts
Default

Quote:
when hovering over myEvent in debug mode it confirms that it is null.
Before or after you executed the line that assigns the variable a value? Did you look at e.Result as well?

Your code looks fine, so maybe there's a problem with the database or your LINQ to SQL model? Did you make any change to the database or the model?

And when you debug the code below, does e.Exception have a value? Are you using global error handling (in Global.asax for example) somewhere?

Imar
__________________
Imar Spaanjaars
http://Imar.Spaanjaars.Com
Follow me on Twitter

Author of Beginning ASP.NET 4.5 : in C# and VB, Beginning ASP.NET Web Pages with WebMatrix
and Beginning ASP.NET 4 : in C# and VB.
Did this post help you? Click the button below this post to show your appreciation!
 
Old September 19th, 2010, 02:15 PM
Authorized User
 
Join Date: Oct 2009
Posts: 40
Thanks: 4
Thanked 0 Times in 0 Posts
Thumbs up

Code:
protected void LinqDataSource1_Inserted(object sender, LinqDataSourceStatusEventArgs e)
    {
LINE 22 Event myEvent = (Event)e.Result;
LINE 23 Response.Redirect(string.Format
("YourBookNightDetails.aspx?EventId={0}",
            myEvent.Id.ToString()));
    }
I set the break point at line 22, press f5 to begin debugging which takes me to my screen in internet explorer. I then fill that in as a user would and it of course takes me back to my debugging screen. Now when hovering over myEvent it says null and when hovering over e.result it says null. When i press f10 again to step into line 23 myEvent still says null. I do got some errors showing up relating to all.aspx(identical to Reviews/All.aspx in Wrox Site:
Code:
protected void Page_Load(object sender, EventArgs e)
    {
        using (SalfordStudentBooksDataContext myDataContext = new SalfordStudentBooksDataContext())
        {
            var allBooks = from book in myDataContext.Book
                             where book.Authorized == true
                             orderby book.Id descending
                             select book;

            GridView1.DataSource = allBooks;
            GridView1.DataBind();
        }
    }
Code:
Error	1	'SalfordStudentBooksDataContext' does not contain a definition for 'Book' and no extension method 'Book' accepting a first argument of type 'SalfordStudentBooksDataContext' could be found (are you missing a using directive or an assembly reference?)	C:\Documents and Settings\Administrator\My Documents\Visual Studio 2008\WebSites\SALFORDBOOKSHOP\Search\All.aspx.cs	20	

Error	2	The name 'GridView1' does not exist in the current context	C:\Documents and Settings\Administrator\My Documents\Visual Studio 2008\WebSites\SALFORDBOOKSHOP\Search\All.aspx.cs	25	

Error	3	The name 'GridView1' does not exist in the current context	C:\Documents and Settings\Administrator\My Documents\Visual Studio 2008\WebSites\SALFORDBOOKSHOP\Search\All.aspx.cs	26
Also yes i believe ive amended the database, ive added a couple of new tables and records and updated the database diagram accordingly as per chapter 13s guidelines. Would this have caused me problems by doing this? Would it be wise to create the databases again if it affects them by me making changes recently?

Finally e.Exception doesnt have a value that i know have. I have not created a global.asax class yet. I did in chapter 17 to error handle and hide my errors but have deleted it again as i wanted to see my error messages in detail rather than using error404, error500 etc to hide what the problem is.

Any recommendations on how i can get past this problem ive made for myself.

Thanks very much.
 
Old September 19th, 2010, 02:54 PM
Imar's Avatar
Wrox Author
 
Join Date: Jun 2003
Posts: 17,089
Thanks: 80
Thanked 1,576 Times in 1,552 Posts
Default

Quote:
Would it be wise to create the databases again if it affects them by me making changes recently?
It's not the database you want to recreate, but the LINQ to SQL model. Something doesn't work with saving L2S objects, so the L2S model would be the first place I'd look.

Quote:
Any recommendations on how i can get past this problem ive made for myself.
Get rid of the compilation errors by fixing them. You really shouldn't run any code while you're still having compilation errors....

Imar
__________________
Imar Spaanjaars
http://Imar.Spaanjaars.Com
Follow me on Twitter

Author of Beginning ASP.NET 4.5 : in C# and VB, Beginning ASP.NET Web Pages with WebMatrix
and Beginning ASP.NET 4 : in C# and VB.
Did this post help you? Click the button below this post to show your appreciation!
 
Old September 21st, 2010, 04:06 AM
Authorized User
 
Join Date: Oct 2009
Posts: 40
Thanks: 4
Thanked 0 Times in 0 Posts
Default

Hi again Imar. Ive got rid of the compilation errors and rebuilt the linq to sql diagram. Still im getting the same error. In fact in two of my pages im getting the same error mentione above. On having a read in some coding forums, its discussed that this is a frequent error message for beginner programmers.
Im currently reading the following regarding this error:
Why do beginner programmers get this error so frequently: "Object reference not set to an instance of an object"?

The reason is that the program is trying to access a member of a reference type variable which is set to null.

To solve this problem, be sure the problem object is instantiated before being referenced. The following sample source code instantiates problem and, so, avoids the error message:

Problem problem = new Problem(); // instantiate problem

int prop = problem.ProblemProperty; // making member access possible

If the above information is correct, can you see in my code I attached previously what exactly i should be instantiating and then making accessable to hopefully get the error to work? Im unsure and cant seem to solve this error still after a few days.

I'll attach the code again for you. Ive been building my own site as per the instructions from my book. My site is practically functionally identical to Planet Wrox in all but names.

Code Behind:
Code:
          

    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void LinqDataSource1_Inserted(object sender, LinqDataSourceStatusEventArgs e)
    {
        Event myEvent = (Event)e.Result;
        Response.Redirect(string.Format("YourBookNightDetails.aspx?EventId={0}",
            myEvent.Id.ToString()));
    }
}
Code:
<%@ Page Language="C#" MasterPageFile="~/MasterPages/MasterPage.master" AutoEventWireup="true" CodeFile="AdvertiseABookNight.aspx.cs" Inherits="Events_AdvertiseABookNight" Title="Advertise a Night" %>

<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
    <style type="text/css">
        .style1
        {
            font-size: medium;
        }
    </style>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
    <h1>Advertise Your Event</h1>
    <span class="style1">Tell us about any Book Sale Auctions or Book Club Nights your planning on having at your local University here.
Below insert the name of your Book Sale Auction, Book Night or Event you would like to advertise here.</span>
<br /><br />
    <asp:DetailsView ID="DetailsView1" runat="server" AutoGenerateRows="False" 
        DataKeyNames="Id" DataSourceID="LinqDataSource1" DefaultMode="Insert" 
        Height="50px" Width="125px">
        <Fields>
            <asp:BoundField DataField="Id" HeaderText="Id" InsertVisible="False" 
                ReadOnly="True" SortExpression="Id" />
            <asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" />
            <asp:CommandField ShowInsertButton="True" />
        </Fields>
    </asp:DetailsView>
    <asp:LinqDataSource ID="LinqDataSource1" runat="server" 
        ContextTypeName="SalfordStudentBooksDataContext" EnableInsert="True" 
        oninserted="LinqDataSource1_Inserted" TableName="Events">
    </asp:LinqDataSource>
</asp:Content>
In debug if you remember i confirmed that both myEvent and e.Result were null when i hovered over them in debug mode. Any idea what im doing wrong?

Lee
 
Old September 21st, 2010, 08:39 AM
Imar's Avatar
Wrox Author
 
Join Date: Jun 2003
Posts: 17,089
Thanks: 80
Thanked 1,576 Times in 1,552 Posts
Default

Quote:
The reason is that the program is trying to access a member of a reference type variable which is set to null.
Yes, that's indeed exactly the problem. However, you need to find out *why* the variable is null.

My guess is that there's something wrong with the model, so the item doesn't get inserted correctly.

Can you send me a zipped version of just the relevant files (web.config, ASPX page, model, database) so I can try to reproduce the problem and see what's going on?

Imar
__________________
Imar Spaanjaars
http://Imar.Spaanjaars.Com
Follow me on Twitter

Author of Beginning ASP.NET 4.5 : in C# and VB, Beginning ASP.NET Web Pages with WebMatrix
and Beginning ASP.NET 4 : in C# and VB.
Did this post help you? Click the button below this post to show your appreciation!
 
Old September 21st, 2010, 08:21 PM
Authorized User
 
Join Date: Oct 2009
Posts: 40
Thanks: 4
Thanked 0 Times in 0 Posts
Thumbs up

Will email you it now mate.

Thanks, your a real help every time.





Similar Threads
Thread Thread Starter Forum Replies Last Post
Page 456 Step 16 - NullReferenceException mivanov007 BOOK: Beginning ASP.NET 3.5 : in C# and VB BOOK ISBN: 978-0-470-18759-3 17 November 24th, 2010 03:36 AM
Problem in chapter 13 page 451 Try it out morteza BOOK: Beginning ASP.NET 4 : in C# and VB 3 June 6th, 2010 08:11 AM
Chapter 13 page 444 DRAYKKO Beginning VB 6 1 April 19th, 2006 07:10 PM





Powered by vBulletin®
Copyright ©2000 - 2020, Jelsoft Enterprises Ltd.
Copyright (c) 2020 John Wiley & Sons, Inc.