Adding CAPTCHA In ASP.NET Application

26. December 2010 01:44

API ASP.NET 

Using CAPTCHA was never easy for me before I got a class from an unknown user on a community forum post. I have just re-used the class to get my work done. The class is extremely easy to use and let you incorporate the CAPTCHA into your application in just few lines of code.

You can set the height and width of the CAPTCHA image while initializing the CAPTCHA class. The CAPTCHA image generated from the class can be set to the image control directly or it can be save to the local path and then set to the image control. For this example I am saving it to the local path and then set to the image control. And the CAPTCHA image code generated by the class is automatically set to the session variable named CaptchaCode.

Time to get some hand on it

On the page get an image control to display CAPTCHA image, a textbox where user will enter the CAPTCHA text and a button when clicked, we can check and validate if the code entered is correct or not. Plug the DLL in your ASP.NET project and go to the Page_Load event. Here we will generate the image of the height and width we wish to have for out CAPTCHA image and then save the image to the CaptchaImages folder with the random image code generated. The code on the Page_Load event goes like this:

 protected void Page_Load(object sender, EventArgs e)
{
        if (!Page.IsPostBack)
        {
            CaptchaImage cImage = new CaptchaImage(CaptchaImage.generateRandomCode(), 140, 40);
            cImage.Image.Save(Server.MapPath("~\\CaptchaImages\\" + Convert.ToString(Session["CaptchaCode"]) + ".jpg"), ImageFormat.Jpeg);
            CaptachaImage.ImageUrl = "~\\CaptchaImages\\" + Convert.ToString(Session["CaptchaCode"]) + ".jpg";
            cImage.Dispose();
        }
        CaptchaCode = Convert.ToString(Session["CaptchaCode"]);
}

Before you can use the above code, declare a public variable which I have used to hold the value of the CAPTCHA code. I named it CaptchaCode. You can name it whatever you like it. We will be using this variable later to check it against the user input. Hit F5 to start and test your application. If everything is in place and you will be able to see the below output.

To check if the user enters the correct CAPTCHA code, we must have an event on button click which will validate the user input and prompt the user if CAPTCHA code is correct or incorrect. The code on the button click is:

protected void btn_Validate(object sender, EventArgs e)
{
        if (CaptchaCode == txt_ccode.Text)
        {
            ClientScript.RegisterClientScriptBlock(typeof(Page), "ValidateMsg", "<script>alert('You entered Correct CAPTCHA Code!');</script>");
        }
        else
        {
            ClientScript.RegisterClientScriptBlock(typeof(Page), "ValidateMsg", "<script>alert('You entered INCORRECT CAPTCHA Code!');</script>");
        }
}

The above code will check the CAPTCHA code entered by the user and check against the CAPTCHA code we previously saved in the session variable (CaptchaCode). If the validation is a success, user will get the message notifying him that he enters correct CAPTCHA code or the error message otherwise.

And that's it, we have successfully implement a CAPTCHA in our ASP.NET application. So, here are few things we can do with this CAPTCHA library:

  • Set image height and width.
  • Saves the image to the local path.
  • Automatically sets the generated CAPTCHA code to the application session.

I have build the sample project in ASP.NET 4.0, if you wanted to use the library in ASP.NET 3.x, then compile the project with lower version of ASP.NET and it will work perfectly. The below zip file contains both the projects.

Download: Captcha.NET.zip (377.63 kb)

Currently rated 3.8 by 19 people

Autocomplete With jQuery and ASP.NET

19. December 2010 01:46

ASP.NET C# Jquery 

Building auto-complete feature with jQuery is easy and you can build this in no time. It's your wish if you want to use ADO.NET or EF (LINQ) to get this done, it works great for all. The sample application I build is using both ADO.NET and EF. So let's begin up getting files under one hood.

Use the below live links for jQuery auto-complete and CSS.

<link rel="stylesheet" href="http://dev.jquery.com/view/trunk/plugins/autocomplete/jquery.autocomplete.css" type="text/css" />
<script type="text/javascript" src="http://dev.jquery.com/view/trunk/plugins/autocomplete/jquery.autocomplete.js"></script>

You can also download these files and use them in your project, if you are planning to run your application offline. For this demonstration, I have downloaded the files. I am using both ADO.NET and LINQ to auto-complete with jQuery auto-complete pug-in.

Starting up with ADO.NET, as we were/are using this for so many years now and therefore there should be no problem for anyone using it. Simple page behind code to get the full list of countries in the world (I hope I have all of them) and seperate each country name with a '|' pipe symbol so I can split countries name and set it to the text box for auto-complete.

 public partial class _Default : System.Web.UI.Page
    {
        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["constr"].ConnectionString);
        SqlCommand cmd;
        SqlDataReader dr;

        public string Listcountries;

        private string countryName()
        {

            StringBuilder sb = new StringBuilder();
            cmd = new SqlCommand("Select country_name from Country order by country_name", con);
            con.Open();
            dr = cmd.ExecuteReader();

            while (dr.Read())
            {
                sb.Append(Convert.ToString(dr[0] + "|"));
            }

            return Convert.ToString(sb);
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            Listcountries = countryName();
        }
    }

Done with code behind and now only requires few lines of client script on the page to get the auto-complete running.

<script type="text/javascript">
        $(document).ready(function () {
            var cc = '<%=Listcountries%>'.split("|");
            $("#autoText").autocomplete(cc);
        });
</script>

The same can be done with LINQ but the jQuery script part will be the same.

public partial class AutocompleteLINQ : System.Web.UI.Page
    {
        DeveloperDBEntities db = new DeveloperDBEntities();
        public IQueryable countries;
        public string Listcountries;

        protected void Page_Load(object sender, EventArgs e)
        {
            countries = from c in db.Countries select c;
            foreach (Country cobj in countries)
            {
                Listcountries += cobj.Country_Name + "|";
            }
        }
    }

Just for your ease to use this project as it is, I have included the SQL scripts for the country table. Hope this helps you in building another great or a part of your application.

Downalod: JqueryAutoComplete.zip (210.73 kb)

Currently rated 3.3 by 6 people

Extending OpenID Implementation With ASP.NET: User Information / Roles and Membership

25. September 2010 22:21

API ASP.NET 

Last month I have blogged on how you can integrate OpenID login support in your ASP.NET aplication. Some of the reader requested me that it would be better if I could show how you can implement membership and roles with OpenID authentication. It doesn't seems easy in the first place, because you will require a bit more informaton from the user like his name and e-mail address. So, what I am trying to show you here is how you can gather information of the user who has logged in with OpenID and then you can use that information to set roles and membership for your website. I am just extending the old sample project from my previous post to show you how you can get some of the basic information of the user including their e-mail address.

I assume you have downloaded the complete solution from my previous post with OpenID login support, download here if you haven't yet. There is nothing new to be added in the application, instead we just need to change some properties of the OpenID control we have used. Click the control and press F4 to get the properties up. Set the properties to "Request" to make sure that whenever a user sign-in with OpenID the API also makes a request to the service provider to get the information of the user signing in. I have request some of the basic information of the user by making them "Request". It all depends on the author of the code what information he wants to see/require when the user gets logged in.

Now as you have set the properties, it's time to make a request to the provider and get the infromation. You need to do something special to get the details, sign-in as normally you would have done, but notice while re-directing the page URL will be something like this (only for a while):

.............&openid.sreg.required=&openid.sreg.optional=nickname%2Cfullname%2Cdob%2Cgender%2Ccountry

Notice the last few options in the query string is requesting the parameters we have "Requested". But you should also know that the values will be null if the user has not filled up his Persona (Personal Details). If you try to fetch the details of the user, you will get a null value. So, it's pretty necessary that the user who has logged in using the OpenID should have his personal details filled up at the provider's end. This is how my personal details look like at OpenID (website) login.

 

Personas are actually the information of the user which will be delivered to the site or application where the user has logged in using OpenID. You can add/modify/delete a personas. Once you have the persona of the logged in user you can:

  • Set the OpenID control to request the details of the users instead of providing the user to fill out a long registration form.
  • Save the values to the database for future use.
  • Use the information for setting Roles and Membership for your application.

I've already demonstrate in the above steps on how to set the OpenID user control to request the user details or personas.

What else I need to do

In Visual Studio, select the OpenID control and press F4 to get the properties. Under method section double-click the LoggedIn method (The method name describes itself).

 

In this method, read the response and set it to the session variable. Give a name to the sesison variable.

protected void OpenIdLogin1_LoggedIn(object sender, DotNetOpenAuth.OpenId.RelyingParty.OpenIdEventArgs e)
{
        Session["OpenID"] = e.Response;
}

When the user is successfully authenticated by the provider, user is re-directed to the default home page. Therefore, we need to handle the response on the home page. Add these two namespaces on the page code-behind.

using DotNetOpenAuth.OpenId.RelyingParty;
using DotNetOpenAuth.OpenId.Extensions.SimpleRegistration;

I am using the page load method so as to get the details and display it front of the user, you can also set the same details to fill up a registration form. To read the response from the session variable use the IAuthenticationResponse to read store the session value and then read it with GetResponse<ClaimResponse> method. Below is the complete code for your default.aspx page or the page you want the user to be re-directed. I have store the values in the public variables as I want to show the user details on the default page.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DotNetOpenAuth.OpenId.RelyingParty;
using DotNetOpenAuth.OpenId.Extensions.SimpleRegistration;
namespace DOTNETOAUTH
{
    public partial class _Default : System.Web.UI.Page    
    {
        IAuthenticationResponse OResponse;
        public string UserName = string.Empty;
        public string Gender = "No Gender Specified";
        public string Country = string.Empty;
        public string Nick = string.Empty;
        public string Bday = string.Empty;

        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                OResponse = (IAuthenticationResponse)Session["OpenID"];
                var details = OResponse.GetExtension<ClaimsResponse>();
                UserName = details.FullName;
                //email = details.Email;
                Gender = details.Gender.ToString();
                Country = details.Country;
                Nick = details.Nickname;
                Bday = details.BirthDate.ToString();
            }
            catch { }
        }
    }
}

If any of the above values are not present in the user persona , it will result in an error, so make sure you have handle the exceptions properly. This is it, once you have the details you can use to store the details in the database, set roles and membership to the user logins. I have skip the part to set user roles and membership, once we have the user information we can use that information to set roles or just save the information in the database.

 

Download: DOTNETOAUTH - UserData.zip (552.20 kb)

Currently rated 5.0 by 1 person

Upload Multiple Files With jQuery "Uploadify"

12. September 2010 11:00

API ASP.NET Jquery 

I have found many web developers seeking for help to upload a file in AJAX style, I am not a web developer but among the list of people who used to search the web for some control, way or a workaround to do this. I found a .NET control to do this, but like all good controls....it wasn't free. But the control worth it.

But now we have an excellent open source plugin called Uploadify. I have been using it for sometime and thought I should now blog and spread a word about it. To implement in your ASP.NET project is simple. Download the latest version of Uploadify from its official site here.

Take a look at the downloaded files. Actually, I need NOT to explain it again to you because the download itself has a PDF file which makes it really simple to understand the working and usage of the plugin. If you need to take a look how this plug-in works, then the  best place to look at the demo page at the uploadify page here.

I also compiled a small apllication with ASP.NET to see it in action with ASP.NET

NOTE: The code below I have uploaded is not written by me, I have just compiled a bunch of files under one hood to get it working.

Download: JqueryUploadify.zip (229.05 kb)

Currently rated 4.0 by 2 people

Add OpenID Login Support In Your ASP.NET Application

29. August 2010 14:50

API ASP.NET Visual Studio 

Few days back I was looking at Scott Hanselman and friend's Open Source Nerddinner project, learning and grabbing some new things from there. Apart from looking some internals I looked at the OpenID implementation. This was all a week ago and now it's time for me to write and give some thoughts on DotNetOpenAuth. For folks who are new to OpenID I am going to demonstrate how you can implement one in your project with ease.

To get started download the DotNetOpenAuth API and extract the contents from the zip file. The download also includes some samples for you to get you started. Kickstart by creating a new ASP.NET webforms project. I am just using a default template for my application, you can use the one you like or start by creating a new page. Why I am using the default template for ASP.NET webform project? well you get to know later. So now when we are done creating a new ASP.NET webform project, time to add OpenID stuff in the project. Right click References  and select Add Reference. Browse to the bin folder where you have extracted the contents of the downloaded zip file. Select DotNetOpenAuth.dll and click OK.

Changing the web.config:

A minor change in the web.config is required. Find the below lines in your web.config file:

 <authentication mode="Forms"><forms loginUrl="~/Account/Login.aspx"
timeout="2880" /></authentication>

and replace it with:

<authentication mode="Forms"><forms defaultUrl="/default.aspx"
loginUrl="~/Account/login.aspx"/></authentication>

In the above configuration, loginUrl will always point towards to the login page and the defaultUrl will always point towards the page/URL which will be displayed when the authentication is successfull.

Implemeting OpenID support:

To implement OpenID support, open login.aspx page in the design view and then drag the OpenIdLogin from the toolbox on the page just after the default login implementation ends or where you want to have OpenID login. If you are not able to view the control, then you can browse the same dll you have add a reference in the above step.

If you want to implement this manually then register the control at the top of the page and then use it on the page.

Register the control:

<%@ Register Assembly="DotNetOpenAuth" Namespace="DotNetOpenAuth.OpenId.RelyingParty"
TagPrefix="rp" %>

To use the control on the page you can then simply write:

<rp:OpenIdLogin ID="OpenIdLogin1" runat="server"></rp:OpenIdLogin>

All done now and it's time to test our application. Hit F5 and login with your openID. The page rendered in front of you is

Enter your openID and click login. You will be redirected to the official OpenID login page

Enter your password for openID account and after the authentication is successfull you will be re-directed to the default page. Remember the web.config configuration we did!!? If everything goes well you can see your openID name login name on the top of the page.

This is the simplest way to implement openID. You can also implement openID on your ASP.NET MVC project to add some flexibility for you site users. Apart from this you can also download the Visual Studio 2010 template

Download: DOTNETOAUTH.zip (542.85 kb)

Related Links:

Currently rated 4.0 by 2 people