Wednesday, March 15, 2006

Generating 'FAQ Article xxx' links

In the website, i often refer to or cross-reference FAQ Articles. In general, they are linked as "FAQ Article XXX" which will open the link in the browser when clicked.

To ease development and page generation, I use a shortcut to generate these links - I code the FAQ Article number between square brackets [[ ]], which then generates a hyperlink and also adds a tooltip on the link with the title of the article.

ie, [[340]] turns into: FAQ Article 340.

To do this, I use Response.Filter in the Global.asax to utilise some code I found at http://www.codeproject.com/aspnet/WhitespaceFilter.asp

Global.asax:
Sub Application_BeginRequest(ByVal sender As Object, ByVal e As EventArgs)
If Not Request.Url.PathAndQuery.ToLower.IndexOf(".aspx") = -1 Then
Response.Filter = New MyHttpFilter(Response.Filter)
End If
End Sub

The filter itself is as above from the codeproject site. I change the 'Write' function though with my own customization.
Public Overrides Sub Write(ByVal MyBuffer() As Byte, _
ByVal offset As Integer, ByVal count As Integer)
Dim data(count) As Byte
Buffer.BlockCopy(MyBuffer, offset, data, 0, count)
Dim s As String = System.Text.Encoding.UTF8.GetString(data)
Dim myDelegate As New MatchEvaluator(AddressOf MatchHandler)
Dim pattern As String = "\[\[(\d{2,})\]\]"
Dim re As New Regex(pattern, RegexOptions.Multiline _
Or RegexOptions.IgnoreCase)
s = re.Replace(s, myDelegate)
' Finally, we spit out what we have done.
Dim outdata() As Byte = System.Text.Encoding.UTF8.GetBytes(s)
_sink.Write(outdata, 0, outdata.GetLength(0))
End Sub 'Write

Private Function MatchHandler(ByVal m As Match) As String
Dim mFaqId As String
Dim faqTitle As String = ""
Dim returnString as string = "<a "
mFaqId = m.Groups(1).Value
Try
Dim c As New cacheClass
Dim dv As DataView
dv = c.getfaqList()
dv.RowFilter = "id = '" & mFaqId & "'"
faqTitle = CStr(dv.Item(0).Item("title")).Replace(Chr(34), "''")
Catch ex As Exception
End Try
returnString += "title=" & Chr(34) & faqTitle & Chr(34)
returnString += " href=" & Chr(34) & "/faq/article/" & _
mFaqId & ".aspx" & Chr(34) & " >"
returnString += "FAQ Article " & mFaqId & "</a>"
Return returnString
End Function

Note how it uses the regular expression to find a match and make the change.

The whole aim is to reduce the time I spend on the site - it does that nicely!

No comments: