Array of objects + For Each = Error?

Author Message
obiwaynekenobi

  • Total Posts : 3
  • Scores: 0
  • Reward points : 0
  • Joined: 3/12/2008
  • Status: offline
Array of objects + For Each = Error? Wednesday, March 12, 2008 7:41 AM (permalink)
0
I normally work with ASP.NET, not Classic, but my current position has a legacy ASP application (poorly written) that I'm trying to refactor.  I'm looking at modularizing the code and using OOP techniques - I have a sample class that sets a few basic properties of a Customer entity, and uses the ActiveRecord pattern to return an array of all of them.

When I try to iterate though the collection using a simple For Each loop, and display the object's properties, VBScript complains.

My code is as follows:
' Customer class
Class Customer
    Private m_idCustomer ' As Integer
    Private m_name ' As String
    Private m_lastName ' As String
   
    Public Function Create(id, name, lastName)
      m_idCustomer = id
      m_name = name
      m_lastName = lastName
    End Function
   
    Public Property Get ID ' As Integer
      ID = m_idCustomer
    End Property
   
    Public Property Get Name ' As String
      Name = m_name
    End Property
   
    public property get LastName ' As String
      LastName = m_lastName
    end property
   
    Public Function FindAll() ' As Array
      Dim aryCustomers()
      Set rs = DbManager.ExecuteStatement("SELECT TOP 10 idCustomer, name, lastName FROM customers")
      If Not rs.EOF Then
        ReDim aryCustomers(rs.RecordCount)
        While Not rs.EOF
          For i = 0 To (UBound(aryCustomers) - 1)
            Set c = New Customer
            Call c.Create(rs("idCustomer"), rs("name"), rs("lastName"))
            Set aryCustomers(i) = c
            rs.MoveNext
          Next
        Wend
      End If
      FindAll = aryCustomers
    End Function
  End Class

<!-- This is in the calling page -->
Set someCust = New Customer
custList = someCust.FindAll()
 
For Each cust In custList
  Response.Write "ID: " & cust.ID & "<br />"
  Response.Write "First Name: " & cust.Name & "<br />"
  Response.Write "Last Name: " & cust.LastName & "<hr />"
Next

----
This seems to be pretty simple, and I'm not sure why VBScript is complaining.  The exact error I get points to the "For Each cust In custList" line, with the specific error being "Object required: cust" - clearly, VBScript isn't setting cust to be a Customer object, and is trying to call a property on a String.  However, I get it to work when I use a normal For..Next loop (e.g. "For i = 0 To UBound(custList) - 1"), and when I use custList(i) instead of cust.  While it's not a big deal, I Prefer the For Each syntax; I think it's cleaner and more natural to use. 

Can I do what I want to in VBScript, or am I stuck using For i = 0 To UBound(custList) - 1?  As I said, I'm not really familiar with VBScript, but I'm trying to clean up the horrendous codebase I've "inherited" - the previous programmer didn't indent anything, used cryptic variable names, and made gratuitious use of On Error Resume Next to make sure that his code worked (in other words, if I remove it, the code dies with some nonsense error like calling a method on an item that hasn't been created yet, because it's created twenty lines further down the page).
 
#1
    ebgreen

    • Total Posts : 8219
    • Scores: 98
    • Reward points : 0
    • Joined: 7/12/2005
    • Status: offline
    RE: Array of objects + For Each = Error? Wednesday, March 12, 2008 8:18 AM (permalink)
    0
    I'll give your actual issue some thought. The thing that first leapt out at me was:
     
    Why not just return the recordset?
    "... when you are good and crazy, oooh, oooh, oooh, the sky is the limit!" - The Tick
    Goog places to start:http://www.visualbasicscript.com/m_24727/tm.htm
    http://www.visualbasicscript.com/m_47117/tm.htm
     
    #2
      obiwaynekenobi

      • Total Posts : 3
      • Scores: 0
      • Reward points : 0
      • Joined: 3/12/2008
      • Status: offline
      RE: Array of objects + For Each = Error? Wednesday, March 12, 2008 8:29 AM (permalink)
      0
      Well, mainly because I'm trying to properly encapsulate things - I'm used to C#/VB.NET and ASP.NET, so I'm used to having an entity class wrap the database calls, so the page can deal with natural properties of the model, instead of knowing it's using a RecordSet.  I mean, I could use the recordset, it's mainly a semantic thing.  The current code is full of recordset calls (usually with names such as rTemp and rsTemp), and I find it hard to follow the flow.  Also, the data doesn't really explain what columns are often, the previous dev used a lot of abbreviations, so it's more natural to use product.PartNumber than rs("mfr_numb")
       
      #3
        ebgreen

        • Total Posts : 8219
        • Scores: 98
        • Reward points : 0
        • Joined: 7/12/2005
        • Status: offline
        RE: Array of objects + For Each = Error? Wednesday, March 12, 2008 8:35 AM (permalink)
        0
        All valid points. I still don't see anything in your code that would explain the error. Gimme a while and I will try to recreate it if I can since I still don't see anything glaringly obvious.
        "... when you are good and crazy, oooh, oooh, oooh, the sky is the limit!" - The Tick
        Goog places to start:http://www.visualbasicscript.com/m_24727/tm.htm
        http://www.visualbasicscript.com/m_47117/tm.htm
         
        #4
          ebgreen

          • Total Posts : 8219
          • Scores: 98
          • Reward points : 0
          • Joined: 7/12/2005
          • Status: offline
          RE: Array of objects + For Each = Error? Wednesday, March 12, 2008 9:12 AM (permalink)
          0
          Well, until someone comes along and proves me wrong I would consider this a bug. I can reproduce it and it makes no sense.
          "... when you are good and crazy, oooh, oooh, oooh, the sky is the limit!" - The Tick
          Goog places to start:http://www.visualbasicscript.com/m_24727/tm.htm
          http://www.visualbasicscript.com/m_47117/tm.htm
           
          #5
            TNO

            • Total Posts : 2094
            • Scores: 36
            • Reward points : 0
            • Joined: 12/18/2004
            • Location: Earth
            • Status: offline
            RE: Array of objects + For Each = Error? Wednesday, March 12, 2008 9:53 AM (permalink)
            0
            Out of curiosity, what is the VarType of custList?

            Here's my wild theory (take with a grain of salt):

            For Each cust In custList

            In this structure cust can only be a variant, generic object, or Automation object IF custList is an object collection (which an Array is not). If custList is an Array like in this case, cust can ONLY be a variant type hence throwing the exception "Object required: cust".

            So my theoretical solution:

            For Each cust In custList
            Set cust.........
            <message edited by TNO on Wednesday, March 12, 2008 9:58 AM>
            To iterate is human, to recurse divine. -- L. Peter Deutsch
             
            #6
              ebgreen

              • Total Posts : 8219
              • Scores: 98
              • Reward points : 0
              • Joined: 7/12/2005
              • Status: offline
              RE: Array of objects + For Each = Error? Wednesday, March 12, 2008 10:29 AM (permalink)
              0
              The vartype is 8204 so array of variants.
              "... when you are good and crazy, oooh, oooh, oooh, the sky is the limit!" - The Tick
              Goog places to start:http://www.visualbasicscript.com/m_24727/tm.htm
              http://www.visualbasicscript.com/m_47117/tm.htm
               
              #7
                ebgreen

                • Total Posts : 8219
                • Scores: 98
                • Reward points : 0
                • Joined: 7/12/2005
                • Status: offline
                RE: Array of objects + For Each = Error? Thursday, March 13, 2008 6:06 AM (permalink)
                0
                Ok so this bothered me. I have found a way to give you For Each access to all the items. It isn't exactly what you were doing but it does put you on familiar ground. The workaround is to use an arraylist. Here is sample straight vbs code but I can't see any reason why it wouldn't work in asp as long as any version of the .Net framework is present wherever it is running.
                 
                 
                Dim oOuterFoo
                Dim alOuterAL
                Dim oItem
                Set oOuterFoo = New Foo
                Set alOuterAL = oOuterFoo.FindAll()
                For Each oItem In alOuterAL
                 WScript.Echo oItem.Index & " -> " & oItem.Value
                Next
                Class Foo
                 Private nIndex
                 Private strValue
                 
                 Public Property Get Index
                  Index = nIndex
                 End Property
                 
                 Public Property Get Value
                  Value = strValue
                 End Property
                 
                 Public Function Create(nInd, strVal)
                  nIndex = nInd
                  strValue = strVal
                 End Function
                 
                 Public Function FindAll()
                  Dim i
                  Dim oFoo
                  Dim alOut : Set alOut = CreateObject("System.Collections.ArrayList")
                  
                  For i = 1 To 5
                   Set oFoo = New Foo
                   Call oFoo.Create(i, "Value " & i)
                   alOut.Add oFoo
                  Next
                  
                  Set FindAll = alOut
                 End Function

                End Class

                "... when you are good and crazy, oooh, oooh, oooh, the sky is the limit!" - The Tick
                Goog places to start:http://www.visualbasicscript.com/m_24727/tm.htm
                http://www.visualbasicscript.com/m_47117/tm.htm
                 
                #8
                  TNO

                  • Total Posts : 2094
                  • Scores: 36
                  • Reward points : 0
                  • Joined: 12/18/2004
                  • Location: Earth
                  • Status: offline
                  RE: Array of objects + For Each = Error? Thursday, March 13, 2008 7:45 AM (permalink)
                  0
                  Would the Dictionary object work as well?
                  To iterate is human, to recurse divine. -- L. Peter Deutsch
                   
                  #9
                    ebgreen

                    • Total Posts : 8219
                    • Scores: 98
                    • Reward points : 0
                    • Joined: 7/12/2005
                    • Status: offline
                    RE: Array of objects + For Each = Error? Thursday, March 13, 2008 8:16 AM (permalink)
                    0
                    Not for what the OP is trying to do. To make it work you would have to make the key some index value and the value the customer object. That in itself would not be as clean as an array or arraylist but even worse would be the retrieval. It would look like this:
                     
                    For Each cust In custList.Keys
                    Response.Write "ID: " & custList(cust).ID & "<br />"
                    Response.Write "First Name: " & custList(cust).Name & "<br />"
                    Response.Write "Last Name: " & custList(cust).LastName & "<hr />"
                    Next

                     
                     
                    Which just isn't as clean as I think the OP wanted.
                    "... when you are good and crazy, oooh, oooh, oooh, the sky is the limit!" - The Tick
                    Goog places to start:http://www.visualbasicscript.com/m_24727/tm.htm
                    http://www.visualbasicscript.com/m_47117/tm.htm
                     
                    #10
                      mcnd

                      • Total Posts : 50
                      • Scores: 2
                      • Reward points : 0
                      • Joined: 4/27/2008
                      • Status: offline
                      RE: Array of objects + For Each = Error? Sunday, April 27, 2008 4:15 AM (permalink)
                      0
                      As far as i know, this is the correct behaviour for the dictionary object. The for each statement iterates over the Keys "array" of the dictionary object, returning the keys asociated with each of the items.
                       
                      #11
                        ehvbs

                        • Total Posts : 3320
                        • Scores: 112
                        • Reward points : 0
                        • Joined: 6/22/2005
                        • Location: Germany
                        • Status: offline
                        RE: Array of objects + For Each = Error? Sunday, May 04, 2008 9:17 AM (permalink)
                        0
                        Hi mcnd,

                        the problem you described in your first posting is caused by this line:

                              ReDim aryCustomers(rs.RecordCount)

                        aryCustomers will now contain (rs.RecordCount + 1) empty variants. Your
                        loop

                              For i = 0 To (UBound(aryCustomers) - 1)

                        will fill rs.RecordCount of the elements, the last item will stay empty. If you
                        for-each-loop over the returned array, the last element won't be an object;
                        that causes the (correct) error message: Not an object.

                        So use

                             ReDim aryCustomers(rs.RecordCount - 1)

                        and

                             For i = 0 To (UBound(aryCustomers))

                        and your script will work.

                        Good luck!

                        ehvbs



                             



                         
                        #12

                          Online Bookmarks Sharing: Share/Bookmark

                          Jump to:

                          Current active users

                          There are 0 members and 1 guests.

                          Icon Legend and Permission

                          • New Messages
                          • No New Messages
                          • Hot Topic w/ New Messages
                          • Hot Topic w/o New Messages
                          • Locked w/ New Messages
                          • Locked w/o New Messages
                          • Read Message
                          • Post New Thread
                          • Reply to message
                          • Post New Poll
                          • Submit Vote
                          • Post reward post
                          • Delete my own posts
                          • Delete my own threads
                          • Rate post

                          2000-2012 ASPPlayground.NET Forum Version 3.9