file extension validation in jQuery

Hello Friends,

Recently one of my project require file extension validation. I am using jquery to achive this. So, i have done it in simple way with jquery as follow

$(function ()
   $('#btnSubmit').click(function ()
      var ext = ['jpeg', 'jpg', 'png', 'gif'];
      var file = $("file").val();
      if ($.inArray(file.split('.').pop().toLowerCase(), ext) == -1)
          alert ('Only jpg, png and gif are allowed.');

Include HTML as follow.

It is work with jQuery js. So, include jQuery js file. Hope it will help someone!!!!

File Upload plugin with jCrop in c#

Hello Friends,

I want to add jCrop in my previous blog. I have describe how we use jquery file upload plugin in my previous blog. I want to add image crop functionality.

To add crop you need jCrop which is also available in Github from or go to

First add jquery file upload then add jcrop js and css in your project.

After uploading of image reference image file to “imgCrop”. Here, i have not allow user to resize in crop you can give them by simple allowResize parameter to true same way you can allow reselect too.

Now, add following to html.


Add some code to cs file

        protected void btnCrop_Click(object sender, EventArgs e)
            String path = Server.MapPath("~/Files");
            string cropImagePath = "";
            string cropImageName = "";

            string ImageName = hdImageName.value;
            int w = Convert.ToInt32(hdW.Value);
            int h = Convert.ToInt32(hdH.Value);
            int x = Convert.ToInt32(hdX.Value);
            int y = Convert.ToInt32(hdY.Value);

            byte[] CropImage = Crop(path + "\\" + ImageName, w, h, x, y);
            using (MemoryStream ms = new MemoryStream(CropImage, 0, CropImage.Length))
                ms.Write(CropImage, 0, CropImage.Length);
                using (System.Drawing.Image CroppedImage = System.Drawing.Image.FromStream(ms, true))
                    cropImageName = GetPhysicalFileName("c" + ImageName, path);
                    cropImagePath = path + "\\" + cropImageName;
                    CropImage.Save(cropImagePath, CropImage.RawFormat);

            ScriptManager.RegisterStartupScript(this, typeof(Page), new Guid().ToString(), "CloseCrop();", true);

        static byte[] Crop(string tImg, int Width, int Height, int X, int Y)
                using (System.Drawing.Image orgImage = System.Drawing.Image.FromFile(tImg))
                    using (System.Drawing.Bitmap tbmp = new System.Drawing.Bitmap(Width, Height))
                        bmp.SetResolution(orgImage.HorizontalResolution, orgImage.VerticalResolution);
                        using (System.Drawing.Graphics Graphic = System.Drawing.Graphics.FromImage(tbmp))
                            Graphic.SmoothingMode = SmoothingMode.AntiAlias;
                            Graphic.InterpolationMode = InterpolationMode.HighQualityBicubic;
                            Graphic.PixelOffsetMode = PixelOffsetMode.HighQuality;
                            Graphic.DrawImage(orgImage, new System.Drawing.Rectangle(0, 0, Width, Height), X, Y, Width, Height, System.Drawing.GraphicsUnit.Pixel);
                            MemoryStream ms = new MemoryStream();
                            bmp.Save(ms, orgImage.RawFormat);
                            return ms.GetBuffer();
            catch (Exception ex)
                throw ex;
        protected string GetPhysicalFileName(string fileName, string directoryPath)

            string orgFileName = fileName;
            string phyFileName = fileName;

                if (File.Exists(directoryPath + "\\" + orgFileName))
                    int count = 1;
                    string fileNameWithoutExt = Path.GetFileNameWithoutExtension(orgFileName);
                    string extension = Path.GetExtension(orgFileName);
                    string tempName;

                    while (true)
                        tempName = fileNameWithoutExt + count.ToString() + extension;

                        if (!File.Exists(directoryPath + "\\" + tempName))
                            phyFileName = tempName;
                            count += 1;

            return phyFileName;

You are ready with code. May it will help you.

Example of jQuery File Upload in c#

Hello all,

Today i want to share you example of jQuery File Upload plugin. You can download jQuery file upload plugin from github here.

There are some example provided by them in .net also. But my requirement is not set with that so, i have prepared one example.

First include some necessary files like following.

Here you can exclude ifrmae-transport if you are not using cross domain. Also, process is used for processing and validate use to validate file.

Now, initialize the fileupload

        $(function ()
            var tbodyList = "";
            var trListRowClone = "";
            'use strict';

            var url = '/Handler/Handler.ashx';
            // Initialize the jQuery File Upload widget:
                url: url,
                dataType: 'text',
                autoUpload: true,
                acceptFileTypes: /(jpg)|(jpeg)|(png)|(gif)|(pdf)$/i, // Allowed file types
                progress: function (e, data)
                    var bar = $('.bar');
                    var progress = parseInt(data.loaded / * 100, 10);
                    var percentVal = progress + '%';
                done: function (e, data)
                    var newRow = trListRowClone.cloneNode(true)
                    newRow.physicalFileName = this.files[0].name; // data
                    newRow.cells[0].getElementsByTagName("span")[0].childNodes[0].data = this.files[0].name;

Now, we write html


The Last thing is handler.

public void ProcessRequest (HttpContext context) {
        context.Response.ContentType = "text/plain";
        context.Response.Expires = -1;
        foreach (string file in context.Request.Files)
            HttpPostedFile hpf = context.Request.Files[file] as HttpPostedFile;
            string FileName = string.Empty;
            if (HttpContext.Current.Request.Browser.Browser.ToUpper() == "IE")
                string[] files = hpf.FileName.Split(new char[] { '\\' });
                FileName = files[files.Length - 1];
                FileName = hpf.FileName;
            if (hpf.ContentLength == 0)
            string savedFileName = context.Server.MapPath("~/Your-folder-name/" + FileName);

            context.Response.StatusCode = 200;
    public bool IsReusable {
        get {
            return false;

Now, everything is ready. You can find your file at “your-folder-name”. Enjoy!!!

How to show div vertical/horizontal scroll

Hello All,

All we know that by overflow property we can handle overflow of element. Sometime we want overflow only vertical or horizontal. To achieve this we can set overflow-x and overflow-y.

/* For vertical scroll */
scroll text....scroll text....scroll text....scroll text....scroll text....scroll text....scroll text.... scroll text....scroll text....scroll text....scroll text....scroll text....scroll text....scroll text....
/* For horizontal scroll */
scroll text....scroll text....scroll text....scroll text....scroll text....scroll text....scroll text.... scroll text....scroll text....scroll text....scroll text....scroll text....scroll text....scroll text....

Here white-space is also important to set overflow. With white-space we can set wrap and nowrap default white-space is wrap or normal.

Hope it will help someone.

Age validation in

Hello Friends,

Recently i have requirement to validate sign up age +18. I have search many sites to how it will calculate age on date. I found simple RangeValidator to accomplish this.

Now, in back end set RangeValidator minimum date and maximum date. To set it use following

rvDOB.MinimumValue = DateTime.Today.AddYears(-60).ToString("MM/dd/yyyy");
rvDOB.MaximumValue = DateTime.Today.AddYears(-18).ToString("MM/dd/yyyy");

You can set your years in AddYears as per your requirement. Hope it will help you!!!

Bind Dropdown in Gridview

Hello All,

I want to share example of bind dropdown in gridview. In Edit mode when you want to show your value in dropdown it will help you.

To add dropdown use following code for gridview.

                        <%# Eval("BusinessEntityID")%>
                        <%# Eval("Title") %>
                        First Name
                        <%# Eval("FirstName") %>
                        Last Name
                        <%# Eval("LastName") %>
                        <%# Eval("AddressLine1") %>
                        <%# Eval("City") %>
                        Postal Code
                        <%# Eval("PostalCode") %>

Now, add following code in cs file. We are using Edit event and BindDropDown function to achieve our goal. In Edit mode you can use other objects too like checkbox, radiobutton etc…

protected void gvData_Editing(object sender, GridViewEditEventArgs e)
        gvData.EditIndex = e.NewEditIndex;

        HiddenField hdTitle = (HiddenField)gvData.Rows[e.NewEditIndex].FindControl("hdTitle");
        DropDownList ddlTitle = (DropDownList)gvData.Rows[e.NewEditIndex].FindControl("ddlTitle");


        if (ddlTitle != null)
            ddlTitle.SelectedValue = hdTitle.Value;

private void BindDropDown(DropDownList ddl)
        ddl.Items.Add(new ListItem("-- Select --", ""));
        ddl.Items.Add(new ListItem("Mr.", "Mr"));
        ddl.Items.Add(new ListItem("Mrs.", "Mrs"));
        ddl.Items.Add(new ListItem("Miss", "Miss"));
        ddl.Items.Add(new ListItem("Dr.", "Dr"));
        ddl.Items.Add(new ListItem("Sr.", "Sr"));

protected void gvData_Updating(object sender, GridViewUpdateEventArgs e)
        GridViewRow row = gvData.Rows[e.RowIndex];
        int id = 0;
        int.TryParse(e.Keys["BusinessEntityID"].ToString(), out id);

        TextBox txtFirstName = (TextBox)row.FindControl("txtFirstName");
        TextBox txtLastName = (TextBox)row.FindControl("txtLastName");
        TextBox txtAddressLine1 = (TextBox)row.FindControl("txtAddressLine1");
        TextBox txtCity = (TextBox)row.FindControl("txtCity");
        TextBox txtPostalCode = (TextBox)row.FindControl("txtPostalCode");
        DropDownList ddlTitle = (DropDownList)row.FindControl("ddlTitle");

        DBM.SqlCommandEx sqlCmd = new DBM.SqlCommandEx(
                    String.Format("UPDATE Person.Person" +
                    " SET firstName='{0}', lastName='{1}', title='{3}'" +
                    " WHERE BusinessEntityID = {2}"
                    , txtFirstName.Text, txtLastName.Text, id, ddlTitle.SelectedValue) +

                    String.Format(" UPDATE Person.Address" +
                    " SET addressLine1='{0}', city='{1}', postalCode='{2}'" +
                    " WHERE addressID = (SELECT addressID FROM Person.BusinessEntityAddress WHERE BusinessEntityID = {3})"
                    , txtAddressLine1.Text, txtCity.Text, txtPostalCode.Text, id)


        DataTable i = sqlCmd.GetDataTable();

        gvData.EditIndex = -1;

Now, all done you can run it and see when you are in edit mode you will see your dropdown with selected value. I am attaching example with this article. Demo

How to use reCaptcha with c#

Hello all,

Today i want to share example of reCaptcha. Some of us have try to implement reCaptcha with c# but they are facing some issues to implement it. So, i have create one simple example with update panel.

First register your site at By clicking on create key you will get your public key and private key. We will need this key to implement our captcha.

Now, we need recaptcha.dll for c#. You will get dll from here or go to resourses in recaptcha site.

We are ready to code in our application. First add below code in your aspx page.

// Add to register captcha
<%@ Register TagPrefix="recaptcha" Namespace="Recaptcha" Assembly="Recaptcha" %>

// Add in your page html

Post a Comment

Now, add following code in cs file.

// Add following code for your button btnSubmit_Click event.
if (Page.IsValid && recaptcha.IsValid)
     // your code here
        divRecaptcha.Visible = true;
          + "if ( RecaptchaOptions && \"custom\" == RecaptchaOptions.theme )"
          + "{"
          + "  if ( RecaptchaOptions.custom_theme_widget )"
          + "  {"
          + "    Recaptcha.widget = Recaptcha.$(RecaptchaOptions.custom_theme_widget);"
          + "    Recaptcha.challenge_callback();"
          + "  }"
          + "} else {"
          + "  if ( Recaptcha.widget == null || !document.getElementById(\"recaptcha_widget_div\") )"
          + "  {"
          + "    jQuery(\"#" + divRecaptcha.ClientID + "\").html('
');" + " Recaptcha.widget = Recaptcha.$(\"recaptcha_widget_div\");" + " }" + " Recaptcha.reload();" + " Recaptcha.challenge_callback();" + "}", true ); }

Here, script manager block is for reload the captcha when captcha is incorrect. I have faced many issues to implement captcha like my dialog box is not submited, captcha is submit but invalid captcha enter and reload captcha not done etc…

Use custom validator to validate reCaptcha. Also, reload captcha issue solved by script manager.

Increase textbox width onclick by jQuery

Hello Friends,

Today i want to share one small example of increase textbox width onclick by jquery. Actually to increase width of textbox we will animate textbox with jquery.

We will use following code to animate textbox.

        $(document).ready(function ()
            $('#txtSearch').focus(function ()
                /*to make flexible, store the current width in an attribute*/
                $(this).attr('width-default', $(this).width());
                $(this).animate({ width: 250 }, 'slow');
            }).blur(function ()
                /* restore the original width */
                var w = $(this).attr('width-default');
                $(this).animate({ width: w }, 'slow');

Replace txtSearch with your textbox name and also change width in animate as appropriate your width. Enjoy!!!