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 https://github.com/tapmodo/Jcrop or go to http://deepliquid.com/content/Jcrop.html.

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)
        {
            try
            {
                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;
                            break;
                        }
                        else
                        {
                            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:
            $('#fileupload').fileupload({
                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 / data.total * 100, 10);
                    var percentVal = progress + '%';
                    bar.width(percentVal);
                },
                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;
                    tbodyList.appendChild(newRow);
                }
            });            
        });

Now, we write html

        
File-Name  

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];
            }
            else
            {
                FileName = hpf.FileName;
            }
            if (hpf.ContentLength == 0)
                continue;
            
            string savedFileName = context.Server.MapPath("~/Your-folder-name/" + FileName);
            hpf.SaveAs(savedFileName);

            context.Response.Write(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 asp.net

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 asp.net 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.

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")%>
                    
                
                
                    
                        Title
                    
                    
                        <%# Eval("Title") %>
                    
                    
                        
                        
                        
                    
                
                
                    
                        First Name
                    
                    
                        <%# Eval("FirstName") %>
                    
                    
                        
                    
                
                
                    
                        Last Name
                    
                    
                        <%# Eval("LastName") %>
                    
                    
                        
                    
                
                
                    
                        Address
                    
                    
                        <%# Eval("AddressLine1") %>
                    
                    
                        
                    
                
                
                    
                        City
                    
                    
                        <%# 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;
        BindData();

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

        BindDropDown(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;
        BindData();
    }

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 get IP address in asp.net

Hello Friends,

Today I am going to represent article on how to get client IP address using asp.net.

We know the asp.net method “Request.UserHostAddress” for retrieving a client IP address.
This method gets the IP address of the current request. It uses the UserHostAddress property in the ASP.NET framework. This is usually the user’s ISP’s IP address, not exactly the user’s machine IP address.

we can retrieve same by using other request server variables i.e HTTP_X_FORWARDED_FOR and REMOTE_ADDR

REMOTE_ADDR : This method is same as UserHostAddress. it returns the IP address of the proxy server/router, not the client machine.

HTTP_X_FORWARDED_FOR : By using this method we can get client IP address if user is behind the proxy server. This variable contains a list of comma separated IP addresses in the format client IP, proxy1 IP, proxy2 IP, …

See the below code for retrieving a client machine IP address:


 var ipAddress = (HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null
                  && HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != "")
                 ? HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"]
                 : HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
        if (ipAddress.Contains(","))
            ipAddress.Split(',').First().Trim();

Here you can see that, First I have check HTTP_X_FORWARDED_FOR because if user behind the proxy then we get the client machine IP address otherwise it returns the null.

Hope this will help !!!

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 recaptcha.net. 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.
recaptcha.Validate();
if (Page.IsValid && recaptcha.IsValid)
{
     // your code here
}
else
{
        divRecaptcha.Visible = true;
        ScriptManager.RegisterClientScriptBlock(
          recaptcha,
          recaptcha.GetType(),
          "recaptcha",
          "Recaptcha._init_options(RecaptchaOptions);"
          + "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.

Remove invalid characters from uploaded file name

Hi,

Today I have a requirement in my web application to remove the invalid characters from uploaded file name.

For this, I have created small function which removes the invalid characters from file name.

see the below function which I have used for the above requirement.


     string invalid = new string(Path.GetInvalidFileNameChars());
     foreach (char c in invalid)
     {
          fileName = fileName.Replace(c.ToString(), "");
     }
}

you can also replace it with “underscore sign” or any other valid character by using below code


     string invalid = new string(Path.GetInvalidFileNameChars());
     foreach (char c in invalid)
     {
          fileName = fileName.Replace(c.ToString(), "_");
     }
}

If you want to remove invalid characters from path then use below code


     string invalid = new string(Path.GetInvalidPathChars());
     foreach (char c in invalid)
     {
          fileName = fileName.Replace(c.ToString(), "_");
     }
}

Hope this will help.

Update xml element in asp.net using linq

Hi Friends,

In my earlier post, we have seen that how can we delete xml element using linq to xml query.

you can check it from here

Today we will see how to update element in existing XML file.

For this, we need to load XML file from the disk, update the element and save the updated XML to the disk.

Let’s see how can we do this using below example.

see the below searched xml element:

 
   3
   Gautam
   bhatia
   30
 
 

I have searched xml element in my previous post for deleting it.
Now we will update last name for the Employee Gautam


.............
.............
first search the element employee from the emplyees.xml file
load it into xmlData variable
.............
.............

XDocument doc = XDocument.Load(XMLDocPath);
var xmlData = (from item in doc.Descendants("employee")
               select item).ToList();

foreach (var item in xmlData)
{
   item.Element("lastname").Value = "Gambhir";
}

doc.Save(XMLDocPath);

hope this will help you.