RSS
 

Archive for the ‘Web Design’ Category

Dynamic Parameterized Queries in VB.Net

01 Jun

I have a bit of code which can be found here. I use this all the time when I am developing classic ASP web application.

I recently found that I have a need for the same methodolgy was needed in a .Net application I recently started developing, so I came up with the following:

Code:

  1. Imports System
  2. Imports System.Data
  3. Imports System.Data.SqlClient
  4.  
  5.  
  6. Namespace ZipCM
  7.  
  8.     Public Class Database
  9.  
  10. #Region "Properties"
  11.         Public ConnString As String
  12.         Public CmdType As Integer
  13.         Public Query As String
  14.         Public Values As Object
  15.         Public ParamNames As Object
  16.         Public ReturnValues As Object
  17.         Public FieldCount As Long
  18.         Public TotalRecords As Long
  19.         Public AffectedRows As Long
  20.         Public ReturnValue As Object
  21.         Public HasReturn As Boolean
  22.         Public ReturnParamName As String
  23.         Public ReturnDataType As Object
  24.  
  25.         Private i As Integer
  26. #End Region
  27.  
  28. #Region "ExecuteDataReader"
  29.         Public Sub ExecuteDataReader()
  30.             Try
  31.                 Dim objConn As New SqlConnection(ConnString)
  32.                 Dim objCmd As New SqlCommand(Query, objConn)
  33.                 Dim objDA As New SqlDataAdapter()
  34.                 Dim objDS As New DataSet()
  35.                 If IsArray(Values) And IsArray(ParamNames) Then
  36.                     If UBound(Values) = UBound(ParamNames) Then
  37.                         ‘Prepare our parameters
  38.                        For Me.i = 0 To UBound(Values)
  39.                             objCmd.Parameters.AddWithValue(ParamNames(i), Values(i))
  40.                         Next
  41.                         objCmd.CommandType = CmdType
  42.                         objCmd.Connection.Open()
  43.                         objDA.SelectCommand = objCmd
  44.                         objDA.Fill(objDS, "Tbl")
  45.                         objCmd = Nothing
  46.                         objConn.Close() : objConn = Nothing
  47.                         Dim DT As DataTable = objDS.Tables("Tbl")
  48.                         FieldCount = DT.Columns.Count
  49.                         TotalRecords = DT.Rows.Count
  50.                         Dim c As Integer
  51.                         Dim r As Integer
  52.                         Dim tmpRetVals(FieldCount – 1, TotalRecords – 1) As Array
  53.                         For c = 0 To FieldCount – 1
  54.                             For r = 0 To TotalRecords – 1
  55.                                 tmpRetVals(c, r) = New String() {DT.Columns.Item(c).ColumnName, DT.Rows(r)(c).ToString()}
  56.                             Next
  57.                         Next
  58.                         ReturnValues = tmpRetVals
  59.  
  60.                     End If
  61.                 End If
  62.             Catch ex As Exception
  63.  
  64.             End Try
  65.         End Sub
  66.  
  67. #End Region
  68.  
  69. #Region "Execute Non Data Reader"
  70.  
  71.         Public Sub ExecuteNDQuery()
  72.             Try
  73.                 Dim objConn As New SqlConnection(ConnString)
  74.                 Dim objCmd As New SqlCommand(Query, objConn)
  75.                 Dim objParam As SqlParameter
  76.                 If IsArray(Values) And IsArray(ParamNames) Then
  77.                     If UBound(Values) = UBound(ParamNames) Then
  78.                         ‘Prepare our parameters
  79.                        If HasReturn Then
  80.                             objParam = New SqlParameter(ReturnParamName, ReturnDataType)
  81.                             objParam.Direction = ParameterDirection.Output
  82.                             objCmd.Parameters.Add(objParam)
  83.                             objParam = Nothing
  84.                         End If
  85.                         For Me.i = 0 To UBound(Values)
  86.                             objCmd.Parameters.AddWithValue(ParamNames(i), Values(i))
  87.                         Next
  88.                         objCmd.CommandType = CmdType
  89.                         objCmd.Connection.Open()
  90.                         If HasReturn Then
  91.                             objCmd.ExecuteNonQuery()
  92.                             ReturnValue = objCmd.Parameters(ReturnParamName).Value
  93.                         Else
  94.                             objCmd.ExecuteNonQuery()
  95.                         End If
  96.                         objCmd.Connection.Close() : objConn = Nothing
  97.  
  98.                     End If
  99.                 End If
  100.             Catch ex As Exception
  101.  
  102.             End Try
  103.         End Sub
  104.  
  105. #End Region
  106.  
  107.     End Class
  108. End Namespace
 
 

Optimizing Scripts

22 Jan

I’ve found that by optimizing my javascript and CSS files a bit, I can decrease the load times of my pages by quite a bit.

Combining script files, and removing a few elements decreased the total filesize by 36%.

Here is how I do it!

Using it!

  1. <!–#include virtual="/includes/server/classes/compress.asp"–>
  2. <%
  3. Set objCompress = New clsCompress
  4.         Dim FilePath : FilePath =       Split(Request.QueryString("file"), ",")
  5.         objCompress.strFile =           FilePath
  6.         objCompress.ReturnScripts()
  7. Set objCompress = Nothing
  8. %>

{please note, you will have to change the location of the include file.}

Include File

  1. <%
  2. Class clsCompress
  3.         Public strFile
  4.         Private objFSO, objFile, objRegExp, strCompressedFile, strFileType
  5.         Private Sub Class_Initialize()
  6.                 strCompressedFile = ""
  7.         End Sub
  8.         Public Sub ReturnScripts()
  9.                 Set objFSO = CreateObject("Scripting.FileSystemObject")
  10.                         If IsArray(strFile) Then
  11.                                 For i = 0 To UBound(strFile)
  12.                                         Set objFile = objFSO.OpenTextFile(Server.MapPath(strFile(i)))
  13.                                                 If Not(objFile.AtEndOfStream) Then
  14.                                                         strCompressedFile = strCompressedFile & VbCrLf & objFile.ReadAll
  15.                                                 End If
  16.                                         Set objFile = Nothing
  17.                                         tmp = Right(strFile(i), 3)
  18.                                         strFileType = Replace(tmp, ".", "")
  19.                                 Next : i = Null
  20.                                 Erase strFile
  21.                         End If
  22.                 Set objFSO = Nothing
  23.                 Select Case UCase(strFileType)
  24.                         Case "CSS" ‘CSS
  25.                                 Set objRegExp = New RegExp
  26.                                         objRegExp.IgnoreCase = True
  27.                                         objRegExp.Global = True
  28.                                         objRegExp.Pattern = "/\*[^*]*\*+([^/][^*]*\*+)*/"
  29.                                         strCompressedFile = objRegExp.Replace(strCompressedFile, "")
  30.                                 Set objRegExp = Nothing                        
  31.                                 ‘Strip Line Breaks
  32.                                 Set objRegExp = New RegExp
  33.                                         objRegExp.IgnoreCase = True
  34.                                         objRegExp.Global = True
  35.                                         objRegExp.Pattern = "\n+"
  36.                                         strCompressedFile = objRegExp.Replace(strCompressedFile, "")
  37.                                 Set objRegExp = Nothing                        
  38.                                 ‘Strip Tabs
  39.                                 Set objRegExp = New RegExp
  40.                                         objRegExp.IgnoreCase = True
  41.                                         objRegExp.Global = True
  42.                                         objRegExp.Pattern = "\t+"
  43.                                         strCompressedFile = objRegExp.Replace(strCompressedFile, "")
  44.                                 Set objRegExp = Nothing
  45.                                 ‘Strip Spaces Greater than 2 long
  46.                                 Set objRegExp = New RegExp
  47.                                         objRegExp.IgnoreCase = True
  48.                                         objRegExp.Global = True
  49.                                         objRegExp.Pattern = "\s{2}"
  50.                                         strCompressedFile = objRegExp.Replace(strCompressedFile, "")
  51.                                 Set objRegExp = Nothing
  52.                                 Response.ContentType = "text/css"
  53.                                 Response.Write(strCompressedFile)
  54.                                 Response.Flush
  55.                                 Response.Clear
  56.                         Case "JS" ‘Javascript
  57.                                 ‘Strip New Lines
  58.                                 strCompressedFile = Replace(strCompressedFile, VbCr, "")
  59.                                 ‘Strip Spaces Greater than 2 long
  60.                                 strCompressedFile = Replace(strCompressedFile, "  ", "")
  61.                                 Response.ContentType = "text/javascript"
  62.                                 Response.Write(strCompressedFile)
  63.                                 Response.Flush
  64.                                 Response.Clear
  65.                 End Select
  66.         End Sub
  67. End Class
  68. %>
 
 

Couple of JQuery Ajax Loaders

22 Dec

I had a couple of instances where I needed some nice, clean AJAX content loaders. Once to slide a page, one to page, and one with no effects.

Here is the code for them… enjoy (p.s. these require you include the JQuery library, also make sure to change any path inside to the path of your loading images)

  1. function loadPageFade(strPageToLoad, strWhereToLoadIt) {
  2.         $.ajax({
  3.                 url: strPageToLoad,
  4.                 beforeSend: function(){
  5.                         $(strWhereToLoadIt).queue( function() {
  6.                                 $(this).html(‘<p style="text-align:center;"><img src="/icons/loading_bar.gif" alt="Loading…" /></p>’);
  7.                                 $(this).animate({opacity:0}, 500);
  8.                                 $(this).dequeue();
  9.                         });
  10.                 },
  11.                 cache: false,
  12.                 success: function(html){
  13.                         $(strWhereToLoadIt).queue( function() {
  14.                                 $(this).html(html).animate({opacity:1}, 500);
  15.                                 $(this).dequeue();
  16.                         });
  17.                 },
  18.                 error: function(){
  19.                         $(strWhereToLoadIt).queue( function() {
  20.                                 $(this).html(‘<div class="err_message">There was an error processing your request.</div>’).animate({opacity:1}, 500);
  21.                                 $(this).dequeue();
  22.                         });
  23.                 }
  24.                 });
  25. }
  26. function loadPageSlide(strPageToLoad, strWhereToLoadIt) {
  27.         $.ajax({
  28.                 url: strPageToLoad,
  29.                 beforeSend: function(){
  30.                         $(strWhereToLoadIt).slideUp(300);
  31.                 },
  32.                 cache: false,
  33.                 success: function(html){
  34.                         $(strWhereToLoadIt).html(html).slideDown(500);
  35.                 },
  36.                 error: function(){
  37.                         $(strWhereToLoadIt).html(‘<div class="err_message">There was an error processing your request.</div>’).hide().slideDown(500);
  38.                 }
  39.                 });
  40. }
  41. function loadPage(strPageToLoad, strWhereToLoadIt) {
  42.         $.ajax({
  43.                 url: strPageToLoad,
  44.                 cache: false,
  45.                 success: function(html){
  46.                         $(strWhereToLoadIt).html(html);
  47.                 },
  48.                 error: function(){
  49.                         $(strWhereToLoadIt).html(‘<div class="err_message">There was an error processing your request.</div>’).hide().fadeIn(1000);
  50.                 }
  51.                 });
  52. }
 
 

Dynamic Parameterized Queries w/ Paging

16 Dec

I did this because it was said that it could not be done.

Here we have a method to utilize the ADO.Command object, ADO.GetRows(), and true recordset paging, all wrapped in one neat little class.

Usage.asp

  1. <!–#include virtual="/cls_db.asp"–>
  2. <%
  3. ‘*****************************************************************************  
  4. ‘*****************************************************************************  
  5. ‘  
  6. ‘ This code can be used anywhere you like, all I ask is that you keep this  
  7. ‘ notice here, so people know who actually made it! =D  Thanks!  
  8. ‘  
  9. ‘ This code was developed by Kevin Pirnie, c/o o7th Web Design  
  10. ‘ support@07th.com :: http://www.07th.com  
  11. ‘  
  12. ‘*****************************************************************************  
  13. ‘*****************************************************************************
  14. ‘——————————————————————————
  15. ‘——————————————————————————
  16. ‘Dimension our variables
  17. Dim objData, intPage
  18. Dim intCols, intRows, intTotPages, intTotRecs, strDisplayPaging, strConnString
  19. ‘——————————————————————————
  20. ‘——————————————————————————
  21. ‘Get the page we are on, if any
  22. intPage = Request.QueryString("p")
  23. ‘If we don’t have a page, set it to 1
  24. If Not(IsNumeric(intPage)) Then intPage = 1
  25. ‘——————————————————————————
  26. ‘——————————————————————————
  27. ‘Set our data object to the class
  28. Set objData = New DBv1
  29.         With objData ‘just because i don’t feel like typing out objData everytime I need it
  30.                 ‘Set our command type: 1 = Inline SQL Statement, 4 = Stored Procedure
  31.                 .intCommandType =               1
  32.                 ‘Pass our Connection String … if we have one, uncomment the line below, and comment the … section
  33.                 ‘.strConnString =               strConnString
  34.                 ‘Or we can simply build it here, just uncomment the lines in between …
  35.                 ‘ …
  36.                 .intDBType =                    3
  37.                 ‘Supported database types:
  38.                 ‘       1 = SQL 2000
  39.                 ‘       2 = SQL 2005
  40.                 ‘       3 = SQL 2005 Express
  41.                 ‘       4 = MS Access
  42.                 ‘       6 = MS Access 2007
  43.                 ‘       7 = MySQL
  44.                 ‘       8 = Borland Interbase ‘<- requires the proper driver installed on the server
  45.                 .strDBServer =                  "The Address to your Database Server"
  46.                 .strDBUser =                    "The Database Username"
  47.                 .strDBPassword =                "The Database Password"
  48.                 .strDBDatabase =                "The default database"
  49.                 ‘ …
  50.                 ‘Pass the class our SQL statement, use ? in the WHERE clause
  51.                 ‘You can also use this to fire off a stored procedure
  52.                 .strQry =                               "Select Field1, Field2 From Table Where Field3 = ? Or Field4 = ?"
  53.                 ‘Pass an array of values to look for in our WHERE clause
  54.                 .arrParamValues =               Array(Val1, Val2) ‘If none, use ""
  55.                 ‘Pass an array of Data Types for our values (These are ADO DataTypes, and the list of them can be found here -> http://www.w3schools.com/ADO/ado_datatypes.asp)
  56.                 ‘Only use the numeric value for this, we also only support the following:
  57.                 ’2, 3, 4, 5, 6, 7, 11, 14, 72, 128, 129, 200, 203, 204
  58.                 .arrParamDataTypes =    Array(200, 200) ‘If none, use ""
  59.                 ‘If we fire a stored procedure, and it has an output variable
  60.                 ‘.intRetDataType =              3 ‘Set the return value data type
  61.                 ‘.intRetSize =                  4 ‘Set the return value size
  62.                 ‘Do we want to page the results?
  63.                 .boolUsePaging =                True ‘or False
  64.                 ‘How many records per page do we want to display?
  65.                 .intRecPerPage =                10 ‘any numeric value
  66.                 ‘What page number are we on?
  67.                 .intPageNumber =                intPage
  68.                 ‘What page are we displaying these results?
  69.                 .strPagingPage =                "usage.asp?a=a" ‘We use a=a because the paging method expects a querystring to already be available
  70.                 ‘What should we use to display for the left arrows?
  71.                 .strPagingLeft =                "&laquo;"
  72.                 ‘What should we use to display for the right arrows?
  73.                 .strPagingRight =               "&raquo;"
  74.                 ‘Execute our query, and store the resulting 2d array in a variable for use later
  75.                 ‘If we fire a stored procedure and it has an output variable, this variable will equal that value
  76.                 tmpArray =                              .ExecuteQry()
  77.                 ‘Get the total number of pages returned from the recordset
  78.                 intTotPages =                   .intTotalPages
  79.                 ‘Get the total number of records returned from the recordset
  80.                 intTotRecs =                    .intTotalRecords
  81.                 ‘Get our paging links for the recordset
  82.                 strDisplayPaging =              .RecordPaging()
  83.         End With ‘End our With block
  84. ‘Clean up the object
  85. Set objData = Nothing
  86. ‘——————————————————————————
  87. ‘——————————————————————————
  88. ‘Now that we have done all this, let’s see what the results are.
  89. ‘First we check to see if we have an array
  90. If IsArray(tmpArray) Then
  91.         ‘We have an array, so let’s work with it
  92.         ‘I’d like to put in the info about the paging, total records & total pages
  93.         Response.Write("<strong>" & intTotRecs & "</strong> total records in <strong>" & intTotPages & "</strong> pages.")
  94.         ‘Now I want to display my paging links
  95.         Response.Write(strDisplayPaging)
  96.         ‘Now Let’s display the results of the recordset…
  97.         Response.Write("<table width=""100%"" cellpadding=""2"" cellspacing=""0"" border=""1"">" & VbCrLf)
  98.         ‘Since I know how many columns, I will simply put the table header here
  99.         Response.Write("        <thead>" & VbCrLf)
  100.         Response.Write("                <tr>" & VbCrLf)
  101.         Response.Write("                        <th>ISO CC</th>" & VbCrLf)
  102.         Response.Write("                        <th>ISO CC3</th>" & VbCrLf)
  103.         Response.Write("                        <th>Country Number Code</th>" & VbCrLf)
  104.         Response.Write("                        <th>Country Name</th>" & VbCrLf)
  105.         Response.Write("                </tr>" & VbCrLf)
  106.         Response.Write("        </thead>" & VbCrLf)
  107.         ‘Now let’s start the body of our table
  108.         Response.Write("        <tbody>" & VbCrLf)
  109.         ‘Let’s start a FOR loop to get and display all available rows
  110.         For intRows = 0 To UBound(tmpArray, 2) ‘The 2 is representative of the rows in the recordset
  111.                 ‘If we didn’t know what columns we have, we would do another FOR loop inside this using:
  112.                 ‘UBound(tmpArray, 1)
  113.                 Response.Write("                <tr>" & VbCrLf)
  114.                 Response.Write("                        <td>" & tmpArray(1, intRows) & "</td>" & VbCrLf)
  115.                 Response.Write("                        <td>" & tmpArray(3, intRows) & "</td>" & VbCrLf)
  116.                 Response.Write("                        <td>" & tmpArray(4, intRows) & "</td>" & VbCrLf)
  117.                 Response.Write("                        <td>" & tmpArray(2, intRows) & "</td>" & VbCrLf)
  118.                 Response.Write("                </tr>" & VbCrLf)
  119.         Next
  120.         intRows = Null ‘Clear intRows out
  121.         Response.Write("        </tbody>" & VbCrLf)
  122.         Response.Write("</table>" & VbCrLf)
  123.         ‘Id like to display the record paging again, in case the list is long
  124.         Response.Write(strDisplayPaging)
  125.         ‘I’d also like to display that paging info again
  126.         Response.Write("<strong>" & intTotRecs & "</strong> total records in <strong>" & intTotPages & "</strong> pages.")
  127.         Erase tmpArray ‘Releases the array from memory
  128. Else
  129.         ‘We have no array, so let’s display a message stating this!
  130.         Response.Write("There are no records for that query.")
  131. End If
  132. %>

cls_db.asp

  1. <%
  2. ‘*****************************************************************************  
  3. ‘*****************************************************************************  
  4. ‘  
  5. ‘ This code can be used anywhere you like, all I ask is that you keep this  
  6. ‘ notice here, so people know who actually made it! =D  Thanks!  
  7. ‘  
  8. ‘ This code was developed by Kevin Pirnie, c/o o7th Web Design  
  9. ‘ support@07th.com :: http://www.07th.com  
  10. ‘  
  11. ‘*****************************************************************************  
  12. ‘*****************************************************************************
  13. Class DBv1
  14.     ‘Private Declarations
  15.    Private i, p, pp, strDataLength, objCmd, objRS, objConn, objError
  16.     Private intCurrPage, ini, fim
  17.     ‘Public Declarations
  18.    Public intDBType, strDBUser, strDBPassword, strDBServer, strDBDatabase
  19.         Public strConnString, intCommandType
  20.     Public strQry, arrParamValues, arrParamDataTypes, intRetDataType, intRetSize
  21.     Public boolUsePaging, intTotalPages, intTotalRecords
  22.     Public intRecPerPage, intPageNumber, strPagingPage, strPagingLeft, strPagingRight
  23.     ‘Initialize
  24.    Private Sub Class_Initialize()
  25.         intDBType = 0
  26.         intCommandType = 0
  27.         strDBServer = Null
  28.         strDBUser = Null
  29.         strDBPassword = Null
  30.         strDBDatabase = Null
  31.         strQry = Null
  32.         arrParamValues = Null
  33.         arrParamDataTypes = Null
  34.         boolUsePaging = False
  35.         intTotalPages = 0
  36.         intTotalRecords = 0
  37.         intRecPerPage = 0
  38.         intPageNumber = 0
  39.         strPagingPage = Null
  40.         strPagingLeft = " &lt; "
  41.         strPagingRight = " &gt; "
  42.     End Sub
  43.     ‘Terminate
  44.    Private Sub Class_Terminate()
  45.         intDBType = 0
  46.         intCommandType = 0
  47.         strDBServer = Null
  48.         strDBUser = Null
  49.         strDBPassword = Null
  50.         strDBDatabase = Null
  51.         strQry = Null
  52.         arrParamValues = Null
  53.         arrParamDataTypes = Null
  54.         boolUsePaging = False
  55.         intTotalPages = 0
  56.         intTotalRecords = 0
  57.         intRecPerPage = 0
  58.         intPageNumber = 0
  59.         strPagingPage = Null
  60.         strPagingLeft = " &lgt; "
  61.         strPagingRight = " &rgt; "
  62.     End Sub
  63.     ‘Execute the Query
  64.    Public Function ExecuteQry()
  65.         Set objConn = CreateObject("ADODB.Connection")
  66.             objConn.Open strConnectionString
  67.                 Set objCmd = CreateObject("ADODB.Command")
  68.                     objCmd.CommandText = strQry
  69.                     objCmd.CommandType = intCommandType
  70.                     If IsArray(arrParamValues) And IsArray(arrParamDataTypes) Then
  71.                         If UBound(arrParamValues) = UBound(arrParamDataTypes) Then
  72.                             For i = 0 To UBound(arrParamValues)
  73.                                 Select Case arrParamDataTypes(i)
  74.                                     Case 2 ‘Small Integer
  75.                                        strDataLength = 2
  76.                                     Case 3 ‘Integer
  77.                                        strDataLength = 4
  78.                                     Case 4 ‘Single
  79.                                        strDataLength = 4
  80.                                     Case 5 ‘Float
  81.                                        strDataLength = 8
  82.                                     Case 6 ‘Currency
  83.                                        strDataLength = 8
  84.                                     Case 7 ‘Date
  85.                                        strDataLength = 8
  86.                                     Case 11 ‘Bit
  87.                                        strDataLength = 1
  88.                                     Case 14 ‘Decimal
  89.                                        strDataLength = 9
  90.                                     Case 72 ‘GUID
  91.                                        strDataLength = 16
  92.                                     Case 128 ‘Binary
  93.                                        strDataLength = 50
  94.                                     Case 129 ‘Char
  95.                                        If Not ReqValue(arrParamValues(i)) Then
  96.                                             strDataLength = 1
  97.                                         Else
  98.                                             strDataLength = Len(arrParamValues(i))
  99.                                         End If
  100.                                     Case 200 ‘VarChar
  101.                                        If Not ReqValue(arrParamValues(i)) Then
  102.                                             strDataLength = 1
  103.                                         Else
  104.                                             strDataLength = Len(arrParamValues(i))
  105.                                         End If
  106.                                     Case 203 ‘NText
  107.                                        If Not ReqValue(arrParamValues(i)) Then
  108.                                             strDataLength = 1
  109.                                         Else
  110.                                             strDataLength = Len(arrParamValues(i))
  111.                                         End If
  112.                                     Case 204 ‘VarBinary
  113.                                        strDataLength = 50
  114.                                     Case Else ‘Hmm…guess
  115.                                        If Not ReqValue(arrParamValues(i)) Then
  116.                                             strDataLength = 1
  117.                                         Else
  118.                                             strDataLength = Len(arrParamValues(i))
  119.                                         End If
  120.                                 End Select
  121.                                 If arrParamDataTypes(i) = 14 Then
  122.                                     Set p = objCmd.CreateParameter(, CInt(arrParamDataTypes(i)), , CInt(strDataLength), InputCleaner(arrParamValues(i)))
  123.                                     p.NumericScale = 2
  124.                                     p.Precision = 10
  125.                                     objCmd.Parameters.Append p
  126.                                 Else
  127.                                     objCmd.Parameters.Append (objCmd.CreateParameter(, CInt(arrParamDataTypes(i)), , CInt(strDataLength), InputCleaner(arrParamValues(i))))
  128.                                 End If
  129.                             Next
  130.                             i = Null
  131.                             Erase arrParamValues
  132.                             Erase arrParamDataTypes
  133.                         Else
  134.                             ExecuteQry = "Your values and data type arrays need to be the same length."
  135.                         End If
  136.                     End If
  137.                                         ‘Debug the parameters if necessary
  138.                                         ‘For each Item In objCmd.Parameters
  139.                                         ‘       Write("Name:" & Item.Name & "-Type:" & Item.Type & "-Value:" & Item.Value & "<br />")
  140.                                         ‘Next  
  141.                    Set objCmd.ActiveConnection = objConn
  142.                         Select Case intCommandType
  143.                             Case 1
  144.                             If InStr(1, UCase(strQry), "SELECT") > 0 Then
  145.                                 Set objRS = CreateObject("Adodb.RecordSet")
  146.                                     If boolUsePaging Then
  147.                                         objRS.PageSize = intRecPerPage
  148.                                         objRS.CacheSize = intRecPerPage
  149.                                         objRS.CursorType = 3
  150.                                     End If
  151.                                     objRS.Open objCmd
  152.                                     If Not (objRS.EOF) Then
  153.                                         If boolUsePaging Then
  154.                                             If Not (validNumber(intPageNumber)) Then
  155.                                                 objRS.AbsolutePage = 1
  156.                                             Else
  157.                                                 objRS.AbsolutePage = intPageNumber
  158.                                             End If
  159.                                             ExecuteQry = objRS.GetRows(intRecPerPage)
  160.                                             intTotalPages = objRS.PageCount
  161.                                             intTotalRecords = objRS.RecordCount
  162.                                         Else
  163.                                             ExecuteQry = objRS.GetRows()
  164.                                         End If
  165.                                     Else
  166.                                         ExecuteQry = "There are no records."
  167.                                         Exit Function
  168.                                     End If
  169.                                 Set objRS = Nothing
  170.                                 Exit Function
  171.                             ElseIf InStr(1, UCase(strQry), "INSERT") > 0 Then
  172.                                 If InStr(1, UCase(strQry), "@@IDENTITY") > 0 Or InStr(1, UCase(strQry), "NEWID()") > 0 Then
  173.                                     Set objRS = objCmd.Execute()
  174.                                         If Not (objRS.EOF) Then
  175.                                             ExecuteQry = objRS(0)
  176.                                         End If
  177.                                     Set objRS = Nothing
  178.                                 Else
  179.                                     objCmd.Execute
  180.                                     ExecuteQry = "Your command has been executed."
  181.                                 End If
  182.                             ElseIf (InStr(1, UCase(strQry), "DELETE") > 0 Or InStr(1, UCase(strQry), "UPDATE") > 0 Or Left(UCase(strQry), 2) = "SP") Then
  183.                                 If Left(UCase(strQry), 2) = "SP" And intRetDataType > "" Then
  184.                                     objCmd.Parameters.Append (objCmd.CreateParameter("@ret", intRetDataType, 2, , intRetSize))
  185.                                     objCmd.Execute
  186.                                     ExecuteQry = objCmd.Parameters("@ret")
  187.                                 Else
  188.                                     ExecuteQry = objCmd.Execute
  189.                                 End If
  190.                             End If
  191.                         Case 4
  192.                             If intRetDataType > "" Then
  193.                                 objCmd.Parameters.Append (objCmd.CreateParameter("@ret", intRetDataType, 2, , intRetSize))
  194.                                 objCmd.Execute
  195.                                 ExecuteQry = objCmd.Parameters("@ret")
  196.                             Else
  197.                                 If boolUsePaging Then
  198.                                     Set objRS = CreateObject("Adodb.RecordSet")
  199.                                         objRS.PageSize = intRecPerPage
  200.                                         objRS.CacheSize = intRecPerPage
  201.                                         objRS.CursorType = 3
  202.                                         objRS.CursorLocation = 3
  203.                                         objRS.Open objCmd
  204.                                         If Not (objRS.EOF) Then
  205.                                             If boolUsePaging Then
  206.                                                 If Not (validNumber(intPageNumber)) Then
  207.                                                     objRS.AbsolutePage = 1
  208.                                                 Else
  209.                                                     objRS.AbsolutePage = intPageNumber
  210.                                                 End If
  211.                                                 ExecuteQry = objRS.GetRows(intRecPerPage)
  212.                                                 intTotalPages = objRS.PageCount
  213.                                                 intTotalRecords = objRS.RecordCount
  214.                                             Else
  215.                                                 ExecuteQry = objRS.GetRows()
  216.                                             End If
  217.                                         Else
  218.                                             objCmd.Execute
  219.                                         End If
  220.                                     Set objRS = Nothing
  221.                                 Else
  222.                                     objCmd.Execute
  223.                                 End If
  224.                             End If
  225.                         End Select
  226.                     Set objCmd.ActiveConnection = Nothing
  227.                 Set objCmd = Nothing
  228.             objConn.Close
  229.         Set objConn = Nothing
  230.     End Function
  231.     ‘Paging Links
  232.    Public Function RecordPaging()
  233.         tmpString = ""
  234.         tmpString = tmpString & "<div class=""paging_links"">" & vbCrLf
  235.         If Not (validNumber(intPageNumber)) Then
  236.             CurrentPage = 1 ‘We’re On the first page
  237.            NumPerPageOf = 1
  238.         Else
  239.             CurrentPage = CInt(intPageNumber)
  240.             NumPerPageOf = ((CurrentPage * NumPerPage) – NumPerPage) + 1
  241.         End If
  242.         If CurrentPage > 1 Then
  243.             If CurrentPage > 5 And intTotalPages > 10 Then
  244.                 tmpString = tmpString & "   <span><a href=""" & strPagingPage & "&amp;p=1"">1</a></span> "
  245.                 tmpString = tmpString & "<span class=""prevChunk""> &laquo; </span>"
  246.             End If
  247.             If intTotalPages > 10 Then
  248.                 If CurrentPage > 5 Then
  249.                     If intTotalPages > (CurrentPage + 5) Then
  250.                         ini = (CurrentPage – 4)
  251.                         fim = (CurrentPage + 5)
  252.                     Else
  253.                         ini = (intTotalPages – 9)
  254.                         fim = intTotalPages
  255.                     End If
  256.                 Else
  257.                     ini = 1
  258.                     fim = 10
  259.                 End If
  260.             Else
  261.                 ini = 1
  262.                 fim = intTotalPages
  263.             End If
  264.             For a = ini To fim
  265.                 If a = CInt(intPageNumber) Then
  266.                     tmpString = tmpString & " <span class=""curPage"">" & a & "</span> "
  267.                 Else
  268.                     tmpString = tmpString & "   <span><a href=""" & strPagingPage & "&amp;p=" & a & """>" & a & "</a></span> "
  269.                 End If
  270.             Next: a = Null
  271.         Else
  272.             If intTotalPages = 1 Then
  273.                 tmpString = tmpString & ""
  274.             Else
  275.                 tmpString = tmpString & "<span class=""curPage"">1</span> "
  276.             End If
  277.             If intTotalPages > 10 Then     ‘id=161&MWC=Layouts
  278.                fim = 10
  279.             Else
  280.                 fim = intTotalPages
  281.             End If
  282.             For a = 2 To fim
  283.                 If a = CInt(intPageNumber) Then
  284.                     tmpString = tmpString & "<span class=""curPage"">" & a & "</span> "
  285.                 Else
  286.                     tmpString = tmpString & "   <span><a href=""" & strPagingPage & "&amp;p=" & a & """>" & a & "</a></span> "
  287.                 End If
  288.             Next: a = Null
  289.         End If
  290.         If CurrentPage < intTotalPages – 5 And intTotalPages > 10 Then
  291.             tmpString = tmpString & "<span class=""lastChunk""> &raquo; </span>"
  292.                         tmpString = tmpString & "   <span><a href=""" & strPagingPage & "&amp;p=" & intTotalPages & """>" & intTotalPages & "</a></span> "
  293.         End If
  294.         tmpString = tmpString & "</div>" & vbCrLf
  295.         RecordPaging = tmpString
  296.         tmpString = ""
  297.     End Function
  298.     ‘Get our connection string
  299.    Private Function strConnectionString()
  300.         If ReqValue(strConnString) Then
  301.             strConnectionString = strConnString
  302.         Else
  303.             Select Case intDBType
  304.                 Case 1 ‘SQL 2000
  305.                    strConnectionString = "Provider=SQLOLEDB.1;Password=" & strDBPassword & ";User ID=" & strDBUser & ";Initial Catalog=" & strDBDatabase & ";Data Source=" & strDBServer & ""
  306.                 Case 2 ‘SQL 2005
  307.                    strConnectionString = "Provider=SQLNCLI;Server=" & strDBServer & ";Database=" & strDBDatabase & ";Uid=" & strDBUser & ";Pwd=" & strDBPassword & ";DataTypeCompatibility=80;"
  308.                 Case 3 ‘SQL 2005 Express
  309.                    strConnectionString = "Provider=SQLOLEDB;Data Source=" & strDBServer & ";Persist Security Info=True;Password=" & strDBPassword & ";User ID=" & strDBUser & ";Initial Catalog=" & strDBDatabase & ";DataTypeCompatibility=80"
  310.                 Case 4 ‘MS Access
  311.                    strConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & strDBDatabase & ";User Id=" & strDBUser & ";Password=" & strDBPassword & ";"
  312.                 Case 6 ‘MS Access 2007
  313.                    strConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & strDBDatabase & ";Persist Security Info=False;"
  314.                 Case 8 ‘Borland Interbase – requires the SIBProvider to be installed on the server
  315.                    strConnectionString = "provider=sibprovider;location=" & strDBServer & ":;data source=" & strDBDatabase & ";user id=" & strDBUser & ";Password=" & strDBPassword & ";"
  316.                 Case 7 ‘MySQL
  317.                    strConnectionString = "Driver={MySQL ODBC 3.51 Driver};Server=" & strDBServer & ";Database=" & strDBDatabase & "; User=" & strDBUser & ";Password=" & strDBPassword & ";Option=3;"
  318.             End Select
  319.         End If
  320.     End Function
  321.     ‘Input cleaning … just in case
  322.    Private Function InputCleaner(ByVal strStringToClean)
  323.         If Not (ReqValue(strStringToClean)) Then
  324.             If InStr(1, strStringToClean, "’") > 0 Then strStringToClean = Replace(strStringToClean, "’", "&#39;")
  325.             If InStr(1, strStringToClean, Chr(34)) > 0 Then strStringToClean = Replace(strStringToClean, Chr(34), "&#34;")
  326.             If InStr(1, strStringToClean, "@") > 0 Then strStringToClean = Replace(strStringToClean, "@", "&#64;")
  327.             If InStr(1, strStringToClean, "|") > 0 Then strStringToClean = Replace(strStringToClean, "|", "&#124;")
  328.             If InStr(1, strStringToClean, "*") > 0 Then strStringToClean = Replace(strStringToClean, "*", "&#42;")
  329.             If InStr(1, strStringToClean, "–") > 0 Then strStringToClean = Replace(strStringToClean, "–", "&#45;&#45;")
  330.             If InStr(1, strStringToClean, "(") > 0 Then strStringToClean = Replace(strStringToClean, "(", "&#40;")
  331.             If InStr(1, strStringToClean, ")") > 0 Then strStringToClean = Replace(strStringToClean, ")", "&#41;")
  332.         End If
  333.         InputCleaner = strStringToClean
  334.     End Function
  335.     ‘Required Value?
  336.    Private Function ReqValue(ByVal strValue)
  337.         ReqValue = True ‘by default
  338.        If strValue = "" Then ReqValue = False
  339.         If IsNull(strValue) Then ReqValue = False
  340.         If Len(strValue) <= 0 Then ReqValue = False
  341.         If IsEmpty(strValue) Then ReqValue = False
  342.     End Function
  343.     ‘Valid Number?
  344.    Private Function validNumber(ByVal strValue)
  345.         If ReqValue(strValue) Then
  346.             validNumber = False ‘Default
  347.            Set objRegExp = New RegExp
  348.                 objRegExp.Pattern = "^(?:-?(?:[0-9]+\.?|[0-9]*(?:\.[0-9]+){1}))$"
  349.                 validNumber = objRegExp.Test(strValue)
  350.             Set objRegExp = Nothing
  351.         End If
  352.     End Function
  353. End Class
  354. %>
 
 

Domain Branding

10 Dec

When it comes down to choosing the perfect domain for your website, there are a few important factors that will come into play with helping you keep traffic coming to your site. Here I’m going to discuss some of these factors in detail and explain each one, so sit tight and have yourself a good read!

While your sitting down planning out your site and you have the perfect niche you want to create your site in and the perfect ideas to make your site amusing, you have to think carefully when it comes to the name and the domain. Choose as short of a domain as possible, but easy to remember for your viewers.

Pick a keyword that describes your site and play around with different terms to make it work and be easily remembered. I’ll use one of my own projects as an example, TalkDeveloping. The site is a community and discussion board for developers of programming / coding and design talents, with that being said the site is obviously about developing and the users talk with one another of the subjects, so TalkDeveloping makes perfect sense and is the best route to go for the site. Another example would be Good Tutorials. The domain is good-tutorials.com and matches the site perfectly. Why? It has the main aspect of the site in the domain (tutorials) and is very easy to remember. It makes perfect sense for this domain as it’s a large tutorial listing site where you can list your tutorials free of charge and get great traffic in return.

You want your name to be as unique as possible. One of the obvious ways to find out is when you’re doing the domain search it’ll list if it’s taken of available. If it’s not you’re best bet is choosing a different name and branding it as your own to go with your project.

Another large factor in careful domain choosing is the all great search engines. If your domain is descriptive and short, the search engines will love it and visit your site numerous times which will increase the likeliness of your content going higher to the top of popular search terms for content you may have on your site, and at the same time could increase your sites PageRank (common with Google).

Take all of what I said into consideration and choosing your next project domain should be a great pay-off in the end, and remember to always think of the user. Will the user easily remember my domain? Will the search engines pick up on it?

 
 

Prevent Image “Leaching”

10 Dec

I came across a situation where people where “leaching” images off my family photo site. “File Leaching” means that instead of the person downloading the file, and simply serving it up from their server, they were simply linking to my version of it.

While this may seem trivial, it happened on a site that has 10,000 family pictures, and was causing serious bandwidth issues for me.

So… being the good developer I think I am, I came up with a way to prevent that.

The basics of it are, simply store your files above the websites root directory, and stream them to the user upon request.

I found using ADO.Stream this is possible, and very efficient.

Hope you find it as useful as I do… Enjoy!

Usage:

  1. <%  
  2. ‘*****************************************************************************  
  3. ‘*****************************************************************************  
  4. ‘  
  5. ‘ This code can be used anywhere you like, all I ask is that you keep this  
  6. ‘ notice here, so people know who actually made it! =D  Thanks!  
  7. ‘  
  8. ‘ This code was developed by Kevin Pirnie, c/o o7th Web Design  
  9. ‘ support@07th.com :: http://www.07th.com  
  10. ‘  
  11. ‘*****************************************************************************  
  12. ‘*****************************************************************************
  13. Dim strPath : strPath = "C:\WebStorage\thefile.zip" ‘physical path to the file
  14. Dim strFileName : strFileName = "WhatIWantToCallIt.zip" ‘whatever I feel like naming the file
  15. Call downloadFile(strPath, strFileName)
  16. %>

Code:

  1. <%
  2. ‘Force File Download
  3. Sub DownloadFile(ByVal strFileName, ByVal strFileNamePass, ByVal intFileType)
  4.      Response.Buffer = True
  5.      Response.Clear
  6.      Set objStream = CreateObject("ADODB.Stream")
  7.      objStream.Open
  8.      objStream.Type = 1
  9.      Set objFilesystem = CreateObject("Scripting.FileSystemObject")
  10.                  If Not objFilesystem.FileExists(strFilename) Then
  11.                           Write("<h1>Error</h1>: " & strFilename & " does not exist<p>")
  12.                           Response.End
  13.                  End If
  14.                  Set objFilestream = objFilesystem.GetFile( strFilename )
  15.                          intFilelength = objFilestream.size
  16.                          objStream.LoadFromFile( strFilename )
  17.                          If Err Then
  18.                                   Write("<h1>Error: </h1>" & Err.Description & "<p>")
  19.                                   Response.End
  20.                          End If
  21.                          If Len( Trim(strDownloadFilename) ) > 0 Then
  22.                                   strFileNamePass = Trim( strFileNamePass )
  23.                          Else
  24.                                   strFileNamePass = objFilestream.Name
  25.                          End If
  26.                          Select Case intFileType
  27.                                 Case 1 ‘CSV
  28.                                         Response.ContentType = "text/csv"
  29.                                 Case 2 ‘XML
  30.                                         Response.ContentType = "text/xml"
  31.                          End Select
  32.                          Response.AddHeader "Content-Disposition", "attachment; filename=" & strFileNamePass
  33.                          Response.AddHeader "Content-Length", intFilelength
  34.                          Response.Charset = "UTF-8"
  35.                          For i = 0 To objStream.Size
  36.                                   i = i + 128000
  37.                                   Response.BinaryWrite(objStream.Read(128000))
  38.                                   Response.Flush
  39.                          Next : i = Null
  40.                  Set objFilestream = Nothing
  41.         Set objFilesystem = Nothing
  42. End Sub
  43. %>
 
 

Recordset Paging With .GetRows()

10 Dec

I constantly use a .GetRows() array when displaying a recordset from a database.  However, I found that I needed to be able to page the records ont he page, so that so many records won’t display all at once potentially crashing the page.

Here is a function that I use to display a Google like recordset paging system.

  1. <%
  2. ‘Usage = Response.Write(PagingLinks(TheArrayNameFromRecordset, HowManyPerPage, URLOfThePageWeAreOn, 1stLinkDisplay, PrevLinkDisplay, NextLinkDisplay, LastLinkDisplay, StartingPage#Display, EndingPage#Display))
  3. Function PagingLinks(ByVal strArrName, ByVal strNumPerPage, ByVal strPageName, ByVal strFirst, ByVal strPrev, ByVal strNext, ByVal strLast, ByVal iStart, ByVal iStop)
  4.         PagingLinks = ""
  5.         iStart = Request.QueryString("s")
  6.         iOffset = Request.QueryString("o")
  7.         If Not IsNumeric(iStart) Then
  8.                 iStart = 0
  9.         Else
  10.                 iStart = CLng(iStart)
  11.         End If
  12.         If Not IsNumeric(iOffset) Then
  13.                 iOffset = strNumPerPage
  14.         Else
  15.                 iOffset = CLng(iOffset)
  16.         End If
  17.         If UBound(strArrName, 2) < strNumPerPage Then
  18.                 iRows = (UBound(strArrName,2) + 1)
  19.         Else
  20.                 iRows = UBound(strArrName,2)
  21.         End If
  22.         If iRows > (iOffset + iStart) Then
  23.                 iStop = iOffset + iStart – 1
  24.         Else
  25.                 iStop = iRows
  26.         End If
  27.         If iStop > iRows – iOffset Then
  28.                 iStop = iStop – 1
  29.         End If
  30.         If Not(IsNumeric(iOffset)) Then iOffset = 1
  31.         pages = RoundUp(iRows / iOffset)
  32.         pgNum = RoundUp(iStart / iOffset) + 1
  33.         PagingLinks = PagingLinks & "<a href="" strpagename="" &s="0&o=&quot;" ioffset="" &="">" & strFirst & "</a> "
  34.         If iStart > 0 Then
  35.                 PagingLinks = PagingLinks & "<a href="" strpagename="" &="" &s=" & iStart – iOffset & " &o=" & iOffset & ">" & strPrev & "</a> "
  36.         End If
  37.         Dim MaxPagesToShow, MaxLBound, MaxUBound
  38.         MaxPagesToShow = 10
  39.         MaxLBound = pgNum – Int(MaxPagesToShow/2)
  40.         If MaxLBound < 1 Then MaxLBound = 1
  41.         MaxUBound = MaxLBound + MaxPagesToShow
  42.         If MaxUBound > pages Then
  43.                 MaxUBound = pages
  44.                 MaxLBound = MaxUBound – MaxPagesToShow
  45.         End If
  46.         If MaxLBound < 1 Then MaxLBound = 1
  47.         If (iRows – iOffset) < 0 Then
  48.                 l = 0
  49.         Else
  50.                 l = (iRows – iOffset)
  51.         End If
  52.         For z = MaxLBound To MaxUBound
  53.                 pgOffset = z * iOffset – iOffset
  54.                 If z = pgNum Then
  55.                         PagingLinks = PagingLinks & ("<b>" & z & "</b> ")
  56.                 Else
  57.                         PagingLinks = PagingLinks & ("<a href="" strpagename="" &="" &s=" & pgOffset & " &o=" & iOffset & ">" & z & "</a> ")
  58.                 End If
  59.         Next
  60.         If iStop + 1 < iRows Then
  61.                 PagingLinks = PagingLinks & "<a href="" strpagename="" &="" &s=" & iStart + iOffset & " &o=" & iOffset & ">" & strNext & "</a> "
  62.         End If
  63.         PagingLinks = PagingLinks & "<a href="" strpagename="" &="" &s=" & l & " &o=" & iOffset & ">" & strLast & "</a><br>"
  64. End Function
  65. %>
 
 

Importance Of Browser Compatibility

10 Dec

One of the most important aspects you need to think of when you’re coding your website is to make it work across all browsers. If you don’t and a user visits your website from a browser you haven’t tested, and it’s broken, chances are they won’t be returning.

Like most things when developing your website, you need to take into consideration the different browsers and how you will be coding each one. If your website is supposed to look a certain way and you let a few alignment errors go in a certain browser, if could affect the users take on your site.  You may not think it to be a big deal losing a few viewers, but you need to think of the larger picture. If there are a few viewers using the certain browser where your site appears broken, there’s a high guess that a lot of viewers using the same browser will see the exact same problems and possibly might not return again because of it.

Always thoroughly test your site in the most popular browsers then work your way down the list. Having your site work in each browser can be one of the big key aspects of making your website a success.

Happy coding!

 
 

Regular Expression String Validation

10 Dec

When developing forms for a website it is always a good idea to implement server-side validation for your strings.

While client-side validations are handy and pretty, they can also be easily compromised.

Here are some server-side validation checks that utilize Regular Expressions.  They return a boolean value if the string passes the test or not.

  1. <%
  2. ‘Valid Zip Code
  3. Function ValidZipCode(ByVal strValue)
  4.         ValidZipCode = False
  5.         If Not(ReqValue(strValue)) Then
  6.                 ValidZipCode = False
  7.         Else
  8.                 Set objRegExp = New RegExp
  9.                         objRegExp.Pattern = "^\d{5}$|^\d{5}-\d{4}$"
  10.                         ValidZipCode = objRegExp.Test(strValue)
  11.                 Set objRegExp = Nothing
  12.         End If
  13. End Function
  14. ‘Valid Date
  15. Function ValidDate(ByVal strValue)
  16.         ValidDate = False
  17.         If Not(ReqValue(strValue)) Then
  18.                 ValidDate = False
  19.         Else
  20.                 Set objRegExp = New RegExp
  21.                         objRegExp.Pattern = "^[0,1]?\d{1}\/(([0-2]?\d{1})|([3][0,1]{1}))\/(([1]{1}[9]{1}[9]{1}\d{1})|([2-9]{1}\d{3}))$"
  22.                         ValidDate = objRegExp.Test(strValue)
  23.                 Set objRegExp = Nothing
  24.                 If Not(ValidDate) Then
  25.                         ValidDate = IsDate(strValue)
  26.                 End If
  27.         End If
  28. End Function
  29. ‘Valid Email email@domain.com
  30. Function ValidEmail(ByVal strValue)
  31.         ValidEmail = False‘default
  32.         If Not(ReqValue(strValue)) Then
  33.                 ValidEmail = False
  34.         Else
  35.                 Set objRegExp = New RegExp
  36.                         objRegExp.Pattern = "^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$"
  37.                                 ValidEmail = objRegExp.Test(strValue)
  38.                 Set objRegExp = Nothing
  39.         End If
  40. End Function
  41. ‘Valid Letters
  42. Function ValidLetters(ByVal strValue)
  43.         ValidLetters = False‘Default
  44.         If Not(ReqValue(strValue)) Then
  45.                 ValidLetters = False
  46.         Else
  47.                 Set objRegExp = New RegExp
  48.                         objRegExp.Pattern = "^([a-zA-Z])"
  49.                                 ValidLetters = objRegExp.Test(strValue)
  50.                 Set objRegExp = Nothing
  51.         End If
  52. End Function
  53. ‘Valid Characters A-Z/a-z/0-9
  54. Function ValidChars(ByVal strValue)
  55.         ValidChars = False‘Default
  56.         If Not(ReqValue(strValue)) Then
  57.                 ValidChars = False
  58.         Else
  59.                 Set objRegExp = New RegExp
  60.                         objRegExp.Pattern = "^([a-zA-Z0-9])"
  61.                                 ValidChars = objRegExp.Test(strValue)
  62.                 set objRegExp = Nothing
  63.         End If
  64. End Function
  65. ‘Valid Number
  66. Function ValidNumber(ByVal strValue)
  67.         ValidNumber = False‘Default
  68.         If Not(ReqValue(strValue)) Then
  69.                 ValidNumber = False
  70.         Else
  71.                 Set objRegExp = New RegExp
  72.                         objRegExp.Pattern = "^([0-9])"
  73.                                 ValidNumber = objRegExp.Test(strValue)
  74.                 set objRegExp = Nothing
  75.         End If
  76. End Function
  77. ‘Valid Phone
  78. Function ValidPhone(ByVal strValue)
  79.         ValidPhone = False‘default
  80.         If Not(ReqValue(strValue)) Then
  81.                 ValidPhone = False
  82.         Else
  83.                 Set objRegExp = New RegExp
  84.                         objRegExp.Pattern = "^([0-1]([\s-./\\])?)?(\(?[2-9]\d{2}\)?|[2-9]\d{3})([\s-./\\])?(\d{3}([\s-./\\])?\d{4}|[a-zA-Z0-9]{7})$"
  85.                                 ValidPhone = objRegExp.Test(strValue)
  86.                 Set objRegExp = Nothing
  87.         End If
  88. End Function
  89. ‘Valid GUID
  90. Function ValidGUID(ByVal strValue)
  91.         ValidGUID = False‘default
  92.         If Not(ReqValue(strValue)) Then
  93.                 ValidGUID = False
  94.         Else
  95.                 Set objRegExp = New RegExp
  96.                         objRegExp.Pattern = "^(?:{[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}})$"
  97.                                 ValidGUID = objRegExp.Test(strValue)
  98.                 Set objRegExp = Nothing
  99.         End If
  100. End Function
  101. ‘Valid Credit Card
  102. Function ValidCreditCard(ByVal strValue)
  103.         ValidCreditCard = False‘default
  104.         If Not(ReqValue(strValue)) Then
  105.                 ValidCreditCard = False
  106.         Else
  107.                 Set objRegExp = New RegExp
  108.                         objRegExp.Pattern = "^((?:4\d{3})|(?:5[1-5]\d{2})|(?:6011)|(?:3[68]\d{2})|(?:30[012345]\d))[ -]?(\d{4})[ -]?(\d{4})[ -]?(\d{4}|3[4,7]\d{13})$"
  109.                         ValidCreditCard = objRegExp.Test(strValue)
  110.                 Set objRegExp = Nothing
  111.         End If
  112. End Function
  113. %>
 
 

SQL Format Name Function

10 Dec

I was working for an ASP (application service provider) awhile back and got sick of formatting our members names in code at the time of rendering the page.

I asked our DBA for advice if he thought it would be better performance to simply do this in the SQL calls to the database, of course his answer was yes, however what he suggested was to simply concatenate the name parts into an alias field.

Needless to say, it ended up bombing the page out around 1000 records.

After searching online for a few hours I came across a SQL Function that does exactly what was needed, and WHAMMMOOO!!!   No more page bombing.

Here it is, with usage to share with all (because it took so long to find it)

  1. SET ANSI_NULLS ON
  2. SET QUOTED_IDENTIFIER ON
  3. GO
  4. ALTER FUNCTION [dbo].[FormatName](@NameString varchar(100), @NameFormat varchar(20))
  5. returns varchar(100) AS
  6. begin
  7. –FormatName parses a NameString into its component parts and returns it in a requested format.
  8. –@NameString is the raw value to be parsed.
  9. –@NameFormat is a string that defines the output format.  Each letter in the string represents
  10. –a component of the name in the order that it is to be returned.
  11. –    [H] = Full honorific
  12. –    [h] = Abbreviated honorific
  13. –    [F] = First name
  14. –    [f] = First initial
  15. –    [M] = Middle name
  16. –    [m] = Middle initial
  17. –    [L] = Last name
  18. –    [l] = Last initial
  19. –    [S] = Full suffix
  20. –    [s] = Abbreviated suffix
  21. –    [.] = Period
  22. –    [,] = Comma
  23. –    [ ] = Space
  24.  
  25. –Example: select dbo.Formatname(‘Reverend Gregory Robert Von Finzer Junior’, ‘L, h. F m. s.’)
  26. –Result: ‘Von Finzer, Rev. Gregory R. Jr.’
  27.  
  28. –Test variables
  29. – declare    @NameString varchar(50)
  30. – declare    @NameFormat varchar(20)
  31. – set    @NameFormat = ‘L, h. F m. s.’
  32. – set    @NameString = ‘Reverend Gregory Robert Von Finzer Junior’
  33.  
  34. Declare    @Honorific varchar(20)
  35. Declare    @FirstName varchar(20)
  36. Declare    @MiddleName varchar(30)
  37. Declare    @LastName varchar(30)
  38. Declare    @Suffix varchar(20)
  39. Declare    @TempString varchar(100)
  40. Declare    @IgnorePeriod char(1)
  41.  
  42. –Prepare the string
  43. –Make sure each period is followed by a space character.
  44. SET    @NameString = rtrim(ltrim(REPLACE(@NameString, ‘.’, ‘. ‘)))
  45. –Eliminate double-spaces.
  46. while  charindex(‘  ‘, @NameString) &gt; 0 SET @NameString = REPLACE(@NameString, ‘  ‘, ‘ ‘)
  47. –Eliminate periods
  48. while  charindex(‘.’, @NameString) &gt; 0 SET @NameString = REPLACE(@NameString, ‘.’, )
  49.  
  50. –If the lastname is listed first, strip it off.
  51. SET    @TempString = rtrim(LEFT(@NameString, charindex(‘ ‘, @NameString)))
  52. IF    @TempString IN (‘VAN’, ‘VON’, ‘MC’, ‘Mac’, ‘DE’) SET @TempString = rtrim(LEFT(@NameString, charindex(‘ ‘, @NameString, len(@TempString)+2)))
  53. IF    RIGHT(@TempString, 1) = ‘,’ SET @LastName = LEFT(@TempString, len(@TempString)-1)
  54. IF    len(@LastName) &gt; 0 SET    @NameString = ltrim(RIGHT(@NameString, len(@NameString) - len(@TempString)))
  55.  
  56. –Get rid of any remaining commas
  57. while  charindex(‘,’, @NameString) &gt; 0 SET @NameString = REPLACE(@NameString, ‘,’, )
  58.  
  59. –Get Honorific and strip it out of the string
  60. SET    @TempString = rtrim(LEFT(@NameString, charindex(‘ ‘, @NameString + ‘ ‘)))
  61. IF    @TempString IN (‘MR’, ‘MRS’, ‘MS’, ‘DR’, ‘Doctor’, ‘REV’, ‘Reverend’, ‘SIR’, ‘HON’, ‘Honorable’, ‘CPL’, ‘Corporal’, ‘SGT’, ‘Sergeant’, ‘GEN’, ‘General’, ‘CMD’, ‘Commander’,  ‘CPT’, ‘CAPT’, ‘Captain’, ‘MAJ’, ‘Major’, ‘PVT’, ‘Private’, ‘LT’, ‘Lieutenant’, ‘FATHER’, ‘SISTER’) SET @Honorific = @TempString
  62. IF    len(@Honorific) &gt; 0 SET    @NameString = ltrim(RIGHT(@NameString, len(@NameString) - len(@TempString)))
  63.  
  64. –Get Suffix and strip it out of the string
  65. SET    @TempString = ltrim(RIGHT(@NameString, charindex(‘ ‘, Reverse(@NameString) + ‘ ‘)))
  66. IF    @TempString IN (‘Jr’, ‘Sr’,  ‘II’, ‘III’, ‘Esq’, ‘Junior’, ‘Senior’) SET @Suffix = @TempString
  67. IF    len(@Suffix) &gt; 0 SET @NameString = rtrim(LEFT(@NameString, len(@NameString) - len(@TempString)))
  68.  
  69. IF @LastName IS NULL
  70. begin
  71. –Get LastName and strip it out of the string
  72. SET    @LastName = ltrim(RIGHT(@NameString, charindex(‘ ‘, Reverse(@NameString) + ‘ ‘)))
  73. SET    @NameString = rtrim(LEFT(@NameString, len(@NameString) - len(@LastName)))
  74. –Check to see if the last name has two parts
  75. SET    @TempString = ltrim(RIGHT(@NameString, charindex(‘ ‘, Reverse(@NameString) + ‘ ‘)))
  76. IF    @TempString IN (‘VAN’, ‘VON’, ‘MC’, ‘Mac’, ‘DE’)
  77. begin
  78. SET @LastName = @TempString + ‘ ‘ + @LastName
  79. SET @NameString = rtrim(LEFT(@NameString, len(@NameString) - len(@TempString)))
  80. end
  81. end
  82.  
  83. –Get FirstName and strip it out of the string
  84. SET    @FirstName = rtrim(LEFT(@NameString, charindex(‘ ‘, @NameString + ‘ ‘)))
  85. SET    @NameString = ltrim(RIGHT(@NameString, len(@NameString) - len(@FirstName)))
  86.  
  87. –Anything remaining is MiddleName
  88. SET    @MiddleName = @NameString
  89.  
  90. –Create the output string
  91. SET    @TempString =
  92. while len(@NameFormat) &gt; 0
  93. begin
  94. IF @IgnorePeriod = ‘F’ OR LEFT(@NameFormat, 1) &lt;&gt; ‘.’
  95. begin
  96. SET @IgnorePeriod = ‘F’
  97. SET @TempString = @TempString +
  98. case ascii(LEFT(@NameFormat, 1))
  99. when ’72′ then case @Honorific
  100. when ‘Dr’ then ‘Doctor’
  101. when ‘Rev’ then ‘Reverend’
  102. when ‘Hon’ then ‘Honorable’
  103. when ‘Maj’ then ‘Major’
  104. when ‘Pvt’ then ‘Private’
  105. when ‘Lt’ then ‘Lieutenant’
  106. when ‘Capt’ then ‘Captain’
  107. when ‘Cpt’ then ‘Captain’
  108. when ‘Cmd’ then ‘Commander’
  109. when ‘Gen’ then ‘General’
  110. when ‘Sgt’ then ‘Sergeant’
  111. when ‘Cpl’ then ‘Corporal’
  112. else isnull(@Honorific, )
  113. end
  114. when ’70′ then isnull(@FirstName, )
  115. when ’77′ then isnull(@MiddleName, )
  116. when ’76′ then isnull(@LastName, )
  117. when ’83′ then case @Suffix
  118. when ‘Jr’ then ‘Junior’
  119. when ‘Sr’ then ‘Senior’
  120. when ‘Esq’ then ‘Esquire’
  121. else isnull(@Suffix, )
  122. end
  123. when ’104′ then case @Honorific
  124. when ‘Doctor’ then ‘Dr’
  125. when ‘Reverend’ then ‘Rev’
  126. when ‘Honorable’ then ‘Hon’
  127. when ‘Major’ then ‘Maj’
  128. when ‘Private’ then ‘Pvt’
  129. when ‘Lieutenant’ then ‘Lt’
  130. when ‘Captain’ then ‘Capt’
  131. when ‘Cpt’ then ‘Capt’
  132. when ‘Commander’ then ‘Cmd’
  133. when ‘General’ then ‘Gen’
  134. when ‘Sergeant’ then ‘Sgt’
  135. when ‘Corporal’ then ‘Cpl’
  136. else isnull(@Honorific, )
  137. end
  138. when ’102′ then isnull(LEFT(@FirstName, 1), )
  139. when ’109′ then isnull(LEFT(@MiddleName, 1), )
  140. when ’108′ then isnull(LEFT(@LastName, 1), )
  141. when ’115′ then case @Suffix
  142. when ‘Junior’ then ‘Jr’
  143. when ‘Senior’ then ‘Sr’
  144. when ‘Esquire’ then ‘Esq’
  145. else isnull(@Suffix, )
  146. end
  147. when ’46′ then case RIGHT(@TempString, 1)
  148. when ‘ ‘ then
  149. else ‘.’
  150. end
  151. when ’44′ then case RIGHT(@TempString, 1)
  152. when ‘ ‘ then
  153. else ‘,’
  154. end
  155. when ’32′ then case RIGHT(@TempString, 1)
  156. when ‘ ‘ then
  157. else ‘ ‘
  158. end
  159. else
  160. end
  161. IF ((ascii(LEFT(@NameFormat, 1)) = 72 AND @Honorific IN (‘FATHER’, ‘SISTER’))
  162. OR (ascii(LEFT(@NameFormat, 1)) = 115 AND @Suffix IN (‘II’, ‘III’)))
  163. SET @IgnorePeriod = ‘T’
  164. end
  165. SET @NameFormat = RIGHT(@NameFormat, len(@NameFormat) - 1)
  166. end
  167.  
  168. RETURN @TempString
  169. end
 
 
 

Optimized by SEO Ultimate