Awes VB ASP .NET Tips & Tricks

Tips and tricks for .NET using ASP and VB code.

Give user a .CSV file from a GridView without writing file to server.

    Protected Sub GridViewToCsv(SourceGridView As GridView, Optional DefaultClientCsvFilename As String = "Table.csv")
        Dim SourceDataTable As Data.DataTable = SourceGridView.DataSource
        If SourceDataTable Is Nothing Then
            SourceDataTable = ViewState("SourceDataTable")
        End If
        If SourceDataTable IsNot Nothing Then
            Dim CsvMemoryStream As New IO.MemoryStream
            Dim CsvStreamWriter As New IO.StreamWriter(CsvMemoryStream)
            Dim FieldsAndColumnHeadersDictionary As New Dictionary(Of String, String)
            For Each SourceGridViewRow As GridViewRow In SourceGridView.Rows
                If SourceGridViewRow.RowType = DataControlRowType.DataRow Then
                    For Each GridViewDataControlFieldCell As DataControlFieldCell In SourceGridViewRow.Cells
                        If TypeOf GridViewDataControlFieldCell.ContainingField Is BoundField Then
                            Dim GridViewBoundField As BoundField = GridViewDataControlFieldCell.ContainingField
                            If GridViewBoundField.Visible = True Then
                                Dim GridViewDataField As String = GridViewBoundField.DataField
                                Dim GridViewColumnHeaderText As String = GridViewBoundField.HeaderText
                                FieldsAndColumnHeadersDictionary.Add(GridViewDataField, ControlChars.Quote & GridViewColumnHeaderText.Replace(ControlChars.Quote, ControlChars.Quote & ControlChars.Quote) & ControlChars.Quote)
                            End If
                        End If
                    Next GridViewDataControlFieldCell
                    Exit For
                End If
            Next SourceGridViewRow
            Dim JoinedColumns As String = Join(FieldsAndColumnHeadersDictionary.Values.ToArray, ",")
            CsvStreamWriter.WriteLine(JoinedColumns)
            For Each SourceDataRow As Data.DataRow In SourceDataTable.Rows
                Dim DataList As New Generic.List(Of String)
                For Each GridViewColumn As String In FieldsAndColumnHeadersDictionary.Keys
                    DataList.Add(ControlChars.Quote & SourceDataRow.Item(GridViewColumn).ToString.Replace(ControlChars.Quote, ControlChars.Quote & ControlChars.Quote) & ControlChars.Quote)
                Next GridViewColumn
                Dim JoinedData As String = Join(DataList.ToArray, ",")
                CsvStreamWriter.WriteLine(JoinedData)
            Next SourceDataRow
            CsvStreamWriter.Flush()
            Dim CsvStreamBytes() As Byte = CsvMemoryStream.ToArray
            CsvMemoryStream.Close()
            Response.Clear()
            Response.ContentType = "application/force-download; charset=utf-8"
            Response.AddHeader("content-disposition", "attachment; filename=" & DefaultClientCsvFilename)
            Context.Response.BinaryWrite(System.Text.Encoding.UTF8.GetPreamble())
            Response.BinaryWrite(CsvStreamBytes)
            Response.End()
        End If
    End Sub

Select an area of page on button click

<html>
<head runat="server">
    <title>Select Text</title>
</head>
<body>
    <form id="form1" runat="server">
        <div id="SelectDiv">
            <table style="width: 100%;">
                <tr>
                    <td>Text to select.</td>
                </tr>
            </table>
        </div>
        <br />
        <asp:Button ID="SelectDataButton" runat="server" Text="Select Data" OnClientClick="selectText(); return false;" UseSubmitBehavior="False" />
    </form>
    <script type='text/javascript'>
        function selectText() {
            if (document.selection) {
                var div = document.body.createTextRange();
                div.moveToElementText(document.getElementById('SelectDiv'));
                div.select();
            }
            else {
                var div = document.createRange();
                div.setStartBefore(document.getElementById('SelectDiv'));
                div.setEndAfter(document.getElementById('SelectDiv'));
                window.getSelection().addRange(div);
            }
        }
    </script>
</body>
</html>

Reliably watch for new files in a folder

Public Class Form1
    Dim PublicWaitUntil As New Date
    Private Sub Me_Load(sender As Object, e As EventArgs) Handles Me.Load
        Me.Show()
        Dim SourceFolderText As String = "C:\Temp\Source\"
        Do
            Dim SourceFolderFileSystemWatcher As New IO.FileSystemWatcher
            SourceFolderFileSystemWatcher.Path = SourceFolderText
            SourceFolderFileSystemWatcher.Filter = "*.*"
            SourceFolderFileSystemWatcher.NotifyFilter = (IO.NotifyFilters.CreationTime Or IO.NotifyFilters.LastWrite Or IO.NotifyFilters.LastAccess Or IO.NotifyFilters.FileName Or IO.NotifyFilters.LastWrite Or IO.NotifyFilters.Size)
            AddHandler SourceFolderFileSystemWatcher.Changed, AddressOf SourceFolderFileSystemWatcher_Changed
            AddHandler SourceFolderFileSystemWatcher.Created, AddressOf SourceFolderFileSystemWatcher_Changed
            AddHandler SourceFolderFileSystemWatcher.Renamed, AddressOf SourceFolderFileSystemWatcher_Changed
            AddHandler SourceFolderFileSystemWatcher.Deleted, AddressOf SourceFolderFileSystemWatcher_Changed
            SourceFolderFileSystemWatcher.EnableRaisingEvents = True
            Paws(99999)
        Loop
    End Sub
    Public Sub Paws(ByVal Milliseconds As ULong)
        PublicWaitUntil = Now + New TimeSpan(0, 0, 0, 0, Milliseconds)
        Dim RemainingTimeSpan As New TimeSpan
        While Now < PublicWaitUntil
            Threading.Thread.Sleep(18)
            Application.DoEvents()
        End While
    End Sub
    Public Sub SourceFolderFileSystemWatcher_Changed()
        PublicWaitUntil = Now
        'Code to run when source folder changes.
    End Sub
End Class

Epoch functions

Dim EpochYears As Long = DateDiff(DateInterval.Year, Date.MinValue, Today)
Dim EpochQuarters As Long = DateDiff(DateInterval.Quarter, Date.MinValue, Today)
Dim EpochMonths As Long = DateDiff(DateInterval.Month, Date.MinValue, Today)
Dim EpochDays As Long = DateDiff(DateInterval.Day, Date.MinValue, Today)
Dim EpochHours As Long = DateDiff(DateInterval.Hour, Date.MinValue, Now)
Dim EpochMinutes As Long = DateDiff(DateInterval.Minute, Date.MinValue, Now)
Dim EpochSeconds As Long = DateDiff(DateInterval.Second, Date.MinValue, Now)

Case insensitive text replacement.

        Dim ReplacementString As String = "Text"
        ReplacementString = Strings.Replace(ReplacementString, "Text to replace", "Replacement text", 1, -1, CompareMethod.Text))

Default to Excel filetypes when uploading a file

<asp:FileUpload ID="FileUpload1" runat="server" accept="application/vnd.ms-excel, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" />

Delete files in a folder that are over a week old

        If IsPostBack = False Then
            For Each ActivityFileInfo As IO.FileInfo In New IO.DirectoryInfo(Server.MapPath(".") & "\ActivityFiles\").GetFiles("*.txt")
                If DateDiff(DateInterval.Day, ActivityFileInfo.CreationTime, Now) > 6 Then
                    ActivityFileInfo.Delete()
                End If
            Next ActivityFileInfo
        End If

Show countdown while generating page

Dim PreviousPageTitle As String = Page.Title
Dim TotalIterations As Integer = 1000
Dim StartTime As DateTime = Now
    For CurrentInteration As Integer = 0 To TotalIterations
        If CurrentInteration > 0 Then
            Dim RemainingIterations As Integer = TotalIterations - CurrentInteration
            Dim RemainingProgressPercent As Single = 1 - CurrentInteration / TotalIterations
            Dim TimePassed As TimeSpan = Now - StartTime
            Dim TimeToEnd As New TimeSpan(TotalIterations * TimePassed.Ticks / CurrentInteration)
            Dim TimeRemaining As TimeSpan = TimeToEnd - TimePassed
            Threading.Thread.Sleep(18)
            Response.Flush()
            Response.Write(String.Format("<script>document.title = '{0} {1} {2}'</script>", RemainingIterations, TimeRemaining.ToString("m':'ss"), RemainingProgressPercent.ToString("p1")))
        End If
    Next CurrentInteration
Page.Title = PreviousPageTitle
Response.Write("<script>document.title = '" & PreviousPageTitle & "'</script>")

Initialize values from cookies

Partial Class _Default
    Inherits System.Web.UI.Page

    Function GetCookie(ByVal Sender As Control, ByVal PropertyName As String) As String
        Dim ReturnValue As String = Nothing
        Dim ControlId As String = Sender.ID
        Try
            If Request.Cookies(ControlId) IsNot Nothing Then
                ReturnValue = Server.HtmlDecode(Request.Cookies(ControlId)(PropertyName)).ToString
            End If
        Catch
        End Try
        Return ReturnValue
    End Function

    Protected Sub SetCookie(ByVal Sender As Control, ByVal PropertyName As String, ByVal CookieValue As String)
        Dim ThisCookie As New HttpCookie(Sender.ID)
        ThisCookie.Expires = Now.AddYears(1)
        ThisCookie.Values(PropertyName) = Server.HtmlEncode(CookieValue)
        Try
            Response.Cookies.Add(ThisCookie)
        Catch
        End Try
    End Sub

    Protected Sub CheckBox1_CheckedChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles CheckBox1.CheckedChanged
        SetCookie(CType(sender, Control), "Checked", CheckBox1.Checked.ToString)
    End Sub

    Protected Sub CheckBox1_PreRender(ByVal sender As Object, ByVal e As System.EventArgs) Handles CheckBox1.PreRender
        If IsPostBack = False Then
            If GetCookie(CType(sender, Control), "Checked") IsNot Nothing Then
                CheckBox1.Checked = CBool(GetCookie(CType(sender, Control), "Checked"))
                Dim temp1 As Boolean = CBool("True")
                Dim temp2 As Boolean = CBool("False")
                Dim temp3 As String = GetCookie(CType(sender, Control), "Checked")
            End If
        End If
    End Sub

    Protected Sub CheckBoxList1_PreRender(ByVal sender As Object, ByVal e As System.EventArgs) Handles CheckBoxList1.PreRender
        If IsPostBack = False Then
            If GetCookie(CType(sender, Control), "SelectedValues") IsNot Nothing Then
                Dim SelectedValuesJoined As String = GetCookie(CType(sender, Control), "SelectedValues")
                Dim SelectedValuesArray() As String = Split(SelectedValuesJoined, ",")
                For Each CheckBoxListItem As ListItem In CheckBoxList1.Items
                    If SelectedValuesArray.Contains(CheckBoxListItem.Value) Then
                        CheckBoxListItem.Selected = True
                    Else
                        CheckBoxListItem.Selected = False
                    End If
                Next CheckBoxListItem
            End If
        End If
    End Sub

    Protected Sub CheckBoxList1_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles CheckBoxList1.SelectedIndexChanged
        Dim SelectedValuesList As New Generic.List(Of String)
        For Each CheckBoxListItem As ListItem In CheckBoxList1.Items
            If CheckBoxListItem.Selected = True Then
                SelectedValuesList.Add(CheckBoxListItem.Value)
            End If
        Next CheckBoxListItem
        Dim SelectedValuesJoined As String = String.Join(",", SelectedValuesList.ToArray)
        SetCookie(CType(sender, Control), "SelectedValues", SelectedValuesJoined)
    End Sub

    Protected Sub TextBox1_PreRender(ByVal sender As Object, ByVal e As System.EventArgs) Handles TextBox1.PreRender
        If IsPostBack = False Then
            If GetCookie(CType(sender, Control), "Text") IsNot Nothing Then
                'Receiving text from a cookie can be hazardous.
                TextBox1.Text = GetCookie(CType(sender, Control), "Text")
            End If
        End If
    End Sub

    Protected Sub TextBox1_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles TextBox1.TextChanged
        SetCookie(CType(sender, Control), "Text", TextBox1.Text)
    End Sub

    Protected Sub RadioButton1_PreRender(ByVal sender As Object, ByVal e As System.EventArgs) Handles RadioButton1.PreRender
        If IsPostBack = False Then
            If GetCookie(CType(sender, Control), "Checked") IsNot Nothing Then
                RadioButton1.Checked = CBool(GetCookie(CType(sender, Control), "Checked"))
            End If
        End If
    End Sub

    Protected Sub RadioButton1_CheckedChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles RadioButton1.CheckedChanged
        SetCookie(CType(sender, Control), "Checked", RadioButton1.Checked.ToString)
    End Sub

Search This Blog