Tuesday, August 15, 2006

How it works: IP address filtering

When I started this site, I thought i'd occasionally post some code samples on how I actually do things on the site, just in case others needed the information.

I haven't done very many of these, and so here is the next one.

The issue I see is that for some IP addresses, I need to perform certain tasks (such as blocking them, showing the site without advertising, enabling me to administer the site etc).

Each of these tasks has an XML file dedicated to it, which is read at least once each page request. These operation needs to be lightning fast, and initially, it wasn't. A typical XML file will look like this:


<?xml version="1.0" encoding="utf-8"?>

<blockedurls>

<url ip="192.168.0.1"></url>

<url ip="192.168.0.10"></url>

</blockedurls>


After getting some help, I learnt using an XPath query seemed to be the best solution.

I created a generic function to parse the XML for me, and return a boolean value if a match was found. This function is below


Public Shared Function parseXMLIP(ByVal XPathString As String, ByVal XMLfile As String, ByVal cachename As String) As Boolean
Dim parseResult As Boolean = False
Dim xpdocument As XPathDocument

Try
If HttpContext.Current.Application.Item(cachename) Is Nothing Then
xpdocument = New XPathDocument(HttpContext.Current.Server.MapPath(XMLfile))
HttpContext.Current.Application.Add(cachename, xpdocument)
Else
xpdocument = DirectCast(HttpContext.Current.Application.Item(cachename), XPathDocument)
End If

Dim Navigator As XPathNavigator = xpdocument.CreateNavigator()
Dim Iterator As XPathNodeIterator = Navigator.Select(XPathString)

If Iterator.Count > 0 Then
parseResult = True
End If
Catch ex As Exception
End Try
Return parseResult
End Function



Because I have the individual operations and the generic function, I pass certain parameters to the function so I don't have it in triplicate :-)


Dim showData as boolean
showData = myFunctions.parseXMLIP("//block[@ip='" & ipaddr & "']", "~/App_Data/ipblock.xml", "ipBlockListXML")



And that's all there is to it. Maintenance is a matter of adding, changing or deleting a line in the XML file and uploading it to the site (and deleting the cached version).

No comments: