ASP.NET to implement Web controls for verification code features

xiaoxiao2021-03-06  16

ASP.NET design and design concepts and others such as ASP, JSP, PHP, Perl

Almost different, almost completely object-oriented design! The multiplexing of the code is

One of the large differences in the difference, ASP.NET is available in addition to include in Include

Amazing web control, including: ASCX form and controlled control

This article belongs to the latter], in order to familiarize yourself with these new concepts, I wrote a web control.

It will continue to improve in the actual project.

How to use the ValidateCode control:

first step:

Compile I provide the original code, then on the Studio.Net 2003 toolbar, select Add / Transfer (Subscription ", select the compiled DLL file.

Step 2:

There will be more web control validatecode on the toolbar, do a web form, on the Studio.Net 2003 development interface, drag the control directly to Webform, OK!

third step:

Get the character information of the verification code in the Graphicok event of the control, it is compared to the user!

last step:

Under the root of the website, build a TEMP directory (you can also specify your own directory), used to store the verification code

Image, don't worry, the code will automatically delete the useless picture!

The original code is as follows:

using System; using System.Web.UI; using System.Web.UI.WebControls; using System.ComponentModel; using System.IO; using System.Drawing; using System.Drawing.Drawing2D; using System.Drawing.Imaging;

Namespace WebValidatecode {///

/// validatecode's summary description. /// Designer: Wang Haibo 2004-11-20 /// /// public enum graphictype {jpg = 0, GIF = 1, PNG = 2, BMP = 3,}

//[ToolboxBitmap(@"D:/DotnetApp/ValidateCode/ValidateCode.bmp ")] // set the control icon public class ValidateCode in the toolbox: System.Web.UI.WebControls.WebControl, INamingContainer {private int pCodelen = 5; private int pChartwidth = 100; private int pChartHeight = 20;

Private graphictype pcharttype; private stringpauthencode;

private string pTempImageURLPath = "/ temp"; private string pAuthenImageFullname; private string pAuthenImageFullURL; // check code generating variable start private Bitmap validateImage; private Graphics g; // check code generating variable End

private TextBox txt = new TextBox (); private System.Web.UI.WebControls.Image img = new System.Web.UI.WebControls.Image (); # region defines the control events public delegate void GraphicCreated (object sender, EventArgs e) Public Event EventHandler Graphicok; // Triggered after the check image generation

Protected Virtual Void ONGRAPHICOK (Object Sender, Eventargs E) {IF (graphicok! = null) {// invokes the delegates. Graphicok (Sender, e);}} #endregion #Region control property // Generate the length of the check code [ Bindable (True), Browsable (TRUE), Category ("Appearance"), DefaultValue (TRUE), Description ("Requires the length of the verification code, it is recommended between 5 ~ 8 digits!")] Public int codelength {get {Return Pcodelen;

Set {pcodelen = value;}}

/ / Generate the length of the check code [Bindable (TRUE), Browsable (True), Category ("Appearance"), DefaultValue (TRUE), Description ("Generates the temporary storage path of the verification code picture, the requirements must be the virtual website Directory! ")] Public string tempimageurlpath {get {return pTEMPIMPIMPIMEURLPATH;

Set {ptempimageurlpath = value;}}

[Bindable (True), Browsable (TRUE), Category ("APPEARANCE"), DefaultValue (GraphiType.jpg), Description ("Select the type of generated checkup file (JPG; GIF; PNG; BMP)!")] Public GraphicType ChartType {get {return pCharttype;

Set {pChartType = value;}}

/ / Generate the width of the code code PUBLIC INT ChartWidth {Get {Return PCHARTWIDTH;

Set {pChartWidth = value;}}

{Get {Return PChartHeight;

Set {pChartHeight = value;}}

/ / Need to generate the check code public string authencode {get {returnparthhencode;}

Set {pauthencode = value;}}

#ndregion

///

/// presented this control to the specified output parameter. /// /// HTML writer to be written protected override void render (htmltextwriter output) {system.web.ui.webcontrols.image objimage; // textbox objtxt; // Draw the included control objimage = (system.web.ui.webcontrols.image) Controls [0]; // objtxt = (textbox) Controls [1]; if (PAUTHENCODE == null) PAUTHENCODE = GetValidatecode (); ONGRAPHICOK (this, Eventargs.empty); getrandomimage; objimage.Imageurl = PauthenImageFullurl; Objimage.RenderControl (Output);}

///

/ // protected override void createchildControls (); controls.add (img); //controls.add (iv); //controls.add (iv); TXT); }

///

/// Control LOAD Attribute Initial /// /// protected override void online (system.eventargs e) {ERASEOLDGRAPHIC ( ); // Delete expired pictures}

///

/// Generate random /// private void makerandomfilename () {string strrandname = datetime.now.ticks.tostring () ". jpg"; pauthenimagefullname = this.page.mAppath (TempimageURLPATH) @ "/" StrrandName; PAUTHENIMAGEFULLURL = TempimageURLPATH "/" STRRANDNAME;

Private void getrandomage (String strign) {// generates full name, and full url manetAndomfileName ();

ValidateImage = New Bitmap (PCHARTWIDTH, PCHARTHETIGHT, PIXELFORMAT.FORMAT24BPPRGB); // .format24bpprgb); g = graphics.fromimage (validateImage); g.clear (color.lightgray);

//g.drawstring( 4TrValidatecode, New Font ("Song", 16, FontSty.Bold, New Solidbrush (Color.darkRed), New Pointf (2, 2)); for (int i = 0; i

//g.fillRectangle (New Point (0, 0), New Point (120, 30), Color.Fromargb (0, 0, 0), Color.Fromargb (255, 255, 255, 255)), 0, 0, 120, 30); Switch (PCHARTTYPE) {copy graphictype.jpg: validateImage.save (PauthenImageFullname, Imageformat.jpeg); Break; Case GraphicType.gif:

ValidateImage.save (PauthenImageFullname, Imageformat.gif); Break;

Case graphictype.png:

ValidateImage.save (PauthenImageFullname, Imageformat.png); Break; Case GraphicType.bmp:

ValidateImage.save (PauthenimageFullname, Imageformat.bmp); Break; default: validateImage.save (PauthenImageFullname, Imageformat.jpeg); Break;} validateImage.dispose ();

g.dispose ();

///

/// Dynamic selection from the elements of numbers and letters to generate a check code /// private string getValidatecode () {char [] s = new char [] {'0' , '1', '2', '3', '4', '5', '9', 'A', 'B', 'C', ' D ',' E ',' F ',' G ',' H ',' I ',' J ',' K ',' L ',' M ',' N ',' O ',' P ' , 'q', 'r', 's',' t ',' u ',' V ',' W ',' X ',' Y ',' Z ',' A ',' B ',' C ',' D ',' E ',' F ',' G ',' H ',' I ',' J ',' K ',' L ',' M ',' N ',' O ' , 'P', 'q', 'r', 's', 't', 'u', 'V', 'W', 'x', 'Y', 'Z'}; String Num = " "; Random R = new random (); // Defines the number of digits of the verification code according to the length required by the user (INT i = 0; I

///

/// Clear time More than 20 seconds temporary picture record /// /// successfully returns true, failed to return false public bool EraseOLDGRAPHIC () {

try {DirectoryInfo Dinfo = new DirectoryInfo (this.Page.MapPath (pTempImageURLPath)); FileInfo [] FileSet; if (Dinfo.Exists) {switch (pChartType) {case GraphicType.Jpg: FileSet = Dinfo.GetFiles ( "* jpg. "); Break; Case GraphicType.gif:

FileSet = DINFO.GETFILES ("*. GIF"); Break;

Case graphictype.png:

FileSet = DINFO.GETFILES ("*. Png"); break; case graphictype.bmp: fileset = dinfo.getfiles ("*. Bmp"); break; default: fileset = DINFO.GETFILES ("*. Jpg"); Break;

Foreach (fileInfo fileInfo in fileset) {if (fileinfo.exists) {datetime dts = datetime.now; datetime dtc = fileinfo.creationTIME;

Timespan TS = DTS-DTC; IF (ts.seconds> 20) {fileInfo.delete ();}}}}

Return true;} catch (ioexception ie) {returnif value;}}}}

转载请注明原文地址:https://www.9cbs.com/read-45141.html

New Post(0)