Force SSL ON or OFF Function

When working on a site that may have some pages in SSL (the check out pages) and most pages not I use a function to switch between SSL and Non SSL pages.

First, I set the non secure and SSL URL’s in the config file under appSettings:

    <add key=”SSLURL” value=”https://www.mydomain.com”/>
    <add key=”NonSSLURL” value=”http://www.mydomain.com”/>

Next, in my utility class I add this function:

    Public Function PageStartUp()
        If Request.ServerVariables(“HTTPS”).ToLower = “on” And Not gIsSSLRequired Then
            If Request.QueryString.ToString.Length > 0 Then
                Response.Redirect(ConfigurationManager.AppSettings(“NonSSLURL”) & Request.ServerVariables(“SCRIPT_NAME”) & “?” & Request.QueryString.ToString)
            Else
                Response.Redirect(ConfigurationManager.AppSettings(“NonSSLURL”) & Request.ServerVariables(“SCRIPT_NAME”))
            End If
        End If
        If Request.ServerVariables(“HTTPS”).ToLower = “off” And gIsSSLRequired And ConfigurationManager.AppSettings(“SSLURL”).ToLower.Substring(0,5)=”https” Then
            If Request.QueryString.ToString.Length > 0 Then
                Response.Redirect(ConfigurationManager.AppSettings(“SSLURL”) & Request.ServerVariables(“SCRIPT_NAME”) & “?” & Request.QueryString.ToString)
            Else
                Response.Redirect(ConfigurationManager.AppSettings(“SSLURL”) & Request.ServerVariables(“SCRIPT_NAME”))
            End If
        End If
        Return True
    End Function

Be sure to add the public variable gIsSSLRequired in the class as well.

Then in the page load event of each page I add the following:

gIsSSLRequired = True
Call PageStartUp()

Cool, huh?

JavaScript Code To Toggle Check Boxes

Here is some JavaScript code to toggle check boxes (same action as radio buttons).

In the page load event register the JavaScript: 

   chkTwoYear.Attributes.Add(“onclick”, “javascript: CheckTwoProgram(” + chkTwoYear.ClientID + “);”); 
   chkFourYear.Attributes.Add(“onclick”, “javascript: CheckFourProgram(” + chkFourYear.ClientID + “);”);

In the HTML of the page add the JavaScript:

<SCRIPT Language=”JavaScript”><!–
function CheckTwoProgram(id) { 
   if(id.checked) 
      document.forms[0].chkFourYear.checked=false; 
   }
function CheckFourProgram(id) { 
   if(id.checked) 
      document.forms[0].chkTwoYear.checked=false; 
   }
//–>
</SCRIPT>

VB.Net Format Phone Number Function

Here is a function to format phone numbers. I picked it up from here: http://www.freevbcode.com/ShowCode.asp?ID=1968

‘Takes any entered phone number and returns it in ###-#### format
‘or (###) ###-####

Public Function FormatPhoneNumber(ByVal sNumToBeFormatted As _
   String) As String

Dim iNumberLength As Integer ‘Used for the Phone Number length
  
‘Trim any leading and trailing spaces

sNumToBeFormatted = Trim$(sNumToBeFormatted)
  
‘Length of the phone number.

iNumberLength = Len(sNumToBeFormatted)
  
Select Case iNumberLength

  Case 7  ‘Format : #######

    FormatPhoneNumber = Left$(sNumToBeFormatted, 3) & _
        “-” & Right$(sNumToBeFormatted, 4)
    Exit Function

  Case 8  ‘Format : ###-#### or ### ####

    If Mid$(sNumToBeFormatted, 4, 1) = “-” Then
       FormatPhoneNumber = sNumToBeFormatted
       Exit Function
    Else
       FormatPhoneNumber = Left$(sNumToBeFormatted, 3) & “-” & _
          Right$(sNumToBeFormatted, 4)
       Exit Function
    End If

  Case 10 ‘Format : ##########

 FormatPhoneNumber = “(” & Left$(sNumToBeFormatted, 3) & “) ” _
   & Mid$(sNumToBeFormatted, 4, 3) & “-” & _
     Right$(sNumToBeFormatted, 4)
 
   Exit Function

  Case 11 ‘Format ######-####

 FormatPhoneNumber = “(” & Left$(sNumToBeFormatted, 3) & “) ” & _
       Right$(sNumToBeFormatted, 8)
    Exit Function

  Case 12 ‘Format : ### ###-####

 FormatPhoneNumber = “(” & Left$(sNumToBeFormatted, 3) & “) ” & _
      Mid$(sNumToBeFormatted, 5, 3) & “-” & _
      Right$(sNumToBeFormatted, 4)
    Exit Function

  Case 13 ‘Format : (###)###-####
     FormatPhoneNumber = Left(sNumToBeFormatted, 5) & ” ” & _
        Right(sNumToBeFormatted, 8)
     Exit Function


  Case Else
        ‘Return Value Passed
     FormatPhoneNumber = sNumToBeFormatted
          
End Select

End Function

How to run client side javascript on a server control

Here is some code to run a javascript function on the client side when a value changes in a drop down box. In this case I have a list of dates populating a drop down box. When the date changes the value of a DIV section changes to a corresponding end date.

In the appSetting section of the web.config file:

<add key=StartDates value=12/06/06, 02/27/07, 05/09/07, 07/03/07, 10/10/07, 01/08/08, 03/02/08/>
<
add key=EndDates value=10/08/07, 12/21/07, 03/18/08, 05/29/08, 08/18/08, 10/29/08, 01/27/09/>

In the page load section:

 ‘ Get the start and end dates from the web.config file
 
 Dim StartDates As Array
 StartDates = ConfigurationManager.AppSettings(“StartDates”).Split(“,”)
 EndDates = “‘” & ConfigurationManager.AppSettings(“EndDates”).Replace(“, “, “‘, ‘”) & “‘”  ‘ format the string for a javascript array
 EndDate = EndDates.Substring(0, EndDates.IndexOf(“,”)).Replace(“‘”, “”)
 
 ‘ Populate the Start Date drop down / combo box
 
 ddlStartDate.AppendDataBoundItems = True
 Dim Item As String
 For Each Item In StartDates
  Items = New ListItem
  Items.Text = Item
  Items.Value = Item
  ddlStartDate.Items.Add(Items)
 Next
 
 ‘ Register the javascript code to run on the client side
 
 ddlStartDate.Attributes.Add(“onchange”, “javascript: doAction(” + ddlStartDate.ClientID + “)”)

Then in the web form:

<table border =”0″><tr><td><asp:DropDownList ID=”ddlStartDate” runat=”server”></asp:DropDownList></td><td><div id=”EstCompDate”>Est. Comp. Date: <b><%=EndDate%></b></div></td></tr></table>

Then at the bottom of the HTML of the page (just above the </html> tag):

<script language=”javascript”>
var
endDates = new Array(<%=EndDates %>);
function doAction(id) {
   var selection = id.options[id.selectedIndex].value;
   EstCompDate.innerHTML =
‘Est. Comp. Date: <b>’ + endDates[id.selectedIndex] + ‘</b>’;
}
</script>

How to send an email by authenticating with any mail server

If you want to send an email from an application that might not be on a server that allows relaying you can use the System.Net.NetworkCredential. Just add your account login and password and your email will route through the remote server.

    Dim sTo As String = “someone@someemail.com
    Dim sFrom As String = “me@myemail.com
    Dim sSubject As String = “Using the new SMTP client.”
    Dim sBody As String = “Using this new feature, you can send an e-mail message from an application very easily.”
    Dim msg As New Net.Mail.MailMessage(sFrom, sTo, sSubject, sBody)
 
    Dim client As New Net.Mail.SmtpClient(“mail.myemail.com”, 25)
    Dim SMTPUserInfo As New System.Net.NetworkCredential(“me@myemail.com“, “password”)
    client.UseDefaultCredentials = False
    client.Credentials = SMTPUserInfo
 
    client.Send(msg)

GridView Format Note

When applying a Format expression in the DataFormatString property of a column such as “{0:d}” the HtmlEncode property must be set to False. If HtmlEncode is set to True the format expression will not be applied.