Results 1 to 14 of 14

Thread: DirectCast - Object not set to an instance of an object???

  1. #1

    Thread Starter
    Hyperactive Member
    Join Date
    Jul 2004
    Location
    Kansas, USA
    Posts
    352

    DirectCast - Object not set to an instance of an object???

    I am trying to deserialize a custom object that has been previously serialized and saved in a file. and I have the following code:
    PHP Code:
            If open.ShowDialog Windows.Forms.DialogResult.OK Then
                Dim fs 
    As FileStream = New FileStream(open.FileNameFileMode.Open)
                Try
                    
    testing = New ItemInfo
                    Dim formatter 
    As New BinaryFormatter
                    Dim obj 
    As Object formatter.Deserialize(fs)
                    
    testing DirectCast(objItemInfo)
                Catch 
    ex As Exception
                    MsgBox
    (ex.Message)
                Finally
                    
    fs.Close()
                
    End Try
            
    End If 
    The problem is the line
    PHP Code:
    testing DirectCast(objItemInfo
    I am getting an exception:
    Object not set to an instance of an object
    I have verified that the variable testing and obj are actually instantiated. That leaves ItemInfo which is the name of my custom type (Not an instance of the class).

    Since the variable testing and obj are instantiated it seems like it does not like the reference to the class ItemInfo.
    What could I be doing wrong here?
    Thanks,
    Eric
    --------------------------------------------------------------------------------------------------------------------
    VB.net/C# ... Visual Studio 2019
    "None of us are as smart as all of us."

  2. #2
    Super Moderator dday9's Avatar
    Join Date
    Mar 2011
    Posts
    12,370

    Re: DirectCast - Object not set to an instance of an object???

    Try bypassing the obj variable altogether.
    Code:
    testing = New ItemInfo 
    Dim formatter As New BinaryFormatter 
    testing = DirectCast(formatter.Deserialize(fs), ItemInfo)
    See if that works.

    Edit -

    Also I wanted to let you know that I visited your website, visited the first website in your portfolio and it doesn't display correct in IE10, but it does in Mozilla. Just an FYI :]
    Last edited by dday9; Oct 3rd, 2013 at 08:52 AM.
    "Code is like humor. When you have to explain it, it is bad." - Cory House
    VbLessons | HtmlLessons | CssLessons | Code Tags | Sword of Fury - Jameram

  3. #3
    Super Moderator Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    40,102

    Re: DirectCast - Object not set to an instance of an object???

    The variable 'Testing' couldn't cause the problem, only obj could be causing this problem in the line you show. However, you state that you verified that obj was instantiated. How did you do this?
    My usual boring signature: Nothing

  4. #4
    Angel of Code Niya's Avatar
    Join Date
    Nov 2011
    Posts
    9,017

    Re: DirectCast - Object not set to an instance of an object???

    You wrapped that code in an exception handler so how do you know which line cause the exception ?
    Treeview with NodeAdded/NodesRemoved events | BlinkLabel control | Calculate Permutations | Object Enums | ComboBox with centered items | .Net Internals article(not mine) | Wizard Control | Understanding Multi-Threading | Simple file compression | Demon Arena

    Copy/move files using Windows Shell | I'm not wanted

    C++ programmers will dismiss you as a cretinous simpleton for your inability to keep track of pointers chained 6 levels deep and Java programmers will pillory you for buying into the evils of Microsoft. Meanwhile C# programmers will get paid just a little bit more than you for writing exactly the same code and VB6 programmers will continue to whitter on about "footprints". - FunkyDexter

    There's just no reason to use garbage like InputBox. - jmcilhinney

    The threads I start are Niya and Olaf free zones. No arguing about the benefits of VB6 over .NET here please. Happiness must reign. - yereverluvinuncleber

  5. #5

    Thread Starter
    Hyperactive Member
    Join Date
    Jul 2004
    Location
    Kansas, USA
    Posts
    352

    Re: DirectCast - Object not set to an instance of an object???

    Shaggy Hiker:
    I verified that obj was instantiated by using a breakpoint and following execution line by line.

    Niya:
    Same as above - following line by line using breakpoints
    Thanks,
    Eric
    --------------------------------------------------------------------------------------------------------------------
    VB.net/C# ... Visual Studio 2019
    "None of us are as smart as all of us."

  6. #6

    Thread Starter
    Hyperactive Member
    Join Date
    Jul 2004
    Location
    Kansas, USA
    Posts
    352

    Re: DirectCast - Object not set to an instance of an object???

    Additionally, If I serialize a string and then deserialize it it works fine.

    Serialize:
    Code:
            Dim test As String = "Hello"
    
            ' Persist to file
            Dim save As New SaveFileDialog
            If save.ShowDialog = Windows.Forms.DialogResult.OK Then
                Dim stream As FileStream = File.Create(save.FileName)
                Dim formatter As New BinaryFormatter()
                formatter.Serialize(stream, test)
                stream.Close()
            End If
    Deserialize:
    Code:
            Dim test As String = ""
            If open.ShowDialog = Windows.Forms.DialogResult.OK Then
                Dim fs As FileStream = New FileStream(open.FileName, FileMode.Open)
                Try
                    Dim formatter As New BinaryFormatter
                    Dim obj As Object = formatter.Deserialize(fs)
                    test = CType(obj, String)
                Catch ex As Exception
                    MsgBox(ex.Message)
                Finally
                    fs.Close()
                End Try
            End If
    Thanks,
    Eric
    --------------------------------------------------------------------------------------------------------------------
    VB.net/C# ... Visual Studio 2019
    "None of us are as smart as all of us."

  7. #7
    Super Moderator Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    40,102

    Re: DirectCast - Object not set to an instance of an object???

    That particular exception is only raised when some object is Nothing when it can't be Nothing. In the line in question, the object "testing" doesn't matter at all, since it's state doesn't matter in that line. The only other object in the line is Obj. If you stepped through the line and looked at Obj at the time of the exception and it was not Nothing, and the next step took you to the exception handler...that would be quite interesting, really. The test with the string doesn't really mean anything. All that would be testing is whether the code works as advertised, which it does.

    The specific way you answered my question left just enough wiggle room that I'd like to nail that down before going on. After all, stepping through the code should work just fine...and could leave Obj at Nothing. The key point is this: When you stepped through the code, at the point execution reached this line:

    testing = DirectCast(obj, ItemInfo)

    did you look at what Obj held using Shift+F9, and did it hold a valid Object?

    Second, if you then stepped one line further (or at least attempted to do so), did you immediately jump to the exception handler?

    If you answer Yes to both of those, then the exception isn't in the line in question....and it IS quite interesting.
    My usual boring signature: Nothing

  8. #8

    Thread Starter
    Hyperactive Member
    Join Date
    Jul 2004
    Location
    Kansas, USA
    Posts
    352

    Re: DirectCast - Object not set to an instance of an object???

    Hmmm...
    Getting closer. This works:
    Code:
                    Dim obj As ItemInfo = formatter.Deserialize(fs)
                    With testing
                        .CompileHistory = obj.CompileHistory
                        .Description = obj.Description
                        .FileLocation = obj.FileLocation
                        .ItemNumber = obj.ItemNumber
                    End With
    This did not:
    Code:
                    Dim obj As ItemInfo = formatter.Deserialize(fs)
                    testing = obj
    The exception is happening when I do the assignment. I have a custom event written in ItemInfo to get around the serialization error that happens when you have a custom class with events. Basically the serializer tried to serialize both the target and it's caller (in this case the form which cannot be serialized). The exception is being thrown in the AddHandler part the custom error
    Code:
        <NonSerialized()> _
        Private Events As New System.ComponentModel.EventHandlerList
    'Then later...
    Code:
        Public Custom Event APropertyChanged As EventHandler
            AddHandler(ByVal value As EventHandler)
                Try
                    Events.AddHandler("APropertyChanged", value)
                Catch ex As Exception
                    MsgBox(ex.Message)
                End Try
            End AddHandler
    
            RemoveHandler(ByVal value As EventHandler)
                Try
                    Events.RemoveHandler("APropertyChanged", value)
                Catch ex As Exception
                    MsgBox(ex.Message)
                End Try
            End RemoveHandler
    
            RaiseEvent(ByVal sender As Object, ByVal e As System.EventArgs)
                CType(Events("APropertyChanged"), EventHandler).Invoke(sender, e)
            End RaiseEvent
        End Event
    So value is nothing. I am not real strong on custom events and I am pretty confused about what is happening here.
    Last edited by flycast; Oct 3rd, 2013 at 05:14 PM.
    Thanks,
    Eric
    --------------------------------------------------------------------------------------------------------------------
    VB.net/C# ... Visual Studio 2019
    "None of us are as smart as all of us."

  9. #9
    Super Moderator Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    40,102

    Re: DirectCast - Object not set to an instance of an object???

    So, the problem wasn't really in the line that showed the exception, but in the underlying class. It happens, but it's a bit rare.

    In that first snippet, testing is only something because you created a New ItemInfo. You then set a few members in the With statement...then overwrite testing with obj. That's really quite odd. The variable testing holds the address of some NewInfo object, as does the variable obj. You set a few properties of the fist instance from the same properties in the second instance, then you throw out the first instance and replace it with the second instance and it works? That suggests that something happens to NewInfo as a side effect of accessing one of those four properties, because once you execute this line:

    testing = obj

    the instance that had been in testing is no longer accessible. Shared members of the class would be accessible, but not instance members. It sure doesn't look like you are setting any Shared members in the With statement, but maybe you are. The point is that in both the first and the second snippet, the result of the line:

    testing = obj

    is that whatever instance was being referenced by testing is now lost, and the variable testing now holds the address of the instance that was being referenced by obj. So, any changes to testing in the With statement don't matter because that instance is no longer accessible. Which means that accessing the properties must be changing obj in some way, since testing is no longer in the picture (unless you overloaded the = operator).
    My usual boring signature: Nothing

  10. #10

    Thread Starter
    Hyperactive Member
    Join Date
    Jul 2004
    Location
    Kansas, USA
    Posts
    352

    Re: DirectCast - Object not set to an instance of an object???

    Shaggy:
    You set a few properties of the fist instance from the same properties in the second instance, then you throw out the first instance and replace it with the second instance and it works?
    No. IT was either/or. When I set a few property values of "testing" with the values from "obj" it worked. When I just assign testing = obj then it does not. When I do that then it adds events and that is when there is a nothing gumming up the works.

    I didn't overload the = operator.

    The root is when I do testing = obj then the class goes into the customer event and removes events handlers and then adds event handlers.
    Thanks,
    Eric
    --------------------------------------------------------------------------------------------------------------------
    VB.net/C# ... Visual Studio 2019
    "None of us are as smart as all of us."

  11. #11
    Super Moderator Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    40,102

    Re: DirectCast - Object not set to an instance of an object???

    I'm a bit confused. Your first snippet in post #8, which you said worked, ended with the testing = obj line. In the second snippet you said that that line, alone, didn't work. Was that assignment not supposed to have been the final line in the first snippet? That would make more sense, certainly, but it's not what is shown.
    My usual boring signature: Nothing

  12. #12

    Thread Starter
    Hyperactive Member
    Join Date
    Jul 2004
    Location
    Kansas, USA
    Posts
    352

    Re: DirectCast - Object not set to an instance of an object???

    Shaggy:
    That line is missing it's comment - it should be commented out...my bad. It has been edited.
    Thanks,
    Eric
    --------------------------------------------------------------------------------------------------------------------
    VB.net/C# ... Visual Studio 2019
    "None of us are as smart as all of us."

  13. #13
    Super Moderator Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    40,102

    Re: DirectCast - Object not set to an instance of an object???

    Ah, that changes things completely. It's a pretty interesting case. In all the classes that I have serialized, I don't recall ever serializing one that has an event. I can see why that would be a problem, since it would normally want to serialize all the data members, and the data members for an event would be the list of method pointers that get called when the event is raised, which would be bad, since they wouldn't retain any meaning.

    I think that the exception is showing in the wrong place, which seems to be what you have found, too. What happens if you check whether Value Is Nothing in both the add and remove handlers, and take no action if it is?
    My usual boring signature: Nothing

  14. #14
    eXtreme Programmer .paul.'s Avatar
    Join Date
    May 2007
    Location
    Chelmsford UK
    Posts
    26,413

    Re: DirectCast - Object not set to an instance of an object???

    Classes with eventhandlers don't serialize correctly unless you remove the handlers. I suppose that applies when deserializing too...

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width