Remove Name Mangling from ASP.Net Master Pages (get your ID back!)

If you have been programming using ASP.Net Master Pages and javascript then you have no doubt come across the problem where you try to access an element in javascript using:

var sValue = document.getElementById('TextBox1').value;

And you keep getting an error that the element cannot be found. If you check the HTML source for the page, you see that asp.net has “helpfully” added something like ‘ctl00_ContentPlaceHolder1_’ to the front of the control ID, so you have to use:

var sValue = document.getElementById('ctl00_ContentPlaceHolder1_TextBox1').value;

I’m not going to try & sugar coat it - this totally sucks.

The solution that I have been using overwrites the .getElementById method, allowing you to search for the element just using the normal ID.


<script type='text/javascript'>
document.newGetElementById = document.getElementById;
document.getElementById = function(sElementID)
{
var oFirstTry;

oFirstTry = document.newGetElementById(sElementID);
if (oFirstTry)
	return oFirstTry;
else
	return document.newGetElementById('ctl00_ContentPlaceHolder1_' + sElementID);
}
</script>

Thanks to Scooby Doo for pointing out the earlier error, it has now been corrected

Add this code to the top of your asp.net page or .js file, and then you can go back to using:

var sValue = document.getElementById('TextBox1').value;

without caring if it is in a content page or not.

Note: The above code won’t work if you change the name of your ContentPlaceHolder control from the standard ‘ContentPlaceHolder1′. If you do like to have unique names then change

return document.getElementById('ctl00_ContentPlaceHolder1_' + sElementID);

to

return document.newGetElementById('<%=me.Form.Controls(1).ClientID %><%=Me.ClientIDSeparator %>' + sElementID);

The code must now always be placed in your asp.net page (not an external .js file). However, calls to .getElementById can still be in external .js files.

Finally: A common solution to the problem is to use the ClientID property:

var sValue = document.getElementById('<% =TextBox1.ClientID %>').value;

but this method requires that all calls to getElementById be in the asp.net page, which is not as flexible as the solution given.

Create a Website Comparison Widget using GoogleTrends

Google Trends for Websites is a pretty cool way to compare sites. While I was using it, I thought it would be great as a ‘motivational widget’ - I would enter my site and a competitor and then display the widget on my desktop.

To try it, add this to your page:

<script src='http://lolcats.com.89.seekdotnet.com/WebsiteComparison.aspx?site1=techcrunch.com&site2=mashable.com' type='text/javascript'></script>

To get:

(change mashable and techcrunch to whoever you want).

So now the code:
Add a page to your project, and call it WebsiteComparison.aspx


Imports System.Net
Imports System.IO

Partial Public Class WebsiteComparison
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Dim sHTML As String
        Dim sSite1URL As String = Request.QueryString("site1") '"mashable.com"
        Dim sSite2URL As String = Request.QueryString("site2") '"techcrunch.com"
        Dim sCacheKey As String = "CACHE_WebsiteComparison:" & sSite1URL & "," & sSite2URL

        sHTML = CType(Cache(sCacheKey), String)

        If sHTML = Nothing Then
            sHTML = ChartGenerate(sSite1URL, sSite2URL)
            Cache.Insert(sCacheKey, sHTML, Nothing, Now.AddHours(10), System.Web.Caching.Cache.NoSlidingExpiration)
        End If

        sHTML = "document.write(""" & sHTML & """);"
        Response.Write(sHTML)

    End Sub

    Private Function ChartGenerate(ByVal sSite1 As String, ByVal sSite2 As String)
        Dim sURL As String
        Dim sAllHTML As String
        Dim oHTML As New HtmlAgilityPack.HtmlWeb
        Dim oDoc As New HtmlAgilityPack.HtmlDocument
        Dim sCSS As String
        Dim sStyle As String
        Dim sChartHTML As String

        sURL = "http://trends.google.com/websites?q=" & sSite1 & "%2C" & sSite2 & "&geo=all&date=all&sort=0"
        oDoc = oHTML.Load(sURL)

        sChartHTML = oDoc.DocumentNode.SelectSingleNode("//div[@id='trends-history']").OuterHtml
        sChartHTML = HttpUtility.HtmlDecode(sChartHTML)

        sCSS = oDoc.DocumentNode.SelectSingleNode("//style").InnerHtml
        sCSS = "http://trends.google.com" & sCSS.Split(Chr(34))(1)
        sStyle = "<LINK href='" & sCSS & "' type='text/css' rel='stylesheet' >"

        sAllHTML = sStyle & sChartHTML
        sAllHTML = sAllHTML.Replace(vbLf, "")
        sAllHTML = sAllHTML.Replace(Chr(34), "'")

        ChartGenerate = sAllHTML
    End Function

End Class

Only 2 real things to note about the above code:

  1. We are using the fantastic HTML Agility Pack to read the chart page as HTML from Google and then extract the part we need. If you don’t want to use it, then you can substitute a WebClient call and add your own string processing.
  2. The result is put in the cache, so we don’t get banned from Google by calling their server too many times.

Add GeoLocation to your site in less time than it takes to Drink a Beer

This is what a regular programmer looks like
Adding Geolocation to your website is so easy these days that I’ve decided that not only can we do it within 5 minutes, but to make it interesting I’ll bet that you’ve finished it before you can finish a beer.

OK? Got your beer? Lets go.

  1. Crack open the beer and start a new vb.net project. Call it ‘GEOTest’. Take a well deserved drink.
  2. Download the MaxMind Geo database and vb.net wrapper code from MaxMind (Complete list of supported languages - thanks again to MaxMind for doing all the work). Have some more beer while it downloads (thanks to my spankinglyfast ADSL2+ connection, no beer for me).
  3. Open the zip file into your project directory. Another sip. Add the files  ‘testCountryLookUp.aspx’, ‘testCountryLookUp.aspx.vb’ and ‘CountryLookup.vb’ to your project.
  4. Thirsty? More beer.
  5. Set the page ‘testCountryLookUp.aspx’ as your startup page, and then run the project. At this point it should run, but you may get a ‘Parser Error’ in the ‘testCountryLookUp.aspx’ file. To fix it, change:
    Inherits="testCountryLookUp"
    to
    Inherits="GEOTest.testCountryLookUp"
    in the  ‘testCountryLookUp.aspx’ file.
  6. Thats it! Done! You’ve probably still got plenty of beer left, so lets make some of our own code to get the country from IP Address.


Function CountryFromIP(ByVal Address As String) As String
   Dim oCountryLookup As CountryLookup = New CountryLookup(Server.MapPath("data/GeoIP.dat"))

   CountryFromIP = oCountryLookup.LookupCountryName(Address)
End Function

To call it, just use:
CountryName = CountryFromIP(Request.UserHostAddress)
Doesn’t work? Maybe too much beer…Passing your UserHostAddress won’t work from your local machine. To test, grab your IP address from somewhere like whatismyipaddress.com.

Still doesn’t work? Definitely time for another beer…