Wednesday, August 15, 2012

Windows 8 App Development - JavaScript (Data)Binding

This is my fourth blog post related to Windows 8 Application Development with HTML5, CSS3 and JavaScript. You can find the previous ones on my blog's main page.

Last time I presented the HouseRental project, which is a very simple one, you can check the code on GitHub. In this project all data is simply written inside the default.html file, the only JS(JavaScript) code existed was generated by Visual Studio 2012 RC from the blank project template.

This time I will take a step further and improve the HouseRental application. I will do two things:
  1. Store the data in JavaScript objects.
  2. Use data-binding to display data from JavaScript objects to HTML elements.
You can take a look at the source code at GitHub. I've named the project HouseRental_Binding.

For web developers it is not clear what are you referring to when are talking about bindings. Most of them work a lot with jQuery and the first thing which comes in their minds is the bind() method from jQuery API and clearly we are not referring to that when talking about Windows 8 App Development. So we should be more precise, I will stick with data-binding expression from now-on. I mentioned jQuery, but I am pretty sure from those who are reading this post right now, have heard about knockout.js. I had the opportunity to use it in real projects. Having a more solid desktop application development background and some WPF knowledge I had no problem applying the MVVM pattern. Who has not heard about the MVVM design pattern, do not panic, if you heard and know about MVC you'll understand MVVM in a blink of an eye.

I'm writing about MVVM because the Windows 8 Application Development embraces this design pattern. If you are not familiar with it, in a short period of time you'll understand it's benefits.

The CSS story...

I have not made any change to the design of the application. The default.css file was not modified, it's exactly the same as it was in the HouseRental project.


The HTML5 story...

To apply the data-bindigs the default.html file has to be changed. I deleted the hard coded data, and added attributes to the HTML tags, here is an example:

 <!-- HOUSE 1 -->
        <div id="topLeftContainer" class="gridLeft">
            <h2 data-win-bind="innerText: Data.city1"></h2>
            <div class="contentContainer">
                <img data-win-bind="src: Data.imageSource1" />
                <div class="price">
                    <h4 data-win-bind="innerText: Data.price1"></h4>
                </div>
            </div>
        </div>

The data-win-bind attribute is set to a key : value pair. The key is a property of the HTML element, the value is a property from the data source of the container. In this case this will cause to bind the value from data source property Data.city1 / Data.imageSource1 / Data.price1 to the innerText / src / innerText property of the HTML tag. There is some additional information related to  data-win-bind on MSDN.


The JavaScript story...

Most of the changes occur in the JS code. A new JS file was added in the js folder of the application, data.js. The content can be seen below:

 1. /// <reference path="//Microsoft.WinJS.0.6/js/base.js" /> 
 2. /// <reference path="//Microsoft.WinJS.0.6/js/ui.js" /> 
 3.
 4. (function () {
 5.    "use strict";
 6.
 7.    WinJS.Namespace.define("ViewModel.Data", {
 8.        price1: "",
 9.        price2: "",
10.        price3: "",
11.        price4: "",
12.
13.        imageSource1: "",
14.        imageSource2: "",
15.        imageSource3: "",
16.        imageSource4: "",
17.
18.        city1: "",
19.        city2: "",
20.        city3: "",
21.        city4: ""
22.    });
23.
24.    //init prices
25.    ViewModel.Data.price1 = "650.000 $";
26.    ViewModel.Data.price2 = "890.000 $";
27.    ViewModel.Data.price3 = "380.000 $";
28.    ViewModel.Data.price4 = "740.000 $";
29.
30.    //init image sources
31.    ViewModel.Data.imageSource1 = "/images/house1.jpg";
32.    ViewModel.Data.imageSource2 = "/images/house2.jpg";
33.    ViewModel.Data.imageSource3 = "/images/house3.jpg";
34.    ViewModel.Data.imageSource4 = "/images/house4.jpg";
35.
36.    //init the cities
37.    ViewModel.Data.city1 = "New York";
38.    ViewModel.Data.city2 = "Los Angeles";
39.    ViewModel.Data.city3 = "Boston";
40.    ViewModel.Data.city4 = "San Francisco";
41.
42. })();

The first two lines of  the file with the /// <reference ... />  cause the "import" of the two named files. These references are also used by the Visual Studio's IntelliSense. Who have ever worked with  the Cassette.Web project (it can be downloaded from NuGet package gallery) for those these kind of reference declarations are familiar (The idea behind the Cassette.Web project is, to include only the required .css and .js files into a webpage. It helps you build up assets and bundles which can be referenced afterwards from server side code in ASP.NET MVC projects.  This tool helps to create a cleaner and faster website).

After the references have been declared comes a self executing JavaScript function. I wrote about the "use strict" declaration in one of my previous blog post, so I will not detail this, you can read more about it on MSDN.

The line WinJS.Namespace.define("ViewModel.Data", { causes to define a new object (the second parameter of the define function) which will be assigned to the namespace written in the first parameter. In the current example this means, that after the 
WinJS.Namespace.define("ViewModel.Data", {
...
...
...
});
line of code is executed a new object will be available which can be accessed through the ViewModel.Data property as it can be seen in the init prices, init image sources and init the cities code region.

To view from a higher level, all I did in this data.js file was, to declare in the ViewModel.Data namespace a new object with 12 public properties initialized with empty strings. After the declaration I assign new values to the public properties.

So, the default.html file was changed to have bindings towards javascript objects, the javascript objects were created but these two have to be connected, otherwise it won't work. To connect the HTML bindings and the JS objects some changes has to be made in the default.js file.

The only thing changed is that a new function was added and this is invoked when the application is launched.

37. function init() {
38.        WinJS.Binding.processAll(document.body, ViewModel);
39.
40.    }
The init() function, invokes the processAll(...) method with 2 parameters, the first one refers to the HTML elements where the binding should occur, the second one is the object (dataContext) which stores the data. 
The  init() function is invoked in the handler of onactivated:
10. app.onactivated = function (args) {
11.        if (args.detail.kind === activation.ActivationKind.launch) {
12.            if (args.detail.previousExecutionState !== activation.ApplicationExecutionState.terminated) {
13.                // TODO: This application has been newly launched. Initialize
14.                // your application here.
15.
16.                init();
17.
18.            } else {
19.                // TODO: This application has been reactivated from suspension.
20.                // Restore application state here.
21.            }
22.            args.setPromise(WinJS.UI.processAll());
23.        }
24.    };


When the application is launched, the onactivated event occurs and the handler assigned to this event is invoked; the init() function is invoked also, this calls the processAll() method of Bindings namespace and this, together with the HTML attributes (data-win-bind) will resolve the binding between JS objects and HTML tags.

In the next posts I will present two way bindings, observable collections and templates.

Saturday, August 11, 2012

Windows 8 App Development – Follow Up


After the first two blog posts, lets look at the basics of Windows 8 Application Development with JavaScript and HTML from a more technical point of view.

To summarize, for the development I am using Windows 8 Release Preview, with Visual Studio 2012 RC. All these are installed on a virtual machine(VM), using VirtualBox. The VM has 2 CPU cores assigned (from the existing 4) and 2 GB of memory. Due to the 5400 RPM hard drive which I have in my notebook, the VM does not have the speed of a rocket, but for learning purpose it is OK.

I created 2 Windows 8 Applications, in this post only one is presented. Here is a little overview of the projects along with their GitHub links:
  • HouseRental (access to GitHub repository) – This application was created from a Blank Windows 8 app template. It only contains static/hard coded data and HTML5/CSS3 code. The only JavaScript (from now on JS) code that appears is the minimum, which is necessary for the Windows 8 app; this JS code is generated by the project template. 

  • HouseRental_Binding (access to GitHub repository) – This Win 8 app is an improved version of the first HouseRental project. The concept of Binding is introduced and the data is stored in JS. The CSS structure was not modified at all, the HTML code has changed, the static data was removed from the main page and bindings were added.

The HouseRental project

The project is a very simple one, which creates the following app:

House Rental Application UI draft

In this post I will present this application, it is a very simple one. I have never been a good designer, I don’t really have the talent for it, luckily there are very good designers in the world who can create astonishing designs for the applications depending on the customers need.

In my previous blog post I presented the business case for the project, here is a reminder; I am an estate agent who knows some programming and I definitively need a Windows 8 app to increase my market share with.
In the current situation I have 4 houses to sell, so I thought that I will create an application with a single page, which has 4 parts/regions and in each of the regions I put a picture of the house, the name of the city where this is, and the price of the house.

The CSS3 story…


As the idea of these series of blog posts was to present Windows 8 application development with JS and HTML5, there is no way to leave the CSS out of the list. Although the W3C is working from a long time ago on HTML5 and CSS3 drafts these are not finalized yet. Besides learning the development of Windows 8 apps, I am learning in parallel, the goodies of HTML5 and CSS3.

In CSS3 there will be support for grid layout. The problem is, that the specifications are not finished 100%. If you look at the W3C website you’ll see that the guys from Microsoft are working on the grid layout’s specs. I think this CSS3 feature will be an embraced one. This new layout will give possibility to create sophisticated designs without floating elements and JS code which helps the adoption of design in case of browser window resize or other cases. Microsoft did implement a temporary version, for supporting Windows 8 App development.

To use these style properties implemented by Microsoft the –ms prefix has to be added to each property. For example in CSS3 draft to use grid layout you would write:
#grid { 
     display: grid;
}
but for using the version implemented by Microsoft in their Windows 8 apps you should write:

#grid { 
     display: –ms-grid;
}
To use the grid layout you have to specify the number and size of the rows and columns of the grid. Besides these there has to be a possibility to specify which element goes to which cell from the grid; this is achieved using the style grid-row and grid-column properties. 
NOTE: As these CSS style elements are still drafts, Microsoft also added the –ms prefix to them, so instead of grid-row, there is –ms-grid-row, and instead of grid-column there is –ms-grid-row.
To create the 4 regions(city + picture + price) seen on the image above, I used the new grid layout feature from CSS3. In the default.css file I created a new style where the grid layout is defined as seen in the code below:
#mainContent {
    display: -ms-grid;     -ms-grid-rows: 1fr 1fr;     -ms-grid-columns: 60% 60%;     height: 100%;     overflow: scroll; }
The display property is set to -ms-grid, this creates the grid layout, with the help of –ms-grid-rows I define 2 rows each having a height of one Fractional Value. With –ms-grid-columns I define 2 columns, each with a 60% width. This causes that the application has an overall width of 120% instead of 100%. This helps the app to fit in the use and feel of Windows 8 apps, a part of the content is visible, but another part of it overflows and the user can swipe to fully view it .

Afterwards I created 4 elements, one for each cell, these are called #topLeftContainer, #bottomLeftContainer, #topRightContainer and #bottomRightContainer; each of these 4 styles have the –ms-grid-row and ms-grid-column properties set.
There is one extra style, I have created it for displaying the price of the houses in a round cornered rectangle, to resolve this I used the following style:

.contentContainer {
    position:relative;
}
.contentContainer .price {
    background-color:#79a1be;
    border-radius:10px;
    bottom:12px;
    right:125px;
    position: absolute;
    padding:3px;
}

I highlighted the border-radius property. This is another one from CSS3 features.

The HTML5 story…



After building the styles and defining the grids, lets see the default.html file. The file starts with the DOCTYPE definition for HTML5.
In the head section of the file, the Windows 8 app default style file (ui-dark.css) is referenced along with the JS files needed from WinJS framework.

NOTE: The best part of Windows 8 App development is, that you can see the referenced source files. This means that you can open ui-dark.css or even the Microsoft.WinJS.1.0.RC/js/base.js file. You can access these by simply double clicking the Windows Library for JavaScript 1.0 RC from the project References (see the image below – red rectangle)


Windows 8 App Default References

After the obligatory references, the default.css and default.js file are linked. I wrote about the    default.js file in the last blog post, I will not give further explanations because no changes were made to it.
In the body section of the page, a div element is defined( <div id="mainContent"> ), the grid styling is applied to this. Inside it, the 4 elements are defined for the 4 images, city names and   prices. All the data is hard coded inside the HTML, there is absolutely nothing created dynamically. Each of the 4 elements have a heading with the city name (the default styling of headings, paragraphs, images..etc are defined in the ui-dark.css and ui-light.css files). Besides the     heading another container element is added, this stores the image element and the heading    which displays the price.
There is a really great HTML5 tutorial on Channel9, it is presented by Bob Tabor from LearnVisualStudio. It is a great tutorial, also containing a lot of explanation for beginners; besides  the presentation of HTML5 Bob also tries to present the idea why HTML5 was created, why dothe HTML tags have semantic meanings, how it is optimal to format the content of a website so the information presented on it can be reused, scanned by software focusing on semantic computing.
The overall HTML code and design is very simple, I’ve done this with intention. I wanted to create a very simple app, which can be improved afterwards, which I can build on for further learning.You can check out the github repos which I linked in above, any idea, comment is welcomed.
The next post will present the HouseRental_Binding project and will focus on the bindings       inside Windows 8 JavaScript and HTML5 applications.
 
Disclaimer: 
1. The pictures used in the application were downloaded from the internet, by simply typing the work house in Microsoft’s search engine: BING, these images are in the first 100 results, I downloaded the 4 pictures which I liked the most. 
2. The data presented in the application is the born of my imagination, the data does not present real estates and prices.

Tuesday, August 7, 2012

First Windows 8 App with JavaScript and HTML

     As I promised, I continue my previous blog post related to application development for Windows 8. First I will focus on development with JavaScript and HTML. After getting used to the WinJS framework and earning a little experience with, I will also present the C# and XAML development for Windows 8.



Visual Studio 2012 - First Impressions

     In the last post I wrote that I will detail some of the new features of Visual Studio 2012. The first thing which you will notice if you try VS2012 is the huge change in the design. The development team which worked on VS tried to create the same look and feel that exist in other apps of Windows 8. I am referring to the buttons, the fonts, the whole design of UI. Even the icon of Visual Studio 2012 has changed to a more angular form, trying to convince the user that this app is not different from other ones existing inside Windows 8. 

Here is a screenshot of the Visual Studio 2012

Visual Studio 2012 - Start Page

     The first thing you can notice is that a Quick Launch  region was added to the title bar. This can be used as a search box and it scans the menus and opened files for the typed text.

     To see some additional functionality you have to create/open a project.  A new feature of VS2012 is the Preview Window/Tab, see the screenshot below to see what I am referring to.

Visual Studio 2012 - Preview Window/Tab


     I have marked with red rectangles the new feature. If you select a file in Solution Explorer a Preview Tab appears in the right hand-side of the tab control used for opened documents. If you press the Keep Open button, the file will be opened normally. The idea is that this Preview Feature only opens the file for reading, for preview, if you start to make changes in the file this will be opened normally. This can be useful when working with TFS or other source controls.


     The next interesting thing which appeared is the Refresh Windows App button. If you are debugging an application and you have made changes in the JavaScript or HTML files you don't need to stop debugging, rebuild the app and re-run the application; in VS2012 all you need is to press this button and everything on the Simulator or local machine will be refreshed. I marked the button and it's tool-tip with a red rectangle.

Visual Studio 2012 - Refresh Windows App Button


There are many new features in VS2012, I think the best one, which was needed and requested by web developers is the full Intellisense support for JavaScript and the Go To functionality for JavaScript functions. On the following link all the new features of Visual Studio 2012 are explained and presented.



Creating the first Windows 8 Application

     When installing the VS2012 from this link, this will be installed with some application templates for developing Windows 8 Apps. So, to create a new Windows 8 Application, simply select from the menu FILE -> New Project OR press CTRL + SHIFT + N and the New Project window will open.

Visual Studio 2012 - New Project - Templates


     Select JavaScript and Windows Metro Style from the tree in the left hand-side. Initially I've created a Blank App(lication), because I wanted to go step by step and see how things are melting together. After specifying the Name of the project, setting the Location and pressing the OK button a Blank App is created. But let's hold our horses for a minute and talk about the project which will be developed.

I thought about a very simple project, I imagined that I am an estate agent (who knows a little bit of programming :D ) and I would need an application for the all new OS, Windows 8. This app would have pictures and some details about the estates which I want to sell. In the beginning I will make a static application and hardcode everything. Taken into account that the financial crisis is not over yet and the estate market is not a dynamic one in these days; :) there is no need for a large application architecture and database integration..etc. Currently I try to follow the KISS method (Keep It Simple, Stupid). As you can see project purpose is defined, lets get to work. ;)

     I named my project HouseRental because I will sell only houses. After creating the Blank project, I have this project structure.

Visual Studio 2012 - HouseRental Project


     There are 3 important files that have to be mentioned:
    • default.css
    • default.js
    • default.html
     The names of these files are quite intuitive, the default.css will contain the default styles defined for the application, you'll see that in our case this contains some empty styles defined. The default.html is a HTML5 file, where the HTML tags will be added, this along with the default.css file will create the UI of the application. The default.js file is more interesting, here is it's content:


// For an introduction to the Blank template, see the following documentation:
// http://go.microsoft.com/fwlink/?LinkId=232509
(function () {
    "use strict";

    var app = WinJS.Application;
    var activation = Windows.ApplicationModel.Activation;
    WinJS.strictProcessing();

    app.onactivated = function (args) {
        if (args.detail.kind === activation.ActivationKind.launch) {
            if (args.detail.previousExecutionState !== activation.ApplicationExecutionState.terminated) {
                // TODO: This application has been newly launched. Initialize
                // your application here.
            } else {
                // TODO: This application has been reactivated from suspension.
                // Restore application state here.
            }
            args.setPromise(WinJS.UI.processAll());
        }
    };

    app.oncheckpoint = function (args) {
        // TODO: This application is about to be suspended. Save any state
        // that needs to persist across suspensions here. You might use the
        // WinJS.Application.sessionState object, which is automatically
        // saved and restored across suspension. If you need to complete an
        // asynchronous operation before your application is suspended, call
        // args.setPromise().
    };

    app.start();
})();


     This is how VS has generated it, there are no modifications in it. The first thing which is different from other JavaScript files, is the "use strict" string. This string causes the Strict Mode to activate. By switching on the Strict Mode, you get errors when trying to create a global JavaScript variable inside a function. There are also other benefits of using it, the ECMAScript Language Specification gives more detail related to this. It is not a must to use Strict Mode, but the experts say that it is a good practice to use it.

     After the "use strict" part, local variables are created, there are made 2 subscriptions for onactivated  and oncheckpoint events and finally the app.start() is invoked. The whole logic is inside a self executing function. The file, default.js along with the default.css is referenced by the default.html.   



Final Words


     This was the second post for Windows 8 app development. It does not have many technical details, but I wanted to say a few words about Visual Studio 2012 also and did not want to make this post a very long one. In the following post I will present the first version of the HouseRental project. The project will be added to GitHub. There is a really nice program made by the guys at GitHub, it is called GitHub for Windows, I really like it, and the nice thing is, it can be fully used on Windows 8.


Monday, August 6, 2012

Let's try Win 8 Release Preview and VS2012

     I've got the weekly newsletter from CodeProject and saw that Windows 8 was Released to Manufacturing along with Visual Studio 2012, so I thought this would be an ideal time to try this fresh version of Windows and this new version of VS. I've already tested the BETA version of Windows 8, but that was quite slow, everything was new for me in that version, I didn't know anything about the new features or the changes made, I only installed it to see how it is. Since then I watched some tutorials which explain new features of Windows 8 and how can this be used more efficiently without touch input.
    In the following posts I will try to present some steps about Windows Application Development for Windows 8 using HTML5/JavaScript and also WPF and XAML.



Setting Up Test Environment

     I've had a version of VirtualBox on my machine, but when I fired it up, it said that there is an update for it so I installed that also. The version of VirtualBox I tested with is 4.1.18 r78361. I created a new virtual machine, assigned for it 2GB of memory and 2 CPU cores. I have to mention that I have 4GB of memory in my laptop abd the 64bit Windows7 says that 3.79GB is usable; by assigning 2GB to this new virtual machine,VirtualBox gives a warning message, that I've assigned more than 50% of my system memory to the virtual machine and the hosting OS can remain without memory and I may continue for my own risk; what can I say :) ok, thanks for the warning, I will assume this risk. 



Installation

    The next step was to download the RTM version of Windows 8 from Microsoft's website...but this will be available for developers only from 15 August. I did not want to give up and wanted something newer than the BETA version and also my main aspect was to see how VS2012 looks and feels like. I started searching the internet and saw that the Windows 8 Release Preview was free for public access, so I downloaded this version from http://windows.microsoft.com/en-US/windows-8/release-preview. I have downloaded the 64bit version. The size of the ISO file is 3352.8MB. 
     I've added the Windows 8 Release Preview ISO to the virtual machine and I've fired it up. The same start up message appeared as in older version of windows: Press any key to boot from CD or DVD......The install wizard is very similar to the Windows 7's wizard, there are minor graphical changes, but the logical flow and the steps done are the same. I was quite impressed, because the installation was finished in 20 minutes. Taken into account that there were only 2GB of memory, 2 CPU cores and a hard drive with 5400RPM I think this was fast :). 
I think it is important to talk about the user management in this version of Windows. There are 3 possibilities to create users.
     The first one is to use an existing Windows Live ID, I have a Windows Live ID so I started to use Windows 8 with this, it automatically configured the Mail application to connect to the live mail account, the Messenger program automatically added the contacts which I had assigned to my windows live account, it configured the SkyDrive app also. At the first start up I had the impression that in less time I had much more things configured and ready for use that I've had when installing Windows7 and to be honest I like this thing a lot.
    The second option is to create a new Windows Live Account and start to use that, the result is the same as in the case of the first option.
    The third option is to create an account locally without adding Windows Live ID, I guess if you don't have an internet connection when installing the OS than this is the only option for you to get the system running. I don't know if afterwards the account can be changed to use a Windows Live ID, but I guess this is possible, otherwise it really does not make sense to have this option.



     After configuring the account I've started to look around in the system a little bit and I noticed that you can check for updates, so I pressed the button and waited and waited and waited; it took almost 5 minutes to identify that there are 7 new updates for Windows 8 Release Preview, I've chosen to install them. The installation was much faster, in 3 minutes the 7 updates were installed, but a reboot was required.
     The thing which amazed me was that there is a significant improvement in performance and responsiveness of the OS related to the BETA version. Most people say, ohhh if the BETA version is slow which is only a fraction of the final product how slow the final version will be? I don't agree with this affirmation, I think the BETA version of a product is BETA because it is not optimized, the features exist, but do not work well are slow and buggy.

     After using Windows 8 a little more I had the same feeling which I've had with my Windows Phone. The system is much smarter, it configures a lots of things for you and really tries to offer a complete package of services for the user. Finally Microsoft seems to understand the philosophy that Apple used for years when developing his products (I think this discussion will worth another blog post :) ).


The OS installation was done, let's start with the second part, Visual Studio 2012.



Installing VS2012

     The base idea was to test VS2012 and to get in touch with the new Windows 8 UI Style (as I've read the Metro name will vanish from the Microsoft terminology - http://arstechnica.com/information-technology/2012/08/microsoft-metro-out-windows-8-style-ui-in-amid-rumors-of-a-trademark-dispute/ ).
    I've started to look for Windows 8 application development and found this page: http://msdn.microsoft.com/en-us/windows/apps/br229516. From here you can download the "tools and SDK" which only contains Visual Studio 2012 Express RC. It's not the RTM version, but it will be OK to make some tests and samples. The installation of Visual Studio was quite fast. I think if you are installing onta real machine and have at least 4GB of memory (I think 4GB of memory is not much for a software developer) it will run well.
I have to admit that I like the design of the new Visual Studio the icon's design are the same as the ones used for Windows Phone 7 Development.
    
     There are a lot of things which I like in Visual Studio 2012 I will discuss about these when I start to present how apps can be made for the new Windows 8...