mercredi 22 septembre 2021

Random string generating same values in different iterations of loop

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?




Aucun commentaire:

Enregistrer un commentaire