Click here to Skip to main content
15,881,882 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I think i have a simple situation which i can't seem to solve and i'm hoping someone would shed some light on this:

basically i have a method that is generating a random number like this:


p
C#
Public static string Code()
            {
                var characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
                var c= new char[6];
                var random = new Random();
    
                for (int i = 0; i < c.Length; i++)
                {
                    c[i] = characters[random.Next(characters.Length)];
                }
    
                var code = new String(c);
                return code;
            }


I have another method that is checking if the generated code in the method above already exists in the database. If the code exists then re - generate another code .

C#
public void SetCode()
        {

           string _code = Code();
            using(var db = new Database())
                    {
                        var p = db.Codes.Where(pc => pc.Code.Equals(Code));

                        
                        if (p.Any())
                        {
                          // this is where i'm stuck, if the code exist i'll do i send it back to generate another code?
                        }
                      //if code doesn't exist in the db save it....
                    }
                   
        }


How can I go ahead and achieve this?
Thank you

What I have tried:

Looked at do while loops and

C#
if (p.Any())
                        {
                          // this is where i'm stuck, if the code exist i'll do i send it back to generate another code?
                        }
                      //if code doesn't exist in the db save it....
                    }
                   
        }
Posted
Updated 29-Aug-17 1:38am
Comments
Thanks7872 25-Aug-17 6:59am    
Which database is there?
BillWoodruff 25-Aug-17 10:02am    
Do you know how to write to a Database ? How to change an existing value in a Database ? Unless you know how, with your current Database, to Create, Read, Update and Delete (CRUD), you will not make progress.

You need to review your Database documentation.
Richard Deeming 25-Aug-17 12:47pm    
Either a while[^] or a do..while[^] will do the trick. What's the problem?
string code;
using (var db = new Database())
{
    do
    {
        code = Code();
    }
    while (db.Codes.Any(pc => pc.Code == code))
}

string code = Code();
using (var db = new Database())
{
    while (db.Codes.Any(pc => pc.Code == code))
    {
        code = Code();
    }
}
BillWoodruff 25-Aug-17 15:17pm    
I'd be voting #5 for this if posted as solution.

Solution A:
1) Set a unique constraint on that field in the table
2) Check for insert failure
3) regenerate upon failure.

Solution B:
1) Generate random string
2) use query to check for it in field
3) regenerate if it exists

For A and B
4) Repeat as necessary, but, if your random strings are short, I'd possibly limit retries in case your table gets too densely populated and it runs 'forever'-ish.

Solution A will, overall, require fewer table queries. Also, it prevents other users who were less careful from screwing up the columns uniqueness because the constraint is always in effect.

 
Share this answer
 
Comments
1Future 25-Aug-17 6:43am    
Hi thanks for the response .. I think solution B is what i'm trying to achieve in the code above . but, i'm stuck on how i can regenereate if code still exists .. maybe this is where can show me in code example?
W Balboos, GHB 25-Aug-17 6:50am    
You marked this as a C# question so I would expect you to be familiar with C#'s conditional loops. Use a loop - break with success (like uid/pwd input would do in a login).

With 26^6 possible combinations, unless they're rapidly machine generated for some kind of test, this will not happen very often. There's nearly 40 billion unique combinations.

An additional hint: if you use Solution B, in particular, I'd put an index on that field if it's going to start to fill up.
Dave Kreskowiak 25-Aug-17 8:57am    
It's 36^6 and it's only 2.176 billion combinations. :)
Dave Kreskowiak 25-Aug-17 8:54am    
Option A is the only one that is feasible.

Option B has the problem of checking for it then doing the insert in a separate operation. Well, what if, during the check, it doesn't exist, but during the insert it suddenly does because of multiple users? Now you have to handle the case where the check is good but the insert fails. Sure you could get around this with carefully crafted SQL, but given the skill level of the OP, ...
If you must use randomized strings, then the solution that I would recommend is:
C#
var random = Guid.NewGuid().ToString("N");
 
Share this answer
 
Comments
1Future 25-Aug-17 6:34am    
How do I sepecify how many characters?? ... I Would like 6 characters in length
Graeme_Grant 25-Aug-17 6:37am    
6 characters? maybe base32 encoding might get you there: Base32 Encoder and Decoder in C#[^] but you would be better off increasing the size of the field just incase encoding causes dupelicates.
As I mentioned in the comments, either a while[^] or a do..while[^] will do the trick.
string code;
using (var db = new Database())
{
    do
    {
        code = Code();
    }
    while (db.Codes.Any(pc => pc.Code == code))
}
string code = Code();
using (var db = new Database())
{
    while (db.Codes.Any(pc => pc.Code == code))
    {
        code = Code();
    }
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900