Tuesday, October 22, 2013

Introduction to AngularJS

AngularJS is a pure JavaScript framework. It extends HTML attributes with Directives known as ng-directives. A very basic angular application looks like below,



Here we define the ng-app in which the angular code resides. We add ng-model directive to input for data binding and show it in curly brackets in mustache style in next line. (We usually define a model nested inside a controller. Since we have not done that here it resides in $rootScope). We'll look at some useful things comes in AngularJS next.

Directives (documentation)

These are markers on a DOM element that tells AngularJS's HTML Compiler ($compile) to attach specific behavior to that DOM element. Below are some directives which comes with AngularJS. There are quite a lot of directives comes with the library. You can also create custom directives.
  • ng-app : defines AngularJS application
  • ng-model : binds the value of HTML controls (input, select, textarea) to a property on the scope. 
    • Binds view to a model
    • Provides validation behavior
  • ng-bind : binds application data to HTML view. Tells angular to replace text content inside a HTML element with expression's value
Model Binding (ng-model)
This directive binds an form element to a property on the scope using NgModelController, which is created and exposed by this directive. 

Module

You can configure your module using this.
Constants in AngularJS. You can inject constants to a module.

Dependency Injection
https://docs.angularjs.org/guide/di

Controllers

AngularJS applications are controlled by controllers. Look at the below example,
\
Above MyApp is the name we gave  to the ng-app attribute. We define the controller (SubController) and put it inside the module. After that we can reference it from the DOM. Without adding the controller into the module, we can also keep it global and reference from DOM. but it is not a good practice. Controllers should not have any logic.  


Services

Service is a component that does a specific job like logging, timer etc. Services are wired using Dependency Injection. Services in AngularJS are,
  • Lazily initialized : Instantiated only when a component depends on it
  • Singleton: Components depends on the services gets a reference to the single instance of the service through a factory
To use a service you should add a dependency to that from your controller, service etc. Developers can also create there own custom services.

AngularJS provides services like $route, $window, $location etc. 

Factory

You can create service using Factory as well. Factory and Services are kind of same.

Application Structure and Code organizing

AngularJS projects can be structured in many different ways. Each carries there own pros and cons. It solely depends on what is your requirements are. Following are some useful articles for you to make the decision.  

http://stackoverflow.com/questions/17461242/angularjs-application-file-structure
http://cliffmeyers.com/blog/2013/4/21/code-organization-angularjs-javascript

Angular 1.4 and 2.0

Angular 2.0 is the rewritten version of Angular optimized for mobile and future browsers. It's yet to be released but you can take a look from https://angular.io/. See whats new in Angular 2.0 and this.

AngularJS 1.4 and 2.0 can exist within the same project. See how to do it.

Authentication

https://medium.com/opinionated-angularjs/techniques-for-authentication-in-angularjs-applications-7bbf0346acec

The calling order of AngularJS application (link)
  • app.config
  • app.run
    • you can use run block for authentication
  • directive's compile functions
  • app.controllers()
  • directive's link functions

Tips and Tricks

http://demisx.github.io/angularjs/2014/09/14/angular-what-goes-where.html
https://github.com/johnpapa/angular-styleguide

Resources

Saturday, October 12, 2013

HTML5 WebSockets

WebSockets is the next generation bi-directional communication technology for web applications. This operates over a single socket and is exposed via a JavaScript interface. 


var Socket = new WebSocket(url, [protocal] );



The socket starts out as a HTTP request and updates to TCP socket after a HTTP handshake. After that either can receive data. 



Is a real time messaging system build using WebSockets. This is implemented using Node.js. 


Check this getting started guide

Thursday, October 10, 2013

Structural elements in HTML5



<header>

Specifies a header for a document or a section. Can have several header elements for a page. You cannot place header tag within a footer, address or another header

<footer>

Just like header defines a footer for a document or a section. It typically contains author of the document, copyright information etc. You can have several footers

<article>

Specifies a independent, self-contained content. It should make sense of its own. You can typically use article element for Forum posts, blog posts, comments etc.

<aside>

Defines some content aside from the content it is placed in. It should be related to the surrounding content.  Appears in a side

<nav>

Defines a set of navigational links. Not all links of a document should be inside a <nav> element. It is intended only for major block of navigational links (such as menu). Screen readers for disabled can use this element  to determine whether to omit the rendering of this content.

<section>

Defines sections in a document, such as chapters, headers, footers. It's like a div. 

Above I listed basic info about some of the html5 elements. You might be asking yourselves why use html5 elements instead of <div>? These are included in html5 as for the move towards semantic web. Semantic web helps programmers understand the DOM structure better and also allows search engines to have a clear picture about the web page. It also helps screen readers to better parse the content as per there needs.

Media Controls in HTML5

To make our lives easier HTML5 introduced better media support via. <audio> and <video> elements.

You can embed videos in your page using following codes

<video src="http://v2v.cc/~j/theora_testsuite/320x240.ogg" controls>
  Your browser does not support the <code>video</code> element.
</video>


You can embed several video sources, browser will choose the most suitable one. Below are some attribute you can use with video.

  • autoplay - boolean attribute ; If specified it will automatically begin to play before loading fully.
  • controls - If present, Gecko will offer controls
  • src - URL of the video to embed. This is optional. You can instead use <source> element within video block to specify video to embed
  • height and width is also available
HTML5 Player with Controls

 Like videos you can also add audio to your web page. 

<audio src="/test/audio.ogg">
<p>Your browser does not support the audio element.</p>
</audio>

The src attribute can be a URL or a path to the audio file on local system. 
  • controls - Display standard HTML5 controls 
  • autoplay - Make the audio play automatically
  • loop - Make audio repeat (loop) automatically
  • preload - for buffering large files
    • "none" does not buffer the file
    • "auto" buffer the file
    • "metadata" buffer only the metadata for the file
In both video and audio multiple sources can be specified using <source> element to provide different formats

<video controls>
  <source src="foo.ogg" type="video/ogg">
  <source src="foo.mp4" type="video/mp4">
  Your browser does not support the <code>video</code> element.
</video>

You can also specify the codecs the media file requires. 
<video controls>
  <source src="foo.ogg" type="video/ogg; codecs=dirac, speex">
  Your browser does not support the <code>video</code> element.
</video>
 
You can also control the media element from after getting it using a selector.

var v = document.getElementsByTagName("video")[0];
v.play();
 
source 

Saturday, October 5, 2013

Design patterns for cloud


Strangler pattern

Incrementally developing a newer system replacing the old system. Parts of the old system is replaced with features in new system eventually replacing the complete system. This pattern is mainly helpful for backend systems (API).


Federated Identity Pattern

Delegate authentication to an external identity provider. Simplify the development, minimizes requirements for user administration. 

Cache-Aside pattern
Load data on demand to a cache. Can improve performance.



Monday, September 9, 2013

Introduction to Web API

HTTP is not just for serving up web pages. It is also a powerful platform for building APIs that expose services and data. ASP.NET Web API is a framework for building web APIs on top of the .NET Framework. In general, you don't need to know ASP.NET MVC to use Web API.

See this nice poster http://www.asp.net/media/4071077/aspnet-web-api-poster.pdf

Unlike Controllers which inherits Controller base class, Web API controllers inherits ApiController class. You should use Web API if you're creating an API which exposes data. Use Controllers if you're writing HTML based application. (Difference between ApiController and Controller)

Web API Controller actions
Web controller action can return - (See more at asp.net)
  • void (returns 204 - No content)
  • HttpResponseMessage : returns Http Response. 
  • IHttpActionResult : introduced in Web API 2. Simplifies unit testing
  • Other types : Web API uses media formatter
Web API vs WCF (MSDN and SO)

  • Web API supports only HTTP. 
    • WCF Supports multiple  transports (HTTP, TCP, UDP)
  • Web API supports wide variety of media types (XML, JSON)
    • WCF supports multiple encoding types (Text, MTOM, Binary)
  • Web API supports HTTP, Web Sockets, SSL etc. 
    • WCF supports building services using WS-* standards


Routing (web-api-routing-and-actions)
Web API routing is similar to MVC routing. The main difference is Web API uses HTTP method, not URI path to select actions.

Here's a good article from asp.net about creating a RESTful API

Resources

Saturday, August 24, 2013

Control flow in KnockoutJS

foreach binding

duplicates section of markup for each entry in an array. Binds each copy of that markup to array item. You can nest foreach binding with other control-flow bindings such as if and with.

You can use special context property $data, to refer the current array item itself.

You can also use $index to refer the index of current array element. $index is an observable. Similarly you can use $parent to refer to data outside foreach.

Use as option to create alias for the array elements. 

In scenarios like in middle of a list, you can't use foreach binding as above, in such a case you can use containerless control flow syntax which is based on comment tags. 

Note : Destroyed entries are hidden by default. but you can set includeDestroyed option in foreach loop to make them visible. 

if binding

show/hide section of markup based on a condition. This is similar to visible binding.

with binding

Creates a new binding context. Descendent elements are bound in the context of a specified object. with can be used without a container element as well. 

Introduction to KnockoutJS

KnockoutJS is a JavaScript library of MVVM pattern with templates. It does not depend on jQuery. 

With KnockoutJS you can have,

  • Dependency tracking : Automatically update UI when model changes
  • Declarative bindings: Connect parts of your UI to your data model
  • Extensible: Implement custom behaviors

What is MVVM pattern

  • Model : objects and operations in your business domain, this is independent from the UI
  • View Model : Pure code representation of data and operations on a UI. No HTML
  • View: Interactive UI. Representing the state of the ViewModel
Here's a simple example of using KnockoutJS


To achieve two way binding you can use observables. When using observables when you update something in View, changes will be reflected in ViewModel as well.


Explicit subscribing

Used to get notifications when subscribed observable gets changed. You can assign the subscription to a variable and dispose it later.

You can force observables to notify subscribers always by using  
myViewModel.personName.extend({ notify: 'always' });

You can delay change notification by using 
myViewModel.personName.extend({ rateLimit: 50 });

 

Observable Arrays

Just like Observables but for arrays. Observable arrays only track which objects are in the array. Not the state of those objects. Observable array is actually an observable whose value is an array (with some additional methods). Check the documentation for other methods available. For the array also you can delay change notifications like for observables.

 

Computed observables (documentation)

functions that dependent on one or more other observables. Will automatically update when dependencies changes. You can also create writable observables. You can extend this by using rateLimit and notify attributes. 

See complete reference from documentation here


Writable computed observables (documentation

//see the documentation

Pure computed observables (documentation)

This was introduced in 3.2V. Use this if your computed do some calculation and simply returns a value. Here the evaluator does not modify other objects state).

This provides performance and memory benefits. Doesn't maintain subscriptions to its dependencies when it has no subscribers itself.


KnockoutJS - EcmaScript 5 Plugin


http://blog.stevensanderson.com/2013/05/20/knockout-es5-a-plugin-to-simplify-your-syntax/
https://github.com/SteveSanderson/knockout-es5

Friday, August 23, 2013

Using Canvas and SVG in HTML5

Canvas

<canvas> element is used to draw graphics using JavaScript. <canvas> element is only a container to hold the graphics. You must script it to draw the actual graphic.

A canvas is a rectangular area on an HTML page. 

<canvas id="myCanvas" width="200" height="100"

style="border:1px solid #000000;"> </canvas>

Using JavaScript you can manipulate the canvas


var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.fillStyle = "#FF0000";
ctx.fillRect(0,0,150,75); 


svg

SVG stands for Scalable vector graphics. They are used to define vector-based graphics for web. SVG defines the graphics in XML format. 

SVG images can be created and edited using any text editor and they can be searched, indexed. SVG images are scalable so it can be printed in high quality at any resolution. 

<svg width="300" height="200">

  <polygon points="100,10 40,198 190,78 10,78 160,198"

  style="fill:lime;stroke:purple;stroke-width:5;fill-rule:evenodd;" />
</svg>

You now see that in HTML5 graphics there are 2 ways you can go with either Canvas or SVG. comparison between these 2 will be good in understanding which is better

Monday, August 19, 2013

Bindings in KnockoutJS

Visible binding #

Make associate DOM element hidden or visible. Sets yourElement.style.display as none. 


Text binding #

Display associated text value on DOM. Since the binding sets your text value using a text node, its safe to set any string value without risking HTML or script injection. 


HTML binding #

KO sets element's innerHTML property to your parameter value. Don't use this with untrusted model value due to possible script injection attack. 

CSS Binding #

adds or removes one or more named CSS classes to the associated DOM element. 


Styling Binding #

Directly bind CSS styles


Attr Binding #

provides a generic way to set the values of any attribute for the associated DOM element

Saturday, August 17, 2013

Form field bindings in KnockoutJS

the article is incomplete


click binding



When calling your handler, Knockout will supply the current model value as the first parameter. 

Accessing the event object, passing more parameters
Allowing default click action
Preventing the event from bubbling

event binding



 



Saturday, August 10, 2013

Template binding in KnockoutJS

Template binding populates the associated DOM element with the results of a rendering a template. It’s a good way to build UI structures.

    <div data-bind="template: { name:'person-template', data: buyer }">
    </div>

    <script type="text/html" id="person-template">
        <h3 data-bind="text: name"></h3>
    </script>

    <script type="text/javascript">
        var vm = {
            buyer: {
                name: 'Peter'
            },
            seller: {
                name: 'Jason'
            }
        };

        ko.applyBindings(vm);


    </script>

Native templating: underpins foreach, if, with and other control flow bindings. These will capture the HTML markup contained in your element and use it as a template to render against arbitrary data item. This is built into KO.

String based templating: way to connect KO to 3rd party templating engines. KO will pass your model values to external template engine and inject the resulting markup string into document.

Notes:
Avoid combining other bindings with template binding, especially under data-heavy scenarios. Knockout uses one computed observable to track all bindings of an element.

See Ryan's article here

Parameters
Main parameter: Shorthand syntax: if you just supply a string value, KO will interpret this as the ID of a template to render.


For more control, pass a JavaScript object with some combination of the following properties

Rendering a named template
Normally when using control flow bindings, there’s no need to give names to your template. But if you want you can factor out template in to separate element and reference them by name.

Resources
http://www.strathweb.com/2012/08/knockout-js-pro-tips-working-with-templates/
http://aboutcode.net/2012/11/15/twitter-bootstrap-modals-and-knockoutjs.html

Powered by Blogger.


Software Architect at Surge Global/ Certified Scrum Master

Experienced in Product Design, Software Engineering, Team management and Practicing Agile methodologies.

Search This Blog

Facebook