Getting error when I run my extension: Message : Object reference not set to an instance of an object

Apr 28, 2011 at 4:59 PM

I've written a custom extension which is working fine when running on my local machine. However, when uploaded to an actual site, an error keeps occurring when I access the front page. The plugin parses articles from an XML feed and then creates posts from the data and displays it on the front page. When I access the front page, I get this message displayed as a post: 

 

Ooops! An unexpected error has occurred.

This one's down to me! Please accept my apologies for this - I'll see to it that the developer responsible for this happening is given 20 lashes (but only after he or she has fixed this problem).       

 

and the actual error:

 

Error Details:

Url : myurl

Raw Url : /News/default.aspx


Message : Exception of type 'System.Web.HttpUnhandledException' was thrown.

Source : System.Web

StackTrace :    at System.Web.UI.Page.HandleError(Exception e)

   at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)

   at System.Web.UI.Page.ProcessRequest(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)

   at System.Web.UI.Page.ProcessRequest()

   at System.Web.UI.Page.ProcessRequestWithNoAssert(HttpContext context)

   at System.Web.UI.Page.ProcessRequest(HttpContext context)

   at ASP.default_aspx.ProcessRequest(HttpContext context)

   at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()

   at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)

TargetSite : Boolean HandleError(System.Exception)

Message : Object reference not set to an instance of an object.

Source : App_Code.z3uiccf3

StackTrace :    at BraftXMLHandler.loadXMLFeed()


   at BraftXMLHandler.ServingHandler(Object sender, ServingEventArgs e)

   at System.EventHandler`1.Invoke(Object sender, TEventArgs e)

at BlogEngine.Core.Post.OnServing(Post post, ServingEventArgs arg) in E:\Projects\BlogEngine-HG-10\Source\BlogEngine\BlogEngine.Core\Post.cs:line 893

 at BlogEngine.Core.Web.Controls.PostViewBase.get_Body() in E:\Projects\BlogEngine-HG-10\Source\BlogEngine\BlogEngine.Core\Web\Controls\PostViewBase.cs:line 64

 at BlogEngine.Core.Web.Controls.PostViewBase.OnLoad(EventArgs e) in E:\Projects\BlogEngine-HG-10\Source\BlogEngine\BlogEngine.Core\Web\Controls\PostViewBase.cs:line 320

   at System.Web.UI.Control.LoadRecursive()

   at System.Web.UI.Control.LoadRecursive()

   at System.Web.UI.Control.LoadRecursive()

   at System.Web.UI.Control.LoadRecursive()

   at System.Web.UI.Control.LoadRecursive()

   at System.Web.UI.Control.LoadRecursive()

   at System.Web.UI.Control.LoadRecursive()

   at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)

TargetSite : Void loadXMLFeed()

I'm not sure what the reason for this is. 

Apr 29, 2011 at 8:55 PM

I don't know if this helps as far as finding a solution, but it appears even when I try and add a new post, I'm getting this error. When I disable my extension, it stops and I can add a post.

May 1, 2011 at 11:17 PM
Edited Oct 24, 2011 at 9:37 PM

Message : Object reference not set to an instance of an object.

Source : App_Code.z3uiccf3

StackTrace :    at BraftXMLHandler.loadXMLFeed()

 

 

The elments in the feed does not match the xml elments for the post most likely problem. 

 

 

The plugin parses articles from an XML feed and then creates posts from the data and displays it on the front page.

 

Got to make sure when it creates a post it has all of the post xml elments.  I bet its only one element is missing.


Java Blog

May 2, 2011 at 4:18 PM

But it works on my local machine...?

I found what was causing the error. Apparently, my xpath is null. I'm not sure why. Here is my code:

private XPathNavigator getUrls(String link, int num)
    {
        XPathNavigator xpath = null;
        WebRequest req = null;
        try
        {
            switch (num)
            {
                case 1:
                    req = (WebRequest)WebRequest.Create(_settings.GetSingleValue("FeedURL"));
                    break;
                case 2:
                    req = (WebRequest)WebRequest.Create(link);
                    break;
                case 3:
                    req = (WebRequest)WebRequest.Create(link + "/categories");
                    break;
                case 4:
                    req = (WebRequest)WebRequest.Create(link + "/photos");
                    break;
            }

            req.Method = "GET";
            //req.ContentType = "text/xml;charset=utf-8";
            req.Timeout = 600000;

            using (WebResponse res = (WebResponse)req.GetResponse())
            {
                Stream resStream = res.GetResponseStream();
                XPathDocument doc = new XPathDocument(resStream);
                xpath = doc.CreateNavigator();
            }

        }
        catch (Exception e)
        {
            FileStream file = new FileStream("log.txt", FileMode.OpenOrCreate, FileAccess.Write);
            StreamWriter sw = new StreamWriter(file);
            sw.Write(e);
            sw.Close();
            file.Close();
            return null;   //could use better error reporting here
        }
        return xpath;

    }

    /* Feed Loading Logic
     * Procedures to parse the XML file, map it to BlogEngine Post fields, and save it to the
     * underlying database or XML structure.  
     */        
    private void loadXMLFeed(){

                //initialize parser             
                if(_settings.GetSingleValue("FeedURL") == "myurl") return;
        XPathNavigator xpath = getUrls("", 1);

        XPathNodeIterator articles = xpath.Select("//newsListItem");        

        while(articles.MoveNext()){
            string[] paths = new string[4];
            String title = nodeValue("headline", articles.Current);
            String link = getAttribute("href", articles.Current);
                       
            XPathNavigator xpathNews = getUrls(link, 2);
            XPathNodeIterator newsarticles = xpathNews.Select("/newsItem/text");
            String content = "";
            while (newsarticles.MoveNext()){
                content = newsarticles.Current.Value;
            }

            XPathNavigator xpathCat = getUrls(link, 3);
            Post post = new Post();
                   
                        Guid gid = post_exists(title);
            if(gid != Guid.Empty){  //load old post
                post = Post.Load(gid);
                
                        } else { //is new               
                post.Title = title;
                post.DateCreated = formatDate(nodeValue("publishDate", articles.Current));
                                                                
                                String slug = convertToURL(title);
                                slug = String.Concat(slug, "-", nodeValue("id", articles.Current));
                                post.Slug = slug;

                XPathNodeIterator tags = xpathNews.Select("/newsItem/keywords"); //add keywords as tags
                while (tags.MoveNext())
                {
                    String tagsin = tags.Current.Value;
                    String[] tagarray = tagsin.Split(',');
                    for (int i = 0; i < tagarray.Length; i++) 
                        post.Tags.Add(tagarray[i]);
                }
                                
                                addCategories(post, xpathCat);
                        }

                        XPathNavigator xpathPic = getUrls(link, 4);
            XPathNodeIterator pic = xpathPic.Select("//photos/photo/instances/instance/url");
            
            string picture = " ";
            string[] picarray = new string[1]; //change to '2' for thumbnail
            int x = 0;
            while (pic.MoveNext())
            {                                
            if( x < 1) //change to '2' for thumbnail
                picarray[x] = "<img class=\"article_pic\" src=\"" + pic.Current.Value + "\">  ";
            x++;                
            }

            post.Content = picarray[0] + content; //change '0' to '1' for thumbnail
            post.Author = "Admin"; //set author name here
                        post.Import();
                }
                Post.Reload();

    }
May 2, 2011 at 4:20 PM

A sample XML file:

<newsListItem href="myurl">
                <id>800495126</id>
                <publishDate>2011-04-28T10:07:00</publishDate>
                <lastModifiedDate>2011-04-28T10:39:57</lastModifiedDate>
                <headline>Messi magic downs Madrid in fractious semi-final</headline>
</newsListItem>

And 'href' links to: 

<newsItem encoding="UTF-8">
        <id>800495126</id>
        <state>Trial</state>
        <publishDate>2011-04-28T10:07:00</publishDate>
        <createdDate>2011-04-28T08:08:03</createdDate>
        <lastModifiedDate>2011-04-28T10:39:57</lastModifiedDate>
        <headline>headline goes here</headline>
        <extract>extract goes here.</extract>
        <categories href="myurl/categories/"/>
        <photos href="myurl/photos/"/>
        <comments href="myurl/comments/"/>
        <text format="html">text goes here</text>
</newsItem>

It seems "XPathNavigator xpath = getUrls("", 1); " is returning null. Everything looks ok to me. Any ideas?
Coordinator
May 2, 2011 at 8:33 PM
You probably need a full trust to run this code. 
Locally you have it by default, in your host you need either change trust level in web.config or use control panel to do it, depending on your host setup.