The best way to Upload Image and resize it for gallery


Sometimes we need to use galleries in our sites such as light box or any JQuery photo gallery , But the gallery needs two separate image files . One is big and the other is small or thumbnail.
We don't need to bother the user for uploading 2 files with different sizes (width and height).
consider this example :

first of all create Uploading folder inside your root

aspx page
<asp:FileUpload ID="imageFile" runat="server" />
<asp:Button ID="btnFileUpload" runat="server" Text="Upload"
            onclick="btnFileUpload_Click" />

<asp:Label ID="lblStatus" runat="server" Text=""></asp:Label>

C# code behind
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;

public Bitmap ResizeBitmap(Bitmap src, int newWidth, int newHeight)
{
        Bitmap result = new Bitmap(newWidth, newHeight);
        using (Graphics g = Graphics.FromImage((System.Drawing.Image)result))
        {
            g.DrawImage(src, 0, 0, newWidth, newHeight);
        }
        return result;
}


protected void btnFileUpload_Click(object sender, EventArgs e)
{
        bool fileExist = false;
        if (imageFile.HasFile)
        {
            try
            {
                string fileName = imageFile.FileName;
                string location = Server.MapPath("./Uploading/") + fileName;
                if (!File.Exists(location))
                {
                    // Get the bitmap data from the uploaded file
                    Bitmap src = Bitmap.FromStream(imageFile.PostedFile.InputStream) as Bitmap;
                    // Resize the big Image
                    Bitmap bigResult = ResizeBitmap(src, 640, 480);
                    bigResult.Save(location, ImageFormat.Jpeg);

                    string smallFileName = "small_" + imageFile.FileName;
                    // Resize the small image
                    Bitmap smallResult = ResizeBitmap(src, 200, 150);
                    string smallLocation = Server.MapPath("./Uploading/") + smallFileName;
                    smallResult.Save(smallLocation, ImageFormat.Jpeg);
                }
                else
                {
                    fileExist = true;
                    this.ClientScript.RegisterStartupScript(this.GetType(), "Startup",
"<script language='javascript'>alert('The file is exist !!! ');</script>");

                }
            }
            catch (Exception ex)
            {
                lblStatus.Text = "Upload status: The file could not be uploaded. The following error occured: " +     ex.Message;
            }
           
        }

       
}




How To Validate CheckBox with CustomValidator


The CustomValidator control allows you to create a validation control with customized validation logic. For example, you can create a validation control that checks whether the checkbox is checked or not .

To validate the checkbox with The CustomValidator control Use the ClientValidationFunction property to specify the name of the client-side validation script function associated with the
CustomValidator control. Since the script function is executed on the client, the function must be in a language that the target browser supports, such as JavaScript.

The following example demonstrates how to use The CustomValidator control to validate the checkbox :

*Add this script inside the <head> tag
<script type="text/javascript">
function ValidateCheckBox(source,args)
{
    if (document.getElementById('<%=CheckBox1.ClientID%>').checked==true)
    args.IsValid=true;
    else
    args.IsValid=false;
}
</script>

*Add this code in your aspx page
<div>
    <asp:CheckBox ID="CheckBox1" runat="server" Text="You must Agree" />
    <asp:CustomValidator ID="CustomValidator1" runat="server" Display="Dynamic"
    ToolTip="CheckBox must be checked!" ClientValidationFunction="ValidateCheckBox">*
    </asp:CustomValidator>
    
    <br />
           
    <asp:Button ID="btnSubmit" runat="server" Text="Submit" />
</div>

How To Set Multiple DataKeyNames in GridView


The following example demonstrates how to use the DataKeyNames property to specify the key field of the data source. In the example, the DataKeyNames attribute of the GridView element
in markup specifies two key fields by using a comma to separate the names.

aspx page
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
OnRowDeleting="GridView1_RowDeleting" DataKeyNames="ProductID,OrderID">
<Columns>

<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("ProductName") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>   

 </Columns>
</asp:GridView>

C# code behind
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{

        //To retrieve the values from a DataKeyNames collection,
        //you can use "Key Names" or "index"

        //Get the values with key names
        string productId = GridView1.DataKeys[e.RowIndex].Values["ProductID"].ToString();
        string orderId = GridView1.DataKeys[e.RowIndex].Values["OrderID"].ToString();

        //Or

        //Get the values with index
        string productId = GridView1.DataKeys[e.RowIndex].Values[0].ToString();
        string orderId = GridView1.DataKeys[e.RowIndex].Values[1].ToString();

}

How to Redirect a page after clicking OK of javascript alert box


Sometimes you need to redirect the user to another page after he clicks on 'OK' button in the javascript alert box.

Just type your complete script and assign it to a string variable.
register it with RegisterStartupScript as follows.

Look at this example :

C# code behind:
string strScript = "<script>";
strScript += "alert('Type your message here');";
strScript += "window.location='TestPage.aspx';";
strScript += "</script>";
this.ClientScript.RegisterStartupScript(this.GetType(), "Startup", strScript);

This code will display an alert box and when 'OK' button is clicked it will redirect to TestPage.aspx page.

How To Increase File Upload Size in ASP.NET


To increase this size limit you have to make some changes in either the web.config file for the application or in the machine.config file of the machine if you want to apply to all applications that are on the server.

Add this line under the <system.web> tag

<system.web>
  <httpRuntime  maxRequestLength="1000000" executionTimeout="420"/>
</system.web>



Now you get one gigabyte file upload. By the way the default size is 4000kb