asp.net random Number application example

Source: Internet
Author: User
Tags current time datetime generator html page random seed tostring
Asp.net| Random | Application Examples Everyone may have used the Chinaren alumni, not long ago its guest book added a method to prevent irrigation, that is, each time the system produces a random number and letters of the picture, each message must correctly enter these randomly generated characters, otherwise can not add a message. This is a good way to prevent malicious attacks, the core of the technology is how to generate random numbers. Chinaren Web site is implemented using PHP, and we can make full use of the powerful features of ASP.net easily implemented.

?? A class System.Random specifically designed to generate random numbers is provided in the. NET Framework, and the System namespace must be imported when you use this class. Of course, the namespace system is automatically imported in every ASP.net page, so we can use this class directly.

?? For random numbers, we all know that computers can not produce completely random numbers, the so-called random number generators are through a certain algorithm for the selected random seed to do complex operations, with the resulting results to approximate the simulation of complete random numbers, this random number is called pseudo random number. Pseudorandom numbers are selected from a limited set of numbers with the same probability. The chosen number does not have complete randomness, but from a practical point of view, its random degree is sufficient. The selection of pseudorandom numbers starts from random seeds, so the selection of random seeds is very important in order to ensure that the pseudorandom numbers obtained are sufficiently "random". If the random seed is the same, then the random number generated by the same random number generator will be the same. Generally, we use parameters related to the system time as random seeds, which is the default method used by the random number generator in the. NET Framework.


?? We can initialize a random number generator in two ways:

?? The first method does not specify a random seed, and the system automatically selects the current time as a random seed:

?? Random ro = new Random ();


?? The second method can specify an int type parameter as a random seed:


?? int iseed=10;

?? Random ro = new Random (10);

?? Then we can use the object of this random class to generate random numbers, which means the Random.next () method is used. This method is quite flexible, and you can even specify the upper and lower limits of the random numbers that are generated.

?? Do not specify the following use of the upper and lower limits:

?? int Iresult;

?? Iresult=ro. Next ();


?? The following code specifies that a random number less than 100 is returned:

?? int Iresult;

?? int iup=100;

?? Iresult=ro. Next (IUP);

?? The following code specifies that the return value must be within the range of 50-100:


?? int Iresult;

?? int iup=100;

?? int idown=50;

?? Iresult=ro. Next (IDOWN,IUP);


?? In addition to the Random.next () method, the random class also provides a random.nextdouble () method to produce a random double-precision floating-point number ranging from 0.0 to 1.0:


?? Double Dresult;

?? Dresult=ro. Nextdouble ();


?? Another method similar to the Random.nextdouble () method is Random.sample (), which differs only from the Random.nextdouble () method in the access level, and we can look at their original declarations:


?? Protected virtual double Sample ();

?? Public virtual double nextdouble ();


?? The Random.sample () method is a protection method that only allows object access to subclasses, whereas the Random.sample () method can be considered a public version of Random.sample (). Generally, the user rewrites the sample () method in the random subclass to get a more general distribution.

?? In this example, we use the Random.next () method to produce random numbers.

?? The following function is the core of this example, and we use him to produce a random array of int:

private int []getrandomarray (int length,int up,int down) {int ifirst=0; int []rtarray=new int32[length]; Random ro=new Random (length*unchecked ((int) DateTime.Now.Ticks)); Ifirst=ro. Next (Up,down); Rtarray[0]=ifirst; for (int i=1;i

?? Readers may have noticed that we used a rather troublesome way to produce this random array, why not simply use the following code? Take a look at the code below, where we use the system time as a random seed to get two random numbers consecutively and output them:

<%@ Page language= "C #" debug= "true" Trace= "false" tracemode= "sortbycategory"% ><% @Import namespace= "System"% >
< script language=c# Runat=server >
public void Page_Load (Object Sender,eventargs e) {int re=0; int re1=0; Getrandomdefault (ref re); Getrandomdefault (ref Re1); Randomnum.text=re. ToString (); randomnum.text+= "" +re1. ToString ();} private void Getrandomdefault (ref int re) {Random ro=new Random unchecked ((int) DateTime.Now.Ticks)); Next (10,20);} private void Getrandombyint (ref byte []re) {Random ro=new Random (); Ro. Nextbytes (re);
</script >
< HTML >
< head >
< title > Random number Test </title >
< meta http-equiv= "Content-type" content= "text/html; charset=gb2312 ">

< body bgcolor= "#FFFFFF" text= "#000000" >
< form Runat=server >
< Asp:label id= "Randomnum" Runat=server/>

</form >
</body >


The following is a screenshot of the results produced on the author's machine:



?? Yes, as you can see, the same two random numbers are produced, no matter how many times they are repeated. What's the reason?



?? Do not assume that using system time as a random seed is foolproof?? If your application is running on a faster computer, the system clock for that computer may not have time to change between calls to this constructor, and the seed values for different instances of Random may be the same. In this case, we need another algorithm to ensure the randomness of the resulting numbers. So in order to ensure that the random numbers produced are "random" enough, we have to use a more complex method to obtain random seeds.


?? In the above procedure, we first use the system time as the random seed, then multiply the last random number with the cyclic variable and an integral parameter which is related to the system time, take it as the random seed, and get the random seed which is different at each time, so that the random number with enough "random" is produced.


?? When we get a random array of integers, we turn it into a string and then use the System.Drawing-related class to generate a picture and display it on the Web page.

The full code for the ASP.net page that generates the picture is as follows:


<%@ Page language= "C #" debug= "true" Trace= "false" tracemode= "sortbycategory"% ><% @Import namespace= " System.Drawing "% ><% @Import namespace=" System.Drawing.Imaging "% ><% @Import namespace=" System.Drawing.Text "% ><% @Import namespace=" System.IO "% >< script language=c# runat=server >
public void Page_Load (Object Sender,eventargs e) {string strnum=getrandomstring ();
String Strfontname;
int ifontsize;
int iwidth;
int iheight;
Strfontname= "Song Body";
ifontsize=12;
Iwidth=10*strnum.length;
iheight=25;

Color Bgcolor=color.yellow;
Color forecolor=color.red;

Font forefont=new font (strfontname,ifontsize,fontstyle.bold);

Bitmap pic=new Bitmap (IWIDTH,IHEIGHT,PIXELFORMAT.FORMAT32BPPARGB);
Graphics g=graphics.fromimage (Pic);
Rectangle r=new Rectangle (0,0,iwidth,iheight);

G.fillrectangle (New SolidBrush (bgcolor), R);

g.DrawString (strnum,forefont,new SolidBrush (ForeColor), 2,2);
MemoryStream mstream=new MemoryStream ();
Pic.save (mstream,imageformat.gif);
G.dispose ();
Pic.dispose ();

Response.clearcontent ();
Response.contenttype= "Image/gif";
Response.BinaryWrite (Mstream.toarray ());
Response.End ();
}
private int []getrandomarray (int length,int up,int down)
{
int ifirst=0;
int []rtarray=new int32[length];
Random ro=new Random (length*unchecked ((int) DateTime.Now.Ticks));
Ifirst=ro. Next (Up,down);
Rtarray[0]=ifirst;
for (int i=1;i< length;i++)
{
Random ri=new Random (i*ifirst*unchecked ((int) DateTime.Now.Ticks));
Rtarray[i]=ri. Next (Up,down);
Ifirst=rtarray[i];
}
return rtarray;
}


?? The part of the generated picture is relatively complex, but because it is not the subject of this article, so this article does not elaborate, interested readers can refer to Du Liang prepared "intimate contact asp.net" book related content.

?? Finally, we can write a normal HTML page to see the effect, just put the src attribute of the picture to the page on the line (here we assume that the above asp.net file name is "Randompic.aspx"):


<! DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 transitional//en" >
< HTML >
< head >
< TITLE > New Document </title >
< META name= "generator" content= "EditPlus" >
< META name= "Author" content= "" >
< META name= "Keywords" content= "" >
< META name= "Description" content= "" >

< BODY >
< img src= "randompic.aspx" >
</body >



?? The following results were successfully seen on the author's machine:



?? To achieve the effect of malicious attacks like the Chinaren Web site, simply generate random numbers in the guest book page and write the corresponding Java Script validation code (in fact this work can be done easily to ASP.net's validation controls), and then passed on to the page where the picture was generated to generate a picture prompting the user.

?? In addition, there are many other uses for random numbers, especially when developing games. To this end, the reader should fully master the method of generating random numbers in asp.net, so the purpose of this article is achieved.

?? Finally, interested readers can try to solve this problem:

?? In bridge games, licensing can be regarded as a random process, but the following process is affected by the previous, that is, the cards have been issued cannot be issued again. Try to write a program to simulate the licensing process.


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.