using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

using System.Drawing;
using Telerik.WebControls;
using Telerik.WebControls.RadUploadUtils;

public partial class CustomValidationUpload : System.Web.UI.Page 
{
    protected void Page_Load(object sender, EventArgs e)
    {
        statusLabel.Text = "";
        errorLabel.Text = "";
    }
    
    protected void Button1_Click(object sender, EventArgs e)
    {
        try
        {
            if (RadUpload1.UploadedFiles.Count > 0)
            {
                String message = "</br>The following files are upload succcessfully</br>";
                foreach (UploadedFile file in RadUpload1.UploadedFiles)
                {
                    message += file.GetName() + "</br>";
                    file.SaveAs(@"c:\MyUploadDir\" + file.GetName(), true);
                }
                DisplayMessage(message, false);
            }                       

            if (RadUpload1.InvalidFiles.Count > 0)
            {
                String error = "</br>The following files are not allowed for upload</br>";
                foreach (UploadedFile ifile in RadUpload1.InvalidFiles)
                {
                   error += ifile.GetName() + "</br>";
                }
                DisplayMessage(error, true);
            }        
        }
        catch (Exception ex)
        {
            DisplayMessage("Upload failed" + ex.Message, true);
        }       
    }
 
    private void DisplayMessage(string text, bool isError)
    {       
        if (isError)
        {
            this.errorLabel.ForeColor = Color.Red;
            this.errorLabel.Text = text;
        }
        else
        {
            this.statusLabel.ForeColor = Color.Green;
            this.statusLabel.Text = text;
        }        
    }

    protected void RadUpload1_ValidatingFile(object sender, ValidateFileEventArgs e)
    {
        int maxZip = 10485760; //10 MB
        int maxText = 4096; //4 KB
        int maxJpg = 512000; // 500KB

        switch(e.UploadedFile.GetExtension().ToLower())
        {
            case ".zip":
               if (e.UploadedFile.ContentLength > maxZip)
                  e.IsValid = false;
               e.SkipInternalValidation = true;
               break;
            case ".txt":
                if (e.UploadedFile.ContentLength > maxText)
                    e.IsValid = false;
                e.SkipInternalValidation = true;
                break;
            case ".jpg":
                if (e.UploadedFile.ContentLength > maxJpg)
                    e.IsValid = false;
                e.SkipInternalValidation = true;
                break;
        }       
    }
}
