ASP.net random number application instance

Source: Internet
Author: User
Tags random seed
Home users may have used Chinaren's transcript. Not long ago, the system added a method to its guestbook to prevent bumping, that is, every time the system generates an image consisting of random numbers and letters, you must enter these random characters correctly for each message. Otherwise, you cannot add a message. This is a good way to prevent malicious attacks. Its core technology is how to generate random numbers. Chinaren websites are implemented using PHP, and we can make full use of the powerful features of ASP.net to easily implement them.

In. net Framework, a class System. Random is provided to generate Random numbers. To use this class, you must import the System namespace. Of course, the namespace System is automatically imported on every ASP.net page, so we can directly use this class.

As we all know about random numbers, computers cannot generate completely random numbers. The so-called random number generator uses a certain algorithm to perform complex operations on the randomly selected seeds, use the generated results to simulate a completely random number, which is called a pseudo-random number. A pseudo-random number is selected from a finite number with the same probability. The selected number is not completely random, but from a practical point of view, the random degree is enough. The selection of pseudo-random numbers starts with the random seed. To ensure that each pseudo-random number obtained is "random", the selection of Random Seed is very important. If the random seed is the same, the random number generated by the same random number generator will also be the same. Generally, we use parameters related to system time as random seeds, which is also the default method used by the random number generator in. net Framework.

We can initialize a random number generator in two ways:

The first method does not specify the random seed. The system automatically selects the current time as the 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 this Random class object to generate a Random number. At this time, we need to use the Random. Next () method. This method is quite flexible. You can even specify the upper and lower limits of the generated random number.

If the upper and lower limits are not specified, use the following:

Int iResult;

IResult = ro. Next ();

The following code returns a random number less than 100:

Int iResult;

Int iUp = 100;

IResult = ro. Next (iUp );

The following code specifies that the returned value must be within the range of 50:


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 the Random. NextDouble () method to generate a Random double-precision floating point number ranging from 0.0 to 1.0:


Double dResult;

DResult = ro. NextDouble ();

Another one works with Random. the method similar to NextDouble () is Random. sample (), which corresponds to Random. the only difference between the NextDouble () method is the access level. Let's look at their original declarations:


Protected virtual double Sample ();

Public virtual double NextDouble ();

The Random. Sample () method is a protection method that only allows access to subclass objects. The Random. Sample () method can be viewed as a public version of Random. Sample. Generally, the user overwrites the Sample () method in the sub-class of Random to obtain a more general distribution. In this example, we use the Random. Next () method to generate a Random number.

The following function is the core of this example. We use it to generate a random int array:

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 have adopted a rather troublesome method to generate this random array. Why not simply use the following code? Let's take a look at the following code. Here we use the system time as the Random Seed to obtain 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); re = ro. 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">
</Head>

<Body bgcolor = "# FFFFFF" text = "#000000">
<Form runat = server>
<Asp: Label id = "RandomNum" runat = server/>

</Form>
</Body>
</Html>

The following is the result of my machine:

Yes, as you can see, two random numbers are generated, regardless of how many times they are repeated. Why?

Do not think that using the system time as a random seed is foolproof-if the application runs on a fast computer, the system clock of the computer may not have time to change between calls of this constructor, and the seed values of different Random instances may be the same. In this case, we need another algorithm to ensure the randomness of the generated numbers. Therefore, to ensure that the random number is "random", we have to use a more complex method to obtain random seeds.

In the above program, we first use the system time as the random seed, and then multiply the random number generated last time with the cyclic variable and an integer Parameter Related to the system time, as a Random Seed, different random seed is obtained each time, and a random number is generated.

After obtaining a random array of integers, we convert it into a string, and then use the class related to GDI + in System. Drawing to generate an image and display it on the webpage.

The code for generating the image's ASP.net page 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 = "";
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 image generation part is relatively complex, but it is not the subject of this article, so this article does not provide a detailed description, interested readers can refer to related content in the book "close contact with ASP.net" written by Du Liang.

Finally, we can write a common HTML page to view the effect. Just point the src attribute of the image to this page (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 = "">
</HEAD>

<BODY>

</BODY>

</HTML>

The following results are successfully displayed on the author's machine:

To implement the effects of malicious attacks like Chinaren, you only need to generate random numbers on the page of the message book and write the corresponding JavaScript verification code (in fact, this work can be easily done by the ASP.net verification control ), then, you can generate an image on the page that generates the image and prompt the user.

In addition, random numbers have many other purposes, especially when developing games. At this point, the reader should fully master the method for generating random numbers in ASP.net, so that the purpose of this article is achieved.

Finally, interested readers can try to solve this problem:

In a bridge game, licensing can be regarded as a random process, but the subsequent process is affected by the previous influence, that is, the cards that have been issued cannot be issued again. Write a program to simulate the licensing process.

Author: Unknown please contact me quickly

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.