In my last article – Creating a Captcha Control – Part 1, I discussed on the front end of the user control that creates the captcha. In this article, I will discuss on the code-behind of the control – that is, what properties are set and how and what methods are used.
The following code shows the properties that are used.
- #region field initialisation
- public Captcha cc;
- private int captchaLength;
- private double fontSize;
- private string fontFamily;
- private string backgroundImagePath;
- private string textColor;
- private string successMessage;
- private string errorMessage;
- private string characterSet;
- #endregion
Then, the setters and getters for these properties are created as per below.
- #region GetterSetter
- public string TestButtonText
- {
- get { return B1.Text; }
- set { B1.Text = value; }
- }
- public string SpeakButtonText
- {
- get { return BSpeak.Text; }
- set { BSpeak.Text = value; }
- }
- public string ReLoadButtonText
- {
- get { return B2.Text; }
- set { B2.Text = value; }
- }
- public string SuccessMessage
- {
- get { return successMessage; }
- set { successMessage = value; }
- }
- public string ErrorMessage
- {
- get { return errorMessage; }
- set { errorMessage = value; }
- }
- public int CaptchaLength
- {
- get { return captchaLength; }
- set
- {
- try
- {
- int k = Convert.ToInt32(value);
- if (k < 5 || k > 10)
- captchaLength = 6;
- else
- captchaLength = k;
- }
- catch (Exception ex)
- {
- captchaLength = 6;
- }
- }
- }
- public string FontFamily
- {
- get { return fontFamily; }
- set
- {
- if (value != string.Empty && value != null)
- fontFamily = value;
- else
- fontFamily = "Arial";
- }
- }
- public double FontSize
- {
- get { return fontSize; }
- set
- {
- try
- {
- fontSize = Convert.ToInt32(value);
- if (fontSize <= 10 && fontSize >= 24)
- fontSize = 16;
- }
- catch (Exception ex)
- {
- fontSize = 16;
- }
- }
- }
- public string BackgroundImagePath
- {
- get { return backgroundImagePath; }
- set
- {
- if (System.IO.File.Exists(Server.MapPath(value)))
- backgroundImagePath = value;
- else
- backgroundImagePath = System.Configuration.ConfigurationManager.AppSettings["defaultImagePath"];
- }
- }
- public string TextColor
- {
- get { return textColor; }
- set
- {
- if (value == string.Empty || value == null)
- textColor = "Black";
- else
- textColor = value;
- }
- }
- public string CharacterSet
- {
- get { return characterSet; }
- set
- {
- if (value == "" || value == null)
- characterSet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ123456789";
- else
- characterSet = value;
- }
- }
- #endregion
The setters and getters are quite straight forward. The captcha length property defaults to 6 in case the value entered is not a number and if the value is less than 6 or greater than 10.
The default font family is set to Arial.
The default font size is set to 16. If fonts are too small – less than 10px – or too large – greater than 24px – the font is automatically set to 16.
The default colour is set to black.
The default character set consists of all letters in uppercase and number from 1 to 9. I have not included lower case letters and 0 as these are sometimes confusing.
The default background image is set within the web.config file. Note that the background image is expected to be within the solution and would require “~” notation to work properly.
Now, in the Page_Load event shown below, I am setting the default values and loading the captcha.
- protected void Page_Load(object sender, EventArgs e)
- {
- B1.Text = TestButtonText;
- B2.Text = ReLoadButtonText;
- BSpeak.Text = SpeakButtonText;
- SetValues();
- cc = GetCaptchaClass();
- if (!IsPostBack)
- {
- LoadCaptcha();
- }
- }
As can be seen, the Button’s text are set a SetValues method is called which sets values for other properties and the method – LoadCaptcha is called if it is not a postback. Another class Captcha is set to method GetCaptchaClass which initiates a Captcha object. I will talk about the Captcha object in a little while.
The SetValues method is below.
- private void SetValues()
- {
- if (CharacterSet == null)
- CharacterSet = "";
- if(CaptchaLength == 0)
- CaptchaLength = 6;
- if(BackgroundImagePath == null)
- BackgroundImagePath = "";
- if(FontFamily == null)
- FontFamily = "";
- if(FontSize == 0)
- FontSize = 0.0;
- if(TextColor == null)
- TextColor = "";
- }
The LoadCaptcha method is interesting – it creates random text and adds it ViewState and Session, adds the Captcha object to Session and sets the path of the Image control to CaptchaHandler.ashx handler. The code for this method is below.
- private void LoadCaptcha()
- {
- string text = GetRandomText();
- ViewState.Add("captcha", text);
- Session.Add("CaptchaClass", cc);//add captcha object to Session
- Session.Add("captcha", text);//add captcha text to session
- Im1.ImageUrl = "CaptchaHandler.ashx";
- }
The random text for the captcha is generated by GetRandomText method which basically creates random text based on the CharacterSet property. The code for this method is below.
- private string GetRandomText()
- {
- char[] letters = CharacterSet.ToCharArray();
- string text = string.Empty;
- Random r = new Random();
- int num = -1;
- for (int i = 0; i < this.CaptchaLength; i++)
- {
- num = (int)(r.NextDouble() * (letters.Length - 1));
- text += letters[num].ToString();
- }
- return text;
- }
The Captcha class basically properties for the captcha text. The GetCaptchaClass method initiates the Captcha class and set its properties. The code for this method is below.
- private Captcha GetCaptchaClass()
- {
- if (Session["CaptchaClass"] != null)
- cc = (Captcha)Session["CaptchaClass"];
- else
- cc = new Captcha();
- cc.FontSize = this.FontSize;
- cc.FontFamily = this.FontFamily;
- cc.BackgroundImagePath = this.BackgroundImagePath;
- cc.TextColor = this.TextColor;
- return cc;
- }
That’s pretty much all the methods for the user control. When the Reload Button is clicked the LoadAnother method is run that simply calls the LoadCaptcha method as per below.
- protected void LoadAnother(object sender, EventArgs e)
- {
- LoadCaptcha();
- }
When the Test button is clicked, the ValidateCaptcha method is run that compares the text entered with the text in the ViewState. The code is below.
- protected void ValidateCaptcha(object sender, EventArgs e)
- {
- string text = T1.Text;
- if (text == (string)ViewState["captcha"])
- LStatus.Text = SuccessMessage;
- else
- LStatus.Text = ErrorMessage;
- }
In my next article, I will explain how the reading out the captcha text works. The captcha control is also available for download from CodePlex at http://captchadotnet.codeplex.com/
0 comments:
Post a Comment