Random.Next question

A

Andre

I'm trying to write a Password generating program which will fill one
of the fields in our Accounts Table with an eight-digit password made
up of numerals, upper and lower case letters. I'm generating a random
number from 48 to 122, then converting its ASCII value to a char and
concatenating it to the end of a string called sPassword. When
sPassword has eight characters, the string is updated to the accounts
record in our database.

THE PROBLEM I'm having is that in run time all eight characters of the
password end up being the same, ie YYYYYYYY. If I step through the
same code in debug mode, I get eight unique numbers, ie Ysdf365D. Can
anyone fill me in on what I'm doing wrong here?

Thanks in advance,

Andre Ranieri


private void PassGen(SqlConnection cn, string sAccountKey)
{
try
{
String sPassword = "";
SqlCommand cmd = cn.CreateCommand();
while (sPassword.Length<8)
{
int p = 0;
Random rGen = new Random();
p = rGen.Next(47,123);
if ((p>47 && p<91) || (p>96 && p<123)) {
sPassword += (char)p;
Console.WriteLine(p + " " + (char)p + " " + sAccountKey);
}
}
//Write password back to UDF2
String sSQL = "UPDATE tblMainAccounts SET UDF2 = '" + sPassword +
"' "
+ "WHERE (AccountKey = " + sAccountKey + ");";
cmd.CommandText = sSQL;
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
Console.Write(ex.Source + ex.Message);
}
 
F

Fred Mellender

You want to create ONE Random object, and call Next repeatedly against that
object. Take
Random rGen = new Random();
out of the while loop. Better, create it outside the PassGen function, and
pass it in as a parameter.

Read about the Random constructor you are using. If you created the Random
objects fast enough, they are all initialized with the same time dependent
seed.
 
A

Andre

Fred,

Thanks a bunch! It turns out I was seeding the Random so fast it was
using the time-dependent stamp for several at once. I moved the
Random rGen; line of code into Main and passed it as a paramater as
you suggested, it worked great.

Cheers,

Andre
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top