dimanche 26 août 2012

HTML5 Tags

Here is a list of with description of HTML tags:
  • article This tag specifies independent, self-contained content.An article should make sense on its own, and it should be possible to distribute it independently from the rest of the site.Examples of possible articles: forum post, newspaper article, blog entry, user comment, etc.
  • aside This tag defines some content aside from the content it is placed in. The aside content should be related to the surrounding content
  • audio Sound or audio stream
  • canvas This element provides scripts with a resolution-dependent bitmap canvas, which can be used for rendering graphs, game graphics, or other visual images on the fly.
  • command Command that users can invoke
  • datalist Set of option elements that represent predefined options for other controls
  • details Disclosure widget from which users can obtain additional information or controls
  • figure Flow content, optionally with a caption, that is self-contained and is typically referenced as a single unit from the main flow of the document
  • footer Footer for its nearest ancestor sectioning content or sectioning root element
  • header Group of introductory or navigational aids
  • hgroup Heading of a section
  • keygen Key pair generator control
  • mark Run of text in one document marked or highlighted for reference purposes, due to its relevance in another context
  • math MathML a2 + b2 = c2
  • meter Scalar measurement within a known range, or a fractional value; for example disk usage, the relevance of a query result, or the fraction of a voting population to have selected a particular candidate
  • Nav Section of a page that links to other pages or to parts within the page: a section with navigation links.
  • output Result of a calculation
  • progress Completion progress of a task
  • Example of indeterminate progress: 0%
  • ruby This element allows one or more spans of phrasing content to be marked with ruby annotations.
  • section Generic section of a document or application
  • source This element allows authors to specify multiple alternative media resources for media elements.
  • summary Summary, caption, or legend for the rest of the contents of the summary element's parent details element, if any
  • svg Scalable Vector Graphics (SVG)
  • time Time on a 24-hour clock, or a precise date in the proleptic Gregorian calendar, optionally with a time and a time-zone offset
  • video Used for playing videos or movies, and audio files with captions. 
Here is some examples of these tags usage.

samedi 25 août 2012

Test Driven Development

Testing Overview

In Waterfall development process, developers finish code then do some ad-hoc testing. In the contrary with Agile development process, testing is part of every Agile iteration and developers are the responsible for testing own code. Also, testing tools & processes are highly automated.

With Behavior-Driven Design (BDD), one has to develop user stories to describe features, then thanks to Cucumber, user stories become acceptance tests and integration tests.
With Test-driven development (TDD), specify step definitions for new story (this may require new code to be written), write unit & functional tests for that code first, before the code itself. In a nutshell, write tests for the code you wish you had.

How both works together? Use Cucumber to describe behavior via features & scenarios (behavior driven design), and RSpec to test individual modules that contribute to those behaviors (test driven development).
When Cucomber test fails, it calls for RSpec test, if it fails you need to add missing methods. Keep iterating until passing feature implementation test, when features are implemented properly it will pass the Cucomber test then keep going to development.

TDD Getting Started

Unit Test should be FIRST: Fast to run, Independent the order of running tests should no matter, Repeatable if a test fails once then it should fail again if we re-run it again (i.e. always same result), Self-checking which means no human intervention to interpret test result as failed or successful. Timely   can be run on background while developing and bring developers attention when it find bugs, also when code change test should also.
RSpec is a Domain-Specific Language for testing. DSL stands for small programming language that simpifies one task at expense of generality (e.g. migrations, regexes, SQL). RSpec tests are called specs, and inhabit spec directory.
Typing following command rails generate rspec:install will creates this directory structure:

  • app/models/*.rb                                    spec/models/*_spec.rb
  • app/controllers/*_controller.rb              spec/controllers/*_controller_spec.rb
  • app/views/*/*.html.haml                       (use Cucumber!)

Te be continued from slide 13 ...

jeudi 23 août 2012

Basic JavaScript - HTTP Requests

This post corresponds to notes taken while reading Eloquent JavaScript.

To be able to request information from a web page, first, we create an object to make an HTTP request with the help of XMLHttpRequest() method. Second, the open method is used to configure the HTTP request, it specifies GET as the method, and "page.html" as the requested resource from the server. The third parameter indicates whether the request is performed synchronously in case it is false, or asynchronously if it is true. Finally, the send method made the request. Its parameter indicates the data to be sent to the server. Here it is set to null as we made a GET request.
var request = new XMLHttpRequest();
request.open("GET", "page.html", true);
request.onreadystatechange = function() {
 if (request.readyState == 4)
When response is received from the server:
  • resposeText: contains the content of the server response, if it is in XML then it could be retrived as DOM from responseXML.
  • getAllResponseHeaders(): returns all headers of the response
  • getResponseHeader("Date"): returns value of the corresponding header, here Date.
  • setRequestHeader(key, value): can be used to set the value of a header for the current HTTP request.
  • status property contains the response code 200 for OK, 404 for resource doesn't exist, 300 for redirection.
  • statusText contains a description of the returned response code.
  • readyState used in the asynchronous case to indicate the state of the request: 0 'uninitialized' is the state before calling open(), calling open() moves it to 1 'open', calling send moves it to 2 'sent', a server response moves it to 3 'receiving', at the end the state become 4 'loaded'.
  • onreadystatechange is used to set a callback function that will be called when the state property of the request changes.
A JSON string can be converted to a JSON object with the eval function:
var json_obj = eval("(" + json_txt + ")");
The parenthesis are added to avoid interpreting the text as a block of code as it is enclosed by braces.

The document.body.linkBack property allows to set to the previously visited page.

Basic JavaScript - Browser Events

This post corresponds to notes taken while reading Eloquent JavaScript.

Event handling is a powerfull tool that allows to execute some interesting actions after the occurrence of a given events. As JavaScript is single-threaded, only one event can be handled at time.
If no actions is registered for an event then this one is bubbled through the DOM tree. For example, if a user clik on a link and no event handler is registered for this then the event will be forwarded to the link parent (e.g. paragraph element) until document.body.
For handling events, someone should:
  1. Register an event handler by setting an element's onclick (or onkeypress, etc.) property. If someone need more than one handler then use addEventListener function. This later needs boolean parameter to indicate event 'bubble' through the DOM tree as normal when false.
  2. Get the event object than can be passed to the handler as a local variable 'event' or stored in the top-level variable window.event. This code event || window.event can be used to get the event object.
  3. Extract information from the event object such as the source element that can be find in the srcElement or target event property, also the precise corrdinates of a click are available in clientX and clientY properties. pageX and pageY properties are usefull when the document is scrolled, document.body.scrollLeft and document.body.scrollTop tells how many in pixels the document has been scrolled.
  4. Signal the event handling.
// register a handler for 'onclick' event
$('button').onclick = function() {console.log("Click !");};

$('button').addEventListener("click", function() {console.log("Click !");}, false);

// unregister a handler for 'onclick' event
$('button').removeEventListener("click", function() {console.log("Click !");}, false);
 Example of common events that can be registered for:
  • load is a window event that fires when the document is fully loaded.
  • onunload fires when leaving a page
  • click/dbclick fires when user click or double click on an element
  • mousedown, mouseup
  • mousemove fires whenever the mouse moves while it is over a given element.
  • mouseover and mouseout fires when the mouse enters or leaves a node/element.
  • focus and blur are fired on elements that can be focused (e.g. input) when the element has focus or the focus leaves the element.
  • change is fired when the node content changed (e.g. input).
  • submit is a form event fired when the form is submitted.
  • resize fired when window is resized.
The target or srcElement property points to which node the event is fired for, while relatedTarget or toElement or fromElement property gives which node the mouse came from.

Key related events:
  • keydown and keyup are used when someone is interested in which key was pressed (e.g. arrow keys).
  • keypress to be used when someone interested in the typed character.
The event property keyCode/charCode tells the code to identify the key (for mouseup) or character (for keypress). String.fromCharCode can be used to convert the charCode to a string. The properties shiftKey, ctrlKey and altKey tells whether the shift, control or alt key were held during the key/mouse event.

To control event bubble use stopPropagation (or 'cancelBubble' in IE) property.

mercredi 22 août 2012

Basic JavaScript - Document-Object Model (DOM)

This post corresponds to notes taken while reading Eloquent JavaScript.

HTML tags are organized in a tree object called DOM in order to be accessible from JavaScript code. The links in the tree are properties of node:
  • parentNode property refers to the object container of the current node
  • childNodes property refers to a pseudo-array that stores the children of the node
  • firstChild and lastChild refers to the first and last child, or null where there are no children.
  • nextSibling and previousSibling refers to the nodes sitting next or before the current node, these nodes have same parent node as the current one.
There are two types of nodes: HTML tags and simple text. Node type can be found by checking the nodeType property which may has different values:
- 1 for regular nodes
- 3 for text nodes
- 9 for document object
function isTextNode(node) {
 return node.nodeType == 3;
Regular nodes have the nodeName property (which is always capitalized, e.g. "IMG") to store the HTML tag type, while text nodes have the nodeValue that contains the text content.

The innerHTML property gives the HTML text inside the node without the node tag, while the outerHTML property (supported by some browsers) include the node itself.
document.body.firstChild.innerHTML = "bla bla";
An alternative to access a node via tree traversal is to use the document object property getElementById and indicating the node identifier (value of the 'id' attribute), or call it directly with $. In addition, all DOM nodes have the getElementsByTagName property that returns an array of all nodes with a given tag name.
var picture1 = document.getElementById("picture1");
var picture2 = $("picture2");
Nodes can be created dynamically thanks to the document methods createElement to create regular node and createTextNode to create text node. All nodes have an appendChild method to add an element to a node. To insert a node before another one use the parent insertBefore mehod. To replace a node with another one or remove it from its parent use replaceChild and removeChild methods.
var secondHeader = document.createElement("H1");
var secondTitle = document.createTextNode("Chapter 2: Deep magic");
New attributes can be added to a node by using its method setAttribute or directly as a node property. Node's attribute can be accessedd as a property of the DOM node or via getAttribute.
var newImage = document.createElement("IMG");
newImange.setAttribute("src", "img/Alto.png");
The style property refers to the CSS style object of a node. Example:
$("picture").style.borderColor = "green";
$("picture").style.display = "none";
$("picture").style.position = "absolute";
$("picture").style.width = "400px";
$("picture").style.height = "200px";

Basic JavaScript - Web programming

This post corresponds to notes taken while reading Eloquent JavaScript.

The open method of the window object takes an URL argument that will open on a new window. An opened window can be closed with its close method. To escape unwanted characters in the URL (e.g. space), the encodeURIComponent method can be used. To remove them again use decodeURIComponent method.
Every window object has a document property that contains the document shown in that window. To force the browser to load another document, someone can set the document.location.href property.
var perry = window.open("http://www.pbfcomics.com");
// show some information about the URL of the document
// encoding URL
var encoded = encodeURIComponent("aztec empire");
The document object has a property named forms which contains links to all the forms in the document. Example, if a form has a property name="userinfo" then it can be accessed as a propery named userinfo.
The object for the form tag has a property elements that refers to an object containing the fields of the form by their name.
var userForm = document.forms.userinfo;
// set the content (via the value property) of a text input element called 'name'
var nameField = userForm.elements.name;
nameField.value = "Eugène";

mardi 21 août 2012

HTML5 WebSocket API

One of the new features coming with HTML5 is the WebSocket API that provides a full-duplex communication channel through a single socket over the web. This piece of technology eables ease of integration of asynchronous/real-time features to web applications.
Before being able to use (send and receive) this API, the WebSocket client should initiate a handshake with the WebSocket server by creating a new WebSocket object and providing the server URL with ws:// or wss:// prefix to indicate WebSocket or a secure WebScoket connection.

At the client side, the WebSocket interface consists of the following methods:
  • onopen(event) called when the connection is successfully opened
  • onmessage(event) called when a message is received from the remote endpoint 
  • onclose(event) called when the connection is closed by the remote endpoint 
  • send(message) used to send data 
  • close() used to close an opened connection
//Checking for browser support
if(window.WebSocket) {
 Alert("WebSocket is supported by your web browser.");
 // create a new WebSocket object to connect to the server
 var url = "ws://localhost:8080/echo";
 var ws = new WebSocket(url);
 // Adding liseners for connection opened, message received and connection closing events
 ws.onopen = function() {
  log("connection opened");
  // sending a message
  ws.send("thank you for accepting this websocket request");
 ws.onmessage = function(e) {
  log("received message: "+e.data);
 ws.onclose = function(e) {
  log("connection closed");
}else {
 Alert("WebSocket is not supported by your web browser.");

There are many server-side implementations for WebSocket, here is few ones:
  • Netty a Java network framework that includes WebSocket support
  • Jetty Application Server provides a support for WebSocket
  • Node.js multiple WebSocket server implementations for this server-side JavaScript framework.

Next are the steps that should be followed to embed jetty and use it as a WebSocket Server: first, use tomcat as an application server. Second, add jetty jars to a Dynamic Web Application project. Third, implement a ServletContextListener and declare it into the web.xml file to listen to the web applicaion start-up event to launch the WebSocket server and to shut it down at application destruction. Fourth, Create a handler that implements the server-side of the WebSocket API (which is similar to the client-side) to deal with exchanged messages of the websocket protocol.

Jetty provides multiple interfaces for the WebSocket API that may be used for different purposes, org.eclipse.jetty.websocket.WebSocket is an example of an implementation of WebSocket for exchaging strings.

Here is a code snaphot for starting a jetty-based WebSocket server:
// 1) Create a Jetty server with the 8091 port.
Server server = new Server(8081);
// 2) Register SingalingWebSocketHandler in the Jetty server instance.
MyWebSocketHandler wsHandler = new MyWebSocketHandler();
wsHandler.setHandler(new DefaultHandler());
// 2) Start the Jetty server.

To shutdown the WebSocket server:
A complete example of how using WebSocket API can be found here.