Friday, September 16, 2016

Random Methods in ASP.NET

Random Class :


Random class in ASP.NET is used to generate pseudo-random numbers. 

Random numbers are numbers that has no specific sequence. It is useful in
some cases in Programming where we want to display results randomly.

Two constructors of Random class are the following :

(1) Random() which initializes the Random class using time dependent default
seed value.

(2) Random(Int32) which initializes the Random class using the specified integer 
seed value.

Random Methods :


(1) Next() which returns a non-negative random integer.
     For eg.

     Random ran = new Random();
     int i = ran.Next(); 

The output will be a positive random integer and it differs each time we run.

(2) Next(Int32) which returns a non-negative random integer less than the specified
     limit.
     For eg.

     Random ran = new Random();
     int i = ran.Next(10); 

The output will be a positive random integer less than 10.

(3) Next(Int32,Int32which returns a random integer between the specified
     limit which can be positive or negative integer values
     For eg.

     Random ran = new Random();
     int i = ran.Next(-3,3); 

The output will be a random integer between -3 and 3.

(4) NextBytes(Byte[]) which fills the elements of specified byte array with random
numbers.
For eg.

     Random ran = new Random();
     Byte[] b= new Byte[2];
     ran.NextBytes(b); 

This fills the elements of byte array with random numbers.

(5) NextDouble(which returns a random floating point number greater than or 
equal to 0.0 and less than 1.0
For eg.

     Random ran = new Random();
     double d = ran.NextDouble();

Samples using Random :


I will show one example by which a name is selected from an array list of names
on Button click in ASP.NET.

C# Code :

 protected void Button1_Click(object sender, EventArgs e)
 {
        string[] names = { "Mili", "Dia", "Mary", "Ria", "Tom", "John", "Abel" };
        int selectedindex = ran.Next(0, names.Length);
        Response.Write("Selected person is " + names[selectedindex]);
 }

Here we can see the output of single selected person which is picked randomly
from the array list and hence when each time it is run, we get different person.

Next I will show another example by which on each page load it will display
two featured Advertisements selected randomly on any part of a webpage in a
GridView.

C# Code :

protected void Page_Load(object sender, EventArgs e)
{
      DisplayAd();
}

protected void DisplayAd()
{
        Random rn = new Random();
        DataSet ds = new DataSet();
        string connectionString = ConfigurationManager.ConnectionStrings["conn"].ConnectionString;

        using (SqlConnection dbConnection = new SqlConnection(connectionString))
        using (SqlCommand dbCommand = new SqlCommand())
        {

            dbCommand.CommandText = "select * from Ads where featured=1";
            dbCommand.Connection = dbConnection;
            dbConnection.Open();

            SqlDataAdapter da = new SqlDataAdapter(dbCommand);
            da.Fill(ds);

        }
        int[] arr = new int[2];
        if (ds != null)
        {
            if (ds.Tables[0].Rows.Count > 0)
            {
                int selectedindex = ran.Next(0, ds.Tables[0].Rows.Count);
                arr[0] = selectedindex;
                int selectedindex2 = ran.Next(0, ds.Tables[0].Rows.Count);
                arr[1] = selectedindex2;
            }
        }
        for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
        {
            if (i != arr[0] && i != arr[1])
                ds.Tables[0].Rows[i].Delete();
        }
        GridView1.DataSource = ds;
        GridView1.DataBind();
}

Here when each time the page loads and also on refresh it will display two different
Advertisements randomly.

Notes :

In case of generating random numbers multiple times in an Application, it is 
always best to avoid multiple instantiations of Random class. That is, in such 
cases create one common object of a Random class  and use that same object in places 
where we require. This avoids repetitions and also improves performance as 
creating and initializing Random object is an expensive process.

Random classes are not thread safe and hence to be carefully handled when we
call Random methods from multiple threads. 

No comments:

Post a Comment