Question Object Not initialised? Please Help

spiketg

New member
Joined
Dec 14, 2011
Messages
2
Programming Experience
3-5
Hi there,
I recently started programming with Vb, been using JAVA for the last few years. Im trying to read/edit an XML document that will store information for this web service (a music playlist project)

I keep getting the following error when testing any of the functions.

Any help would be greatly appreciated. As long as I can get the file to work I can handle any other errors.
Code is below.

Thanks in advance.
TG

System.NullReferenceException: Object reference not set to an instance of an object.
at Service.getUserPlaylist(String userID) in C:\Users\Tommy\Documents\Visual Studio 2008\WebSites\WebSite3\App_Code\Service.vb:line 70
at Service.InsertNewPlaylist(String userID) in C:\Users\Tommy\Documents\Visual Studio 2008\WebSites\WebSite3\App_Code\Service.vb:line 78
at Service.CreateNewPlaylist(String UserID) in C:\Users\Tommy\Documents\Visual Studio 2008\WebSites\WebSite3\App_Code\Service.vb:line 168
VB.NET:
Imports System.WebImports System.Web.Services
Imports System.Web.Services.Protocols
Imports System.Xml




' To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
' <System.Web.Script.Services.ScriptService()> _
<WebService(Namespace:="http://tempuri.org/")> _
<WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Public Class Service
     Inherits System.Web.Services.WebService


    'This object will provide access to the entire
    ' XML tree of ToDOPlaylist items...
    Private _xmlData As New XmlDocument
    Private _fileName As String


    ' This function will always return a valid name for
    ' the data file...
    Private Function fileName() As String
        Return Server.MapPath("App_Data\AllData.xml")
    End Function


    ' This function makes sure that when we try to access the XML document, 
    ' it is loaded.  The process is called 'lazy instantiation'.  
    ' _xmlData is the entire data set, and should always be accessed via
    ' this function.  Two other functions (below) are used to load and 
    ' save the xml data to a file.  We must ensure that apart from these, 
    ' no other code accesses _xmlData directly...
    Private Function xmlData() As XmlDocument
        If _xmlData Is Nothing Then
            getDataFile()
        End If
        Return _xmlData
    End Function


    ' The XML data file will be stored in the App_Data folder.
    ' It makes sense to have a simple function to call to retrieve
    ' the XML from this file and another to save a modified version...
    Private Function getDataFile() As Boolean
        If IO.File.Exists("test.xml") Then
            _xmlData = New XmlDocument


            _xmlData.Load("test.xml")
            Return True
        Else
            Return False
        End If
    End Function


    ' Save the XML document...
    Private Sub saveDataFile()


        If _xmlData IsNot Nothing Then


            _xmlData.Save("test.xml")
        End If
    End Sub


    ' This function returns a particular user's Playlist of to-do items.
    ' The XPath "//Playlist[@ID=user@domain.com]" selects the Playlist item
    ' that matches that user's ID (email address)
    Private Function getUserPlaylist(ByVal userID As String) As XmlElement
        Dim xmlItems As XmlElement
        ' The XPath says 'Get every Playlist element with the correct userID...
        Dim xPath As String = "//Playlist[@ID='" & userID & "']"
        ' There ought to be only one matching Playlist.
        xmlItems = xmlData.DocumentElement.SelectSingleNode(xPath)
        Return xmlItems
    End Function


    ' This function inserts a new user's empty <List /> element.
    ' Each <playlist /> element has an ID attribute which identifies 
    ' the user.  It returns False if a playlist with that ID already exists.
    Private Function InsertNewPlaylist(ByVal userID As String) As Boolean
        If getUserPlaylist(userID) IsNot Nothing Then
            Return False
        Else
            ' This code will create a new element of the form...
            '     <Playlist ID="whatever userID is"/>
            ' We can later add items to the playlist.
            Dim newPlaylist As XmlElement = xmlData.CreateElement("Playlist")
            Dim newAttr As XmlAttribute = xmlData.CreateAttribute("ID")
            newAttr.Value = userID
            newPlaylist.Attributes.Append(newAttr)
            xmlData.DocumentElement.FirstChild.AppendChild(newPlaylist)
            Return True
        End If
    End Function


    ' This function returns a new XML element, of the form:
    '     <ElementName>Element Value</Element Name> to the
    ' calling code.  Note that MSXML requires an XMLDocument 
    ' to generate new elements - hence the use of xmlData here.
    Private Function newElement(ByVal name As String, ByVal value As String) As XmlElement
        Dim el As XmlElement = xmlData.CreateElement(name)
        el.InnerText = value
        Return el
    End Function


    ' This function create a new XML <Track /> element, creates
    ' the Name attribute, Description and DateTime elements,
    ' and then inserts it into the identified user's <Playlist /> element...
    Private Function InsertNewTrack(ByVal userID As String, _
                                   ByVal trackArtist As String, _
                                   ByVal trackName As String, _
                                   ByVal trackAlbum As String, _
                                   ByVal trackGenre As String, _
                                   ByVal trackYear As Date) As Boolean
        Try
            'THE WHOLE PROCESS OF CREATING A NEW XML ELEMENT WITHIN A DOCUMENT
            '=================================================================
            ' 1. We need variables to refer to the various bits.
            '    This one is the new element to be added...
            Dim anElement As XmlElement
            '    This is the existing list of elements...
            Dim userPlaylist As XmlElement = getUserPlaylist(userID)
            '    Create the element (need to do so from an xmlDocument)...
            Dim newTrack As XmlElement = xmlData.CreateElement("track")
            '    Create an attribute...
            Dim newAttr As XmlAttribute = xmlData.CreateAttribute("name")
            Dim rating As Integer
            rating = 0
            '    Apply the attribute value...
            newAttr.Value = trackName
            '    Assign it to the newly created element...
            newTrack.Attributes.Append(newAttr)
            '    Now make a new sub-element (again from the xmlDocument)...
            anElement = newElement("artist", trackArtist)
            '    Add this to the element created earlier...
            newTrack.AppendChild(anElement)
            '    ...and again...
            anElement = newElement("genre", trackGenre)
            newTrack.AppendChild(anElement)
            '    ...this is a new element, so not yet completed...
            anElement = newElement("year", trackYear.ToString())
            newTrack.AppendChild(anElement)
            '    Finally add the new element to the list of elements...
            userPlaylist.AppendChild(newTrack)
            anElement = newElement("rating", rating)
            userPlaylist.AppendChild(anElement)
            Return True
        Catch ex As Exception
            Return False
        End Try
    End Function


    <WebMethod()> _
    Public Function GetItems(ByVal userID As String) As String
        Return getUserPlaylist(userID).OuterXml
    End Function


    <WebMethod()> _
    Public Function GetItem(ByVal userID As String, ByVal itemName As String) As String
        Dim items As XmlElement = getUserPlaylist(userID)
        Dim item As XmlElement = items.SelectSingleNode("//Item[@name='" & itemName & "']")
        If item Is Nothing Then
            Return "<Item />"
        Else
            Return item.OuterXml
        End If
    End Function


    <WebMethod()> _
    Public Function CreateNewPlaylist(ByVal UserID As String) As Boolean
        If InsertNewPlaylist(UserID) Then
            saveDataFile()
            Return True
        Else
            Return False
        End If
    End Function


   


 
    <WebMethod()> _
    Public Function ratePlaylist(ByVal userId As String, ByVal rating As String) As Boolean
        ' This should set the completed element of the specified item to True...
        Try
            Dim listToRate As XmlElement = getUserPlaylist(userId)
            ' Completed is the last child element...


            listToRate.LastChild.InnerText = rating
            saveDataFile()
            Return True
        Catch ex As Exception
            Return False
        End Try
    End Function


End Class
 
You are calling CreateNewPlaylist, which calls InsertNewPlaylist, which calls getUserPlaylist. getUserPlaylist line 70 throws that exception, and my guess is that is the line that uses xmlData variable, which is at that point is a null reference (Nothing).
 
I figured this was the variable that was giving me the problem. However I am unsure what I can do to create this XML document as I have already declared XmlData as a new variable of type XmlDocument and given a path/filename to save to :/
 
I just noticed that you had "As New", but for empty XmlDocument instance DocumentElement returns Nothing, and you are therefore calling SelectSingleNode method on a null reference.
 
Back
Top