Need help with an ASP.NET 2.0 control

cismajor97

Weaksauce
Joined
Mar 23, 2006
Messages
88
I have an RssReader.ascx control that I have pulling the latest articles and displaying them on my Default.aspx page. For some strange reason I keep getting an error on line 26. If any of the ASP.NET 2.0 guru's our there can assist me I could really use your assistance to point me in the right direction to solve this.

Here is the error:

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:


Line 24: if (value.StartsWith("/") || value.StartsWith("~/"))
Line 25: {
Line 26: url = (this.Page as BasePage).FullBaseUrl + value;
Line 27: url = url.Replace("~/", "");
Line 28: }


Source File: c:\sdalternative_v2\Controls\RssReader.ascx.cs Line: 26

Stack Trace:


[NullReferenceException: Object reference not set to an instance of an object.]
MW.Alternative.UI.Controls.RssReader.set_RssUrl(String value) in c:\sdalternative_v2\Controls\RssReader.ascx.cs:26
ASP.default_aspx.__BuildControlRssReader1() in c:\sdalternative_v2\Default.aspx:5
ASP.default_aspx.__BuildControlContent1(Control __ctrl) in c:\sdalternative_v2\Default.aspx:4
System.Web.UI.CompiledTemplateBuilder.InstantiateIn(Control container) +32
ASP.alternative_master.__BuildControlMainContent() in c:\sdalternative_v2\Alternative.master:170
ASP.alternative_master.__BuildControlMain() in c:\sdalternative_v2\Alternative.master:41
ASP.alternative_master.__BuildControlTree(alternative_master __ctrl) in c:\sdalternative_v2\Alternative.master:1
ASP.alternative_master.FrameworkInitialize() in c:\sdalternative_v2\Alternative.master.cs:912307
System.Web.UI.UserControl.InitializeAsUserControlInternal() +46
System.Web.UI.UserControl.InitializeAsUserControl(Page page) +35
System.Web.UI.MasterPage.CreateMaster(TemplateControl owner, HttpContext context, VirtualPath masterPageFile, IDictionary contentTemplateCollection) +1206
System.Web.UI.Page.get_Master() +72
System.Web.UI.Page.ApplyMasterPage() +30
System.Web.UI.Page.PerformPreInit() +48
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1446

Code:
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml;
using MW.Alternative.UI;

namespace MW.Alternative.UI.Controls
{
    public partial class RssReader : System.Web.UI.UserControl
    {
        public string RssUrl
        {
            get { return lnkRss.NavigateUrl; }
            set
            {
                string url = value;
                if (value.StartsWith("/") || value.StartsWith("~/"))
                {
                    url = (this.Page as BasePage).FullBaseUrl + value;
                    url = url.Replace("~/", "");
                }
                lnkRss.NavigateUrl = url;
            }
        }
        

        public string Title
        {
            get { return lblTitle.Text; }
            set { lblTitle.Text = value; }
        }

        public int RepeatColumns
        {
            get { return dlstRss.RepeatColumns; }
            set { dlstRss.RepeatColumns = value; }
        }

        public string MoreUrl
        {
            get { return lnkMore.NavigateUrl; }
            set { lnkMore.NavigateUrl = value; }
        }

        public string MoreText
        {
            get { return lnkMore.Text; }
            set { lnkMore.Text = value; }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                if (this.RssUrl.Length == 0)
                    throw new ApplicationException("The RssUrl cannot be null.");

                // create a DataTable and fill it with the RSS data,
                // then bind it to the Repeater control
                XmlDataDocument feed = new XmlDataDocument();
                feed.Load(this.RssUrl);
                XmlNodeList posts = feed.GetElementsByTagName("item");

                DataTable table = new DataTable("Feed");
                table.Columns.Add("Title", typeof(string));
                table.Columns.Add("Description", typeof(string));
                table.Columns.Add("Link", typeof(string));
                table.Columns.Add("PubDate", typeof(DateTime));

                foreach (XmlNode post in posts)
                {
                    DataRow row = table.NewRow();
                    row["Title"] = post["title"].InnerText;
                    row["Description"] = post["description"].InnerText;
                    row["Link"] = post["link"].InnerText;
                    row["PubDate"] = post["pubDate"].InnerText;
                    table.Rows.Add(row);
                }

                dlstRss.DataSource = table;
                dlstRss.DataBind();
            }
            catch (Exception)
            {                
                {
                    this.Visible = true; 
                }
                
            }           
        }
    }
}
 
Object reference not set to an instance of an object.


you are referencing something that doesnt exist. So either you misspelled a variable or you might be using a reserved word or something. It also helps if you post the language, im going to assume this is c#. Im very very n00b at this stuff so im not that good at alot of stuff. but try running it in debug mode and hovering over the strings to see if they are populating.
 
I'm using C# 2.0.

When I hover over "this.Page" in line 26: in debug mode I get - this.Page = 'this.Page' threw an exception of type 'System.ArgumentNullException'

When I hover over "this" in line 26: in debug mode and drill down to ApplicationInstance I get: ApplicationInstance = 'this.ApplicationInstance' threw an exception of type 'System.NullReferenceException'

When I drill to base in ApplicationInstance portion I get base {System.SystemException} = {"The pointer for this method was null."}

I'm confused and I'm sure the solution is probably a simple one.
 
Let me start by stating that I'm not a C# web developer, but I do work with C# 2.0 web services frequently.

Object reference not set to an instance of an object.


you are referencing something that doesnt exist. So either you misspelled a variable or you might be using a reserved word or something.

Sort of. This often means you're calling a method (or accessing a member variable) from the Class name instead of an instance of the class. (or you did not properly instantiate the class) In this case you would need:

RssReader myRssReader = new RssReader;
(this line is saying: Define a new object called myRssReader of type RssReader from the class RssReader.

RssReader is the class and myRssReader is an instance of that class.

As a sidenote, static methods are the exception. They are consistent across all instances of a class.



I'm using C# 2.0.

When I hover over "this.Page" in line 26: in debug mode I get - this.Page = 'this.Page' threw an exception of type 'System.ArgumentNullException'

When I hover over "this" in line 26: in debug mode and drill down to ApplicationInstance I get: ApplicationInstance = 'this.ApplicationInstance' threw an exception of type 'System.NullReferenceException'

When I drill to base in ApplicationInstance portion I get base {System.SystemException} = {"The pointer for this method was null."}

I'm confused and I'm sure the solution is probably a simple one.


ApplicationInstance = 'this.ApplicationInstance'

This stands out to me. Are you ever instantiating the RssReader class?

Look at line 68:
feed.Load(this.RssUrl);

Where have you instantiated this class? I assume that is handled in in the .ascx page? Or perhaps the Page_Load method is a special method?

If nobody else replies, I can do some google searching and see if I can help here. Can you post the (relevant) contents of your .ascx page as well?
 
Here is what I have for the RssReader.aspx page

Code:
<%@ Control Language="C#" AutoEventWireup="true" CodeFile="RssReader.ascx.cs" Inherits="MW.Alternative.UI.Controls.RssReader" %>

<h3>
<asp:HyperLink ID="lnkRss" runat="server" ToolTip="Get the RSS for this content">
   <asp:Image runat="server" ID="imgRss" ImageUrl="~/Images/rss.gif" AlternateText="Get RSS feed" />
</asp:HyperLink> 
<asp:Literal runat="server" ID="lblTitle"/> 
</h3>

<asp:DataList id="dlstRss" Runat="server" EnableViewState="false">
	<ItemTemplate>
	   <small><%# Eval("PubDate", "{0:d}") %></small>
		<br />
		<h3><asp:HyperLink Runat="server" ID="lnkTitle"
		   NavigateUrl='<%# Eval("Link") %>' Text='<%# Eval("Title") %>' /></h3>
		<%# Eval("Description") %>
	</ItemTemplate>
</asp:DataList>
<p style="text-align: right;"><small><asp:HyperLink Runat="server" ID="lnkMore" /></small></p>
 
Can you post the source for the BasePage class as well?

I see that you found your inspiration from TheBeerHouse? http://forums.asp.net/thread/1381366.aspx and http://www.jfstudio.net/setup/20070112/161520.shtml

However, I want to see if you've made any changes to their code for the BasePage class...


edit: It looks like BasePage might be an open source c# class? I just wrote the above because I noticed many lines of identical code. I guess that could be due to an open source class being used in each case.
 
Yes I'm using TheBeerHouse template. I've removed the theme selector portion because the site I'm working on won't have different themes other than the default one.

Here is my BasePage.cs file

Code:
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

namespace MW.Alternative.UI
{
    public class BasePage : System.Web.UI.Page
    {
        protected override void InitializeCulture()
        {
            string culture = (HttpContext.Current.Profile as ProfileCommon).Preferences.Culture;
            this.Culture = culture;
            this.UICulture = culture;
        }

        protected override void OnPreInit(EventArgs e)
        {
            string id = Globals.ThemesSelectorID;
            if (id.Length > 0)
            {
                // if this is a postback caused by the theme selector's dropdownlist, retrieve
                // the selected theme and use it for the current page request
                if (this.Request.Form["__EVENTTARGET"] == id && !string.IsNullOrEmpty(this.Request.Form[id]))
                {
                    this.Theme = this.Request.Form[id];
                    (HttpContext.Current.Profile as ProfileCommon).Preferences.Theme = this.Theme;
                }
                else
                {
                    // if not a postback, or a postback caused by controls other then the theme selector,
                    // set the page's theme with the value found in the user's profile, if present
                    if (!string.IsNullOrEmpty((HttpContext.Current.Profile as ProfileCommon).Preferences.Theme))
                        this.Theme = (HttpContext.Current.Profile as ProfileCommon).Preferences.Theme;
                }
            }

            

            base.OnPreInit(e);
        }

        protected override void OnLoad(EventArgs e)
        {
            // add onfocus and onblur javascripts to all input controls on the forum,
            // so that the active control has a difference appearance

            base.OnLoad(e);
        }

        public string BaseUrl
        {
            get
            {
                string url = this.Request.ApplicationPath;
                if (url.EndsWith("/"))
                    return url;
                else
                    return url + "/";
            }
        }

        public string FullBaseUrl
        {
            get
            {
                return this.Request.Url.AbsoluteUri.Replace(
                   this.Request.Url.PathAndQuery, "") + this.BaseUrl;
            }
        }

        protected void RequestLogin()
        {
            this.Response.Redirect(FormsAuthentication.LoginUrl +
               "?ReturnUrl=" + this.Request.Url.PathAndQuery);
        }          
    }
}
 
I've been trying to fix the issue for days. Found out that I was pointing to the wrong Inherits portion of my code-behind file. I have MW.Alternative.UI.Alternative instead of what it need to be which was MW.Alternative.Alternative. So easy to overlook.
 
The wierd thing was even though I had the wrong Inherits location, Visual Studio still allowed me to complie the website without any errors.
 
Sweet glad ya got it figured out :)

This is a cool tutorial project - the dynamically generated classes (from the web.config) are interesting.
 
I agree. This is my first attempt at really understanding object-oriented design, ASP.NET 2.0, and C# as well. Coming from a web designer background with only XHTML and CSS it's a huge thing to wrap my brain around. Luckily I'm using this to build my portfolio and and learn at the same time. I'm redesigning a web site for a client of mine for free, and the trade of is that the organization gets a new website and I get to learn at the same process.

The client is a small non-profit and I'm close friends with the Director of the group, the good thing is that if I pull this off, I can land a bigger project for another non profit that he's associated with and I could actually get paid for the work. So it's a learning experience nonetheless.
 
Back
Top