Reverse Those Short URLs

2. February 2011 02:58

ASP.NET Utils 

Bit.ly is one of the major short URL service provider. There are other also but Bit.ly is used by most of the users because of it's simplicity, API and statistics. But some notorious users create short URLs for the spam sites which doesn't make any sense to us. As you know by looking at the short URLs, they won't reveal anything. But there is a way to get the original/long URL through ASP.NET.

Below is the method which takes short URL as a parameter.

public static string ReverseShortURL(string ShortURL)
{
        HttpWebRequest Webrequest = (HttpWebRequest)HttpWebRequest.Create(ShortURL);
        HttpWebResponse Webresponse = (HttpWebResponse)Webrequest.GetResponse();
        Uri uri = Webresponse.ResponseUri;
        return uri.AbsoluteUri;
}

The Response.Uri will get the actual URL which is being requested.

 

Demo: http://demo.midnightprogrammer.net/ASPNET/ReverseURL/Default.aspx

Download: ReverseShortURL.zip (335.87 kb)

 No Rating

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