Tag Archives: JSON

Access your Google Latitude position from a .Net app

When I saw that Google Latitude now enables you to access your data by a JSON feed, I decided to make it communicate with a little GPS tracking project of mine.

I’m really found of all these ways we now have to make anything communicate with anything. You can build interfaces from any system to any other system really easily.

This code enables you to automatically get your GPS position (or the position of a friend) from your JSON Latitude feed. To be able to do that, you have to enable your KML/JSON feed.
It requires .Net 3.5’s System.Web.Extensions

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
using System;
using System.Collections.Generic;
using System.Text;
using System.Web.Script.Serialization;
using System.Net;
using System.IO;
 
namespace LatitudeReader {
	class Program {
		static void Main() {
 
			Console.WriteLine( "What is your user id ?" );
 
			var userId = Console.ReadLine();
 
			if ( userId == String.Empty )
				userId = "5616045291659744796";
 
			// Url of the JSON Latitude feed
			var url = String.Format( "http://www.google.com/latitude/apps/badge/api?user={0}&type=json", userId );
 
			// We download the file
			var ms = new MemoryStream();
			Download( url, ms );
 
			// JSON in text format
			var textContent = UTF8Encoding.UTF8.GetString( ms.ToArray() );
 
			// We convert the JSON text file to an object
			// It returns 
			var jss = new JavaScriptSerializer();
			var jsonContent = jss.DeserializeObject( textContent ) as Dictionary<String, Object>;
 
			// We get the data
			var features = ( jsonContent[ "features" ] as object[] )[ 0 ] as Dictionary<string, object>;
			var geometry = features[ "geometry" ] as Dictionary<string, object>;
			var coordinates = geometry[ "coordinates" ] as object[];
			var lon = coordinates[ 0 ] as decimal?;
			var lat = coordinates[ 1 ] as decimal?;
 
			// And then the timestamp
			var properties = features[ "properties" ] as Dictionary<string, object>;
			var date = ConvertFromUnixTimestamp( (double) (int) properties[ "timeStamp" ] );
 
			// We convert the UTC date to local time
			date = date.ToLocalTime();
 
			Console.WriteLine( "{0} : {1} x {2}", date, lat, lon );
		}
 
		public static DateTime ConvertFromUnixTimestamp( double timestamp ) {
			DateTime origin = new DateTime( 1970, 1, 1, 0, 0, 0, 0 );
			return origin.AddSeconds( timestamp );
		}
 
		private const int BUFFER_SIZE = 1024;
 
		private static void Download( string url, Stream writeStream ) {
			var request = (HttpWebRequest) WebRequest.Create( url );
			var response = request.GetResponse();
 
			var readStream = response.GetResponseStream();
 
			var data = new Byte[ BUFFER_SIZE ];
 
			int n;
			do {
				n = readStream.Read( data, 0, BUFFER_SIZE );
				writeStream.Write( data, 0, n );
			} while ( n > 0 );
 
			writeStream.Flush();
			readStream.Close();
		}
	}
}

The only references you need are : System and System.Web.Extensions

Lighttpd + Mono ASP.Net : The right configuration

As I already told before, I love the Mono project. It enables to run the powerful Microsoft .Net Framework on UNIX/Linux/BSD systems.

I recently wanted to test a very cool feature of ASP.Net on a mono server. So I did a little

1
apt-get install lighttpd mono-fastcgi-server2 -y

The feature I wanted to try was a web scripting method ( with the “[WebMethod]” attribute) exporting some JSON directly from your method return value.

Here is the web scripting method declaration :

1
2
3
4
5
6
7
8
9
10
 
[ScriptService]
public partial class _Default:Page {
 
	[WebMethod]
	[ScriptMethod( ResponseFormat = ResponseFormat.Json, UseHttpGet = false )]
	public static String TestMethod() {
		return DateTime.Now.ToString();
	}
}

And here is the javascript / JQuery code that gets the data :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<div id="toto"></div>
 
<script type="text/javascript">
    function doIt() {
        $(document).ready(function() {
            $.ajax({
                type: "POST",
                url: "/Default.aspx/TestMethod",
                contentType: "application/json; charset=utf-8",
                data: "{}",
                dataType: "json",
                success: AjaxSucceeded,
                error: AjaxFailed
            });
        });
        function AjaxSucceeded(result) {
            document.getElementById("toto").innerHTML = result.d;
        }
        function AjaxFailed(result) {
           document.getElementById("toto").innerHTML = "Error : "+result.status + ' ' + result.statusText;
        }
        setTimeout("doIt()", 1000);
    }
    doIt();
 
</script>

In my /etc/lighttpd/conf-enabled/10-fastcgi.conf file, I had this :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
server.modules   += ( "mod_fastcgi" )
fastcgi.server    = (
        "" => ((
                "socket" => mono_shared_dir + "fastcgi-mono-server",
                "bin-path" => mono_fastcgi_server,
                "bin-environment" => (
                        "PATH" => "/bin:/usr/bin:" + mono_dir + "bin",
                        "LD_LIBRARY_PATH" => mono_dir + "lib:",
                        "MONO_SHARED_DIR" => mono_shared_dir,
                        "MONO_FCGI_LOGLEVELS" => "Standard",
                        "MONO_FCGI_LOGFILE" => "/var/log/lighttpd/mono.log",
                        "MONO_FCGI_ROOT" => mono_fcgi_root,
                        "MONO_FCGI_APPLICATIONS" => mono_fcgi_applications
                ),
                "max-procs" => 1,
                "check-local" => "disable"
        ))
)

Everytime I launched a call from javascript, I got (with JS) I got a “405 Method not allowed”. Well, that was pretty disturbing. Mostly because a google search on this didn’t give me anything.
My first thought was that mono didn’t react the same way the .Net framework does. But this isn’t it. It came from my crappy lighttpd config file. It didn’t search for the Default.aspx file but for the Default.aspx/TesMethod.
What you need to do is set :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
fastcgi.server    = (
        ".aspx" => ((
            # Everything you have in your file (like my file above)
        )
 
fastcgi.map-extensions = (
        ".asmx"   => ".aspx",
        ".ashx"   => ".aspx",
        ".asax"   => ".aspx",
        ".ascx"   => ".aspx",
        ".soap"   => ".aspx",
        ".rem"    => ".aspx",
        ".axd"    => ".aspx",
        ".cs"     => ".aspx",
        ".config" => ".aspx",
        ".dll"    => ".aspx"
)

And that will even improve your performances because any other file will be handled directly by lighttpd.

One quick note : There’s something weird with VS2008 WebDev.WebServer.Exe, the WebMethod request takes at least 1.0s to complete. On the same host with XSP, it’s around 15 ms. And on the Celeron 2.6Ghz linux server with lighttpd it’s around 12 ms. And on a IIS 7 server (bundled with Windows 7), it takes 12 ms. So why is the Visual Studio’s WebDev.WebServer so slow ?

By the way, why should we use a Linux + lighttpd + Mono server when we can use a Windows + IIS + ASP.Net server ? The reason is mainly that for the same usage, Linux consumes less resources and it’s easier to customize to suit your needs.

An other question you might have : Why use JQuery + JSON when you can use everything in the Microsoft AJAX Framework ? The main reason is that I really have the feeling to lose control with Microsoft AJAX Framework, I don’t like the huge automatically generated code. And it doesn’t make really fast web interfaces. With JQuery, everything goes faster and it’s way simpler to understand (and debug).

Related :
Using JQuery with ASP.Net