<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/rss2full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.feedburner.com/~d/styles/itemcontent.css"?><rss xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" version="0.91"><channel><title>Nerdworks Blogorama - Nerdspeak</title><link>http://blogorama.nerdworks.in/</link><description>Nerdworks Blogorama is a website that let's the author spew forth random pieces of mostly useless information at will.</description><language>en-us</language><managingEditor>avranju@gmail.com</managingEditor><webMaster>avranju@gmail.com</webMaster><image><title>Nerdworks Blogorama - Nerdspeak</title><url>http://blogorama.nerdworks.in/images/nw_logo.png</url><link>http://blogorama.nerdworks.in/</link><description>Nerdworks Blogorama is a website that let's the author spew forth random pieces of mostly useless information at will.</description></image><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/xml" href="http://feeds.feedburner.com/nerdspeak-rss" /><feedburner:info uri="nerdspeak-rss" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com/" /><item><title>Debugging existing Windows Store apps</title><link>http://feedproxy.google.com/~r/nerdspeak-rss/~3/xjW2P6_tYLE/entry-DebuggingexistingWindowsStorea.aspx</link><description>&lt;p&gt;Did you know that you can debug pretty much any installed store app on your machine?&amp;#160; Let’s say you want to know exactly why is it that the Windows Mail app acts funny sometimes.&amp;#160; Here’s what you’d do:&lt;/p&gt;  &lt;ol&gt;   &lt;li&gt;     &lt;p&gt;Go to the modern desktop and type “Debuggable Package Manager” and launch it.&lt;/p&gt;      &lt;blockquote&gt;       &lt;p&gt;&lt;a href="http://blogorama.nerdworks.in/images/_img3.jpg"&gt;&lt;img title="clip_image001" style="border-left-width: 0px; border-right-width: 0px; background-image: none; border-bottom-width: 0px; padding-top: 0px; padding-left: 0px; display: inline; padding-right: 0px; border-top-width: 0px" border="0" alt="clip_image001" src="http://blogorama.nerdworks.in/images/_img4.jpg" width="521" height="127" /&gt;&lt;/a&gt;&lt;/p&gt;     &lt;/blockquote&gt;      &lt;p&gt;This opens up a powershell window.&lt;/p&gt;   &lt;/li&gt;    &lt;li&gt;     &lt;p&gt;Run &lt;b&gt;Get-AppxPackage&lt;/b&gt; to list the packages installed and use &lt;b&gt;Where-Object&lt;/b&gt; to filter for what you’re looking for. Since were interested in the mail app we run this:&lt;/p&gt;      &lt;blockquote&gt;       &lt;pre class="prettyprint"&gt;Get-AppxPackage | Where-Object PackageFullName -like &amp;quot;*commu*&amp;quot;&lt;/pre&gt;
    &lt;/blockquote&gt;
  &lt;/li&gt;

  &lt;li&gt;
    &lt;p&gt;Note the value of the “PackageFullName” property and enable debugging by running this:&lt;/p&gt;

    &lt;blockquote&gt;
      &lt;pre class="prettyprint"&gt;Enable-AppxDebug microsoft.windowscommunicationsapps_17.0.1114.318_x64__8wekyb3d8bbwe&lt;/pre&gt;
    &lt;/blockquote&gt;
  &lt;/li&gt;

  &lt;li&gt;
    &lt;p&gt;Now launch the app.&amp;#160; Then launch Visual Studio, hit &lt;b&gt;Ctrl+Alt+P&lt;/b&gt; and select the instance of &lt;b&gt;WWAHost.exe&lt;/b&gt; which looks like the app you’re interested in.&lt;/p&gt;

    &lt;blockquote&gt;
      &lt;p&gt;&lt;a href="http://blogorama.nerdworks.in/images/_img31.png"&gt;&lt;img title="image" style="border-left-width: 0px; border-right-width: 0px; background-image: none; border-bottom-width: 0px; padding-top: 0px; padding-left: 0px; display: inline; padding-right: 0px; border-top-width: 0px" border="0" alt="image" src="http://blogorama.nerdworks.in/images/_img32.png" width="652" height="100" /&gt;&lt;/a&gt;&lt;/p&gt;
    &lt;/blockquote&gt;
  &lt;/li&gt;

  &lt;li&gt;
    &lt;p&gt;Debug away!&lt;/p&gt;

    &lt;blockquote&gt;
      &lt;p&gt;&lt;a href="http://blogorama.nerdworks.in/images/_img35.png"&gt;&lt;img title="image" style="border-top: 0px; border-right: 0px; background-image: none; border-bottom: 0px; padding-top: 0px; padding-left: 0px; border-left: 0px; display: inline; padding-right: 0px" border="0" alt="image" src="http://blogorama.nerdworks.in/images/_img36.png" width="828" height="496" /&gt;&lt;/a&gt;&lt;/p&gt;
    &lt;/blockquote&gt;
  &lt;/li&gt;
&lt;/ol&gt;&lt;img src="http://feeds.feedburner.com/~r/nerdspeak-rss/~4/xjW2P6_tYLE" height="1" width="1"/&gt;</description><pubDate>Thu, 23 May 2013 12:59:02 GMT</pubDate><feedburner:origLink>http://blogorama.nerdworks.in/entry-DebuggingexistingWindowsStorea.aspx</feedburner:origLink></item><item><title>Screen scraping with your browser’s JavaScript console</title><link>http://feedproxy.google.com/~r/nerdspeak-rss/~3/n86b8yT4J10/entry-Screenscrapingwithyourbrowsers.aspx</link><description>&lt;p&gt;I needed to experiment a bit with &lt;a href="http://www.microsoft.com/en-us/download/details.aspx?id=36804&amp;amp;WT.mc_id=rss_alldownloads_all"&gt;language packs for IE 10&lt;/a&gt; the other day and that involved downloading and installing all the available language packs. Unfortunately I couldn’t find a single convenient file for download that’d install everything. The language packs were available as separate downloads for each supported language. Like this:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;a href="http://blogorama.nerdworks.in/images/_img25.png"&gt;&lt;img title="image" style="border-left-width: 0px; border-right-width: 0px; background-image: none; border-bottom-width: 0px; padding-top: 0px; padding-left: 0px; display: inline; padding-right: 0px; border-top-width: 0px" border="0" alt="image" src="http://blogorama.nerdworks.in/images/_img26.png" width="488" height="188" /&gt;&lt;/a&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;This was a problem as I was in no mood to download each file individually and there were 100s of “download” buttons there. I figured I’d see if I can screen scrape the links from the DOM of this page and then write a little script to download all of them in one go. So I fired up an instance of IE and hit F12 to launch the developer tools and used the “Select element by click” button to quickly navigate to the markup associated with a “download” button.&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;a href="http://blogorama.nerdworks.in/images/_img1.gif"&gt;&lt;img title="select-element" style="display: inline" alt="select-element" src="http://blogorama.nerdworks.in/images/_img2.gif" width="553" height="521" /&gt;&lt;/a&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;As you can tell, all the download buttons are basically anchor tags and the &lt;i&gt;href&lt;/i&gt; attribute points to the MSU file for that particular language. Also, you’ll note that each such anchor tag has a class called “download” applied on it. So I should be able to fetch all the links by simply iterating through all anchor tags which have the “download” class applied on them. I switched to the “Console” tab in the developer tools window and ran the following script:&lt;/p&gt;  &lt;blockquote&gt;   &lt;pre class="prettyprint"&gt;document.querySelectorAll(&amp;quot;a.download&amp;quot;)&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;And sure enough this produced a list of all the anchor tags I was interested in. I needed the URL however and not the DOM elements themselves. So I ran this next:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="prettyprint"&gt;Array.prototype.forEach.call(
    document.querySelectorAll(&amp;quot;a.download&amp;quot;),
    function (a) {
        console.log(a.href);
    });&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;This produced a list of links such as this (snipped since there are quite a lot of them):&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="prettyprint"&gt;http://download.microsoft.com/download/D/9/A/.../IE10-Windows6.1-LanguagePack-x64-zh-tw.msu 
http://download.microsoft.com/download/D/9/A/.../IE10-Windows6.1-LanguagePack-x64-zu-za.msu 
http://download.microsoft.com/download/D/9/A/.../IE10-Windows6.1-LanguagePack-x86-af-za.msu 
http://download.microsoft.com/download/D/9/A/.../IE10-Windows6.1-LanguagePack-x86-am-et.msu&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;If you’re wondering why I had to iterate through each element in the list of nodes returned by &lt;i&gt;querySelectorAll&lt;/i&gt; via &lt;i&gt;Array.prototype.forEach.call&lt;/i&gt; then that’s because what &lt;i&gt;querySelectorAll&lt;/i&gt; returns isn’t a JavaScript array object, i.e., it doesn’t inherit from &lt;i&gt;Array.prototype&lt;/i&gt;. It is instead a &lt;i&gt;NodeList&lt;/i&gt; object which looks a lot like an array! It has numeric properties starting from 0 to N-1 where N is the number of elements returned and it has a &lt;i&gt;length&lt;/i&gt; property as well which is equal to N. It turns out that all the &lt;i&gt;Array&lt;/i&gt; methods are perfectly capable of dealing with such “array like” objects just as well as genuine, certified JavaScript arrays. Here’s an example of what I am talking about:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="prettyprint"&gt;var notArray = {
    0: &amp;quot;This &amp;quot;,
    1: &amp;quot;is &amp;quot;,
    2: &amp;quot;not &amp;quot;,
    3: &amp;quot;really &amp;quot;,
    4: &amp;quot;an &amp;quot;,
    5: &amp;quot;array.&amp;quot;,
    length: 6
};

console.log(Array.prototype.reduce.call(
    notArray,
    function (previous, current) {
        return previous + current;
    },
    &amp;quot;&amp;quot;));&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;This snippet prints the following text to the console:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="prettyprint"&gt;This is not really an array.&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;If you take another look at the list of URLs our script printed to the console, you’ll notice from the file names that this list includes both x86 files and x64 files. I wanted only x64 files. So, I next changed the script to this:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="prettyprint"&gt;Array.prototype.forEach.call(
    document.querySelectorAll(&amp;quot;a.download[href*=x64]&amp;quot;),
    function (a) {
        console.log(a.href);
    });&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;The selector syntax above looks for all anchor tags in the DOM which has a class called “download” applied where the &lt;i&gt;href&lt;/i&gt; attribute’s value contains the string “x64”. I had first implemented this via another call to &lt;i&gt;Array.prototype.filter&lt;/i&gt; before learning that CSS3 selector syntax already provides for it! Pretty nifty no? That’s pretty much it. I wanted to run a download script for fetching all the files so I slightly modified the script to produce &lt;i&gt;&lt;a href="http://www.gnu.org/software/wget/"&gt;wget&lt;/a&gt;&lt;/i&gt; calls like so:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="prettyprint"&gt;Array.prototype.forEach.call(
    document.querySelectorAll(&amp;quot;a.download[href*=x64]&amp;quot;),
    function (a) {
        console.log(&amp;quot;wget &amp;quot; + a.href);
    });&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;And plonked the output into a batch file and ran it. Mission accomplished!&lt;/p&gt;

&lt;p&gt;Now, it turned out that this particular page in question includes the jQuery library as well as can be seen when you pull up the files list from the “Script” tab in the developer console.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;a href="http://blogorama.nerdworks.in/images/_img27.png"&gt;&lt;img title="image" style="border-left-width: 0px; border-right-width: 0px; background-image: none; border-bottom-width: 0px; padding-top: 0px; padding-left: 0px; display: inline; padding-right: 0px; border-top-width: 0px" border="0" alt="image" src="http://blogorama.nerdworks.in/images/_img28.png" width="355" height="172" /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;I could have done the same thing I did above using a slightly terser syntax using jQuery as well. Here’s how:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="prettyprint"&gt;$(&amp;quot;a.download[href*=x64]&amp;quot;).each(function () {
    console.log(&amp;quot;wget &amp;quot; + this.href);
});&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;Not having to resort to the &lt;i&gt;Array.prototype&lt;/i&gt; weirdness does make the code a lot cleaner doesn’t it?&lt;/p&gt;&lt;img src="http://feeds.feedburner.com/~r/nerdspeak-rss/~4/n86b8yT4J10" height="1" width="1"/&gt;</description><pubDate>Sun, 05 May 2013 11:04:43 GMT</pubDate><feedburner:origLink>http://blogorama.nerdworks.in/entry-Screenscrapingwithyourbrowsers.aspx</feedburner:origLink></item><item><title>Building an Instagram clone – Part 2</title><link>http://feedproxy.google.com/~r/nerdspeak-rss/~3/0MSPNXj_Jhc/entry-BuildinganInstagramclonePart2.aspx</link><description>&lt;p&gt;In &lt;a href="http://blogorama.nerdworks.in/entry-BuildinganInstagramclonePart1.aspx"&gt;part 1&lt;/a&gt; we took a look at some of the UI layout implementation details of the &lt;a href="http://blogorama.nerdworks.in/arbit/InstaFuzz/" target="_blank"&gt;InstaFuzz&lt;/a&gt; app.&amp;#160; You can get the source code for the app from &lt;a href="http://sdrv.ms/14B672O" target="_blank"&gt;here&lt;/a&gt; if you wish to run it locally.&amp;#160; In this installment we’ll take a look at some of the other bits such as how drag/drop, File API, Canvas and Web Workers are used.&lt;/p&gt;  &lt;h3&gt;&lt;a name="_Toc353928284"&gt;Drag/Drop&lt;/a&gt;&lt;/h3&gt;  &lt;p&gt;One of the things that &lt;i&gt;InstaFuzz&lt;/i&gt; supports is the ability to drag and drop image files directly on to the big blackish/blue box. Support for this is enabled by handling the “drop” event on the CANVAS element. When a file is dropped onto an HTML element the browser fires the “drop” event on that element and passes in a &lt;a href="http://msdn.microsoft.com/library/ie/ms535861.aspx"&gt;&lt;i&gt;dataTransfer&lt;/i&gt;&lt;/a&gt; object which contains a &lt;a href="http://msdn.microsoft.com/en-US/library/ie/hh772716.aspx"&gt;&lt;i&gt;files&lt;/i&gt;&lt;/a&gt; property that contains a reference to the list of files that were dropped. Here’s how this is handled in the app (“picture” is the ID of the CANVAS element on the page):&lt;/p&gt;  &lt;blockquote&gt;   &lt;pre class="prettyprint"&gt;var pic = $(&amp;quot;#picture&amp;quot;);
pic.bind(&amp;quot;drop&amp;quot;, function (e) {
    suppressEvent(e);
    var files = e.originalEvent.dataTransfer.files;
    // more code here to open the file
});
pic.bind(&amp;quot;dragover&amp;quot;, suppressEvent).bind(&amp;quot;dragenter&amp;quot;, suppressEvent);
function suppressEvent(e) {
    e.stopPropagation();
    e.preventDefault();
}&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;The &lt;i&gt;files&lt;/i&gt; property is a collection of &lt;a href="http://msdn.microsoft.com/en-US/library/ie/hh772305.aspx"&gt;&lt;i&gt;File&lt;/i&gt;&lt;/a&gt; objects that can then subsequently be used with the File API to access the file contents (covered in the next section). We also handle the &lt;i&gt;dragover&lt;/i&gt; and &lt;i&gt;dragenter&lt;/i&gt; events and basically prevent those events from propagating to the browser thereby preventing the browser from handling the file drop. IE for instance might unload the current page and attempt to open the file directly otherwise.&lt;/p&gt;

&lt;h3&gt;&lt;a name="_Toc353928285"&gt;File API&lt;/a&gt;&lt;/h3&gt;

&lt;p&gt;Once the file has been dropped, the app attempts to open the image and render it in the canvas. It does this by using the &lt;a href="http://msdn.microsoft.com/en-us/library/ie/hh673542(v=vs.85).aspx"&gt;File API&lt;/a&gt;. The File API is a W3C specification that allows web apps to programmatically access files from the local file system in a secure fashion. In &lt;i&gt;InstaFuzz&lt;/i&gt; we use the &lt;a href="http://msdn.microsoft.com/en-us/library/ie/hh772310(v=vs.85).aspx"&gt;&lt;i&gt;FileReader&lt;/i&gt;&lt;/a&gt; object to read the file contents as a &lt;a href="http://msdn.microsoft.com/en-us/library/ie/cc848897.aspx"&gt;data URL&lt;/a&gt; string like so using the &lt;a href="http://msdn.microsoft.com/en-us/library/ie/hh772313(v=vs.85).aspx"&gt;&lt;i&gt;readAsDataURL&lt;/i&gt;&lt;/a&gt; method:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="prettyprint"&gt;var reader = new FileReader();
reader.onloadend = function (e2) {
    drawImageToCanvas(e2.target.result);
};
reader.readAsDataURL(files[0]);&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;Here, &lt;i&gt;files&lt;/i&gt; is the collection of &lt;i&gt;File&lt;/i&gt; objects retrieved from the function handling the “drop” event on the CANVAS element. Since we are interested only in a single file we simply pick the first file from the collection and ignore the rest if there are any. The actual file contents are loaded asynchronously and once the load completes, the &lt;a href="http://msdn.microsoft.com/en-us/library/ie/hh772337(v=vs.85).aspx"&gt;&lt;i&gt;onloadend&lt;/i&gt;&lt;/a&gt; event is fired where we get the file contents as a data URL which we then subsequently draw on to the canvas.&lt;/p&gt;

&lt;h3&gt;&lt;a name="_Toc353928286"&gt;Rendering the filters&lt;/a&gt;&lt;/h3&gt;

&lt;p&gt;Now the core functionality here is of course the application of the filters. In order to be able to apply the filter to the image we need a way to access the individual pixels from the image. And before we can access the pixels we need to have actually rendered the image on to our canvas. So let’s first take a look at the code that renders the image that the user picked on to the canvas element.&lt;/p&gt;

&lt;h5&gt;&lt;a name="_Toc353928287"&gt;Rendering images on to the canvas&lt;/a&gt;&lt;/h5&gt;
The canvas element supports the rendering of &lt;i&gt;Image&lt;/i&gt; objects via the &lt;a href="http://msdn.microsoft.com/en-us/library/ie/ff975414(v=vs.85).aspx"&gt;&lt;i&gt;drawImage&lt;/i&gt;&lt;/a&gt; method. To load up the image file in an &lt;i&gt;Image&lt;/i&gt; instance, &lt;i&gt;InstaFuzz&lt;/i&gt; uses the following utility routine: 

&lt;blockquote&gt;
  &lt;pre class="prettyprint"&gt;App.Namespace.define(&amp;quot;InstaFuzz.Utils&amp;quot;, {
    loadImage: function (url, complete) {
        var img = new Image();
        img.src = url;
        img.onload = function () {
            complete(img);
        };
    }
});&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;This allows the app to load up image objects from a URL using code such as the following:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="prettyprint"&gt;function drawImageToCanvas(url) {
    InstaFuzz.Utils.loadImage(url, function (img) {
        // save reference to source image
        sourceImage = img;

        mainRenderer.clearCanvas();
        mainRenderer.renderImage(img);

        // load image filter previews
        loadPreviews(img);
    });
}&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;Here, &lt;i&gt;mainRenderer&lt;/i&gt; is an instance created from the &lt;i&gt;FilterRenderer&lt;/i&gt; constructor function defined in &lt;i&gt;filter-renderer.js&lt;/i&gt;. The app uses &lt;i&gt;FilterRenderer&lt;/i&gt; objects to manage canvas elements – both in the preview pane as well as the main canvas element on the right. The &lt;i&gt;renderImage&lt;/i&gt; method on the &lt;i&gt;FilterRenderer&lt;/i&gt; has been defined like so:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="prettyprint"&gt;FilterRenderer.prototype.renderImage = function (img) {
    var imageWidth = img.width;
    var imageHeight = img.height;
    var canvasWidth = this.size.width;
    var canvasHeight = this.size.height;
    var width, height;

    if ((imageWidth / imageHeight) &amp;gt;= (canvasWidth / canvasHeight)) {
        width = canvasWidth;
        height = (imageHeight * canvasWidth / imageWidth);
    } else {
        width = (imageWidth * canvasHeight / imageHeight);
        height = canvasHeight;
    }

    var x = (canvasWidth - width) / 2;
    var y = (canvasHeight - height) / 2;
    this.context.drawImage(img, x, y, width, height);
};&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;That might seem like a lot of code but all it does ultimately is to figure out the best way to render the image in the available screen area considering the aspect ratio of the image. The key piece of code that actually renders the image on the canvas occurs on the last line of the method. The &lt;i&gt;context&lt;/i&gt; member refers to the 2D context acquired from the canvas object by calling its &lt;a href="http://msdn.microsoft.com/en-us/library/ie/ff975238(v=vs.85).aspx"&gt;&lt;i&gt;getContext&lt;/i&gt;&lt;/a&gt; method.&lt;/p&gt;

&lt;h5&gt;&lt;a name="_Toc353928288"&gt;Fetching pixels from the canvas&lt;/a&gt;&lt;/h5&gt;
Now that the image has been rendered we will need access to the individual pixels in order to apply all the different filters that are available. This is easily acquired by calling &lt;a href="http://msdn.microsoft.com/en-us/library/ie/ff975418(v=vs.85).aspx"&gt;&lt;i&gt;getImageData&lt;/i&gt;&lt;/a&gt; on the canvas’s context object. Here’s how &lt;i&gt;InstaFuzz&lt;/i&gt; calls this from &lt;i&gt;instafuzz.js&lt;/i&gt;. 

&lt;blockquote&gt;
  &lt;pre class="prettyprint"&gt;var imageData = renderer.context.getImageData(
    0, 0,
    renderer.size.width,
    renderer.size.height);&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;The object returned by &lt;i&gt;getImageData&lt;/i&gt; provides access to the individual pixels via its &lt;i&gt;data&lt;/i&gt; property which in turn is an array like object that contains a collection of byte values where each value represents the color rendered for a single channel of a single pixel. Each pixel is represented using 4 bytes that specify values for the red, green, blue and alpha channels. It also has a &lt;a href="http://msdn.microsoft.com/en-us/library/ie/ff974921(v=vs.85).aspx"&gt;&lt;i&gt;length&lt;/i&gt;&lt;/a&gt; property that returns the length of the buffer. If you have a 2D co-ordinate you can easily transform that into an index into this array using code such as the following. The color intensity values of each channel ranges from 0 through 255. Here’s the utility function from &lt;i&gt;filters.js&lt;/i&gt; that accepts as input an image data object along with 2D coordinates for the pixel the caller is interested in and returns an object containing the color values:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="prettyprint"&gt;function getPixel(imageData, x, y) {
    var data = imageData.data, index = 0;

    // normalize x and y and compute index
    x = (x &amp;lt; 0) ? (imageData.width + x) : x;
    y = (y &amp;lt; 0) ? (imageData.height + y) : y;
    index = (x + y * imageData.width) * 4;

    return {
        r: data[index],
        g: data[index + 1],
        b: data[index + 2]
    };
}&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;h5&gt;&lt;a name="_Toc353928289"&gt;Applying the filters&lt;/a&gt;&lt;/h5&gt;
Now that we have access to the individual pixels, applying the filter is fairly straightforward. Here, for instance is the function that applies a weighted grayscale filter on the image. It simply picks intensities from the red, green and blue channels and sums them up after applying a multiplication factor on each channel and then assigns the result for all 3 channels. 

&lt;blockquote&gt;
  &lt;pre class="prettyprint"&gt;// &amp;quot;Weighted Grayscale&amp;quot; filter
Filters.addFilter({
    name: &amp;quot;Weighted Grayscale&amp;quot;,
    apply: function (imageData) {
        var w = imageData.width, h = imageData.height;
        var data = imageData.data;
        var index;
        for (var y = 0; y &amp;lt; h; ++y) {
            for (var x = 0; x &amp;lt; w; ++x) {
                index = (x + y * imageData.width) * 4;
                var luminance = parseInt((data[index + 0] * 0.3) +
                                         (data[index + 1] * 0.59) +
                                         (data[index + 2] * 0.11));
                	    data[index + 0] = data[index + 1] =
                    data[index + 2] = luminance;
            }

            Filters.notifyProgress(imageData, x, y, this);
        }

        Filters.notifyProgress(imageData, w, h, this);
    }
});&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;Once the filter has been applied we can have that reflected on the canvas by calling the &lt;a href="http://msdn.microsoft.com/en-us/library/ie/ff975423(v=vs.85).aspx"&gt;&lt;i&gt;putImageData&lt;/i&gt;&lt;/a&gt; method passing in the modified image data object. While the weighted grayscale filter is fairly simple most of the other filters use an image processing technique known as &lt;i&gt;convolution&lt;/i&gt;. The code for all the filters is available in &lt;i&gt;filters.js&lt;/i&gt; and the convolution filters were ported from the C code available &lt;a href="http://lodev.org/cgtutor/filtering.html"&gt;here&lt;/a&gt;.&lt;/p&gt;

&lt;h3&gt;&lt;a name="_Toc353928290"&gt;Web Workers&lt;/a&gt;&lt;/h3&gt;

&lt;p&gt;As you might imagine doing all this number crunching to apply the filters can potentially take a long time to complete. The &lt;i&gt;motion blur&lt;/i&gt; filter for instance uses a 9x9 filter matrix for computing the new value for every single pixel and is in fact the most CPU intensive filter among them all. If we were to do all this computation on the UI thread of the browser then the app would essentially freeze every time a filter was being applied. To provide a responsive user experience the app delegates the core image processing tasks to a background script using the support for W3C &lt;a href="http://msdn.microsoft.com/en-us/library/ie/hh673568(v=vs.85).aspxhttp:/msdn.microsoft.com/en-us/library/ie/hh673568(v=vs.85).aspx"&gt;Web Workers&lt;/a&gt; in modern browsers.&lt;/p&gt;

&lt;p&gt;Web workers allow web applications to have scripts run in a background task that executes in parallel along with the UI thread. Communication between the worker and the UI thread is accomplished by passing messages using the &lt;a href="http://msdn.microsoft.com/library/ie/cc197015.aspx"&gt;&lt;i&gt;postMessage&lt;/i&gt;&lt;/a&gt; API. On both ends (i.e. the UI thread and the worker) this manifests as an event notification that you can handle. You can only pass “data” between workers and the UI thread, i.e., you cannot pass anything that has to do with the user interface – you cannot for instance, pass DOM elements to the worker from the UI thread.&lt;/p&gt;

&lt;p&gt;In &lt;i&gt;InstaFuzz&lt;/i&gt; the worker is implemented in the file &lt;i&gt;filter-worker.js&lt;/i&gt;. All it does in the worker is handle the &lt;a href="http://msdn.microsoft.com/library/ie/cc197057.aspx"&gt;&lt;i&gt;onmessage&lt;/i&gt;&lt;/a&gt; event and apply a filter and then pass the results back via &lt;i&gt;postMessage&lt;/i&gt;. As it turns out, even though we cannot pass DOM elements (which means we cannot just hand a CANVAS element to the worker to have the filter applied) we can in fact pass the image data object as returned by the &lt;i&gt;getImageData&lt;/i&gt; method that we discussed earlier. Here’s the filter processing code from &lt;i&gt;filter-worker.js&lt;/i&gt;:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="prettyprint"&gt;importScripts(&amp;quot;ns.js&amp;quot;, &amp;quot;filters.js&amp;quot;);

var tag = null;
onmessage = function (e) {
    var opt = e.data;
    var imageData = opt.imageData;
    var filter;
    
    tag = opt.tag;
    filter = InstaFuzz.Filters.getFilter(opt.filterKey);

    var start = Date.now();
    filter.apply(imageData);
    var end = Date.now();

    postMessage({
        type: &amp;quot;image&amp;quot;,
        imageData: imageData,
        filterId: filter.id,
        tag: tag,
        timeTaken: end - start
    });
}&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;The first line pulls in some script files that the worker depends on by calling &lt;a href="http://msdn.microsoft.com/library/ie/hh772875.aspx"&gt;&lt;i&gt;importScripts&lt;/i&gt;&lt;/a&gt;. This is similar to including a JavaScript file in a HTML document using the SCRIPT tag. Then we set up a handler for the &lt;i&gt;onmessage&lt;/i&gt; event in response to which we simply apply the filter in question and pass the result back to the UI thread by calling &lt;i&gt;postMessage&lt;/i&gt;. Simple enough!&lt;/p&gt;

&lt;p&gt;The code that initializes the worker is in &lt;i&gt;instafuzz.js&lt;/i&gt; and looks like this:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="prettyprint"&gt;var worker = new Worker(&amp;quot;js/filter-worker.js&amp;quot;);&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;Not much is it? When a message is sent by the worker to the UI thread we handle it by specifying a handler for the &lt;i&gt;onmessage&lt;/i&gt; event on the worker object. Here’s how this is done in &lt;i&gt;InstaFuzz&lt;/i&gt;:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="prettyprint"&gt;worker.onmessage = function (e) {
    var isPreview = e.data.tag;
    switch (e.data.type) {
        case &amp;quot;image&amp;quot;:
            if (isPreview) {
                previewRenderers[e.data.filterId].
                    context.putImageData(
                        e.data.imageData, 0, 0);
            } else {
                mainRenderer.context.putImageData(
                    e.data.imageData, 0, 0);
            }

            break;
        // more code here
    }
};&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;The code should be fairly self-explanatory. It simply picks the image data object sent by the worker and applies it to the relevant canvas’s context object causing the modified image to be rendered on screen. Scheduling a filter for conversion with the worker is equally simple. Here’s the routine that performs this function in &lt;i&gt;InstaFuzz&lt;/i&gt;:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="prettyprint"&gt;function scheduleFilter(filterId,
                        renderer,
                        img, isPreview,
                        resetRender) {
    if (resetRender) {
        renderer.clearCanvas();
        renderer.renderImage(img);
    }

    var imageData = renderer.context.getImageData(
        0, 0,
        renderer.size.width,
        renderer.size.height);

    worker.postMessage({
        imageData: imageData,
        width: imageData.width,
        height: imageData.height,
        filterKey: filterId,
        tag: isPreview
    });
}&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;h3&gt;&lt;a name="_Toc353928291"&gt;In&lt;/a&gt; conclusion&lt;/h3&gt;
We saw that fairly intricate user experiences are possible today with HTML5 technologies such as Canvas, Drag/Drop, File API and Web Workers. Support for all of these technologies is quite good in pretty much all modern browsers. One thing that we did not address here is the question of making the app compatible with older browsers. That, truth be told, is a non-trivial but necessary task that I will hopefully be able to talk about in a future article.&lt;img src="http://feeds.feedburner.com/~r/nerdspeak-rss/~4/0MSPNXj_Jhc" height="1" width="1"/&gt;</description><pubDate>Fri, 19 Apr 2013 09:50:27 GMT</pubDate><feedburner:origLink>http://blogorama.nerdworks.in/entry-BuildinganInstagramclonePart2.aspx</feedburner:origLink></item><item><title>Building an Instagram clone – Part 1</title><link>http://feedproxy.google.com/~r/nerdspeak-rss/~3/YoZY5GFcjXM/entry-BuildinganInstagramclonePart1.aspx</link><description>&lt;h3&gt;Introduction&lt;/h3&gt;  &lt;p&gt;When I started out on this app I was only really just interested in seeing if the web platform had really evolved to a point where an app like the hugely popular &lt;a href="http://instagram.com/"&gt;Instagram&lt;/a&gt; app could be built using just HTML, JavaScript and CSS. As it turns out we can in fact do exactly that. This article walks you through the technologies that make this possible and shows how it is entirely feasible today to build interoperable web applications that provide a great user experience no matter what brand of browser the user is running.&lt;/p&gt;  &lt;p&gt;If you happen to be one of the two or so people who have not heard about &lt;i&gt;Instagram&lt;/i&gt; then you might be pleased to hear that it is a hugely popular photo sharing and social networking service that allows you to take pictures, apply interesting digital filters on them and share them with the world to see. The service got so popular that it was &lt;a href="http://finance.fortune.cnn.com/2012/04/09/breaking-facebook-buying-instagram-for-1-billion/"&gt;acquired by Facebook&lt;/a&gt; for a bag full of cash and stock in April of 2012.&lt;/p&gt;  &lt;p&gt;&lt;a href="http://blogorama.nerdworks.in/arbit/InstaFuzz/"&gt;InstaFuzz&lt;/a&gt; is the name of the app I put together and while I don’t expect to be acquired by Facebook or anybody else for a billion green it does however make the case that an app such as this one can be built using only standards compliant web technologies such as Canvas, File API, Drag/Drop, Web Workers, ES5 and CSS3 and still manage to run well on modern browsers such as Internet Explorer 10, Google Chrome and Firefox.&lt;/p&gt;  &lt;h3&gt;About the app&lt;/h3&gt;  &lt;p&gt;If you’d like to take a look at the app, then here’s where it is hosted at:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;a href="http://blogorama.nerdworks.in/arbit/InstaFuzz/"&gt;http://blogorama.nerdworks.in/arbit/InstaFuzz/&lt;/a&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;You can download the source and run locally from &lt;a href="http://sdrv.ms/14B672O"&gt;here&lt;/a&gt;.&amp;#160; While this is a Visual Studio 2012 project there really isn’t any server code or anything like that.&amp;#160; You can use your favorite editor to look at the source and run it from the file system if you are so inclined.&lt;/p&gt;  &lt;p&gt;As soon as you load it up, you’re presented with a screen that looks like this:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;a href="http://blogorama.nerdworks.in/images/_img1.jpg"&gt;&lt;img title="clip_image002" style="border-left-width: 0px; border-right-width: 0px; background-image: none; border-bottom-width: 0px; padding-top: 0px; padding-left: 0px; margin: 0px; display: inline; padding-right: 0px; border-top-width: 0px" border="0" alt="clip_image002" src="http://blogorama.nerdworks.in/images/_img2.jpg" width="244" height="203" /&gt;&lt;/a&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;The idea is that you can load up a photograph into the app either by clicking on the big red “Add” button on the bottom left hand corner or drag and drop an image file into the blackish/blue area on the right. Once you do that you get something that looks like this:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;a href="http://blogorama.nerdworks.in/images/_img15.png"&gt;&lt;img title="clip_image003" style="border-left-width: 0px; border-right-width: 0px; background-image: none; border-bottom-width: 0px; padding-top: 0px; padding-left: 0px; margin: 0px; display: inline; padding-right: 0px; border-top-width: 0px" border="0" alt="clip_image003" src="http://blogorama.nerdworks.in/images/_img16.png" width="244" height="204" /&gt;&lt;/a&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;You’ll note that a list of digital filters are listed on the left of the screen showing a preview of what the image would look like if you were to apply the said filter. Applying a filter is a simple matter of clicking on one of the filter previews on the left. Here’s what it looks like after applying the “Weighted Grayscale” filter followed by a “Motion Blur”. As you can tell filters are &lt;i&gt;additive&lt;/i&gt; – as you keep clicking on filters, they are applied on top of what was applied earlier:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;a href="http://blogorama.nerdworks.in/images/_img17.png"&gt;&lt;img title="clip_image004" style="border-left-width: 0px; border-right-width: 0px; background-image: none; border-bottom-width: 0px; padding-top: 0px; padding-left: 0px; display: inline; padding-right: 0px; border-top-width: 0px" border="0" alt="clip_image004" src="http://blogorama.nerdworks.in/images/_img18.png" width="244" height="204" /&gt;&lt;/a&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;Let’s next take a look at how the UI layout has been put together.&lt;/p&gt;  &lt;h3&gt;UI Layout&lt;/h3&gt;  &lt;p&gt;The HTML markup is actually so little that I can actually reproduce the contents of the BODY tag in its entirety here (excluding the SCRIPT includes):&lt;/p&gt;  &lt;blockquote&gt;   &lt;pre class="prettyprint"&gt;&amp;lt;header&amp;gt;
    &amp;lt;div id=&amp;quot;title&amp;quot;&amp;gt;InstaFuzz&amp;lt;/div&amp;gt;
&amp;lt;/header&amp;gt;
&amp;lt;section id=&amp;quot;container&amp;quot;&amp;gt;
    &amp;lt;canvas id=&amp;quot;picture&amp;quot; width=&amp;quot;650&amp;quot; height=&amp;quot;565&amp;quot;&amp;gt;&amp;lt;/canvas&amp;gt;
    &amp;lt;div id=&amp;quot;controls&amp;quot;&amp;gt;
        &amp;lt;div id=&amp;quot;filters-list&amp;quot;&amp;gt;&amp;lt;/div&amp;gt;
        &amp;lt;button id=&amp;quot;loadImage&amp;quot;&amp;gt;Add&amp;lt;/button&amp;gt;
        &amp;lt;input type=&amp;quot;file&amp;quot; id=&amp;quot;fileUpload&amp;quot;
               style=&amp;quot;display: none;&amp;quot;
               accept=&amp;quot;image/gif, image/jpeg, image/png&amp;quot; /&amp;gt;
    &amp;lt;/div&amp;gt;
&amp;lt;/section&amp;gt;

&amp;lt;!-- Handlebar template for a filter UI button --&amp;gt;
&amp;lt;script id=&amp;quot;filter-template&amp;quot; type=&amp;quot;text/x-handlebars-template&amp;quot;&amp;gt;
    &amp;lt;div class=&amp;quot;filter-container&amp;quot; data-filter-id=&amp;quot;{{filterId}}&amp;quot;&amp;gt;
        &amp;lt;div class=&amp;quot;filter-name&amp;quot;&amp;gt;{{filterName}}&amp;lt;/div&amp;gt;
        &amp;lt;canvas class=&amp;quot;filter-preview&amp;quot; width=&amp;quot;128&amp;quot; height=&amp;quot;128&amp;quot;&amp;gt;&amp;lt;/canvas&amp;gt;
    &amp;lt;/div&amp;gt;
&amp;lt;/script&amp;gt;&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;There’s nothing much going on here. Pretty much everything should be standard fare. I will however draw attention to the fact that I am using the &lt;a href="http://handlebarsjs.com/"&gt;Handlebars&lt;/a&gt; JavaScript templating system here for rendering the markup for the list of filters on the left of the screen. The template markup is declared in the HTML file (the SCRIPT tag in the snippet shown above) and then used from JavaScript. The template markup is then bound to a JavaScript object that supplies the values for handlebars expressions such as &lt;i&gt;{{filterId}}&lt;/i&gt; and &lt;i&gt;{{filterName}}.&lt;/i&gt; Here’s the relevant piece of JS from the app with a bit of DOM manipulation help from &lt;a href="http://jquery.com/"&gt;jQuery&lt;/a&gt;:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="prettyprint"&gt;var templHtml = $(&amp;quot;#filter-template&amp;quot;).html(),
    template = Handlebars.compile(templHtml),
    filtersList = $(&amp;quot;#filters-list&amp;quot;);
var context = {
    filterName: filter.name,
    filterId: index
};

filtersList.append(template(context));&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;As you can tell from the HTML markup all the filter preview boxes feature a CANVAS tag as does the big box on the right where the final output is rendered. We’ll go into a bit more detail later on in the article as to how canvas technology is used to achieve these effects.&lt;/p&gt;

&lt;p&gt;The app also uses &lt;a href="http://msdn.microsoft.com/en-us/library/ie/ms530757(v=vs.85).aspx"&gt;CSS3 @font-face&lt;/a&gt; fonts to render the text in the header and the “Add” button. The fonts have been taken from the excellent &lt;a href="http://fontsquirrel.com/"&gt;Font Squirrel&lt;/a&gt; site and here’s what the declaration looks like:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="prettyprint"&gt;@font-face {
    font-family: 'TizaRegular';
    src: url('fonts/tiza/tiza-webfont.eot');
    src: url('fonts/tiza/tiza-webfont.eot?#iefix')
           format('embedded-opentype'),
         url('fonts/tiza/tiza-webfont.woff') format('woff'),
         url('fonts/tiza/tiza-webfont.ttf') format('truetype'),
         url('fonts/tiza/tiza-webfont.svg#TizaRegular') format('svg');
    font-weight: normal;
    font-style: normal;
}&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;This directive causes the user agent to embed the font in the page and make it available under the name assigned to the &lt;i&gt;font-family&lt;/i&gt; rule which in this case is “TizaRegular”. After this we can assign this font to any CSS &lt;i&gt;font-family&lt;/i&gt; rule like how we normally do. In &lt;i&gt;InstaFuzz&lt;/i&gt; I use the following rule to assign the font to the header element:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="prettyprint"&gt;font-family: TizaRegular, Cambria, Cochin, Georgia, Times,
   &amp;quot;Times New Roman&amp;quot;, serif;&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;You might also have noticed that there is a subtle shadow being dropped on the page by the container element.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;a href="http://blogorama.nerdworks.in/images/_img19.png"&gt;&lt;img title="clip_image001[4]" style="border-left-width: 0px; border-right-width: 0px; background-image: none; border-bottom-width: 0px; padding-top: 0px; padding-left: 0px; display: inline; padding-right: 0px; border-top-width: 0px" border="0" alt="clip_image001[4]" src="http://blogorama.nerdworks.in/images/_img20.png" width="115" height="178" /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;This is made possible using the &lt;a href="http://msdn.microsoft.com/library/ie/jj127322.aspx"&gt;CSS3 box-shadow&lt;/a&gt; rule and here’s how it’s used in &lt;i&gt;InstaFuzz&lt;/i&gt;.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="prettyprint"&gt;-moz-box-shadow: 1px 0px 4px #000000, -1px -1px 4px #000000;
-webkit-box-shadow: 1px 0px 4px #000000, -1px -1px 4px #000000;
box-shadow: 1px 0px 4px #000000, -1px -1px 4px #000000;&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;This causes the browser to render a shadow around the relevant element. Each comma separated section in the value specifies the following attributes of the shadow:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;
    &lt;p&gt;Horizontal offset&lt;/p&gt;
  &lt;/li&gt;

  &lt;li&gt;
    &lt;p&gt;Vertical offset&lt;/p&gt;
  &lt;/li&gt;

  &lt;li&gt;
    &lt;p&gt;Spread distance – positive values have the effect of softening the shadow&lt;/p&gt;
  &lt;/li&gt;

  &lt;li&gt;
    &lt;p&gt;Shadow color&lt;/p&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;One can specify multiple shadow values separated by comma as in fact has been done above. Note that I’ve also specified the shadow using vendor prefix syntax for Firefox and Chrome/Safari using the &lt;i&gt;moz&lt;/i&gt; and &lt;i&gt;webkit&lt;/i&gt; prefixes. This causes the shadow to continue to work in versions of those browsers where support for this capability was provided using the vendor prefixed version of the rule. Note that the W3C version of the rule – &lt;i&gt;box-shadow&lt;/i&gt; – is specified last. This is done deliberately to ensure that in case the browser supports both the forms then only the W3C behavior is actually applied to the page.&lt;/p&gt;

&lt;p&gt;One often finds that web developers either fail to include vendor prefixed version of a given CSS3 rule for all the browsers that support that rule and/or fail to include the W3C version as well. Often developers just put the &lt;i&gt;webkit&lt;/i&gt; version of the rule ignoring other browsers and the W3C standard version. This causes two problems – [1] poor user experience for users who are using non-webkit browsers and [2] it ends up resulting in webkit becoming a de-facto standard for the web. Ideally we want W3C to be driving the future of the web and not one specific browser implementation. So here are some things to remember when playing with experimental implementations of CSS features:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;
    &lt;p&gt;Use vendor prefixed versions of CSS rules by all means but remember to specify the rule for all supported browsers and not just the one that you happen to be testing the page in (if you’re using &lt;a href="http://www.microsoft.com/visualstudio/eng/products/visual-studio-express-products"&gt;Visual Studio&lt;/a&gt; to edit your CSS then you might be interested in the supremely excellent extension for Visual Studio called &lt;a href="http://visualstudiogallery.msdn.microsoft.com/6ed4c78f-a23e-49ad-b5fd-369af0c2107f"&gt;&lt;i&gt;Web Essentials&lt;/i&gt;&lt;/a&gt; that makes the job of managing vendor prefixes about as simple as it can possibly get).&lt;/p&gt;
  &lt;/li&gt;

  &lt;li&gt;
    &lt;p&gt;Remember to specify the W3C version of the rule as well.&lt;/p&gt;
  &lt;/li&gt;

  &lt;li&gt;
    &lt;p&gt;Remember to order the occurrence of the rules so that the W3C version shows up last. This is to allow clients that support both the vendor prefixed version and the W3C version to use the W3C specified semantics for the rule.&lt;/p&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;That’s all for now.&amp;#160; In the &lt;a href="http://blogorama.nerdworks.in/entry-BuildinganInstagramclonePart2.aspx" target="_blank"&gt;next and final post&lt;/a&gt; in this series we’ll take a look at how the app supports drag/drop of files, the use of File API, how the filters themselves work and how we prevent the UI thread from freezing by delegating the core number crunching work to web workers.&lt;/p&gt;&lt;img src="http://feeds.feedburner.com/~r/nerdspeak-rss/~4/YoZY5GFcjXM" height="1" width="1"/&gt;</description><pubDate>Wed, 17 Apr 2013 17:31:26 GMT</pubDate><feedburner:origLink>http://blogorama.nerdworks.in/entry-BuildinganInstagramclonePart1.aspx</feedburner:origLink></item><item><title>Organizing your JavaScript with WinJS</title><link>http://feedproxy.google.com/~r/nerdspeak-rss/~3/Tqc_WYff9R8/entry-OrganizingyourJavaScriptwithWi.aspx</link><description>&lt;div&gt;   &lt;p&gt;While the JavaScript framework for creating metro style apps is surprisingly flexible, in that it allows you to use pretty much any JavaScript framework that’s already out there, there is actually some really useful functionality available in the &lt;b&gt;&lt;a href="http://bit.ly/KSAfwq" target="_blank"&gt;WinJS&lt;/a&gt;&lt;/b&gt; library that ships out of the box. And since the JavaScript projection for WinRT itself uses this library it might make sense to use this for our own code as well. In this post I cover some basic ways you can organize your JavaScript code using WinJS.&lt;/p&gt;    &lt;h4&gt;Namespaces&lt;/h4&gt;    &lt;p&gt;One common challenge that we tend to encounter with any JavaScript app (whether web or desktop), is the question of being disciplined about introducing symbols into the global namespace. The general guideline is to, well, not do it! Using WinJS it is possible to organize your own classes and functions into well-defined namespaces. Here’s an example:&lt;/p&gt;    &lt;blockquote&gt;     &lt;pre class="prettyprint"&gt;(function () {
    'use strict';

    // export this &amp;quot;enum&amp;quot;
    var ShapeType = Object.freeze({
        None: 0,
        Line: 1,
        Ellipse: 2,
        Rectangle: 3,
        Arc: 4,
        Bezier: 5
    });

    WinJS.Namespace.define(&amp;quot;Acme.Shapes&amp;quot;, {
        ShapeType: ShapeType
    });

})();&lt;/pre&gt;
  &lt;/blockquote&gt;

  &lt;p&gt;What this does is to basically create only one new symbol in the global namespace called “Acme”. All the remaining objects are child properties of this root object – essentially acting like a namespace. The above given code snippet for instance will enable you to access the &lt;b&gt;ShapeType&lt;/b&gt; enumeration from pretty much everywhere else like so:&lt;/p&gt;

  &lt;blockquote&gt;
    &lt;pre class="prettyprint"&gt;var type = Acme.Shapes.ShapeType.Arc;&lt;/pre&gt;
  &lt;/blockquote&gt;

  &lt;p&gt;You can see how easy it is to extend this to define pretty much your entire project - grouping all your code under a single root namespace. We’ll see further examples of how namespaces can be used as we talk about other capabilities that WinJS brings to the table.&lt;/p&gt;

  &lt;h4&gt;Classes&lt;/h4&gt;

  &lt;p&gt;While JavaScript itself is a weakly typed language it is possible to pretend like it isn’t and create and use “classes”. With WinJS you define a class by calling &lt;a href="http://bit.ly/rKtESn"&gt;WinJS.Class.define&lt;/a&gt;. This method accepts 3 parameters: a constructor function, a JavaScript object defining the instance members and another JavaScript object defining the static members. Here’s an example:&lt;/p&gt;

  &lt;blockquote&gt;
    &lt;pre class="prettyprint"&gt;(function () {
    &amp;quot;use strict&amp;quot;;

    // constructor function
    function initShape(type) {
        this.id = Acme.Shapes.Shape.newId(); // calling a static member
        if (type) {
            this.type = type;
        }
    }

    var instanceMembers = {
        id: null,
        type: Acme.Shapes.ShapeType.None,
        draw: function () {
            console.log(&amp;quot;Shape.draw&amp;quot;);
        }
    };

    var staticMembers = {
        // private member
        _counter: 0,
        newId: function () {
            return Acme.Shapes.Shape._counter++;
        }
    };

    var Shape = WinJS.Class.define(initShape, instanceMembers, staticMembers);

    // add to namespace
    WinJS.Namespace.define(&amp;quot;Acme.Shapes&amp;quot;, {
        Shape: Shape
    });
})();&lt;/pre&gt;
  &lt;/blockquote&gt;

  &lt;p&gt;Now you can create and use instances of Shape like so:&lt;/p&gt;

  &lt;blockquote&gt;
    &lt;pre class="prettyprint"&gt;var s = new Acme.Shapes.Shape(); 
s.draw();&lt;/pre&gt;
  &lt;/blockquote&gt;

  &lt;p&gt;The first parameter to &lt;a href="http://bit.ly/rKtESn"&gt;WinJS.Class.define&lt;/a&gt; is a constructor function. This gets invoked whenever a new instance is created and is the place where you write your object initialization code. The second parameter is an object that describes the runtime shape of the object, i.e. what instance members it will contain. The third parameter defines the set of static members that you can access directly from the class without creating an instance. In the snippet above you’ll note that we invoke the static method &lt;b&gt;newId&lt;/b&gt; from &lt;b&gt;Shape&lt;/b&gt;’s constructor.&lt;/p&gt;

  &lt;p&gt;Finally, you can have static and instance non-enumerable members by prefixing the name with an underscore character. This has the effect of the member not being available when you reflect on the object and try to access its members. In the example above the static member &lt;b&gt;_counter &lt;/b&gt;is not intended to be accessed directly by client code. We express this by prefixing an underscore character and WinJS makes sure that it sets the &lt;i&gt;enumerable&lt;/i&gt; property descriptor to &lt;b&gt;false&lt;/b&gt; when it creates the property. When we call &lt;a href="http://bit.ly/slawwN"&gt;Object.keys&lt;/a&gt; for instance, on the &lt;b&gt;Shape&lt;/b&gt; constructor, here’s what we get:&lt;/p&gt;

  &lt;blockquote&gt;
    &lt;pre class="prettyprint"&gt;console.log(Object.keys(Acme.Shapes.Shape));
// prints &amp;quot;newId&amp;quot;&lt;/pre&gt;
  &lt;/blockquote&gt;

  &lt;p&gt;As you can see it does not indicate &lt;b&gt;_counter&lt;/b&gt; as being a member of &lt;b&gt;Shape&lt;/b&gt;. Having said that if you do go ahead and access &lt;b&gt;_counter&lt;/b&gt; anyway, it’ll still work! If you want a member to be really inaccessible then you might want to &lt;a href="http://blogorama.nerdworks.in/entry-JavaScriptclosuresactlikeimpli.aspx"&gt;use closures&lt;/a&gt;.&lt;/p&gt;

  &lt;h4&gt;Inheriting from classes&lt;/h4&gt;

  &lt;p&gt;You can inherit one class from another by calling &lt;a href="http://bit.ly/v48nOX"&gt;WinJS.Class.derive&lt;/a&gt;. Here’s an example:&lt;/p&gt;

  &lt;blockquote&gt;
    &lt;pre class="prettyprint"&gt;(function () {
    'use strict';

    // constructor function
    function initLine() {
        // call the base constructor
        Acme.Shapes.Shape.call(this, Acme.Shapes.ShapeType.Line);
    }

    var instanceMembers = {
        // overriding Shape.draw
        draw: function () {
            // call base
            Acme.Shapes.Shape.prototype.draw.call(this);
            console.log(&amp;quot;Line.draw&amp;quot;);
        }
    };

    // inherit from Shape
    var Line = WinJS.Class.derive(Acme.Shapes.Shape, initLine, instanceMembers);

    WinJS.Namespace.define(&amp;quot;Acme.Shapes&amp;quot;, {
        Line: Line
    });
})();&lt;/pre&gt;
  &lt;/blockquote&gt;

  &lt;p&gt;The first parameter is a reference to the base class, followed by the constructor function and the instance members. Just like class definition, you can also pass static members if need be as the fourth argument. Note that when you inherit from another class, you &lt;i&gt;do not&lt;/i&gt; inherit the static members. In the example above you cannot call &lt;b&gt;newId&lt;/b&gt; via &lt;b&gt;Line&lt;/b&gt;. You’ll also note that we call base class methods via &lt;a href="http://bit.ly/sTarX6"&gt;Function.call&lt;/a&gt; instead of directly invoking them, i.e. we &lt;u&gt;do not&lt;/u&gt;, for instance, do the following from &lt;b&gt;Line.draw&lt;/b&gt;.&lt;/p&gt;

  &lt;blockquote&gt;
    &lt;pre class="prettyprint"&gt;Acme.Shapes.Shape.prototype.draw(); // DO NOT do this&lt;/pre&gt;
  &lt;/blockquote&gt;

  &lt;p&gt;This won’t work because in this case the “&lt;b&gt;this&lt;/b&gt;” pointer inside &lt;b&gt;Shape.draw&lt;/b&gt; will point to the &lt;b&gt;Shape&lt;/b&gt;’s prototype and not to the &lt;b&gt;Line&lt;/b&gt; instance on which &lt;b&gt;Line.draw&lt;/b&gt; was called. We will therefore need to explicitly specify the context for the call via &lt;a href="http://bit.ly/sTarX6"&gt;Function.call&lt;/a&gt;.&lt;/p&gt;

  &lt;h4&gt;Mixing functionality in&lt;/h4&gt;

  &lt;p&gt;Let’s say you find this awesome piece of code somewhere that you think would be a great fit for one of the classes you are defining and it’d simply be too much trouble to manually copy and paste all of that code into your class definition (besides being error prone and quite simply a bad idea). In this case you can choose to “mix-in” that functionality into your existing class by calling &lt;a href="http://bit.ly/ty6B6q"&gt;WinJS.Class.mix&lt;/a&gt;. Here’s an example:&lt;/p&gt;

  &lt;blockquote&gt;
    &lt;pre class="prettyprint"&gt;// mix-in some functionality from somewhere; pretend
// that we got this by including a JS or something
var SuperDrawModule = {
    superDraw: function() {
        console.log(&amp;quot;SuperDrawModule.superDraw&amp;quot;);
    }
};

Line = WinJS.Class.mix(Line, SuperDrawModule);&lt;/pre&gt;
  &lt;/blockquote&gt;

  &lt;p&gt;Now the method &lt;b&gt;superDraw&lt;/b&gt; becomes a part of &lt;b&gt;Line&lt;/b&gt; which means I can do the following now:&lt;/p&gt;

  &lt;blockquote&gt;
    &lt;pre class="prettyprint"&gt;var l = new Acme.Shapes.Line();
l.draw();

// call mixin method
l.superDraw();&lt;/pre&gt;
  &lt;/blockquote&gt;

  &lt;h4&gt;Adding eventing capabilities&lt;/h4&gt;

  &lt;p&gt;WinJS ships with a useful little mixin object that automatically adds the ability to call &lt;b&gt;addEventListener&lt;/b&gt;, &lt;b&gt;removeEventListener&lt;/b&gt; and &lt;b&gt;dispatchEvent&lt;/b&gt; on your own objects. The mixin in question is &lt;a href="http://bit.ly/txjWh0"&gt;WinJS.Utilities.eventMixin&lt;/a&gt;. Here’s how you can use it:&lt;/p&gt;

  &lt;blockquote&gt;
    &lt;pre class="prettyprint"&gt;(function () {
    &amp;quot;use strict&amp;quot;;

    // constructor function
    function initShape(type) {
        this.id = Acme.Shapes.Shape.newId(); // calling a static member
        if (type) {
            this.type = type;
        }
    }

    var instanceMembers = {
        id: null,
        type: Acme.Shapes.ShapeType.None,
        draw: function () {
            &lt;b&gt;// fire event &amp;quot;draw&amp;quot; via &amp;quot;dispatchEvent&amp;quot;
            this.dispatchEvent(&amp;quot;draw&amp;quot;, { source: this });&lt;/b&gt;
            console.log(&amp;quot;Shape.draw&amp;quot;);
        }
    };

    var staticMembers = {
        // private member
        _counter: 0,
        newId: function () {
            return Acme.Shapes.Shape._counter++;
        }
    };

    var Shape = WinJS.Class.define(initShape, instanceMembers, staticMembers);

    &lt;b&gt;// add eventing capability to Shape
    Shape = WinJS.Class.mix(Shape, WinJS.Utilities.eventMixin);&lt;/b&gt;

    // add to namespace
    WinJS.Namespace.define(&amp;quot;Acme.Shapes&amp;quot;, {
        Shape: Shape
    });
})();&lt;/pre&gt;
  &lt;/blockquote&gt;

  &lt;p&gt;Take note of the lines in bold. We add the event mixin to &lt;b&gt;Shape&lt;/b&gt; like any other mixin and call &lt;a href="http://bit.ly/sDaohn"&gt;eventMixin.dispatchEvent&lt;/a&gt; to actually fire the event. Client code that handles the event would look like any other event handling code that you might have written to handle DOM events.&lt;/p&gt;

  &lt;blockquote&gt;
    &lt;pre class="prettyprint"&gt;var l = new Acme.Shapes.Line();
l.addEventListener(&amp;quot;draw&amp;quot;, function () {
    console.log(&amp;quot;Line was drawn.&amp;quot;);
});
l.draw();&lt;/pre&gt;
  &lt;/blockquote&gt;

  &lt;p&gt;Note that stuff that you add to a base class via a mixin does in fact get inherited in sub-classes. In the sample snippet above, though the event mixin was added to &lt;b&gt;Shape&lt;/b&gt; I am able to call &lt;b&gt;addEventListener&lt;/b&gt; on the sub-class &lt;b&gt;Line&lt;/b&gt;.&lt;/p&gt;

  &lt;h4&gt;Turning your events into properties&lt;/h4&gt;

  &lt;p&gt;&lt;a href="http://bit.ly/txjWh0"&gt;WinJS.Utilities.eventMixin&lt;/a&gt; allowed us to make our classes act like DOM objects in supporting the registering of event handlers and in dispatching events. We can take things to the next level and add properties to our classes and add an alternative mechanism for registering event handlers. Our &lt;b&gt;Shape&lt;/b&gt; class for instance, supports the raising of the “draw” event. Wouldn’t it be nice if it supported a property called &lt;b&gt;ondraw&lt;/b&gt; to which we can assign a callback function and have it invoked whenever the event is raised? Turns out that is exactly the sort of thing that &lt;a href="http://bit.ly/u7evi6"&gt;WinJS.Utilities.createEventProperties&lt;/a&gt; enables. Here’s an example:&lt;/p&gt;

  &lt;blockquote&gt;
    &lt;pre class="prettyprint"&gt;// add &amp;quot;onevent&amp;quot; properties for all events we support
var eventPropMixin = WinJS.Utilities.createEventProperties(&amp;quot;initialized&amp;quot;, &amp;quot;draw&amp;quot;, &amp;quot;disposed&amp;quot;);
Shape = WinJS.Class.mix(Shape, eventPropMixin);&lt;/pre&gt;
  &lt;/blockquote&gt;

  &lt;p&gt;&lt;code&gt;WinJS.Utilities.createEventProperties&lt;/code&gt; basically creates a mixin object that contains properties which have the same name as the strings passed to it as parameters except for the prefixing of the word “on” to them. This function can accept a variable number of parameters – one for each event that your class supports. With this in place, now you can write code such as the following:&lt;/p&gt;

  &lt;blockquote&gt;
    &lt;pre class="prettyprint"&gt;var l = new Acme.Shapes.Line();
l.ondraw = function () {
    console.log(&amp;quot;Line was drawn.&amp;quot;);
};
l.draw();&lt;/pre&gt;
  &lt;/blockquote&gt;

  &lt;p&gt;One benefit of using WinJS is that you automatically get intellisense support in VisualStudio for stuff you add to your classes using it. Here’s a screen shot:&lt;/p&gt;

  &lt;blockquote&gt;&lt;a href="http://blogorama.nerdworks.in/images/_img12.png"&gt;&lt;img title="p1" style="border-left-width: 0px; border-right-width: 0px; background-image: none; border-bottom-width: 0px; padding-top: 0px; padding-left: 0px; display: inline; padding-right: 0px; border-top-width: 0px" border="0" alt="p1" src="http://blogorama.nerdworks.in/images/_img13.png" width="398" height="128" /&gt;&lt;/a&gt;&lt;/blockquote&gt;

  &lt;p&gt;That’s pretty much all I wanted to talk about. With these few simple methods from WinJS it is quite possible to be fairly disciplined about your JavaScript code and believe me, JavaScript being JavaScript, you’re going to need all the help you can get! &lt;img class="wlEmoticon wlEmoticon-winkingsmile" style="border-top-style: none; border-left-style: none; border-bottom-style: none; border-right-style: none" alt="Winking smile" src="http://blogorama.nerdworks.in/images/_img14.png" /&gt; I have created a small project with all of the code snippets given above &lt;a href="http://blogorama.nerdworks.in/downloads/WinJS101.zip" target="_blank"&gt;here&lt;/a&gt;.&lt;/p&gt;
&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/nerdspeak-rss/~4/Tqc_WYff9R8" height="1" width="1"/&gt;</description><pubDate>Sat, 09 Jun 2012 10:34:17 GMT</pubDate><feedburner:origLink>http://blogorama.nerdworks.in/entry-OrganizingyourJavaScriptwithWi.aspx</feedburner:origLink></item></channel></rss>
