. NET Build Verification Code _ practical tips

Source: Internet
Author: User
Tags border color httpcontext rand sin

This article for everyone to share the. NET build verification code All code, we can do the operation, there will be unexpected harvest.

Let's take a look at the effect chart:

Page code:

 

Background code:

    <summary>///Login///</summary>///<param name= "sender" ></param> protect
    ed void Loginsubmits (object sender, EventArgs e) {checklogin (); #region Private Method #region public static Boolean isnotnull (Object str) {return!
    IsNull (str);
    public static Boolean IsNull (Object str) {return str = NULL; public static void Show (System.Web.UI.Page page, string msg) {page. Clientscript.registerstartupscript (page. GetType (), "message", "<script language= ' JavaScript ' Defer>alert ('" + MSG.
    ToString () + "');</script>"); #endregion private void Checklogin () {if (TbCheckCode.Text.Trim () = "") {Show (.
        "Verify code cannot be empty!");
      Return } else {if (Isnotnull (session["Validatecheckcode"])) {if (TbCheckCode.Text.Trim () != session["Validatecheckcode"].
            ToString ()) {Show (This, "Verify code is not filled out correctly!");
            Tbcheckcode.text = "";
          Return } else {Show (this, "Please refresh the verification code!")
          ");
        Return

 }}} #endregion}}

Generate Authenticode:

Using System;
Using System.Drawing;
Using System.Text;

Using System.Web; namespace Web.text {public partial class VerifyCode:System.Web.UI.Page {public Encoding GB = encoding.getencod

    ING ("GB2312");

      protected void Page_Load (object sender, EventArgs e) {Verifycode v = new Verifycode ();
      V.length = This.length;
      V.fontsize = this.fontsize;
      V.chaos = This.chaos;
      V.backgroundcolor = This.backgroundcolor;
      V.chaoscolor = This.chaoscolor;
      V.codeserial = this.codeserial;
      V.colors = this.colors;
      V.fonts = this.fonts;
      v.padding = this.padding; String code = V.createverifycode (); Take random code V.createimageonpage (code, this.) context); Output picture Response.Cookies.Add (new HttpCookie ("Checkcode", code. ToUpper ()));
      Using cookies to take the value of the verification code system.web.httpcontext.current.session["Validatecheckcode"] = code;
    return checkcode; 

    #region the length of the authentication code (the length of the default 4 authenticode) private int length = 4; Public inT length {get {return Length;}
    set {length = value;}

    #endregion #region Authenticode Font size (default 40 pixel for distortion effect, can be modified by itself) private int fontsize = 12;
      public int FontSize {get {return fontsize;}
    set {fontsize = value;}

    #endregion #region Border complement (default 1 pixels) private int padding = 1;
      public int Padding {get {return Padding;}
    set {padding = value;}

    #endregion #region Whether the output dryness point (default does not output) private bool chaos = true;
      public bool Chaos {get {return Chaos;}
    set {chaos = value;}

    #endregion the color of the #region output dryness point (default gray) Private color chaoscolor = Color.lightgray;
      Public Color Chaoscolor {get {return chaoscolor;}
    set {Chaoscolor = value;}

    #endregion #region Custom background color (default white) private color backgroundcolor = Color.White;
      Public Color BackgroundColor {get {return backgroundcolor;} set {BACKGROUNDCOlor = value; #endregion #region custom Random color array private color[] colors = {color.black, color.red, Color.dar

    Kblue, Color.green, Color.orange, Color.brown, Color.darkcyan, color.purple};
      Public color[] Colors {get {return Colors;}
    set {colors = value;}

    #endregion #region The custom font array private string[] fonts = {"Arial", "Georgia"};
      Public string[] Fonts {get {return Fonts;}
    set {fonts = value;}
    #endregion #region custom Random code string sequence (separated by commas) private string codeserial = "0,1,2,3,4,5,6,7,8,9"; String codeserial = "0,1,2,3,4,5,6,7,8,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 codeserial = "鸯, Yang, Yang, Sham, Yuyang, sheep, Yang, Yang, oxygen, Yang, itching, Foster, sample, Yang, invite, waist, demon, Yao, Shake, Yao, Yao, Yao, the kiln, the rumor, Yao, bite, scoop, medicine, to, Yao, coconut, choke, yes, ye, wild, ye, also, page, tuck, karma, leaf, drag , axillary, night, liquid, one, Yi, medical, Yi, iridium, Yi, Yi, yi, yi, zhi,,,, Miriam, pancreas, Doubt, Yi, Yi, aunt, Yi, chair, ant, leaning, has, B, Yi, Yi, Yi, 肄,,,,, Yi, Yat, yi, Yu, yi , benefit, Overflow, Yi, Yee, Yi, translate, vary, wing, Yan, Yan, Yin, yin,, Yin, tone, yin, marriage, yin, yin, adultery, yin, yin, Yun, lead, Yin, India, British, Cherry, Baby, Eagle, should, the Ying, Ying, the fly, Ying, win, Ying, Ying, Ying, hard, Ying, Yo, Yong, domestic helpers, 臃, Carbuncle, Yong, dance, pupa, Yong, swimming, Chung, Yong, waved, Yong , with, quiet, excellent, leisurely, worry, especially, by, mail, uranium, Judah, oil, swim, unitary, have, friends, right, Woo, glaze, lure, and, young, circuitous, siltation, in, Yu, Elm, Yu, fool, Yu, Yue, Yu, Yu, Fish, Yu, Chongqing, Fishing, corner, to, entertainment, rain, and, Yu, Yu, strains, spiders, Zhu , the pigs, the gods, the Kings, the Bamboos, the candles, the cooks, the Poles, the wills, the Lord, the pillars, the help, the borers, the storage, cast, build, live, note, wish, standing, grasping, claw, pull, special, brick, turn, compose, make, seal, pile, zhuang, outfit, makeup, bump, strong, shape, vertebra, cone, chase, weight, fall, prefix, Zhun, quasi , catch, humble, Zhuo, table, cut, grow, drink, peck, burn, Muddy, hereby, consult, finance, posture, AIDS, Zibo, cumin, violet, zi, seed, residue, son, self, stain, word, mane, brown, Trace, Zong, Ji, total, longitudinal, Zou, walk, play, beat, rent, foot, stroke, clan, ancestor, Curse, block, group, drill
    , compilation, mouth, intoxication, the most, sin, respect, compliance, yesterday, left, Zuo, Zuo, oak, do, make, sit, seat ";
      public string Codeserial {get {return codeserial;}
    set {codeserial = value;}
    #endregion//Generate waveform filter effect #region generate waveform filter effect Private Const double PI = 3.1415926535897932384626433832795;

    Private Const Double PI2 = 6.283185307179586476925286766559; /**////<summary>///sine wave distorted picture (Edit by 51aspx.com)///</summary>///<param name= "sr Cbmp "> Picture path </param>///<param name=" Bxdir "> If distorted then select true</param>///<param name=" Nmultvalu E "> Waveform amplitude multiples, the greater the degree of distortion of the higher, generally 3</param>///<paRam Name= "Dphase" > Waveform starting phase, value interval [0-2*pi) </param>///<returns></returns> public system.drawing.  Bitmap twistimage (Bitmap srcbmp, bool Bxdir, double dmultvalue, double dphase) {System.Drawing.Bitmap destbmp =

      New Bitmap (Srcbmp.width, srcbmp.height);
      Fills a bitmap background with white System.Drawing.Graphics graph = System.Drawing.Graphics.FromImage (destbmp); Graph.
      FillRectangle (New SolidBrush (System.Drawing.Color.White), 0, 0, destbmp.width, destbmp.height); Graph.

      Dispose (); Double Dbaseaxislen = Bxdir?

      (double) Destbmp.height: (double) destbmp.width;
          for (int i = 0; i < Destbmp.width. i++) {for (int j = 0; J < Destbmp.height; J +) {
          Double dx = 0; DX = Bxdir?
          (Pi2* (Double) j)/dbaseaxislen: (pi2* (double) i)/dbaseaxislen;
          DX + + dphase;

          Double dy = math.sin (dx);
          Gets the color of the current point int noldx = 0, Noldy = 0; NOLDX = Bxdir? i + (int) (DY*DMULtvalue): i; Noldy = Bxdir?

          J:j + (int) (dy*dmultvalue);
          System.Drawing.Color Color = Srcbmp.getpixel (i, j); if (noldx >= 0 && noldx < destbmp.width && noldy >= 0 && Noldy < DestBmp.H
          Eight) {Destbmp.setpixel (NOLDX, noldy, color);
    }} return destbmp; 
      #endregion #region generate the checksum code picture public Bitmap Createimagecode (string code) {int fsize = fontsize;

      int fwidth = fsize + Padding; int imagewidth = (int) (code.
      Length*fwidth) + 4 + padding*2;

      int imageheight = fsize*2 + Padding;

      System.Drawing.Bitmap image = New System.Drawing.Bitmap (imagewidth, imageheight);

      Graphics g = graphics.fromimage (image);

      G.clear (BackgroundColor);

      Random rand = new Random (); Add a randomly generated dryness point to the background if (this.
        Chaos) {Pen pen = new Pen (chaoscolor, 0);

        int c = length*10; FoR (int i = 0; i < C; i++) {int x = rand. Next (image.
          Width); int y = rand. Next (image.

          Height);
        G.drawrectangle (pen, x, Y, 1, 1);

      } int left = 0, top = 0, Top1 = 1, top2 = 1;
      int n1 = (imageheight-fontsize-padding*2);
      int n2 = N1/4;
      Top1 = n2;

      TOP2 = n2*2;
      Font F;

      Brush b;

      int CIndex, Findex; #region The validation code character for the random font and color for (int i = 0; i < code. Length; i++) {cindex = rand.
        Next (colors.length-1); Findex = Rand.

        Next (fonts.length-1);
        f = new System.Drawing.Font (Fonts[findex], fsize, System.Drawing.FontStyle.Bold);

        b = new System.Drawing.SolidBrush (Colors[cindex]);
        if (i%2 = = 1) {top = TOP2;
        else {top = TOP1;

        left = I*fwidth; g.DrawString (code.
      Substring (i, 1), F, B, left, top); //Draw a border border color for Color.gainsboro G.drawrecTangle (New Pen (Color.gainsboro, 0), 0, 0, image. Width-1, image.
      HEIGHT-1);

      G.dispose ();

      Generates waveform//image = Twistimage (image, True, 8, 4);
    return image; #endregion//Output The created picture to the page public void Createimageonpage (string code, HttpContext context) {Syst Em. Io.
      MemoryStream ms = new System.IO.MemoryStream (); Bitmap image = this.

      Createimagecode (code); Image.

      Save (MS, System.Drawing.Imaging.ImageFormat.Jpeg); Context.
      Response.clearcontent (); Context.
      Response.ContentType = "Image/jpeg"; Context. Response.BinaryWrite (Ms.

      GetBuffer ()); Ms.
      Close ();
      ms = NULL; Image.
      Dispose ();
    image = NULL;
      #endregion #region Generate random character code public string Createverifycode (int codelen) {if (Codelen = 0)
      {Codelen = Length;

      } string[] arr = codeserial.split (', ');

      String code = "";

      int randvalue =-1; Random rand = new Random (Unchecked (inT)) (DateTime.Now.Ticks)); for (int i = 0; i < Codelen i++) {randvalue = rand. Next (0, arr.

        LENGTH-1);
      Code + + Arr[randvalue];
    } return code;
    public string Createverifycode () {return createverifycode (0);
 } #endregion}}

is not very fulfilling, for everyone to share the code is very complete, you can expand on this basis, I hope you like.

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.