How to download file in

Hi Friends,

Today I am going to describe file download functionality in

we can download file using different methods in

Today I am going to describe Response.TransmitFile method of

Lets see how can we do it

public void Downloadfile(string fileName, string filePath )
    FileInfo file = new FileInfo(filePath + "\\" + fileName);
    Response.AddHeader("Content-Disposition", "attachment; filename=" + fileName);
    Response.AddHeader("Content-Length", file.Length.ToString());
    Response.ContentType = "application/octet-stream";
    Response.TransmitFile(filePath + "\\" + fileName);

You can download file easily by using above function.
1. You need to pass fileName and filePath parameters
2. Here, I have used general content type “application/octet-stream”. Change it as per your requirement
3. Add reference for System.IO

Hope this will help you !!!!

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!!!

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!!!

how to call server side button event in jquery dialog

Hi All,

Generally we are using jquery modal dialog for modal popup window in our application.

Sometimes we need to call server side button event from modal popup window and it creates problem for us.

Today I am going to describe how can we call button event from jquery modal popup window.

lets take an simple example:

Asp.Net Button Code:

Jquery Modal Popup Script:


Code Behind Button Event:

protected void Button1_Click(object sender, EventArgs e)
    //your button click event code comes here
    //you can do anything here

Please note that you need to add jquery modal popup related script reference in your code.

how to send attachment in mail

Hello Friends,

I have write an article on mail sending functionality but i didn’t add attachment in it.
You can check it from here

Today I am going to describe how to send attachment in mail using
see the below code for mail attachment functionality:

    MailMessage Msg = new MailMessage();  
    Attachment attchment = new Attachment(physicalfilepathcomeshere);
    Msg.From = new MailAddress("fromemailaddress");  
    Msg.Subject = "Define your subject line";  
    Msg.Body = "Content of body";  
    SmtpClient smtp = new SmtpClient();  
    smtp.Host = "";  
    smtp.Port = 587;  
    smtp.Credentials=new System.Net.NetworkCredential("gmailID","gmailpassword");  
    smtp.EnableSsl = true;  

you need to provide physical file path in place of “physicalfilepathcomeshere”.

Hope this will help you in sending mail attachment.

IE11 and __doPostBack is undefined

Hi Friends,

Today I have experienced one strange issue on my project. In my local machine everything is working fine but when I have uploaded it on server then it gives me an error.

I have tested it in other browsers and everything going fine but when I tested it on IE11 then it raise the __dopostback error.

I got one link from microsoft regarding this error

I have updated .net framework version 4 and it solves my problem.

Hope this will also help you !!!

How to validate alphanumeric password in

Hi Friends,

In my previous post, we have seen custom validator example.
Now today I am going to describe RegularExpression validator control.

I have taken simple example for this validation. you can validate different things by using this control like email validation, special character validation, alphanumeric validation etc.

Lets see how can we validate alphanumeric password with minimum 5 characters long.

Password Textbox:

RegularExpression Validator:


now when I click on the button then it validates the password textbox whether user enters it as alphanumeric or not

Hope this will help you !!!….

Checkbox custom validation in


In this post I will explain how to validate ASP.Net Checkbox control using ASP.Net Custom Validator and JavaScript.


function CheckboxValidation(sender, args) {
            if (document.getElementById("<%=YourCheckboxControlID.ClientID %>").checked == true) {
                args.IsValid = true;
            } else {
                args.IsValid = false;


asp:CheckBox ID="YourCheckboxControlID" runat="server" />

Custom Validator:


Here, You can see the I have used ClientValidationFunction property of CustomValidator. Which is used to validate control by using javascript function. So when I click on the button then it validates the checkbox whether it is is checked or not.

Hope this 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