Friday, May 4, 2012

Prevent Page from "jumping" on submit



One Solution:

<script type="text/javascript">
          window.scrollTo = function (x, y) {
              return true;
          }
</script>

Thursday, April 19, 2012

Logout when using ASP.NET memberships


What are we cooking today?
Logout when using ASP.NET memberships

RECIPE

  Protected Sub lnkLogout_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles lnkLogout.Click

        FormsAuthentication.SignOut()

        Response.Redirect(FormsAuthentication.LoginUrl)
    
  End Sub

Tuesday, April 17, 2012

Export from generic list of Objects to Excel (skipping provided column names)


What are we cooking today?
Export from generic list to Excel (skipping provided column names)

RECIPE

 Public Sub ExportToExcelFromList(fileName As String, listAID As List(Of AppInfoDay), Optional strArrListToSkip As String() = Nothing)
        'The Clear method erases any buffered HTML output.
        HttpContext.Current.Response.Clear()
        'The AddHeader method adds a new HTML header and value to the response sent to the client.
        HttpContext.Current.Response.AddHeader("content-disposition", String.Format("attachment; filename={0}", fileName & ".xls"))
        'The ContentType property specifies the HTTP content type for the response.
        HttpContext.Current.Response.ContentType = "application/ms-excel"
        'Implements a TextWriter for writing information to a string. The information is stored in an underlying StringBuilder.
        Using sw As New StringWriter()
            'Writes markup characters and text to an ASP.NET server control output stream. This class provides formatting capabilities that ASP.NET server controls use when rendering markup to clients.
            Using htw As New HtmlTextWriter(sw)
                '  Create a form to contain the List
                Dim table As New Table()
                Dim row As New TableRow()

                '---ADD COLS HEADER BASED ON OBJECT PROPERTIES
                For Each proinfo As PropertyInfo In New AppInfoDay().[GetType]().GetProperties()
                    '---SKIP UNDESIRED COLUMNS
                    If strArrListToSkip.Contains(proinfo.Name) Then
                        Continue For
                    Else
                        Dim hcell As New TableHeaderCell()
                        hcell.Text = proinfo.Name
                        row.Cells.Add(hcell)
                    End If
                Next
                table.Rows.Add(row)



                '---ADD ROWS WITH DATA
                For Each aid As AppInfoDay In listAID

                    Dim newRow As New TableRow()
                    For Each proinfo As PropertyInfo In aid.[GetType].GetProperties()
                        If strArrListToSkip.Contains(proinfo.Name) Then
                            Continue For
                        Else
                            Dim NewCell As New TableCell()
                            NewCell.Text = proinfo.GetValue(aid, Nothing).ToString()
                            newRow.Cells.Add(NewCell)
                        End If
                    Next
                    table.Rows.Add(newRow)
                Next

                '  render the table into the htmlwriter
                table.RenderControl(htw)
                '  render the htmlwriter into the response
                HttpContext.Current.Response.Write(sw.ToString())
                HttpContext.Current.Response.[End]()
            End Using
        End Using
    End Sub

Thursday, March 15, 2012

Padding an string with a character (n times) in SQL Server



What are we cooking today?
Padding an string with a character (n times) in SQL Server

RECIPE

Declare @myString as varchar(10)
set @myString = '1234567'

select  RIGHT(REPLICATE('0', 10)
+ CAST(@mystring AS VARCHAR(10)), 10) PaddedResult

RESULT:
0001234567

Friday, February 17, 2012

Loading a dropdownlist from an XML file


What are we cooking today?
One Way of loading a dropdownlist from an XML file (sample: reading dates from an XML file)

RECIPE
The XML looks like:

<?xml version="1.0" encoding="utf-8" ?> <dates> <LocationA> <date>February 17, 2012</date> <date>March 29, 2012</date> <date>April 26, 2012</date> </LocationA> <LocationB> <date>March 29, 2012</date> <date>April 26, 2012</date> </LocationB> </dates>


The procedure:

Public Sub LoadDatesFromXMLFile(ByVal strOption As String) Try Dim doc As XDocument = XDocument.Load(MapPath("MyFile.xml")) If strOption = " LocationA " Then For Each element As XElement In doc.Descendants(" LocationA ") For Each XmlNode In element.Descendants("date") ddlAvailableDates.Items.Add(XmlNode.Value) Next Next Else For Each element As XElement In doc.Descendants("LocationB") For Each XmlNode In element.Descendants("date") ddlAvailableDates.Items.Add(XmlNode.Value) Next Next End If Catch ex As Exception lblError.Text = ex.Message End Try End Sub

Friday, January 20, 2012

Sorting a dropdownlist in VB.net


What are we cooking today?
One Way of Sorting a dropdownlist in VB.net

RECIPE

The Procedure


    Private Sub SortDropDown(ByVal ddl As DropDownList)


        '---Get listItems from dropDownList
        Dim ddlList As New ArrayList
        For Each li As ListItem In ddl.Items
            ddlList.Add(li)
        Next

        '---Sort arraylist
        ddlList.Sort(New ListItemComparer)


        '---Copy sorted list back into the dropDownList
        ddl.Items.Clear()
        For Each li As ListItem In ddlList
            ddl.Items.Add(li)
        Next

    End Sub
    

The Icomparer: I am using this because a listitem has text and value, and we just want to order by the text, which could be a person's name or a product( the criteria could be also the value like price, personId, year...)


 Public Class ListItemComparer : Implements IComparer


    Public Function Compare(ByVal x As Object, _
          ByVal y As Object) As Integer _
          Implements IComparer.Compare
        Dim a As ListItem = x
        Dim b As ListItem = y
        Dim c As New CaseInsensitiveComparer
        Return c.Compare(a.Text, b.Text)
    End Function

End Class

Monday, November 7, 2011

Disable caching (Browser back button problem)


When the user hit the back button a locally cached copy of the previous page is retrieved without notifying the server. As a result the Info is out of sync.

Solution 1 --> Disable caching (do not work for all browsers)
Code to disable caching (to be executed everytime thepage is loaded)

Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Cache.SetExpires(Now.AddSeconds(-1));   //--- (-1) means the page already expired
Response.Cache.SetNoStore();  //--tell the page not to cache the page
Response.AppendHeader("Pragma", "no-cache");  //---adds a header to the HTTP response object


Solution 2 --> Use timestamps or random numbers to track pages and detect when a page is current