Convert www. to non www. urls for ASP.Net websites

Ok, redirecting your www. urls to non www. through IIS is a total pain. Using a url rewriter is a good option - but not always available in shared hosting. Here is a quick method if you have a small ASP.Net site or are using master pages.

Just add this code to the Page_Load sub in the master page, or to every page if you aren’t using master pages.

        If Not IsPostBack Then

            'redirect www. to non www.

            If LCase(Request.Url.AbsoluteUri).StartsWith("http://www.") = True Then

                Response.Status = "301 Moved Permanently"

                Dim sNewLocation As String

                sNewLocation = "http://" & Mid$(Request.Url.AbsoluteUri, 12)

                If LCase(sNewLocation).EndsWith("/default.aspx") Then

                    sNewLocation = Left$(sNewLocation, Len(sNewLocation) - 13)

                End If

                Response.AddHeader("Location", sNewLocation)

                Exit Sub

            End If

        End If

the code removes the www. and does a simple 301 redirect, while preserving case etc in the new url.

Come to think of it, now that Google can follow javascript redirects, you could add this code as a javascript sub to your pages. Anyone want to do a live test on their site? :)

MS Bing integrates Travel with their search engine

For Travel Meta Search engines, this doesn’t seem like good news…

Microsoft bought FareCast in April 09, and now it is helping power Bing Travel. I haven’t seen the travel link on the Australian version of Bing, but I am guessing that it won’t be long. Not that I really care what Bing does, but if the integrated travel works for Microsoft, then Google may do the same thing. And that would be news. How many travel sites depend on traffic from Google? What if that dried up?

Star Wars - By someone that hasn’t seen it

This is the best…

Star Wars: Retold (by someone who hasn’t seen it) from Joe Nicolosi on Vimeo.This post brought to you by - Over 10,000 Aged domains for sale!Related posts:

  1. We Got Domain - over 10,000 aged domains for sale

Copying the contents of one combo box to another

Quick code tip on how to copy the contents of a combo box (HTML Select) to another. Using JQuery, of course.


I use this for forms with several date pickers, country pickers etc.

This post brought to you by - Over 10,000 Aged domains for sale!

Related posts:

  1. We Got Domain - over 10,000 aged domains for sale
  2. Cast your net wiiiide
  3. Copying cookies across domains in ASP.Net

Cool JQuery Plugins

JQuery - it really is all that & a packet of chips.

Smashing Magazine has just published 45+ New jQuery Techniques For Good User Experience and there is plenty of goodness in there.

For the JQuery plugins that I used were:

Date Picker
jCarousel (but I am thinking of replacing it with this Content Slider

This post brought to you by - Over 10,000 Aged domains for sale!

Related posts:

  1. We Got Domain - over 10,000 aged domains for sale
  2. Integrating JQuery with - A Cool Client-side Alert Box

Getting ASP.Net MVC running on IIS6

I have recently finished a new site IWantThatHotel, my first in ASP.Net MVC.

Over the next couple of weeks I will be posting code examples in VB.Net MVC (of which there are hardly any, it seems).

But first, here is a link to 2 posts that were a huge help getting the clean MVC urls running on IIS6
Deploying ASP.NET MVC to IIS 6
Several options are presented - I chose “Use a wildcard mapping for aspnet_isapi.dll” (out of the 4 options presented) because I didn’t want to alter my routes or extensions, and URL rewriting is a pain.

There is a separate post which talks about improving the performance of this method, which is worth implementing:
Disabling wildcard mapping on subdirectories

This post brought to you by - Over 10,000 Aged domains for sale!

No related posts.

Allowing special characters (forward slash, hash, asterisk etc) in ASP.Net MVC URL parameters

I’ve been getting into ASP.Net MVC a lot lately and there is plenty that is good about it.

One thing that is not good is the problems that MVC has when you have a special character (*,/,& etc) in your querystring.

Eg: Say you want to pass the param


MVC won’t like it - ‘/’ is a special character reserved as a separator for routes. But standard URL encoding it won’t work either:

MVC will still give a ‘HTTP Error 400 - Bad Request error’.

After looking around, it seems this error has been coming up a bit here and here and Phil Haack explains why standard encoding won’t work here.

One answer is to use base 64 encoding on any parameters that might contain the special characters.

        Public Function MyURLEncode(ByVal sInString As String) As String
                Dim sInStringNoSpaces As String = sInString.Replace(" ", "")
                Dim sURLEncoded As String = HttpUtility.UrlEncode(sInString)

                If sURLEncoded.Replace("+", "") = sInString.Replace(" ", "") Then
                        Return sURLEncoded
                        Return "=" & ToBase64(sInString)
                End If
        End Function

        Public Function MyURLDecode(ByVal sEncodedString As String) As String
                If sEncodedString.StartsWith("=") = True Then
                        MyURLDecode = FromBase64(Mid$(sEncodedString, 2))
                        MyURLDecode = sEncodedString.Replace("+", " ")
                End If
        End Function

        Private Function ToBase64(ByVal sInString As String) As String
                Dim btByteArray As Byte()
                Dim a As New System.Text.ASCIIEncoding()
                Dim sResult As String

                btByteArray = a.GetBytes(sInString)

                sResult = System.Convert.ToBase64String(btByteArray, 0, btByteArray.Length)
                sResult = sResult.Replace("+", "-").Replace("/", "_")
                ToBase64 = sResult
        End Function

        Private Function FromBase64(ByVal sBase64String As String) As String
                sBase64String = sBase64String.Replace("-", "+").Replace("_", "/")
                Dim obj As New ASCIIEncoding()
                FromBase64 = obj.GetString(Convert.FromBase64String(sBase64String))
        End Function

Because one of the useful things about MVC is the SEO-friendly URLs, the code doesn’t convert to Base 64 unless it is necessary.

To use these functions, here is a brief code snippet:

Public Class HotelsController
        Inherits System.Web.Mvc.Controller

        Function SelectHotelList(ByVal City As String, _
        ByVal Location As String)

                oSearch = New With {.City = MyURLEncode(City), .Location = MyURLEncode(Location)}
                Dim oDO As New RouteValueDictionary(oSearch)
                Return RedirectToAction("List", "Hotels", oDO)
        End Function

        Function List(ByVal City As String, _
                                    ByVal Location As String)

                City = MyURLDecode(City)
                Location = MyURLDecode(Location)


        End Function
End Class

Update: As Justin pointed out below, ‘/’ is a valid character in the base64 alphabet. I have had a quick read about Modified Base64 for URL which basically replaces ‘+’ and ‘/’ characters with ‘-’ and ‘_’ (I leave the padding ‘=’, but you can remove them if you want). I have updated the code with these changes, however I can’t find a test case that puts ‘/’ into the base64 encoded string - anyone know of one?

Also, the above code only encodes ASCII values, if you want to encode UNICode strings, then swap ASCIIEncoding with UnicodeEncoding.

This post brought to you by - Over 10,000 Aged domains for sale!

Related posts:

  1. SEOMoz Linkscape API wrapper in VB.Net
  2. Remove HTML tags and Javascript from pages
  3. Automate FireFox with

Copying cookies across domains in ASP.Net

If you logging in to remote sites using HttpWebRequest then you are probably used to supplying a CookieContainer object to keep track of login sessions etc. However, sometimes a login will do a redirect, leaving your cookies referring to the login url and not usable on the next url.

Post login details to
Site redirects (302) to:

The login cookie is stuck on http://yourdomain/login and is not used at http://yourdomain/admin, so the login fails.

The key is to set:
WebRequestObject.AllowAutoRedirect = false
in the HttpWebRequest for http://yourdomain/login

Code to copy cookies:

Dim oOldCookies As New CookieContainer
Dim oNewCookies As New CookieContainer
Dim oOldCookiesCol As New CookieCollection

'Do HttpRequest on http://yourdomain/login, place cookies in oOldCookies
'Remember to set WebRequestObject.AllowAutoRedirect = false

oOldCookiesCollection = oOldCookies.GetCookies(New System.Uri(""))
For iC = 0 To oOldCookiesCol.Count - 1
     oNewCookies.Add(New Cookie(oOldCookiesCol(iC).Name, oOldCookiesCol(iC).Value, "", ""))

'Now do HttpRequest on http://yourdomain/admin, using oNewCookies

This post brought to you by - Over 10,000 Aged domains for sale!

Related posts:

  1. Easy Cross Domain Cookies (Sharing cookies between domains)
  2. How to set third-party cookies with iframe Facebook Applications
  3. Opening a new browser window with POST data
  4. SEOMoz Linkscape API wrapper in VB.Net

Getting Flights info from the Kayak API in ASP.Net

Kayak is one of the top travel meta-search engines on the web, and they have a free API which allows you to get flight and hotel information.

To use the Kayak API, first get a developer key

Then you can read the full specifications to get the info. Or, just use the code below :)

This gets the flights given an Origin, Destination, Departure date and the number of travellers (note: Origin & Destination must be in the form of a 3 letter Airport code, eg: MEL = Melbourne, SYD = Sydney, LAX = Los Angeles).

You can also Download the full source code

        Private Function Flights(ByVal dtDepartDate As Date, _
                ByVal sOriginCode As String, _
                ByVal sDestinationCode As String, _
                ByVal iTravellers As Integer) As DataTable

                Dim sResult As String
                Dim oCookies As New CookieContainer
                Dim sURL As String
                Dim oDoc As New System.Xml.XmlDocument
                Dim sSID As String
                Dim sSearchID As String
                Dim bMorePending As Boolean = True
                Dim oTripList As System.Xml.XmlNodeList
                Dim oTrip As System.Xml.XmlNode
                Dim oFlights As DataTable
                Dim oFlight As DataRow
                Dim iFlightsFound As Integer
                Dim sDeveloperKey As String = "***Your Key Here****"

                'Full specs at:

                'Get the SessionID
                sURL = "" & sDeveloperKey
                sResult = sGetData(sURL, oCookies)
                sSID = oDoc("ident")("sid").InnerText

                'Start the Flight Search & get the SearchID
                sURL = "" & _
                "basicmode=true&oneway=y" & _
                "&origin=" & sOriginCode & _
                "&destination=" & sDestinationCode & _
                "&depart_date=" & Format(dtDepartDate, "MM/dd/yyyy") & _
                "&depart_time=a&" & _
                "return_date=" & _
                "&return_time=a" & _
                "&travelers=" & iTravellers & _
                "&cabin=b&action=doflights&apimode=1&_sid_=" & sSID
                sResult = sGetData(sURL, oCookies)
                sSearchID = oDoc("search")("searchid").InnerText

                oFlights = dtFlightsTableInit()

                Do While bMorePending = True
                        'Get the first lot of results
                        sURL = "" & _
                        "searchid=" & sSearchID & _
                        "&c=10&apimode=1&_sid_=" & sSID
                        sResult = sGetData(sURL, oCookies)
                        bMorePending = IIf(oDoc("searchresult")("morepending").InnerText = "true", True, False)
                        If bMorePending = True Then
                                'Wait for 5 seconds, then poll again
                                System.Threading.Thread.Sleep(5 * 1000)
                        End If
                iFlightsFound = Val(oDoc("searchresult")("count").InnerText)

                'Build the final request, asking for the total number of flights found by
                sURL = "" & _
                "searchid=" & sSearchID & _
                "&c=" & iFlightsFound & _
                "&apimode=1&_sid_=" & sSID
                sResult = sGetData(sURL, oCookies)

                oTripList = oDoc.SelectNodes("//trip")
                For Each oTrip In oTripList
                        oFlight = oFlights.NewRow()
                        oFlight("DepartDate") = oTrip("legs")("leg")("depart").InnerText
                        oFlight("ArriveDate") = oTrip("legs")("leg")("arrive").InnerText
                        oFlight("Airline") = oTrip("legs")("leg")("airline_display").InnerText
                        oFlight("Price") = oTrip("price").InnerText
                        oFlight("BookURL") = oTrip("price").Attributes("url").Value

                Flights = oFlights
        End Function

        Public Function dtFlightsTableInit() As DataTable
                Dim dtFlights As New DataTable

                dtFlights.Columns.Add(New DataColumn("DepartDate", GetType(String)))
                dtFlights.Columns.Add(New DataColumn("ArriveDate", GetType(String)))
                dtFlights.Columns.Add(New DataColumn("Airline", GetType(String)))
                dtFlights.Columns.Add(New DataColumn("Price", GetType(String)))
                dtFlights.Columns.Add(New DataColumn("BookURL", GetType(String)))

                dtFlightsTableInit = dtFlights
        End Function

        Public Function sGetData(ByVal sURL As String, _
Optional ByRef oCookies As CookieContainer = Nothing) As String

                Dim Writer As StreamWriter = Nothing
                Dim WebRequestObject As HttpWebRequest
                Dim sr As StreamReader
                Dim WebResponseObject As HttpWebResponse
                Dim sbResultsBuilder As New StringBuilder
                Dim sBuffer(8192) As Char
                Dim iRetChars As Integer

                WebRequestObject = CType(WebRequest.Create(sURL), HttpWebRequest)
                WebRequestObject.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)"
                WebRequestObject.Method = "GET"
                WebRequestObject.Timeout = 55000
                WebRequestObject.ReadWriteTimeout = 55000
                WebRequestObject.AllowAutoRedirect = True

                If Not (oCookies Is Nothing) Then
                        WebRequestObject.CookieContainer = oCookies
                End If

                WebResponseObject = CType(WebRequestObject.GetResponse(), HttpWebResponse)

                sr = New StreamReader(WebResponseObject.GetResponseStream)

                        iRetChars = sr.Read(sBuffer, 0, sBuffer.Length)
                        If iRetChars > 0 Then
                                sbResultsBuilder.Append(sBuffer, 0, iRetChars)
                        End If
                Loop While iRetChars > 0
                sGetData = sbResultsBuilder.ToString

        End Function

The Kayak API is pretty good, but does have some limitations, so I think is works best when you use it for stats rather than bookings. Anyone else know of some good travel APIs?

This post brought to you by - Over 10,000 Aged domains for sale!

Related posts:

  1. SEOMoz Linkscape API wrapper in VB.Net
  2. Create a Website Comparison Widget using GoogleTrends
  3. Using to Generate Truly Random Numbers in .Net
  4. Allowing special characters (forward slash, hash, asterisk etc) in ASP.Net MVC URL parameters

See how your website looks in over 60 browsers - in minutes

You’ve just updated your site. The changes look great - both in IE and Firefox - so you release it. And all is good.

Until a few days later, when the emails start to pile up. It doesn’t work in IE6. Problem is, you don’t have IE6 installed anymore, and don’t have access to a machine that does. Enter Browsershots.

Browsershots will give you a screen shot of your website (or specific page) in over 60 browsers. It does this by farming out the work to various ‘factories’ (people that are running the browsers on their machines. Just submit your URL & choose the browsers you want, wait a few minutes in the queue, then view the results.

Here are some results for (the thumbnails are small, but you get bigger pics at browsershots).
Screenshots of

This is so useful, it just blows me away. Oh, and it’s free. Anyone know of any other sites like this?

This post brought to you by - Over 10,000 Aged domains for sale!

Related posts:

  1. How to write a FaceBook Application in 10 minutes
  2. Add Google Maps to your .Net site in 10 minutes