Showing posts with label ASP.NET. Show all posts
Showing posts with label ASP.NET. Show all posts

Export Data From Excel File in ASP.Net

Export Data From Excel File in ASP.Net

The following function takes the following parameter :

    "excelFileName" : Its specify the Path with File Name .i.e: "D:\MyExcel.xls"

Use the following NameSpace :
    using System.IO;
    using System.Reflection;
    using Microsoft.Office.Interop.Excel;
Code :
    /// <summary>
    /// This function convert uploaded Ecxcel sheet into DataTable and then returns 
    /// </summary>
    /// <param name="fileToConvert"></param>
    /// <param name="fileForDs"></param>
    /// <param name="uniqueFileName"></param>
    /// <returns></returns>
    public System.Data.DataTable ReadFromExcelFile(string excelFileName)
    {
        OleDbConnection connection = null;

        //this datatable contains Active Sheet  records 
        System.Data.DataTable dtImprtExcel = new System.Data.DataTable();

        try
        {

            // Get Active Sheet Name
            string activeSheetName = getActiveSheetName(excelFileName);

            //If Active Sheet Name is not Null or Blank
            if (!string.IsNullOrEmpty(activeSheetName))
            {

                // <add key="ExcelConnectionString" value="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Path;Extended Properties=Excel 8.0;"/>
                string connectionString = ConfigurationManager.AppSettings.Get("ExcelConnectionString").Replace("Path", excelFileName);
                OleDbConnection excelCon = new OleDbConnection(connectionString);
                excelCon.Open();
                OleDbDataAdapter adapter = new OleDbDataAdapter("SELECT * FROM [" + activeSheetName + "$]", excelCon);
                adapter.Fill(dtImprtExcel);
                excelCon.Close();

                //cleans up the temporary file that was stored
                File.Delete(excelFileName);
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
        finally
        {
            if (connection != null)
            {
                if (connection.State == ConnectionState.Open)
                {
                    //close a open connection
                    connection.Close();
                }
            }
        }
        return dtImprtExcel;
    }

Get Active Sheet Name :

The following function takes the following parameter :
"strFileName" : Its specify the Path with File Name .i.e: "D:\MyExcel.xls"

Use the following NameSpace :

    using System.IO;
    using System.Reflection;
    using Microsoft.Office.Interop.Excel;

Code :

    /// <summary>
    /// Get Excel Sheet Name
    /// </summary>
    /// <param name="path"></param>
    /// <returns></returns>
    private string getActiveSheetName(string strFileName)
    {
        string activeSheetName = string.Empty;
        try
        {
            Application oXL;
            Workbook oWB;
            Worksheet oSheet;

            // Start Excel and get Application object. 
            oXL = new Application();

            // Set some properties 
            oXL.Visible = false;
            oXL.DisplayAlerts = false;

            // Open the workbook. 
            oWB = oXL.Workbooks.Open(strFileName);

            // Get the active sheet 
            oSheet = (Worksheet)oWB.ActiveSheet;
            activeSheetName = oSheet.Name;

            // Save the sheet and close 
            oSheet = null;
            oWB.SaveAs(strFileName, Excel.XlFileFormat.xlWorkbookNormal,
                Missing.Value, Missing.Value, Missing.Value, Missing.Value,
                XlSaveAsAccessMode.xlExclusive,
                Missing.Value, Missing.Value, Missing.Value,
                Missing.Value, Missing.Value);
            oWB.Close(Missing.Value, Missing.Value, Missing.Value);
            oWB = null;
            oXL.Quit();

            // Clean up 
            // NOTE: When in release mode, this does the trick 
            GC.WaitForPendingFinalizers();
            GC.Collect();
            GC.WaitForPendingFinalizers();
            GC.Collect();
        }
        catch (Exception ex)
        {
            throw ex;
        }
        return activeSheetName;
    }

Get ActiveSheet Name of Uploaded Execl in ASP.Net

 The following function takes the following parameter :

    "strFileName" : Its specify the Path with File Name .i.e: "D:\MyExcel.xls"

Use the following NameSpace :
    using System.IO;
    using System.Reflection;
    using Microsoft.Office.Interop.Excel;
Code :
    /// <summary>
    /// Get Excel Sheet Name
    /// </summary>
    /// <param name="path"></param>
    /// <returns></returns>
    private string getActiveSheetName(string strFileName)
    {
        string activeSheetName = string.Empty;
        try
        {
            Application oXL;
            Workbook oWB;
            Worksheet oSheet;

            // Start Excel and get Application object. 
            oXL = new Application();

            // Set some properties 
            oXL.Visible = false;
            oXL.DisplayAlerts = false;

            // Open the workbook. 
            oWB = oXL.Workbooks.Open(strFileName);

            // Get the active sheet 
            oSheet = (Worksheet)oWB.ActiveSheet;
            activeSheetName = oSheet.Name;

            // Save the sheet and close 
            oSheet = null;
            oWB.SaveAs(strFileName, Excel.XlFileFormat.xlWorkbookNormal,
                Missing.Value, Missing.Value, Missing.Value, Missing.Value,
                XlSaveAsAccessMode.xlExclusive,
                Missing.Value, Missing.Value, Missing.Value,
                Missing.Value, Missing.Value);
            oWB.Close(Missing.Value, Missing.Value, Missing.Value);
            oWB = null;
            oXL.Quit();

            // Clean up 
            // NOTE: When in release mode, this does the trick 
            GC.WaitForPendingFinalizers();
            GC.Collect();
            GC.WaitForPendingFinalizers();
            GC.Collect();
        }
        catch (Exception ex)
        {
            throw ex;
        }
        return activeSheetName;
    }

Download Excel in ASP.Net

The Following Function downloads the Excel .

It accepts the following paramete :
fileName : It contains the path with FileName . I.e : "D:\MyExcel.exe".

Code :
    /// <summary>
    /// Download Excel template with some existing data
    /// </summary>
    /// <param name="fileName"></param>
    private void DownloadExcel(string fileName)
    {
        try
        {
            FileInfo file = new FileInfo(fileName);
            if (file.Exists)
            {
                // Clear the content of the response
                Response.ClearContent();
                Response.Clear();

                // add the header that specifies the default filename for the Download/SaveAs dialog
                Response.AddHeader("Content-Disposition", "attachment; filename=LMSUsers.xls");

                // add the header that specifies the file size, so that the browser can show the download progress
                Response.AddHeader("Content-Length", file.Length.ToString());

                // specify that the response is a stream that cannot be read by the client and must be downloaded
                Response.ContentType = "application/vnd.ms-excel";

                // send the file stream to the client
                Response.WriteFile(file.FullName);
                Response.BufferOutput = true;
                Response.Flush();
                Response.Close();

                //Delete the file if Required
                file.Delete();
            }
        }
        catch (Exception ex)
        {
            throw new Exception(ex.InnerException.Message);
        }
    }

Create Excel with Data in ASP.Net

Create Excel in ASP.Net with Dynamic data .

The following function takes the following parameter :
    "DataTable"  : which holds the data from Database.
    "strFileName" : It is specify the Path with File Name .i.e: "D:\MyExcel.xls"
 
Use the following NameSpace :
    using System.IO;
    using System.Reflection;
    using Microsoft.Office.Interop.Excel;
Code :
    /// <summary>
    /// Creates the excel file from the provided dataset.
    /// </summary>
    /// <param name="dtSource">The dt source.</param>
    /// <param name="strFileName">Name of the STR file.</param>
    private void GenerateExcel(System.Data.DataTable dtSource, string strFileName)
    {
        Application oXL;
        Workbook oWB;
        Worksheet oSheet;
        Range oRange;

        // Start Excel and get Application object. 
        oXL = new Application();

        // Set some properties 
        oXL.Visible = false;
        oXL.DisplayAlerts = false;

        // Get a new workbook. 
        oWB = oXL.Workbooks.Add(Missing.Value);

        // Get the active sheet 
        oSheet = (Worksheet)oWB.ActiveSheet;
        oSheet.Name = "LMS Users";
        int rowCount = 1;

        // Add Headrer to Excel
        for (int i = 1; i < dtSource.Columns.Count + 1; i++)
        {
            oSheet.Cells[1, i] = dtSource.Columns[i - 1].ColumnName;
            oRange = (Microsoft.Office.Interop.Excel.Range)oSheet.Cells[1, i];
            oRange.Font.Bold = true;
        }

        // Add the Data Rows to the Excel
        if (dtSource.Rows.Count > 0)
        {
            foreach (DataRow dr in dtSource.Rows)
            {
                rowCount += 1;
                for (int i = 1; i < dtSource.Columns.Count + 1; i++)
                {
                    if (rowCount > 1)
                    {
                        oSheet.Cells[rowCount, i] = dr[i - 1].ToString();
                    }
                }
            }
        }
        
        // Resize the columns 
        oRange = oSheet.get_Range(oSheet.Cells[1, 1],
                      oSheet.Cells[rowCount, dtSource.Columns.Count]);
        oRange.EntireColumn.AutoFit();

        // Save the sheet and close 
        oSheet = null;
        oRange = null;
        oWB.SaveAs(strFileName, Excel.XlFileFormat.xlWorkbookNormal,
            Missing.Value, Missing.Value, Missing.Value, Missing.Value,
            XlSaveAsAccessMode.xlExclusive,
            Missing.Value, Missing.Value, Missing.Value,
            Missing.Value, Missing.Value);
        oWB.Close(Missing.Value, Missing.Value, Missing.Value);
        oWB = null;
        oXL.Quit();

        // Clean up 
        // NOTE: When in release mode, this does the trick 
        GC.WaitForPendingFinalizers();
        GC.Collect();
        GC.WaitForPendingFinalizers();
        GC.Collect();
    }

How to get File and Function Details from Exception object

Its better to use ErrorLog in Exception Handling. In ErrorLog we need to keep track of the File and the Function details where this Exception occurs. So, instead of sending the Hardcoded Values (i.e : Function Name , File Name ) to ErrorLog, we can directly get this details from Exception object (i.e : Exception ex) as follows :

Code :

Use namespace :
using System.Diagnostics;
using System.Reflection;
Function where Error Occurred :

        /// <summary>
        /// Set AssetName for the AssetID
        /// </summary>
        /// <param name="programId"></param>
        /// <param name="languageId"></param>
        /// <param name="assetId"></param>
        /// <param name="assetName"></param>
        public void SetAssetName(Int32 progId, Int32 langId, int astId, string astName)
        {
            AssetClient assetClient = null;
            try
            {
                assetClient = new AssetClient(appBindingAssets);
                //return assetClient.SetAssetName(progmId, langId, astId, astName);
            }
            catch (Exception ex)
            {
                //call ErrorLog using the File Details
                LogError(ex);
            }
            finally
            {
                if (assetClient != null)
                {
                    assetClient.Close();
                }
            }
        }
ErrorLog Function accepts Exception object as Parameter :
        /// <summary>
        /// Logs the exception. 
        /// </summary>
        /// <param name="ex"></param>
        public static void LogError(Exception ex)
        {
            // Get the File Details from Exception
            StackTrace st = new StackTrace(ex);
 
            // Get the object of MethodBase from StackTrace
            MethodBase mb = st.GetFrame(st.FrameCount - 1).GetMethod();
 
            // Get FileName with NameSpace 
            // Ex: IGroup.Modules.SalesZone.Controller.SalesZoneController"
            string source = mb.DeclaringType.FullName;
 
            // Get Function Name "GetPhraseTranslationList"
            string methodName = mb.Name;
 
            //Implement ErrorLog Logics here using the File Details
            //AddLogError(source, ex, methodName);
        }

Bind same event to Multiple controls in JQuery

When multiple controls needs to fire a same event.
Instead of binding the event to each control separately , we can create an array of controls and loop through it to bind the single event as following :

Code :

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Single Event for Multiple Controls</title>
     <script src="http://code.jquery.com/jquery-1.7.2.min.js" type="text/javascript"></script>
        <script type="text/javascript">
            $(function() {
                var btns = $('#btnA,#btnC,#btnE');
                $.each(btns, function() {
                    $(this).click(function() {
                        alert(this.id);
                    });
                });
            });
        </script>
</head

<body>
    <input id="btnA" type="button" value="Button A" />
    <input id="btnB" type="button" value="Button B" />
    <input id="btnC" type="button" value="Button C" />
    <input id="btnD" type="button" value="Button D" />
    <input id="btnE" type="button" value="Button E" />
</body>
</html>

Add a Web User Control Dynamically (At Runtime).

We can add a Web User Control Dynamically (At Runtime) in 2 steps.

Step 1 : Add a "PlaceHolder" in your aspx page.
Step 2 : Write the following code on page load (Code Behind).

Code :
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

    Dim UCDynamic As Control
    'WebUserControl.ascx : User Control path
    UCDynamic = LoadControl("WebUserControl.ascx")
    PlaceHolder1.Controls.Add(UCDynamic)

End Sub

Add Check Box in Calender Control and Select WeekEnds on click of Button

Format Calender Controls :

Add Check Boxes manually in Calender Control and Select Week Ends on click of Button.



Code :
Partial Class SelectWeekEnds
    Inherits System.Web.UI.Page

    Dim btnclick As Boolean = False

    Protected Sub Calendar1_DayRender(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DayRenderEventArgs) Handles Calendar1.DayRender
        Dim ctl As New CheckBox
        ctl.ID = "chk" & e.Day.Date.ToString.Substring(0, 10)
        If btnclick = True Then
            If CInt(e.Day.Date.DayOfWeek) = 0 Or CInt(e.Day.Date.DayOfWeek) = 6 Then
                ctl.Checked = True
            End If
        End If
        e.Cell.Controls.Add(ctl)
    End Sub

    Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
        btnclick = True
    End Sub

End Class

Add Check Box in Calender Control

Add Checkbox in Calender Control manually.


Code :
Partial Class SelectWeekEnds
  Inherits System.Web.UI.Page

  Protected Sub Calendar1_DayRender(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DayRenderEventArgs) Handles Calendar1.DayRender
      Dim ctl As New CheckBox
      ctl.ID = "chk" & e.Day.Date.ToString.Substring(0, 10)
      e.Cell.Controls.Add(ctl)
  End Sub  

End Class



Check for Internet Connection availability in ASP. Net

Following code Check for Internet Connection availability in ASP. Net

Code :
Partial Class frmChkInternetConnection
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If fnChkInternetConn() Then
            Response.Write("Congrats ! Internet Connection is Available.")
        Else
            Response.Write("Sorry ! Internet Connection is not Available.")
        End If
    End Sub

    Public Function fnChkInternetConn() As Boolean
        Dim objreq As System.Net.HttpWebRequest
        Dim objres As System.Net.HttpWebResponse
        Try
            objreq = CType(System.Net.HttpWebRequest.Create("http://www.google.com"), System.Net.HttpWebRequest)
            objres = CType(objreq.GetResponse(), System.Net.HttpWebResponse)
            objreq.Abort()
            If objres.StatusCode = System.Net.HttpStatusCode.OK Then
                Return True
            End If
        Catch weberrt As System.Net.WebException
            Return False
        Catch except As Exception
            Return False
        End Try
    End Function
End Class

To Verifies that the browser supports the required capabilities of JavaScript

Verifies that the browser supports the required capabilities of JavaScript.
The following code returns "True" else "False" If Browserversion and Javscript enabled .

Code :
    Public Function fnDetectBrowserCapabilities() As Boolean
       Try
           Dim strBrowser As String = String.Empty
           Dim intVersion As Int16 = 0
           Dim boolFrames As Boolean = False
           Dim boolTables As Boolean = False
           Dim boolCookies As Boolean = False
           Dim boolActiveX As Boolean = False
           Dim decJavaScript As Decimal = 0.0

           strBrowser = HttpContext.Current.Request.Browser.Browser
           intVersion = HttpContext.Current.Request.Browser.MajorVersion
           boolFrames = HttpContext.Current.Request.Browser.Frames
           boolTables = HttpContext.Current.Request.Browser.Tables
           boolCookies = HttpContext.Current.Request.Browser.Cookies
           decJavaScript = CDec(HttpContext.Current.Request.Browser.EcmaScriptVersion.ToString)
           boolActiveX = HttpContext.Current.Request.Browser.ActiveXControls

           If strBrowser = "IE" AndAlso intVersion < 6 Then
               Return False
           ElseIf strBrowser = "Firefox" AndAlso intVersion < 2 Then
               Return False
           ElseIf boolFrames = False Then
               Return False
           ElseIf boolTables = False Then
               Return False
           ElseIf boolCookies = False Then
               Return False
           ElseIf decJavaScript < 1 Then
               Return False
           ElseIf strBrowser = "IE" AndAlso boolActiveX = False Then
               Return False
           Else
               Return True
           End If

       Catch ex As Exception
           Return False
       End Try

   End Function

Sort List box in ASP .Net

SortedList :

Represents a collection of key/value pairs that are sorted by the keys and are accessible by key and by index.


Code Behind :
    Partial Class SortListBox
        Inherits System.Web.UI.Page

        Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
            If Not IsPostBack Then
                'Let List box Having the following Item.
                Dim strcountry() As String = {"Denmark", "China", "Italy", "Australia", "India", "Egypt", "Bhutan"}
                Dim strcountryID() As String = {"Den", "Chi", "Ita", "Aus", "Ind", "Egy", "Bhu"}

                'Populate the List Box
                For i As Int16 = 0 To strcountry.Length - 1
                    ListBox1.Items.Add(i)
                    ListBox1.Items(i).Text = strcountry(i)
                    ListBox1.Items(i).Value = strcountryID(i)
                Next
            End If
        End Sub

        'Click on btnSort to Sort the ListBox.
        Protected Sub btnSort_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSort.Click

            'Use the object of SortedList to Sort the Items
            Dim objSortlst As New SortedList

            For i As Int16 = 0 To ListBox1.Items.Count - 1
                'objSortlst.Add(key,value) . It keeps value in sorted Order
                objSortlst.Add(ListBox1.Items(i).Text, ListBox1.Items(i).Value)
            Next

            'Now objSortlst is having data in Sorted order of Key
            ListBox1.DataSource = objSortlst
            ListBox1.DataTextField = "key"
            ListBox1.DataValueField = "value"
            ListBox1.DataBind()
        End Sub

    End Class

Use of Globalization Culture ,CultureInfo and CultureTypes

Globalization is the process of designing and developing applications that function for multiple cultures.
CultureInfo : Provides information about a specific culture (called a "locale" for unmanaged code development). The information includes the names for the culture, the writing system, the calendar used, and formatting for dates and sort strings.

CultureTypes : Defines the types of culture lists that can be retrieved using
System.Globalization.CultureInfo.GetCultures(System.Globalization.CultureTypes)


Use the Following code in aspx (design page).Controls Used : Calender, Label and List box (AutoPostback=true).


Code Behind :
    Partial Class frmGlobalizationCulture
        Inherits System.Web.UI.Page

        Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
            Try
                If Not IsPostBack Then
                    'Bind all the Cultures in List box on First time page load.
                    lstCulture.Items.Clear()
                    Dim CulInfo As System.Globalization.CultureInfo()
                    CulInfo = System.Globalization.CultureInfo.GetCultures(Globalization.CultureTypes.SpecificCultures)
                    Dim StrShort As New SortedList 'Used for the Sorting the Values in ListBox
                    For j As Integer = 0 To CulInfo.Length - 1
                        StrShort.Add(CulInfo(j).DisplayName, CulInfo(j).ToString)
                    Next

                    'Bind all the "SpecificCultures" in the List Box.
                    lstCulture.DataSource = StrShort
                    lstCulture.DataTextField = "key"
                    lstCulture.DataValueField = "value"
                    lstCulture.DataBind()

                    'Select the "CurrentCulture" in the List Box.
                    lstCulture.SelectedValue = System.Threading.Thread.CurrentThread.CurrentCulture.ToString()
                End If
            Catch ex As Exception
                Throw ex
            End Try
        End Sub

        Protected Sub lstCulture_SelectedIndexChanged(ByVal sender As  Object, ByVal e As System.EventArgs) Handles  lstCulture.SelectedIndexChanged
            Try
                'Set the Selected Culture in the ListBox as the CurrentCulture.
                System.Threading.Thread.CurrentThread.CurrentCulture =  New System.Globalization.CultureInfo(Me.lstCulture.SelectedValue)
                System.Threading.Thread.CurrentThread.CurrentUICulture =  New System.Globalization.CultureInfo(Me.lstCulture.SelectedValue)
                lstCulture.Focus()
            Catch ex As Exception
                Throw ex
            End Try
        End Sub

    End Class

To Upload Documents in ASP.Net

Use the Following code to Validate and Upload files in ASP. Net


This Code Validates for the followings.
  • Only .doc, .docx, .ppt, .pptx, .xls, .xlsx, .pdf, .zip, .rtf, .jpg, .jpeg, .gif files can be Uploaded.
  • Filename must not exceed 100 characters (including extension).
  • Total Size of file (per Upload) must not exceed 10 MB.

Use "FileUpload" control to Upload the Doc.
In "web.config" set the following for size of the File allowed.
in "system.web" tag put the "httpRuntime" tag.
httpRuntime executionTimeout="300" maxRequestLength="102400"

Codings :
    Imports System.IO
    Imports System.Data.SqlClient

    Partial Class FileUpload
        Inherits System.Web.UI.Page

    #Region "Variables"
        Dim con As New SqlConnection
        Dim com As New SqlCommand
        Dim upldirinfo As DirectoryInfo
    #End Region

    #Region "Click on Upload"
        Protected Sub btnUpload_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnUpload.Click
            Try
                If Page.IsValid Then
                    If ServerValidation() Then
                        Dim strftpPath1 As String = "C:\UploadFiles"
                        If FileUpload1.FileName.ToString <> "" Then
                            If strftpPath1 <> "" Then
                                upldirinfo = New DirectoryInfo(strftpPath1)
                                If Not upldirinfo.Exists Then
                                    upldirinfo.Create()
                                End If
                                Dim filename As String = FileUpload1.PostedFile.FileName
                                filename = filename.Remove(0, filename.LastIndexOf("\") + 1)
                                Dim filpath As String = strftpPath1 + "\" + filename
                                Dim filinfo As FileInfo
                                filinfo = New FileInfo(filpath)
                                If Not filinfo.Exists Then
                                    FileUpload1.PostedFile.SaveAs(strftpPath1 + "\" + filename)
                                    ClientScript.RegisterStartupScript(Me.GetType(), "onclick", "'<script language='javascript'>alert('" & filename & " is successfully Uploaded .');</script>")
                                    'DB Connection to Save the Deatils in Backend.
                                    con.ConnectionString = "Password=SSSS;Persist Security Info=True;User ID=SSSSSS;Initial Catalog=SSSSSSS;Data Source=SSSSSSSSS"
                                    con.Open()
                                    com.Connection = con
                                    com.CommandType = Data.CommandType.Text
                                    com.CommandText = "INSERT INTO tbFileUpload VALUES('" & strftpPath1 & "','" & filename & "')"
                                    com.ExecuteNonQuery()
                                Else
                                    ClientScript.RegisterStartupScript(Me.GetType(), "onclick", "<script language='javascript'>alert('The File Name " & filename & " already exists .');</script>")
                                End If
                            Else
                                ClientScript.RegisterStartupScript(Me.GetType(), "onclick", "<script language='javascript'>alert('Please Provide a Directory .');</script>")
                            End If
                        Else
                            ClientScript.RegisterStartupScript(Me.GetType(), "onclick", "<script language='javascript'>alert('Please you select a uploaded file .');</script>")
                        End If
                    End If
                End If
            Catch ex As Exception
                Throw ex
            End Try
        End Sub
    #End Region

    #Region "Code for ServerValidation"
        Public Function ServerValidation() As Boolean
            Try
                Dim size, intlen As Long 'Uploaded File Size
                Dim strExt1 As String 'Extension Type
                Dim retVal As Int16
                size = FileUpload1.PostedFile.ContentLength
                intlen = FileUpload1.FileName.LastIndexOf("\")
                retVal = FileUpload1.FileName.Substring(intlen + 1, FileUpload1.FileName.Length - intlen - 1).Length
                'getting uploaded file Extension Type
                If FileUpload1.HasFile Then
                    Dim strArr As String() = FileUpload1.FileName.Split(".")
                    strExt1 = strArr(strArr.Length - 1).ToLower
                End If
                'Checking Validation
                If Not FileUpload1.HasFile Then
                    ClientScript.RegisterStartupScript(Me.GetType(), "onclick", "<script language='javascript'>alert('Notification: Select files to upload.');</script>")
                    Return False
                ElseIf (FileUpload1.HasFile And FileUpload1.FileName.LastIndexOf(".") = -1) Then
                    ClientScript.RegisterStartupScript(Me.GetType(), "onclick", "<script language='javascript'>alert('Notification: Only .doc, .docx, .ppt, .pptx, .xls, .xlsx, .pdf, .zip, .rtf, .jpg, .jpeg, .gif files can be Uploaded.');</script>")
                    SetFocus(FileUpload1)
                    Return False
                ElseIf strExt1 <> "doc" And strExt1 <> "docx" And strExt1 <> "xls" And strExt1 <> "xlsx" And strExt1 <> "ppt" And strExt1 <> "pptx" And strExt1 <> "pdf" And strExt1 <> "zip" And strExt1 <> "rtf" And strExt1 <> "jpg" And strExt1 <> "jpeg" And strExt1 <> "gif" And strExt1 <> "" Then
                    ClientScript.RegisterStartupScript(Me.GetType(), "onclick", "<script language='javascript'>alert('Notification: Only .doc, .docx, .ppt, .pptx, .xls, .xlsx, .pdf, .zip, .rtf, .jpg, .jpeg, .gif files can be Uploaded.');</script>")
                    SetFocus(FileUpload1)
                    Return False
                ElseIf retVal > 100 Then
                    ' To Check File Name Length (100chars)
                    ClientScript.RegisterStartupScript(Me.GetType(), "onclick", "<script language='javascript'>alert('Notification: Filename must not exceed 100 characters (including extension).');</script>")
                    Return False
                ElseIf size > 10240000 Then 'Must not exceed 10 MB.
                    ClientScript.RegisterStartupScript(Me.GetType(), "onclick", "<script language='javascript'>alert('Notification: Total Size of file (per Upload) must not exceed 10 MB.');</script>")
                    Return False
                Else
                    Return True
                End If
            Catch ex As Exception
                Return False
                Throw ex
            End Try
        End Function
    #End Region

    #Region "Code for Clear the Text"
        Protected Sub btnClear_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnClear.Click
            FileUpload1.Visible = True
        End Sub
    #End Region

    #Region "Code for Close"
        Protected Sub btnClose_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnClose.Click
            ClientScript.RegisterStartupScript(Me.GetType(), "onClick", "<script language='javascript'>window.close();</script>")
        End Sub
    #End Region

    End Class

Gadget

This content is not yet available over encrypted connections.