Saturday, June 25, 2011

Best tutorial of C# Async

This is by far the best tutorial of C# Async you can possibly find for the simple reason that the code is all concise and runs in the browser right in front of you!

The examples are also quite nicely / concisely written e.g. here is a sample of a CPU intensive task made async :

public async Task AsyncResponsiveCPU()
    Console.WriteLine("Processing data...  Drag the window around or scroll the tree!");
    int[] data = await ProcessDataAsync(GetData(), 16, 16);
    Console.WriteLine("Processing complete.");

public Task<int[]> ProcessDataAsync(byte[] data, int width, int height)
    return TaskEx.Run(() =>
        var result = new int[width * height];
        for (int y = 0; y < height; y++)
            for (int x = 0; x < width; x++)
                Thread.Sleep(10);   // simulate processing cell [x,y]
            Console.WriteLine("Processed row {0}", y);

        return result;

And heres a sample that uses the CancellationTokenSource (The CancellationToken is polled once per iteration of the y for loop to see if cancellation has been requested, and if so an OperationCanceledException is thrown.)

private CancellationTokenSource cts;

public async Task AsyncCancelSingleCPU()
    cts = new CancellationTokenSource();

        int[] data = await ProcessAsync(GetData(), 16, 16, cts.Token);
    catch (OperationCanceledException)
        Console.WriteLine("Processing canceled.");

public Task<int[]> ProcessAsync(byte[] data, int width, int height, CancellationToken cancellationToken)
    return TaskEx.Run(() =>
        var result = new int[width * height];

        for (int y = 0; y < height; y++)
            for (int x = 0; x < width; x++)
                Thread.Sleep(10);   // simulate processing cell [x,y]
            Console.WriteLine("Processed row {0}", y);

        return result;

And the best of all report progress sample

(Pings several sites, with an EventProgress object passed in to receive progres notifications.

Note that all calls into the ProgressChanged lambda are occurring while AsyncProgressPolling is suspended awaiting GetAllDirsAsync.)

private CancellationTokenSource cts;
public class GetAllPingsPartialResult
    public IList<string> Pings;
    public int Count;
public async Task AsyncProgressPolling() { cts = new CancellationTokenSource(); var progress = new EventProgress<GetAllPingsPartialResult>(); try { progress.ProgressChanged += (source, e) => { ProgressBar.Value = e.Value.Count % 100; //e is of the type GetAllPingsPartialResult }; foreach (var item in await GetAllPingsAsync(@"c:\", cts.Token, progress)) { Console.WriteLine(item); } } catch (OperationCanceledException) { Console.WriteLine("Operation canceled."); } } public async Task<string[]> GetAllPingsAsync(string root, CancellationToken cancel, IProgress progress) { var sites = new List<string>(); for (int i = 0; i < 30; i++) { sites.Add(""); sites.Add(""); sites.Add(""); } var results = new List<string>(sites.Count); foreach (var site in sites) { cancel.ThrowIfCancellationRequested(); var time = DateTime.UtcNow; try {await new WebClient().DownloadStringTaskAsync(site);} catch {} var ms = (DateTime.UtcNow - time).TotalMilliseconds; results.Add(String.Format("[{0}] {1}", ms, site)); if (progress != null) progress.Report(new GetAllPingsPartialResult() { Pings = new ReadOnlyCollection<string>(results), Count = results.Count }); } return results.ToArray(); }

And if you want to read here is an excellent article :


Friday, June 24, 2011

Basic data insertion into a postgis database

I assume you have setup postgis / postgresql using the tutorial here :

The objective is to make a simple table with site + cell + lon + lat and insert a value in it.

First off the SQL to create a the table :

  "LOCATION" geometry,

The geometery type is one of the types that becomes available with postgis. As it is this table is complete. But the real joy of using a GIS based database starts with the ability to add a GIS index. You can do this by : 

  USING gist

Finally lets insert some data into the table : 

    VALUES ('somesite', 'somecell', ST_SetSRID(ST_Point(-71.1043443253471, 42.3150676015829),4326));

Two functions that come with PostGIS are used here : ST_Point and ST_SetSRID
ST_Point is the basic data type for point based geometries. SetSRID is used the set the Spatial reference system ID. 4326 corresponds to the reference system commonly known as WGS 84 and is the most commonly used. In fact this is the system employed by the GPS system. It is important to note that ST_Point and all other similar functions take coordinates in  Longitude ,  Latitude  order.

Till next time.

Tuesday, June 21, 2011

Disabling windows vista UAC + automatic login on a domain in one go :)

I just followed the procedure mentioned here :

  1. Click Start, click Run, type regedit, and then click OK. In Windows Vista/7, simply typeregedit in Start Search and hit Enter.
  2. Navigate to the following registry key:
    HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon
  3. Double-click the DefaultUserName entry, type the user name to log on with, and then click OK.
    If DefaultUserName registry value name is not found, create a new String Value (REG_SZ)with value name as DefaultUserName.
  4. Double-click the DefaultPassword entry, type the password for the user account under the value data box, and then click OK.
    If there is no DefaultPassword value, create a new String Value (REG_SZ) withDefaultPassword as the value name.
    Note that if no DefaultPassword string is specified, Windows automatically changes the value of the AutoAdminLogon registry key from 1 (true) to 0 (false) to turn off theAutoAdminLogon feature.
  5. In Windows Vista/7, DefaultDomainName has to be specified as well, else Windows will prompt for invalid user name with the user name displayed as .\username. To do so, double click onDefaultDomainName, and specify the domain name of the user account. If it’s local user, specify local host name.
    If the DefaultDomainName does not exist, create a new String Value (REG_SZ) registry key with value name as DefaultDomainName.
  6. Double-click the AutoAdminLogon entry, type 1 in the Value Data box, and then click OK.
    If there is no AutoAdminLogon entry, create a new String Value (REG_SZ) withAutoAdminLogon as the value name.
  7. If it exists, delete the AutoLogonCount key.
  8. Quit Registry Editor.
  9. Click Start, click Restart, and then click OK.

One thing not mentioned in the post is that if you set AutoAdminLogin to 1 UAC also gets disabled .... which is awesome. This is because local crontab software will be able to access privalaged services (e.g. reporting services) running on the same computer.

PS: the computer is in a safe location such that anyone who has physical access to the machine is a friend. 

Android / iOS games with flash / flex video demos

Adobe just released Flash Builder 4.5.1 that now supports iOS (iPad / iPhone) development out of the box along with Android development :

I really admire adobe's commitment to their star platform and I think that in the end this will play out well for adobe :)

You can watch a video demonstration of how to target all these amazing phone platforms with one technology here :

Also here is a case study : with and accompanying screencast :

Monday, June 20, 2011

Some interesting facts about Google App Engine

Google App Engine is awesome. So beyond this simple fact here are some other interesting ones:

Account Registration
For the first time you click on "Create Application" (  You need to sign up with a phone number. Facts:
  • If you try this without a supported carrier (mentioned here) You will start to get the error message "You have sent too many SMS verification messages" In this case goto and mention why you are getting this error (your phone number). Your case will be evaluated and if found eligible your appspot account will be activated.
  • You phone number is linked to your google account. You cannot use the same phone number to register for appspot using another account. 
Application Registration

When you create a new application not all options will be changeable. At the time of this writing you can see options which are available for change and which are readonly (Authentication Options used to be readonly as well apparently but as you can see I can change them right now):

And since you cannot reuse the application ID it is important to set it right the first time.

Download Application Files
There is no way to download files from AppEngine (you can only upload....this actually makes me feel secure). So you should use your own version control system (I suggest

AppEngine is designed for fast response times
If an app routinely takes a long time to respond to requests, AppEngine will punish it to make room for faster requests.


Saturday, June 18, 2011

Pycharm is an amazing python ide

There are really a lot of little big details in PyCharm that make it worth and and much much more.
Here are some I noticed immediately:

Project Management 
A working project management system. The eclipse project management (workspace per project!) is deeply broken. PyCharm to the rescue.

A google app engine project in pycharm :
Basically its a folder with a .idea folder inside of it as shown:
Open a project :

Close a project: 

Multi Monitor Support
Its not big for some people. Its big for me. Drag the tab header out of the application to create a new window. Drag it back to place it back into the application. 

Google App Engine deep integration
I've already shown how to debug Google App Engine with PyCharm:
But I would like to mention additional google app engine integration in the tools menu : 

Test driven development (TDD) 
Ability to run tests from the IDE. Additionally you can debug while a test runs :) 

View variable value while debugging
Adding a variable to watch takes typing. Mousing over is faster : 
Access to the debug console while an application runs 
This is super cool. If you find code is not working the way it is not only can you find out why but you can write the correct code and see if it works on the spot using the debug console: 
You can see it works with google app engine as well :) 

About the Code Editor
Yes there is intellisense and all the other bells and whistles that you expect from a basic editor. But PyCharm does more than the other python ides I have seen e.g. : 

Zoom code with Ctrl+ Scroll wheel
Zoomed in:

Zoomed out. You can see more and get an overview of where the function is going thanks to python keeping indentation important :) :
Ctrl Click to navigate to function
Nothing can help you understand code better than go to definition. Comments lie. Code does not :) 
In PyCharm when you hold the ctrl key and mouse over a function / class it turns into a hyperlink as shown: 
Notice that this is a class inside of Google App Engine :) Click it while holding the ctrl key and the class definition is opened for you : 
Can't I get the same thing in Visual Studio ... cause when you are looking at code you probably already have the mouse in your hand and F12 is just so far away :) 

The override icon
A really nice touch. Especially since python does not have the override keyword. Notice the icon on the line def get(self): 
Reformat code
Don't you just have poorly formated code e.g. = hugging the variable , line continuations starting too late or too early. PyCharm fixes these for you : 
Also when looking at another persons code you might want to use the optimize imports :) 

Goto Class
Check it out : 
 This opens a search panel that can even search by Pascal Case (notice I typed rh) :) 

Truly. Python IDEs have been charmed :) 

Friday, June 17, 2011

Google App Engine Python + PyCharm = love

I think I have just found the best debugging / development environment ( IDE ) for google app engine. PyCharm.

Not surprising. Its from JetBrains :) They guys that make ReSharper (a lovely VisualStudio C# plugin) and IntelliJ IDEA (the best performing java development IDE I used a long time ago ... one that people love and use despite free eclipse / netbeans being available).

I like my IDEs snappy and PyCharm is like a Snappy Snake :)

And it feels like its made with google app engine (AND / OR)  django in mind.

NOTE: PyCharm version 1.5, Google App Engine version : 1.5.0

As soon as you start PyCharm you see the following screen :
Click on Create a New Project and you get the option to create a GoogleAppEngine application right off the bat as shown:
Setup the project name (your choice) / location (your choice) and type (as Google App Engine project) and click Ok and you are presented with the following screen:

(NOTE: I was working on x64 machine. That is probably why the SDK is not filled ... nonetheless)
Filled in the SDK as : "C:\Program Files (x86)\Google\google_appengine" (note working on x64 machine otherwise it is : "C:\Program Files\Google\google_appengine"
Setup the python interpreter (I prefer to use portable python that is why it does show up by default) by clicking on the browse icon and then selecting Add.

And Finally click Ok.

I now have a debug-able Google App Engine project available. In the screen shot below I setup a break point, just clicked the debug icon, waited for app engine to start and browsed to http://localhost:8080

Just installing PyCharm and creating a new project and I can already debug! This is much more like the visual studio experience that I love and adore and was afraid I might never find with GAE.

Also check out pycharm figured out the google app engine import locations without me telling it anything other than the google app engine install path:

If it wasn't for this software I really was about to give up on GAE because without a powerful trouble shooting / development environment like this maintaining applications would have been a real hassel.

Yes I am madly in love with Python and now PyCharm.


Facebook programming with python

I just found out that there is a very impressive facebook api implementation for python out there : 

Its got 455 watchers :) 

PyFacebook is also very easy to extend when new Facebook API methods are introduced. Each Facebook API method is described in the PyFacebook library using a simple data structure that specifies the method's name and parameter types. PyFacebook does not appear to have been updated to work with the new stream API methods yet, but it was trivially easy for me to do it myself. You can see my simple PyFacebook modifications here.

Getting started with Google app engine (python) + portable python

I fell in love with python a long long time ago. But somehow didn't get the time to work with google app engine. Now that a project came up that requires some of the cool features of google app engine (like mail receiving) I am working on it.

Getting the development launcher to work with portable python (for version 2.5.4) was slightly tricky in that you need to point to the python executable rather than the folder in which the executable is found. i.e in my case in "Google App Engine Launcher" go to Edit -- Preferences and notice the "Python Path". I needed to set it to "C:\PYTHON\App\pythonw.exe" OR "C:\PYTHON\App\python.exe"

Also I set the editor to pyscripter "C:\PYTHON\App\Pyscripter.exe" as shown.
Next when I click on edit in launcher now I can get a cool editor as shown.:
You can also view the files by using the file explorer in pyscripter using the active script option as shown:

Notice that not only can I view all the files in the same directory but also see my commit options since I have tortoise Hg installed:

NOTE : I have not yet managed to get debugging working with pyscripter .... stop reading here. For debugging with PyDev check this out :)
If you want to simply debug your application with pyscripter you can add the following folder to your PYTHONPATH environment variable "C:\Program Files\Google\google_appengine". The contents of this folder are shown:

You also need to add a pythonpath entry for select folders in"C:\Program Files\Google\google_appengine\lib"
The contents of this folder in my case are shown:

so the complete PYTHONPATH setting is : "C:\Program Files\Google\google_appengine;C:\Program Files\Google\google_appengine\lib\antlr3;C:\Program Files\Google\google_appengine\lib\django_0_96;C:\Program Files\Google\google_appengine\lib\fancy_urllib;C:\Program Files\Google\google_appengine\lib\graphy;C:\Program Files\Google\google_appengine\lib\ipaddr;C:\Program Files\Google\google_appengine\lib\simplejson;C:\Program Files\Google\google_appengine\lib\webob;C:\Program Files\Google\google_appengine\lib\yaml\lib"

Note my python path settings:
After you have set the pythonpath you MUST RESTART GAE Launcher. Now click edit and run
You can see a successful break point below:
But this is just a script running outside a web server. You can launch the Google App Engine web server INSIDE of pyscripter to get the debugging goodness of a running web application as follows.

Notice the commandline for the python started by launcher using process explorer :
In my case it was : "C:\PYTHON\App\pythonw.exe "C:\Program Files\Google\google_appengine\" --admin_console_server= --port=8080 D:\CODETEST\npitracker\npitracker"

Now you are going to configure pyscripter to run the file "C:\Program Files\Google\google_appengine\" for us. 
Open this file in pyscripter and select run -- Command Line parameters.
Set the command parameters to your project as shown:

In my case I kept the command line parameters as : "--admin_console_server= --port=8080 D:\CODETEST\npitracker\npitracker"

Now setup a breakpoint anywhere cool in the project as shown:

Switch back to "" and run. Browse to your website (http://localhost:8080) in my case and enjoy the debugging goodness.

Note: (GAE version 1.5.0)

PS: for python path option in launcher "C:\PYTHON\App\" did not work. If I left it at that and run a project the browse button does not become enabled in the launcher and a busy indicator is shown next to the project.


Thursday, June 16, 2011

How to be an awesome intern

Don't you just love the stackoverflow network? I do :)
This post really caught my eye :

Basically I have seen interns become a burden in programming teams more so than in other fields. This is because a deep knowledge of how to write functioning softwares is something not taught in schools. It is something that only comes with self effort and internet research / books. So the intern's / new hires have a tendency to ask the senior team members questions at every small step of the way. And I feel that joels post hits right on home on how a new team member should actually behave : Quote:

Be respectful of your mentor's time by keeping a list of questions and asking them in batches, to the extent possible. Don't actually interrupt your mentor until you literally cannot make any forward progress without help.

A lot of times you'll learn a lot by struggling to find the answer yourself, even in cases where your mentor can teach you something in 10 seconds. For example, if you want to know where something is in the code, you can ask them (10 seconds), or you can spend four hours studying the code and trying to figure it out yourself. The advantage of the "four hour" option is that you will actually be learning 200 new things about the code, all of which will help you later on. Struggling to find your own answers can be a waste of time, but it can also be a way to learn a big complicated code base.

Needless to say if it's a programming question that doesn't concern your company's own proprietary code, you should try to figure it out yourself using the internet.

The section in bold is what I think is really important. Feel free to use stackoverflow for this. No team has enough resources (and perhaps quality) as stackoverflow :).

Other than this teams should have regular meetings to discuss stuff so that knowledge can be shared. Beyond that the internet and books (lots and lots of books ... start with the programming language essentials e.g c# essential / C# in depth and build up to the technology e.g. wpf / silverlight / wcf) are your best friend. 

Sunday, June 12, 2011

Flex game programming

I have been writing line of business applications for so long that I am beginning to miss the joy of game programming. So I am indulging myself in actionscript / flex / flash / illustrator.

There is a LOT of help out there for writing games with flex.
e.g. :

But before I go there I am gathering expertise in ActionScript. ActionScript 3 is really easy to learn if you know C# 4.0 deeply. The reason is that there are very few new concepts to learn. I am currently busy writing a document "ActionScript 3.0 for C# 4.0 programmers". I will make it public once it is at a reasonalbly useable state. 

Till then, Enjoy!

Friday, June 10, 2011

flex vs silverlight : States model

The Parts / States model is common between silverlight and flex 4+.
But I feel that silverlight with its VisualStateGroup + VisualState provides a better experience than flex 4 with its state only model. E.g check out the states for a toggle button in flex :


Flash is still a fantastic programming opportunity

I have been a very strong advocate of silverlight (for my love of C#) over all other things since the past three years.

I have dabbled with flex / flash before. Infact I even wrote a python script that writes your service access code (in pyamf) on the flex end for you, given your django web service.

I now feel that I have stayed away from the flash / flex ecosystem for too long. A number of facts have convinced me that perhaps I need to jump back into the sea of adobe. These are :

In short, it is all about feeling that I am missing fantastic monetization possibilities by limiting myself to silverlight. 

Monday, June 6, 2011

If null give default value

All this time I did not know about this lovely operator (null coalescing operator) : ??
It does one simple thing, If the value is null use the default value given as rvalue to the operator

Thursday, June 2, 2011

Ensure all caps in silverlight as a part of design process

Look at the picture of the silverlight cosmopolitan theme :

Notice how all the labels are ALLCAPS. It is probably done by typing with the CAPS lock on but there is  a blend behavior available that can do it for you on the content presenter.
Check out the sample + code for this behavior here :