1

Im making referenceIDs in a function and adding the values to a list.

Dim myListOfItems As New List(Of BasketItem)      
Dim refID As String = String.Empty
    
    For Each i In myListOfNames
        refID = HelpClass.GenerateRandomString(20)

        Dim x As New BasketItem
        x.RefID = refID
        myListOfItems.Add(x)

    Next

The Function looks as follows:

Public Shared Function GenerateRandomString(ByVal length As Integer) As String

        Dim chara As Char() = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".ToCharArray()
        Dim randomString As String = String.Empty
        Dim objRandom As New Random()
        For i As Integer = 0 To length Step 1
            Dim x As Integer = objRandom.Next(1, chara.Length)
            If Not randomString.Contains(chara.GetValue(x).ToString()) Then
                randomString += chara.GetValue(x)
            Else
                i = i - 1
            End If
        Next
        Return randomString
    End Function

This all works great on my local visual studio run. But when i upload to my webserver several of the items get the same values.

This is the output on live server:

> Biljettinnehavare: 1 | 1XIh4YqBlHmipkPKV576C  
> Biljettinnehavare: 2 | 1XIh4YqBlHmipkPKV576C 
> Biljettinnehavare: 3 | 1XIh4YqBlHmipkPKV576C 
> Biljettinnehavare: 4 | 1XIh4YqBlHmipkPKV576C 
> Biljettinnehavare: 5 | qvmupeZhcoQ9YgOWtCLN4 
> Biljettinnehavare: 6 | qvmupeZhcoQ9YgOWtCLN4  
> Biljettinnehavare: 7 | qvmupeZhcoQ9YgOWtCLN4  
> Biljettinnehavare: 8 | qvmupeZhcoQ9YgOWtCLN4  
> Biljettinnehavare: 9 | qvmupeZhcoQ9YgOWtCLN4  
> Biljettinnehavare: 10 | qvmupeZhcoQ9YgOWtCLN4 
> Biljettinnehavare: 11 | DdxK4jibcu9s7gXJw6a3m  
> Biljettinnehavare: 12 | DdxK4jibcu9s7gXJw6a3m  
> Biljettinnehavare: 13 | DdxK4jibcu9s7gXJw6a3m 
> Biljettinnehavare: 14 | DdxK4jibcu9s7gXJw6a3m
> Biljettinnehavare: 15 | 32SWpkFfdgbqMtJGa1siw 
> Biljettinnehavare: 16 | 32SWpkFfdgbqMtJGa1siw

Dont really know what is causing this problem. Any ideas?

Is the server executing the loop so quick and basing it on the clock makes the same values appear, what would be the way to counter that in that case?

Jimmy
  • 275
  • 2
  • 6
  • 27

1 Answers1

1

Define your variable as:

 Static objRandom As System.Random = New System.Random()

as in the answer Random integer in VB.NET

Pepe N O
  • 1,678
  • 1
  • 7
  • 11
  • I just tried it and it works. – Jimmy Sep 22 '21 at 14:05
  • Apparently Cassini is so slow so it took longer to go through the loop than the real web server and that make it work locally – Jimmy Sep 22 '21 at 14:09
  • The problem with random number generation always is the seed from where numbers are generated. Look also at this example in official docs https://learn.microsoft.com/en-us/dotnet/api/microsoft.visualbasic.vbmath.rnd?view=net-5.0 – Pepe N O Sep 22 '21 at 14:14
  • Static has to do a lot of work behind the scenes. Just make the variable a class level variable. – Mary Sep 22 '21 at 19:39