Add ‘Tweet This’ button to your Asp.Net site. Twitter + url shortening

Adding your own ‘Tweet This’ buttons so your visitors can post to twitter (complete with URL shortening using is really easy.

Just add a page ‘twitter.aspx’ to your site and remove all the HTML from the page.

Add this code:

Imports System.Net

Partial Public Class Twitter

    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

        If Request.QueryString("url") <> "" And Request.QueryString("com") <> "" Then

            TweetThis(Request.QueryString("url"), Request.QueryString("com"))

        End If

    End Sub

    Private Sub TweetThis(ByVal sIWTFURL As String, ByVal sComment As String)

        Dim sShortURL As String

        Dim sFullTweet As String

        sShortURL = ShortenURL(sIWTFURL)

        sFullTweet = sComment & " - " & sShortURL


    End Sub

    Private Function ShortenURL(ByVal sURL As String) As String

        Dim sJSON As String

        Dim oWebClient As New WebClient

        Dim sBitlyURL As String

        Dim sShortURL As String

        sBitlyURL = "" & Server.UrlEncode(sURL) & "&login=bitlyapidemo&apiKey=R_0da49e0a9118ff35f52f629d2d71bf07"

        sJSON = oWebClient.DownloadString(sBitlyURL)

        sJSON = Mid$(sJSON, InStr(sJSON, Chr(34) & "shortUrl" & Chr(34)) + 9)

        Do While sJSON.ToLower.StartsWith("http://") = False

            sJSON = Mid$(sJSON, 2)


        sShortURL = sJSON.Split(Chr(34))(0)

        ShortenURL = sShortURL

    End Function

    Private Sub SentToTwitter(ByVal sComments As String)

        Dim sURL As String

        sURL = "" & HttpUtility.UrlEncode(sComments)

        Response.Redirect(sURL, False)

    End Sub

End Class

Note: I am using the default login in the example, you should sign up for your own account so you can track usage of your links.

Now you just need to add some javascript to your html pages:

<a href="#" onClick='javascript:PostToTwitter()'>Tweet This</a>

function PostToTwitter()
var sTweet = 'This is the default text that will appear in the tweet';
var ShareURL = window.location.href;''+encodeURIComponent(ShareURL)+'&com='+encodeURIComponent(sTweet));
return false;

Draggable Marker Google Maps Demo

So you’ve been checking out my previous posts on Google Maps and Draggable Markers, and it would be nice to have a demo so you can see the draggable markers in action.

Check this out:

And the code as well? Here is the source for the Google Maps Demo

Add Draggable Markers and Events to your Google Maps

Following on from my last post on how to add Google Maps to your ASP.Net site, I’m now going to show how easy it is to add draggable markers to your map.

First, make sure you have the map working on your webform.

Having the map fire server-side events on user actions is pretty simple, and here is the code:

    Private Sub AddEventToMapDemo()
        Dim GeoCode As Subgurim.Controles.GeoCode
        Dim sMapKey As String = System.Configuration.ConfigurationManager.AppSettings("")

        GeoCode = GMap.geoCodeRequest("3052. VIC. australia", sMapKey)
        Dim gLatLng As New Subgurim.Controles.GLatLng(, GeoCode.Placemark.coordinates.lng)

        GMap.setCenter(gLatLng, 16, Subgurim.Controles.GMapType.GTypes.Normal)
        Dim oOption As New Subgurim.Controles.GMarkerOptions
        oOption.draggable = True
        oMarker = New Subgurim.Controles.GMarker(gLatLng, oOption)

        GMap.addListener(New Subgurim.Controles.GListener(oMarker.ID, Subgurim.Controles.GListener.Event.dragend, _
        "function(){{ var ev = new serverEvent('dragend', 0); ev.addArg(" & oMarker.ID & ".getPoint().lat()); ev.addArg(" & oMarker.ID & ".getPoint().lng()); ev.send(); }}"))

    End Sub

You then need to add code to handle the event:

    Protected Function GMap_ServerEvent(ByVal s As Object, ByVal e As Subgurim.Controles.GAjaxServerEventOtherArgs) As String

        If e.eventName = "dragend" Then
            Response.Write("New Latitude =" & e.eventArgs(0) & ", New Longitude = " & e.eventArgs(1))
        End If

    End Function

The server-side event will be fired every time the marker is dragged and dropped.

In my situation, I wanted to allow the user to drag & drop the marker as many times as they wanted - and only store the new Lat/Long values when the user pressed the Save button.

This is a little bit harder to code as the variables used to reference the marker cannot be accessed globally - so we can’t just read their values when the user presses the save button (to the gurus: I’m sure they can, but I couldn’t find an easy way to get at them) . However, we can store them in hidden fields when the DragEnd event is raised, and examine those fields when Save is pressed.

Add these fields to your webform:

<input type=hidden id="hidLat" name="hidLat" runat=server />
<input type=hidden id="hidLng" name="hidLng" runat=server />
<asp:Button ID="Button1" runat="server" Text="Save" />

And add this sub to your code-behind:

    Private Sub NewLatLongOnSaveMapDemo()
        Dim GeoCode As Subgurim.Controles.GeoCode
        Dim sMapKey As String = System.Configuration.ConfigurationManager.AppSettings("")

        GeoCode = GMap.geoCodeRequest("3052. VIC. australia", sMapKey)
        Dim gLatLng As New Subgurim.Controles.GLatLng(, GeoCode.Placemark.coordinates.lng)

        GMap.setCenter(gLatLng, 16, Subgurim.Controles.GMapType.GTypes.Normal)
        Dim oOption As New Subgurim.Controles.GMarkerOptions
        oOption.draggable = True
        oMarker = New Subgurim.Controles.GMarker(gLatLng, oOption)

            GMap.addListener(New Subgurim.Controles.GListener(oMarker.ID, Subgurim.Controles.GListener.Event.dragend, _
            "function(){ document.getElementById('hidLat').value=" & oMarker.ID & ".getPoint().lat();document.getElementById('hidLng').value=" & oMarker.ID & ".getPoint().lng() }"))

    End Sub

And here is the ‘Save’ button click event:

    Protected Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Response.Write("New Latitude =" & hidLat.Value & ", New Longitude = " & Me.hidLng.Value)
    End Sub

Add Google Maps to your .Net site in 10 minutes

Ever wanted to add a Google Map to your site but only had 15 minutes to spare? Now you can add a map and still have time to brag to your mates and bask in the worship that (inevitably) comes afterward.

Basically, the guys over at have already done all the hard work in writing the .Net wrapper for Google Maps. Problem is, the examples on their site are mostly in spanish & its a bit difficult to find out exactly what is needed to get everything working.

But all this is cutting into your bragging time - so lets get started!

1. Get a Google Maps API key from here:

2. Download the SubGurim wrapper dll from here:

3. Unzip it, and put it in your \bin directory

4. Add it to your toolbox by
Tools -> Choose Toolbox Items -> Browse -> Select the .dll file -> OK
GMap will now be in the ‘Standard’ area of your Toolbox.

5. Add a new webpage.

6. Drag the GMap from the toolbox onto the page. A new instance of the GMap will appear on the page, with the name ‘GMap1′

7. Add the following lines to your web.config file:

    <add key="" value="YourGoogleMapsAPIKeyHere" />

8. Add the following code to your Page.Load sub

        Dim sStreetAddress As String
        Dim sMapKey As String = ConfigurationManager.AppSettings("")
        Dim GeoCode As Subgurim.Controles.GeoCode

        sStreetAddress = "100 Russell St. Melbourne. VIC. 3000. Australia"
        GeoCode = GMap1.geoCodeRequest(sStreetAddress, sMapKey)
        Dim gLatLng As New Subgurim.Controles.GLatLng(, GeoCode.Placemark.coordinates.lng)

        GMap1.setCenter(gLatLng, 16, Subgurim.Controles.GMapType.GTypes.Normal)
        Dim oMarker As New Subgurim.Controles.GMarker(gLatLng)

Press F5, and start basking in the glory!

Update: I’ve now posted the code to add draggable markers and events to your Google Maps

How to set third-party cookies with iframe Facebook Applications

So you’ve written your facebook application, and you’ve gone the quick’n'easy route by making it an iframe application. The world is your oyster and any day now you’ll have your millionth user. Until you try to write a cookie.

Cookies written by your application will be treated as Third Party cookies by your browser, and in IE6 with the default privacy setting of ‘Medium’, they will be deleted. This can lead to all sorts of problems, from user settings not being remembered to total app breakdown (which, funnily enough, is what happened to me).

As it turns out, there is a simple solution. If you supply a ‘compact privacy policy’ with your page, then IE will treat the cookies with respect and let them through.

To the code

Just add this to the start of your page (every page where cookies will be written):


HttpContext.Current.Response.AddHeader("p3p", "CP=\""IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT\""")




How to write a FaceBook Application in 10 minutes

Writing F8 apps is where it’s at right now. Everybody knows it. The userbase is huge and now we have a (free) API to. Everything is good….but the documentation.

I spent a day writing my Sudoku Facebook application yesterday. I already had the sudoku javascript widget ready to go - the time was spent wading through pages of documentation and downloading toolkits that (as it turns out) I didn’t need.

As far as I can tell, Facebook allows you to create applications that appear to the user in 2 different areas.

1 - The profile. This the ‘main user page’ as far as Facebook is concerned. Here is where your main summary details are displayed and your comments wall. It would be great to have your widget displayed here, but the big limitation is that applications that use javascript are not allowed here (You must use FMBL, the facebook version of HTML). Too bad for me. What we can do is display a small ad to take the user to the Canvas page.

2 - The ‘Canvas page’. This is an entire page that your application gets to use (you can have multiple pages if you want). On these pages you can choose to display content from another website through an iframe, so that is what we’re going to do.

Ok, thats it for the overview. Start your clocks and lets get cracking.

1. Create your demo page. (2 minutes)
This is the page that the user will see on their canvas page. If you already have a page that you want to use, great. If not, then just copy this code for a guessing game.

<script type=text/javascript>
var iRandom;
function Restart()
iRandom = Math.floor(Math.random()*10)+1;
alert('OK, I am thinking of a number between 1 and 10');
function Guess()
var yourGuess = document.getElementById('myGuess').value;
if (yourGuess>iRandom)
	alert('Too High.');
if (yourGuess<iRandom)
	alert('Too Low.');
if (yourGuess==iRandom)
	alert('Well done! You guessed it.');
<div>Enter your guess between 1 and 10: <input type=text id='myGuess' name='myGuess'>
<input type='button' onClick='Guess()' value='Guess'>
<input type='button' onClick='Restart()' value='Start Again'>
<script type=text/javascript>

It’s not going to win any awards, but it gets the job done. Save the file somewhere on your website as ‘guess.htm’. Mine is saved at

Ok, now log into Facebook.

2. Install the Developer Application. (1 minute)
This allows you to create applications.

3. Create the Application. (30 seconds)
Click the ‘create application’ link
4. Fill in the Application details. (6 minutes)
There are heaps of fields you can enter, I am just going over the ones you need to get this demo working.

Application Name: Any name you want. I used ‘Guessing Game’.
Terms of Service checkbox: Check it.
Click ‘Optional Fields’.
Callback Url: This should be the root directory that your ‘guess.htm’ page is found at. You must also add a ‘/’ at the end. I used ‘’.
Canvas Page URL: This is the most confusing part, and wasted me heaps of time. What they want you to enter is basically a directory name for your applcaition. The name must be 7 characters or more, and must be unique from other Facebook applications. I used ‘guessab’ (so you can’t). When you add ‘’ to the front you have the Canvas page URL.
NOTE: If you use upper case in the Canvas Page URL, it will be converted to lower case automatically. Also, case is important, so if you use upper case in your links later on THEY WON’T WORK.
Tick ‘Use iframe’: This means that your canvas pages will use an iframe.
Application Type: Leave it at ‘website’.
Can your application be added on Facebook?: Tick ‘Yes’.
Application Description: I used ‘Cool guessing game’. If you disagree, feel free to use your own description.
Default FMBL: We will fill this out last, so leave it for the moment.
Default Profile Box Column: Tick ‘Narrow’.
Side Nav URL:OK, here is where we put a link in the side nav to the canvas page.
The full canvas page has the format:< value entered in Canvas Page URL>/
So for me, the full canvas page URL is:
Facebook maps ‘’ to your Callback URL, so what is loaded in the iframe is:
Note: Notice there is no ‘/’ inserted in guess.htm, that is why you have to put it in your Callback URL.

Anyway, now we can go back to
Default FMBL: This is the text that will go on the user’s profile. Lets just put another link to our game on the Canvas page. I entered:

Lets play a <a href=’’>Guessing Game</a>

5. Add the application (30 seconds)
From within ‘My Applications’, click on ‘View About Page’ for your new application. Then click ‘Add Application’, and confirm this.

6. Done! (Lets play)

Click on the link in either the left nav panel or the main profile panel and knock yourself out.

Test my Facebook Application :)

I’ve developed my first Facebook application (Facebook is a US college social network) and was hoping there are some people who could test it for me.

If you are a member of facebook, just enter:

Then click ‘Add this application’ at the top right of the page.

Any feedback is much appreciated.


MySpace API

I have updated my MySpace API to accept HTTP POST requests as well as GET. This means that the fields can be as long as you like, which is good for blog posts.

Try it out:

The code for the test page is:

<form name='form1' id='form1' method="post" action=''>
<tr><td>Post Subject</td><td><input type="text" id='txtSubject' name='txtSubject'></td></tr>
<tr><td colspan=2>Post Body</td></tr>
<tr><td colspan=2><textarea id='txtBody' name='txtBody' rows=5 cols=31 width=100%></textarea></td></tr>
<tr><td>MySpace Email</td><td><input type="text" id='txtEmail' name='txtEmail'></td></tr>
<tr><td>Myspace Password</td><td><input type="password" id='txtPassword' name='txtPassword'></td></tr>
<tr><td></td><td><input type=submit value="Submit" id='btnsubmit' name='btnsubmit'></td></tr>

As before, I am happy to share the code if you request it.

MySpace API - Automate your Blog posts

I have written a small API which allows you to add blog posts with a simple URL GET.
Update: It seems that sometime recently the MySpace pages for posting to your blog have changed, and so this API is now broken. I will fix it shortly when I have the time.

The format for usage is:[Post Subject]&Body=[Post Body]&Email=[Your Myspace Email]&Password=[Your Myspace Password] 


Remember to HTML encode the [Post Subject] and [Post Body]

To try it out:

The code for this simple test page is:

<script type="text/javascript">
function SubmitBlog()
var sSubject = escape(document.getElementById('iSubject').value);
var sBody = escape(document.getElementById('iBody').value);
var sEmail = document.getElementById('iEmail').value;
var sPW = document.getElementById('iPassword').value;
window.location = "" + sSubject + "&Body=" + sBody + "&Email=" + sEmail + "&Password=" + sPW;

<tr><td>Post Subject</td><td><input type="text" id='iSubject'></td></tr>
<tr><td colspan=2>Post Body</td></tr>
<tr><td colspan=2><textarea id='iBody' rows=5 cols=31 width=100%></textarea></td></tr>
<tr><td>MySpace Email</td><td><input type="text" id='iEmail'></td></tr>
<tr><td>Myspace Password</td><td><input type="text" id='iPassword'></td></tr>
<tr><td></td><td><input type=button value="Submit" onClick="SubmitBlog()"></td></tr>

No logs of requests are kept (I have no interest in stealing your password and becoming the most hated man on the internet). All the source code is in ASP.Net. If you would like a copy, send me an email.

At the moment, because all requests are handled via GET, the body posts must be reasonably small. If there is interest I will expand the API to allow POSTs so that the blog body can be larger.

MySpace API

2 small posts today, and maybe something bigger tomorrow.

I was having a think about big content sources, and the biggest one at the moment is MySpace - and now there is an (unofficial) API to help you get through the data.

Tom Morris has put together a MySpace API which fetches a person’s profile and comments.


Just insert the name of the person of the FriendID in place of ‘tom’ for the profile that you want.

Right, now to use or abuse, use or abuse…