What happened to the Messenger Plus! forums on msghelp.net?
Shoutbox » MsgHelp Archive » Skype & Technology » Tech Talk » Visual Basic Help

Visual Basic Help
Author: Message:
DJeX
Veteran Member
*****

Avatar


Posts: 1138
Reputation: 11
– / Male / –
Joined: Jul 2003
O.P. Undecided  Visual Basic Help
I can't get this piece of code to work with out getting a

[Image: runtime8mg.jpg]

code:
List1.ListIndex = 0
For a = 0 To List1.ListCount - 1
    If InStr(List1, websitein2) Then
        s = ""
        s = s + Mid$(List1, InStrRev(List1, "-") + 2)
        s = Replace(s, "http://", "")
    Else
        List1.ListIndex = List1.ListIndex + 1
    End If
Next a

Can any one help?
[Image: top.gif]
03-19-2006 11:21 PM
Profile PM Web Find Quote Report
matty
Scripting Guru
*****


Posts: 8336
Reputation: 109
39 / Male / Flag
Joined: Dec 2002
Status: Away
RE: Visual Basic Help
InStr() needs 3 parameters

InStr(CharToStartAt,String,TextToFind)

So your wanting to use InStr(1, List1.List(a), websitein2) Then

code:
For j = 0 To List1.ListCount - 1
    If InStr(1, List1(j), websitein2) Then
        s = ""
        s = s + Mid$(List1(j), InStrRev(List1(j), "-") + 2)
        s = Replace(s, "http://", "")
    End If
Next j

This post was edited on 03-19-2006 at 11:48 PM by matty.
03-19-2006 11:45 PM
Profile E-Mail PM Find Quote Report
CookieRevised
Elite Member
*****

Avatar

Posts: 15519
Reputation: 173
– / Male / Flag
Joined: Jul 2003
Status: Away
RE: Visual Basic Help
quote:
Originally posted by Matty
InStr() needs 3 parameters:
InStr(CharToStartAt,String,TextToFind)
Nope, the first paramater is optional though...

If omitted it will always be 1.

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

quote:
Originally posted by DJeX
Can any one help?
It would have been better if you said on what line that error occurs. And that you provided more code (eg: what are the declarations, what is s used for, etc.. etc..)

Anyways, with the info given:
  1. I hope you used Option Explicit at the beginning of each module, form and/or class

  2. Always explicitly use the property name you want to use. Never relay on default property names:
       Don 't use: s = List1
       but use: s = List1.Text

  3. Why using the "s" variable in that way?

       a) This:
               s = ""
               s = s + Mid$(List1, InStrRev(List1, "-") + 2)
               s = Replace(s, "http://", "")
          can be much shorter and faster by doing:
               s = Replace(Mid$(List1, InStrRev(List1, "-") + 2), "http://", "")

       a) What are actually trying to do with that string manipulation? (because at first sight, it seems a bit dodgy (no offense) eg: what if the url itself contains a "-"? What if the whole string doesn't contain a "-"?)

       c) What is the use in calculating/creating that "s" variable anyways; It isn't used anywhere and you also always set it to an empty string first (so it can't be a global kind of stringlist either)?

  4. If you need to parse thru a list, never use the .ListIndex property. This is dead, extremely dead slow...

    Use the .List() property for that. No need for resetting and updating the listindex at all, it is completely useless, makes bigger code and is very slow. Only do what you did when you explicitly need a visual update on each line (but even then your code will not work as it is supposed because Windows will not update the control on screen as long as it don't have th time to do it (not being idle))

    The .List() property is an array containing all the data from the list starting at index 0 to ListCount-1.

    Thus instead of:

          List1.ListIndex = 0
          For a = 0 To List1.ListCount - 1
              If InStr(List1.Text, websitein2) Then
                 s = blahblah
              Else
                 List1.ListIndex = List1.ListIndex + 1
              End If
          Next a

    Do:

          For a = 0 To List1.ListCount - 1
             If InStr(List1.List(a), websitein2) Then
                s = blahblah
             End If
          Next a

  5. Finally, and to come to your actual problem:

      a) What is "websitein2". Is it defined as a string?

      b) What if your list doesn't not contain any elements? Setting ListIndex to 0 will not work then and will produce an error.

      c) If you come to the end of your loop, thus with "a" being equal to listcount-1, there is a big possebility that you set the listindex to one element higher than what the list contains. If that happens an error will occur:

    If ListCount = 5 (meaning there are 5 elements) and "a" is 4 (index of 5th element):

       For a = 0 To List1.ListCount - 1
          If InStr(List1, websitein2) Then
             s = ""
             s = s + Mid$(List1, InStrRev(List1, "-") + 2)
             s = Replace(s, "http://", "")
          Else
             List1.ListIndex = List1.ListIndex + 1
               ' ListIndex can not be set higher than the index of the last element in the list!!!
               ' This is what gives you that error.
               ' But don't try to fix this with ways like If Then Else structures.
               ' Use the method described in point 4 instead

          End If
       Next a

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

;)

This post was edited on 03-20-2006 at 06:51 AM by CookieRevised.
.-= A 'frrrrrrrituurrr' for Wacky =-.
03-20-2006 12:04 AM
Profile PM Find Quote Report
DJeX
Veteran Member
*****

Avatar


Posts: 1138
Reputation: 11
– / Male / –
Joined: Jul 2003
O.P. RE: Visual Basic Help
Ok heres the whole function. This is for a WinSock control. This is the DataArrival function.

Now what I'm trying to do is set up sort of a proxy thing where I set my IE or FireFox to proxy 127.0.0.1:4444 and it connects to my program. Now if a URL with a TLD of .in2 is typed it will search through the database list and find the location of that .in2. For example I type this in IE: www.test.in2. Now my program will see thats its an .in2 so then now it will look up test.in2 in the database list and find the location of the site. Then it sends the information back to the browser to load the correct page. So far it works preaty good but when ever I try and access a site that is the last item on the database list I get that runtime error.

I'm not sure if you will understand what I just typed. I'll be glad to send you my project files because I think that may be more of a help. Any ways the code below is the code thats responsible for checking if its a .in2, looking it up in the list, then sending info back to browser. And it also will allow any normal sites like .com to pass right through.

The code it said it had the error on was:
code:
List1.ListIndex = List1.ListIndex + 1

code:
Private Sub srvIn_DataArrival(Index As Integer, ByVal bytesTotal As Long)
    Dim sckData As String   ' Socket data
    Dim remHost As String   ' What is the remote host ?
    Dim tarSite As String   ' What site is the proxy user requesting ?
    Dim unfSite As String   ' Same as above but unformated!
    Dim websitein2 As String
    Dim tmpb As String
    Dim j As Integer
    Dim s As String
   
        ' Add to log
        AddLog "SrvIn", "Data arrived (" & Index & ")"
   
        ' Get the data
       srvIn(Index).GetData sckData, vbString, bytesTotal
       
        ' Get the targeted site (unformated)
        unfSite = FetchRequestedPage(sckData)
       
        ' Fetch the remote host
        remHost = GetHttpVars(sckData, "Host")
       
        ' Check if a url/host has been fetched so we can confirm that it is http traffic
        If IsEmpty(unfSite) Or IsEmpty(remHost) Then UnloadProxyUser (Index): Exit Sub
       
        ' Fetch the targeted site
        tarSite = StripHost(unfSite)
       
        ' Log the url visited
        'WriteUrlLog (unfSite)
       
         
If InStr(unfSite, ".in2") Then
       
    websitein2 = unfSite
       
        If InStr(websitein2, "www.") Then
            websitein2 = Replace(websitein2, "www.", "")
        End If
        If InStr(websitein2, "http://") Then
          websitein2 = Replace(websitein2, "http://", "")
        End If
        If InStr(websitein2, "/") Then
            websitein2 = Replace(websitein2, "/", "")
        End If

List1.ListIndex = 0
For a = 0 To List1.ListCount - 1
    If InStr(List1, websitein2) Then
        s = ""
        s = s + Mid$(List1, InStrRev(List1, "-") + 2)
        s = Replace(s, "http://", "")
    Else
        List1.ListIndex = List1.ListIndex + 1
    End If
Next a
       
          ' Update http request
        sckData = Replace(sckData, GetDomain(unfSite), "/")
        sckData = Replace(sckData, remHost, s)
        sckData = Replace(sckData, "Proxy-Connection:", "Connection:")
       
        ' Set the data
        ProxyUsers(Index).ProxyUserData = sckData
       
        ' Set remote host
        ProxyUsers(Index).ProxyRequHost = s
       
        ' Init a connection to retrive the data
        MakeProxyConnection (Index)
       
        ' Unload the user
        UnloadProxyUser (Index)
       
GoTo endit
End If
       
       
        ' Update http request
       
        sckData = Replace(sckData, GetDomain(unfSite), "/")
        sckData = Replace(sckData, "Proxy-Connection:", "Connection:")
       
        ' Set the data
        ProxyUsers(Index).ProxyUserData = sckData
       
        ' Set remote host
        ProxyUsers(Index).ProxyRequHost = remHost
        ' Init a connection to retrive the data
        MakeProxyConnection (Index)
       
        ' Unload the user
        UnloadProxyUser (Index)
       
        Exit Sub

endit:
    End Sub
[Image: top.gif]
03-20-2006 01:18 AM
Profile PM Web Find Quote Report
CookieRevised
Elite Member
*****

Avatar

Posts: 15519
Reputation: 173
– / Male / Flag
Joined: Jul 2003
Status: Away
RE: Visual Basic Help
I see...

quote:
Originally posted by DJeX
The code it said it had the error on was:
code:
List1.ListIndex = List1.ListIndex + 1

which indeed confirms point 5 from my previous post...

So use the method described in point 4 in my previous post.

---

Oh and loose the "Goto", that's bad programming practice.
And:
    s = ""
    s = s + blahblah
Is simply the same as:
    s = blahblah

;)

--------

And another possible cause for errors:

The IsEmpty() function only returns meaningful information for variants. Since you have defined "unfSite" and "remHost" as strings, the IsEmpty() function will not work as you intended it!

IsEmpty() does not check if a string is empty...

IsEmpty() is used to check if a variant variable is initialized. Remember that the "Empty" statement in VB does not mean 'nothing', it means 'not initilized'. Big difference there...  If a string contains 'nothing' it is still a string, it is still 'something': a string with no characters, aka "".

IsEmpty(): The required expression argument is a Variant. IsEmpty() returns a Boolean value indicating whether a variable has been initialized. It returns True if the variable is uninitialized, or is explicitly set to Empty; otherwise, it returns False. False is always returned if the expression contains more than one variable. IsEmpty() only returns meaningful information for variants, not for other types!

All this means that if IsEmpty() is used with other types than variants, it will always return False! There is no way that "If IsEmpty(unfSite) Or IsEmpty(remHost) Then" ever becomes True, hence your program will never ever perform "UnloadProxyUser (Index)".

If you want to check if a string is empty, aka it is has no characters, you use:
     If mystring = "" Then
Or a very fast alternative (because it does not use dead slow string manipulations or comparissons):
     If LenB(mystring) = 0 Then

For your code that means:
    If unfSite = "" Or remHost = "" Then
Or with the fast method:
    If LenB(unfSite) = 0 Or LenB(remHost) = 0 Then
Or even:
    If LenB(unfSite) + LenB(remHost) = 0 Then

--------

Another remark:
        ' Fetch the targeted site
        tarSite = StripHost(unfSite)


You nowhere use tarSite in your code, so what's the use?

--------

Another remark:

You have lots of double code.

Statr by loosing that Goto statement and put everything in proper IF THEN ELSE structures. Then you'll see that many code is duplicated and executed in both the True and False cases of the IF THEN ELSE structure. This means that this duplicated code can be put outside of the IF THEN ELSE structure.

eg:
    If saying = "Bye" Then
        Print "bye bye now"
        Call ShowSchedule
    Else
        Print "Hello there"
        Call ShowSchedule
    End If

The above has duplicated code and can be shortened:
    If saying = "Bye" Then
        Print "bye bye now"
    Else
        Print "Hello there"
    End If
    Call ShowSchedule


--------

Another remark:

The variable "a" isn't defined anywhere in your sub procedure. This means that you didn't use Option Explicit at the beginning of each module, form, class, etc. Otherwise your code wouldn't have runned in the first place since VB then would have detected an uninitialized variable.

Add Option Explicit at the beginning of each module, form, class, etc. to avoid undeclared variable errors and many other mistakes which could happen if you don't do this.

(and declare the variable "a").


--------

Attached is the fixed and optimized code. Note that it can still be optimized (and made more logic to follow), example is seen in the srvIn_DataArrival_ALTERNATIVE procedure. Also note that all I did was optimizing the logic behind the procedure (fixing and simplifying the logic), I didn't alter how the procedure works. This means errors could still occur because for example tarSite isn't used anywhere, possible bad entries in the list, etc)

.zip File Attachment: Module1.zip (1.48 KB)
This file has been downloaded 95 time(s).

This post was edited on 03-20-2006 at 09:45 PM by CookieRevised.
.-= A 'frrrrrrrituurrr' for Wacky =-.
03-20-2006 08:31 PM
Profile PM Find Quote Report
« Next Oldest Return to Top Next Newest »


Threaded Mode | Linear Mode
View a Printable Version
Send this Thread to a Friend
Subscribe | Add to Favorites
Rate This Thread:

Forum Jump:

Forum Rules:
You cannot post new threads
You cannot post replies
You cannot post attachments
You can edit your posts
HTML is Off
myCode is On
Smilies are On
[img] Code is On