Copied to clipboard

Flag this post as spam?

This post will be reported to the moderators as potential spam to be looked at


  • stephanie 52 posts 133 karma points
    May 27, 2013 @ 16:52
    stephanie
    0

    Write Code That Won't Break if Node doesn't exist

    Version 6.0.2 mvc

    Last day my web host had disk space issues which caused failures in writing the various xml files (applications.config, trees.config, and umbraco.config). While this caused problems, it was my razor scripting that brought the dreaded ysod. 

    I use a content picker on the home page to grab a blog post (using Ublogsy package) and render it on the home page. All works well except for some reason when this server error occurs, the Author property/node doesn't get rendered to the umbraco.config, and so it doesn't exist at all.

    Here's my script that causes the ysod:

    -----------------------------------------------------------------------------------------------------------

    IPublishedContent node1;

    int blog1node = Convert.ToInt32(Model.Content.GetPropertyValue("mainArticleBlogPost"));

    if(blog1node > 0) 

    node1 = Umbraco.TypedContent(blog1node);

                        if(node1 != null)

                        {

                            if (!String.IsNullOrEmpty(node1.GetPropertyValue("uBlogsyPostAuthor").ToString()))

    .....yada yada yada

    --------------------------------------------------------------------------------------------------------------------

    Obviously it never occurred to me that the entire node might be missing. What's the proper way to write this so I don't get the ysod? I just want it to degrade gracefully. Should I be using .HasProperty? or .HasValue, both?

    Thanks!

    Steph

  • Jason Berkan 7 posts 58 karma points
    Jun 05, 2013 @ 23:09
    Jason Berkan
    0

    In your example, HasValue is the correct solution.  If a property does not exist on a document for any reason, then GetPropertyValue will return a null object.  Calling .ToString() on a null object will result in an exception.  The HasProperty and HasValue functions allow you to see if a property exists or if the property has been filled in by the user.

    HasProperty("uBlogsyPostAuthor") will return true if a property called "uBlogsyPostAuthor" exists on the document, whether it is filled in or not.

    HasValue("uBlogsyPostAuthor") will return true if a property called "uBlogsyPostAuthor" exists on the current document and it is filled in.

    Since your code is looking for a filled in value, the following would be a more robust test that will not crash when the property does not exist for any reason (and, as a bonus, it is easier code to read):

    if (node1.HasValue("uBlogsyPostAuthor")) {
        // yada, yada, yada
    }
Please Sign in or register to post replies

Write your reply to:

Draft