Lesson 3: Control Flow Statements – Loops and Conditionals

This lesson is about Control flow statements – control flow statements are Loops and Conditional Statements. They are the basic building blocks for writing any complicated logic in a program. Here is the Code file associated with the lesson. To download the file, right click on the link below and select “Save As” and save it to disk. Just clicking the link opens it in browser and that may not look right depending on which browser you are using.

22-control_flow

Lesson 2: Javascript – Syntax and basics

Here is the second lesson, syntax and basics. We go over how to run JavaScript code using Node and learn about data types.

Here are the JavaScript files used in this lesson:

10-syntax_and_basics

20-data_types

21-truthy-and-falsy

Follow along the lesson in this video using the files above.

A course on Win8 app development with HTML5 and Javascript – Lesson 1

After a long time thinking, preparing and finally getting to recording, I am pleased to announce that I am starting a course on Windows 8 app development with HTML5 and JavaScript. Today, I am posting the Introduction to the course Video.

To follow along this course, you would need at least the following tools:

  1. Windows 8
  2. Visual Studio (You can get the Express version for Windows 8 applications for free from Microsoft’s website. Click Here Make sure to download the “Visual Studio Express 2012 for Windows 8”)
  3. Node.js. Download and install it from its website

Learning Expression Blend – Finally!

I have been developing Windows Phone apps for a while but like most developers, I had a bit of an block towards tools that require fiddling around buttons to change the UI. Windows Phone is all about XAML + C#. I know C# pretty well but XAML has always been a bit of mystery to me. I used to see UI built using XAML and would go WOW! but when I would look at the actual XAML code, I would give up the ghost – hint, XAML code is quite complicated. I have always known that Blend for Visual Studio exists to develop Windows Phone + Windows 8 apps exists, but I never understood it well enough to use it effectively.

Well, happy to say, finally, after attending a Windows 8 app building workshop in C#, I grit my teeth and decided to learn Blend, once and for all. To this effect, I researched books on Amazon and got the Pro Expression Blend 4 book by Andrew Troelsen.  After I got the book, I sat down on Friday night and started reading. The book is about 350 pages, so it is not too bad. The fact that it is pretty easy going i.e. mostly filled with screenshots makes it go even faster. Suffice to say, by the end of day Saturday, I was jumping up and down and running every 10 minutes to my wife telling her, Oh, did you know, Expression Blend can do X? Then I got busy with work and finally, today I got the time to finish one of the last chapters that I wanted to read very desperately (Chapter 5 – Styles, Templates and UserControls.) I can finally say with confidence that I understand what Blend is all about. I finally understand how powerful it is and what a dummy I have been trying to put learning this tool off. This chapter (chapter 5) is about 2/3rd of the way in, at about page 200, so all I had to read was about 200 pages.

Did I mention, I had to read just 200 pages? Woohoo! That is about the limit of a book I want to read contiguously. More than that and I will treat a book like a reference – looking at only a section here and a section there. This book passes the litmus test of being about 200 pages just like Javascript, the Good parts by Douglas Crockford.

After reading this book I realized that as a developer, not knowing Blend when developing C# apps for Windows Phone or Windows 8 is like having one of your arms tied behind your back while you code. Really, just like the author claimed in the introduction, all the C# code in the entire book is probably under 100 lines. Seriously, I had no idea you could do so much UI fluff + ton of event handling using nothing but just Blend (actually XAML, but whatever.)

If you have been turned off by Blend, well I can recommend this book without any hesitation. There might be other books better than this one, but this one is pretty damn good. The steps are very explicit, very clear with screenshots on where a certain menu is located or what the output should look like. And, the book does not just take one example and keep building on it  like many technical books do. Rather, each sample is in a different project, so if you get stuck in one project, you can start afresh in another. This is brilliant and just the way I like. I suspect, this is going to be on my desk, instead of shelf for quick lookup and re-read for a while.

Windows 8: Finding the details of the current system (including processor architecture) from Win8 app

Someone asked me today how to find the details  of what system/processor architecture the metro app is running on. Searching on the Internet initially did not provide much help, but some deep dive finally did yield some results:

  1. On StackOverflow, someone pointed out that the C function GetNativeSystemInfo would provide all that information. I cannot find a WinRT Javascript/C# projection for this. However, if you do decide to go along this route, you may have to submit architecture specific versions of your app to the store because of the C library dependency. If instead you decide to write your WinRT component in C# and use PInvoke to invoke the function, you can probably do a purely managed version.
  2. A blog post by iLiveDigitally points out a much simpler way of doing this. See the code sample below on how. This approach, I believe, will work only if you upload the architecture specific versions of your app to the store. Purely managed code and Javascript apps are by default architecture neutral, so you when uploading to the store, you will have to deselect the neutral architecture and upload three binaries for arm/x86 and x64. The store automatically downloads the right version of the app for your architecture on your device, so this should work.
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    switch (Windows.ApplicationModel.Package.current.id.architecture) {
    case Windows.System.ProcessorArchitecture.arm:
    // do arm stuff here
    case Windows.System.ProcessorArchitecture.x86:
    // do x86 stuff here
    case Windows.System.ProcessorArchitecture.x64:
    // do x64 stuff here
    case Windows.System.ProcessorArchitecture.neutral:
    // do neutral stuff here
    }

Windows 8: Sharing a HTML5 canvas as an image

Recently, I was working on a Win8 Javascript app where I drawing something on an HTML canvas. One of the requirements was that the user should be able to share the contents of the canvas as an image. The toDataURL function in HTML5 easily converts the content of the canvas to an image, so I thought how hard could it be to share this image. Boy, was I wrong. The toDataURL function returns a base64 encoded image, which needs to be decoded and then sent through the share contract. Here is how an encoded PNG image returned from toDataURL looks like:

1
"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAyAA..."

If you want to save this image to a file, you will need to base64 decode the image. The image here is the part that is present after you strip out the “data:image/png;base64,” part. Once you have base64 decoded the image, you have two ways of sharing this image:

  1. You can save the data as bytes inside a file. Name the file with a PNG extension and then later share that file.
  2. Or you could try to share the image buffer across directly. I went through this route because I reasoned, why would I want to save the file to disk and read it back to memory, when I already have it in memory beforehand. In my smugness, I thought I could just manipulate the buffer to be a stream and then point the resource map to the stream.

Option 1 worked pretty well so I was quite confident that I will get option two working in 20 minutes tops. It… well, it took 0ver a month of trying this and that and asking around before I found the solution. And without further ado, I am presenting it here.

In the ready handler of your page, register the share handler:

1
2
var dataTransferManager = Windows.ApplicationModel.DataTransfer.DataTransferManager.getForCurrentView();
dataTransferManager.addEventListener("datarequested", dataRequested);

Here is the share event handler:

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
    function dataRequested(e) {
        var request = e.request;

        var dataPackage = new Windows.ApplicationModel.DataTransfer.DataPackage();
        dataPackage.properties.title = "title";
        dataPackage.properties.description = "This is description";
        var deferral = request.getDeferral();

        // create an html fragment
        var safeHtml = Windows.ApplicationModel.DataTransfer.HtmlFormatHelper.createHtmlFormat("<div><img src='shareImage.png' /></div>");

        // You can get a HTML5 canvas as a png image by calling toDataURL("image/png"). The string you get back looks like the following
        // "data:image/png;base64,iVBORw0K..."
        // Once you have parsed out the "data:image/png;base64," part, what is left is the actual png image in base64 encoded form. which can be used
        // as shown below.

       
        var imgData = Windows.Security.Cryptography.CryptographicBuffer.decodeFromBase64String("iVBORw0K... - Replace this with a real base64 image string");

        // You can uncomment this line (and comment the above) to see a whole flow of converting a canvas to an image.
        //var imgData = Windows.Security.Cryptography.CryptographicBuffer.decodeFromBase64String(getImageDataFromCanvas());

        var memoryStream = new Windows.Storage.Streams.InMemoryRandomAccessStream();
        var dataWriter = new Windows.Storage.Streams.DataWriter(memoryStream);
        dataWriter.writeBuffer(imgData);

        dataWriter.storeAsync().done(function () {
            dataWriter.flushAsync().done(function () {
                var imgStream = dataWriter.detachStream();
                imgStream.seek(0);
                var streamReference = Windows.Storage.Streams.RandomAccessStreamReference.createFromStream(imgStream);

                dataPackage.resourceMap["shareImage.png"] = streamReference;

                dataPackage.setHtmlFormat(safeHtml);
                request.data = dataPackage;
                deferral.complete();
            });
        });
    }

The above should get a base64 encoded image shared across. You can stop here if all you were looking for was to share an image buffer across. However, if you further want to look into how to to get a canvas element from the page and convert it to image, then read on.

Firstly, add the following canvas element to your html page.

1
<canvas id="MyCanvas" width="400" height="400" >This browser or document mode doesn't support canvas</canvas>

Then add the following extra code to your javascript file. Additionally, uncomment the line that contains getImageDataFromCanvas in the share event handler. Make sure to comment the line above it that sets the imgData variable directly from the base64 string.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
    // converting canvas to image
    function getImageDataFromCanvas() {
        var canvas1 = document.getElementById("MyCanvas");
        var myImage = canvas1.toDataURL("image/png");      // Get the data as an image.
        return myImage.substr(22);
    }

    function drawOnCanvas() {
        // Create some graphics.    
        var canvas = document.getElementById("MyCanvas");
        if (canvas.getContext) {
            var ctx = canvas.getContext("2d");
            ctx.fillStyle = "white";
            ctx.beginPath();
            ctx.rect(5, 5, 300, 250);
            ctx.fill();
            ctx.stroke();
            ctx.arc(150, 150, 100, 0, Math.PI, false);
            ctx.stroke();
        }
    }

About people

People on the side of The People always ended up disappointed, in any case. They found that The People tended not to be grateful or appreciative or forward thinking or obedient. The People tended to be small-minded and conservative and not very clever and were even distrustful of cleverness. And so, the children of the revolution were faced with the age-old problem: It wasn’t that you had the wrong kind of government, which was obvious, but that you had the wrong kind of people. As soon as you saw people as things to be measured, they didn’t measure up.

Terry Pratchett from Night Watch.

Craftsmen

“He wanted to say, oh, how he wanted to say:

Craftsmen, D’you know what that means? It means men with some pride, who get fed up and leave when they’re told to do skimpy work in a rush, no matter what you pay them. So, I am employing people as “Craftsmen” now who’re barely fit to sweep out a workshop. But you don’t care, because if they don’t polish a chair with their arse all day you think a man who’s done a seven-year apprenticeship is the same as some twerp who can’t be trusted to hold a hammer by the right end.

He didn’t say this aloud, because although an elderly man probably has a lot less future than a man of twenty, he’s far more careful about it…”

– Going Postal (Terry Pratchett)

Picard and the Q

I was watching “Tapestry”, one of my favorite episodes on Star Trek: The Next Generation. In this episode, Captain Picard lay dying because of a condition he acquired when he got into a fight when he was young and rash. An omnipotent being called Q talks to Picard in this near delirium state and proposes to turn the clock back and give Picard a chance to correct things. Picard takes up the offer and by the end realizes that he would much rather have made the same choices and died than change anything in his past.

This nicely ties in with this quote from Terry Pratchett’s “Men at Arms”:

“That was always the dream, wasn’t it?  ‘I wish I’d known then what I know now’?  But when you got older you found out that you now wasn’t the you then.  You then was a twerp.  You then was what you had to be to start out on the rocky road of becoming you now, and one of the rocky patches on that road was being a twerp. A much better dream, one that’d ensure sounder sleep, was not to know now what you didn’t know then.”

On what we are… and how we remain what we are

“It was said later that he came under bad influence at this stage. But the secret of the history of Edward d’Eath was that he came under no outside influences at all, unless you count all those dead kings. He just came under the influence of himself. That’s where people get it wrong. Individuals aren’t naturally paid-up members of the human race, except biologically. They need to be bounced around by the Brownian motion of society, which is a mechanism by which human beings constantly remind one another that they are … well … human beings. He was also spiraling inward, as tends to happen in cases like this.”

— Men At Arms (Terry Pratchett)