Click here to Skip to main content
15,886,724 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
In my project I am Uploading some files SQL Server, when the files are uploaded in the table Table1 another function will check that Table Table1 for files and inserts the Random Number or Characters into a table Table2 by getting the Random Numbers or Characters from another function which generates and returns it as string, now my problem is that the Files are correctly Uploading and saving in the Table1 but when Table1 is inserted with files the other function which inserts Random Numbers / Character initiates but throws the Exception My Code is,

C#
protected void trigger()
{
    try
    {
        DataSet ds = ExamManagement.SP.Questionpaper_SP_Selectall().GetDataSet();
        if (ds.Tables[0].Rows.Count > 0)
        {
            string a = RandomNumberGenerator(4);
            string b = RandomNumberGenerator(4);
            string c = RandomNumberGenerator(4);
            ExamManagement.SP.Passkey_insert(a, b, c).Execute();
        }
    }
    catch
    {
        throw; **// Exception Was Thrown Here**
    }



}
public static string RandomNumberGenerator(int length)
{
    System.Security.Cryptography.RandomNumberGenerator rng = System.Security.Cryptography.RandomNumberGenerator.Create();

    char[] chars = new char[length];

    //based on your requirment you can take only alphabets or number 
    string validChars = "aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStTuUvVwWxXzZ";

    for (int i = 0; i < length; i++)
    {
        byte[] bytes = new byte[1];
        rng.GetBytes(bytes);

        Random rnd = new Random(bytes[0]);

        chars[i] = validChars[rnd.Next(0, 61)];
    }

    return (new string(chars));
}
Posted

Your validChars string only has a length of 50, but you're asking for any index in the range of 0 to 60. You might want to try something like:

C#
chars[i] = validChars[rnd.Next(validChars.Length)];
 
Share this answer
 
C#
byte[] bytes = new byte[length-1];

for (int i = 0; i < length; i++)
{
    rng.GetBytes(bytes);

    Random rnd = new Random(bytes[0]);

    chars[i] = validChars[rnd.Next(0, 61)];
}
 
Share this answer
 
v2

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