Wednesday 11 March 2015

Captcha Control - Create your own Captcha to use it in your SharePoint Visual WebPart.



Create your own Captcha to use it in your SharePoint Visual WebPart.

I create a Captcha string using some random numbers and texts. Then I create a BitmapImage from the Captcha string to show it into my WebPart. I use ViewState to preserve Captcha string value after the user clicks the Submit button.

Add the below Panel control to the VisulaWebPart.ascx

<asp:Panel id="Captcha" CSSClass="MyCaptcha" Visible="False"  runat="server">
  <asp:Label ID="LblCaptcha" runat="server" CssClass="LabelQT" Text="Please confirm you are human by typing the text you see in the image."></asp:Label>
  <img runat="server" id="imgCtrl" />
  <asp:ImageButton ID="RefreshCaptcha" runat="server" CssClass="BtnRefresh" ImageUrl="../_layouts/15/images/Refresh.png" OnClick="RefreshCaptcha_Click"  Width="39px" />
   <asp:TextBox ID="TBoxChapctha" CSSClass="TxtBoxChapctha" Text="" runat="server" AutoPostBack="False"></asp:TextBox>
</asp:Panel>

Then in VisulaWebPart.ascx.cs add the below refrences

using System.Drawing.Drawing2D;
using System.Drawing.Text;
using System.Resources;


Then add 2 global stringsas below

string Chaptcha1, CaptchaT;

And add the below public procedure:
public void DrowChaptcha2()
        {

            Random rnd = new Random();
            int a = rnd.Next(1, 9);
            int b = rnd.Next(1, 9);
            int d = rnd.Next(0, 25);
            char letter = (char)('a' + d);
            int c = rnd.Next(1, 9);

            Chaptcha1 = "  " + a + " " + b + "  " + letter + "  " + c + " ";
            CaptchaT = Chaptcha1.Replace(" ", String.Empty);
            ViewState["CaptchaTVS"] = CaptchaT;

            Bitmap BitmapCaptcha = CreateBitmapImage(Chaptcha1);
            MemoryStream ms = new MemoryStream();
            BitmapCaptcha.Save(ms, ImageFormat.Gif);
            var base64Data = Convert.ToBase64String(ms.ToArray());
            imgCtrl.Src = "data:image/gif;base64," + base64Data;

        }
_____________________________________________________________________________________________
In the Page_Load(object sender, EventArgs e) , check the ViewState as below:
protected void Page_Load(object sender, EventArgs e)
        {
            if (Page.IsPostBack)
            {
                if (ViewState["CaptchaTVS"] != null)
                {
                    CaptchaT = (string)ViewState["CaptchaTVS"];                
                }
                else
                {
                    CaptchaT = "Not Set";
                }
            }

            if (!Page.IsPostBack)
            {
                DrowChaptcha2();             
               
            }
}
_____________________________________________________________________________________________
In the Submit Click add the below code:
protected void Submit_Click(object sender, EventArgs e)
        {
            string CaptchaB;
            bool CaptchaOK = false;
            CaptchaB = TBoxChapctha.Text;
            CaptchaB = CaptchaB.Replace(" ", String.Empty);
           
          
            if (CaptchaT == CaptchaB)
            {              
                CaptchaOK = true;               
            }
            else
            {
                CaptchaOK = false;

            }
       
           if (!CaptchaOK)
            {
                ValidationLbl.Text = ValidationCaptchaTxt;
                ValidationLbl.Visible = true;
            } else
            {
                 Do Something ...       
            }
        }
_____________________________________________________________________________________________

Here is the code to refresh Captcha:
protected void RefreshCaptcha_Click(object sender, ImageClickEventArgs e)
        {           
            DrowChaptcha2();
        }
And here is the code to create a BitmapImage from the Captcha string and show it into our Visual WebPart.

 private Bitmap CreateBitmapImage(string sImageText)
        {
            Bitmap objBmpImage = new Bitmap(1, 1);

            int intWidth = 0;
            int intHeight = 0;

            // Create the Font object for the image text drawing.
            Font objFont = new Font("Arial", 20, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Pixel);

            // Create a graphics object to measure the text's width and height.
            Graphics objGraphics = Graphics.FromImage(objBmpImage);

            // This is where the bitmap size is determined.
            intWidth = (int)objGraphics.MeasureString(sImageText, objFont).Width;
            intHeight = (int)objGraphics.MeasureString(sImageText, objFont).Height;

            // Create the bmpImage again with the correct size for the text and font.
            objBmpImage = new Bitmap(objBmpImage, new Size(intWidth, intHeight));

            // Add the colors to the new bitmap.
            objGraphics = Graphics.FromImage(objBmpImage);

            // Set Background color
            objGraphics.Clear(Color.White);
            objGraphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
            objGraphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;
            objGraphics.DrawString(sImageText, objFont, new SolidBrush(Color.FromArgb(102, 102, 102)), 0, 0);
            objGraphics.Flush();

            return (objBmpImage);
        }


You can Change the above code to make your Captcha look different. Here is how my Captcha looks like. 
 

2 comments: