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 WeGotDomain.com - Over 10,000 Aged domains for sale!Related posts:

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

SEOMoz Linkscape API wrapper in VB.Net

SEOMoz have just released a Free API to get Link info & their MozRank for domains. Before you can use the API, go to SEOMoz to get your AccessID and SecretKey.

The code here borrows from the function aws_GetSignature that comes with the Amazon Webservice.


        Private Function dcMozRankGet(ByVal sWebSiteURL As String) As Decimal
                Dim sAccessID As String = "YourAccessID"
                Dim sSecretKey As String = "YourSecretKey"
                Dim lExpires As Long = DateDiff("s", DateSerial(1970, 1, 1), Now()) + 300
                Dim sSafeSignature As String
                Dim sURLToFetch As String
                Dim sResult As String

                sWebSiteURL = HttpUtility.UrlEncode(sWebSiteURL)
                sSafeSignature = Encode(sAccessID, lExpires, sSecretKey, vbLf)

                sURLToFetch = "http://lsapi.seomoz.com/linkscape/mozrank/" & _
                sWebSiteURL & "?AccessID=" & sAccessID & "&Expires=" & lExpires & _
                "&Signature=" & sSafeSignature

                sResult = sGetData(sURLToFetch)
                sResult = Mid$(sResult, InStr(sResult, """umrp"":") + 7)
                sResult = sResult.Split(",")(0)
                dcMozRankGet = CDec(sResult)
        End Function

        Public Function Encode(ByVal sAccessID As String, _
        ByVal lExpires As Long, _
        ByVal SecretAccessKey As String, ByVal Separator As String) As String

                Dim sAccessExpires As String
                sAccessExpires = sAccessID & Separator & lExpires

                Dim strSig_UTF8 As Byte()
                Dim strSignature As String
                Dim objUTF8Encoder As UTF8Encoding
                Dim objHMACSHA1 As HMACSHA1

                objUTF8Encoder = New UTF8Encoding()
                strSig_UTF8 = objUTF8Encoder.GetBytes(sAccessExpires)

                objHMACSHA1 = New HMACSHA1( _
                     objUTF8Encoder.GetBytes(SecretAccessKey))
                strSignature = Convert.ToBase64String _
                     (objHMACSHA1.ComputeHash( _
                     objUTF8Encoder.GetBytes( _
                     sAccessExpires.ToCharArray())))

                Encode = HttpUtility.UrlEncode(strSignature)

        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)

                Do
                        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

An example call is:

dcYourRank = dcMozRankGet("www.seomoz.org")

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

Related posts:

  1. Getting Flights info from the Kayak API in ASP.Net
  2. Allowing special characters (forward slash, hash, asterisk etc) in ASP.Net MVC URL parameters
  3. Automate FireFox with ASP.net

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.


$(”#NewCombo”).html($(”#OriginalCombo”).html());

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

This post brought to you by WeGotDomain.com - 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

Social Media sites to submit your programming content to

I have benefited hugely from submitting my blog posts to the various niche social media sites that focus on programming.

The best (for me) have been:

If you can get to front page on Digg, Reddit or Mixx then you’ve got more luck than me :)

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

Related posts:

  1. We Got Domain - over 10,000 aged domains for sale
  2. Hiding the Digg button from Diggers
  3. Cast your net wiiiide

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 IWantThatHotel.com.au the JQuery plugins that I used were:

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

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

Related posts:

  1. We Got Domain - over 10,000 aged domains for sale
  2. Integrating JQuery with ASP.net - 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 WeGotDomain.com - 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

url=http://google.com

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

url=http%3A%2F%2Fgoogle.com

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
                Else
                        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))
                Else
                        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 WeGotDomain.com - 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 ASP.net

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.

Eg:
Post login details to
http://yourdomain/login
Site redirects (302) to:
http://yourdomain/admin

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("http://www.olddomain.com"))
For iC = 0 To oOldCookiesCol.Count - 1
     oNewCookies.Add(New Cookie(oOldCookiesCol(iC).Name, oOldCookiesCol(iC).Value, "", "http://www.newdomain.com"))
Next

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

This post brought to you by WeGotDomain.com - 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