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

Saturday, July 27, 2013

How SignalR Works

SignalR is a library which can add realtime web functionality to applications. It provides a simple API for creating server to client RPC, that call JavaScript functions from server side .NET code.SignalR handles connection management automatically. It also has a API for this.

SignalR is an abstraction over a connection. It gives you 2 programming models over the connection (Hub and Persistent Connection). 

SignalR applications can scale out to thousands of clients using Service BUS, SQL Server or Redis. 

Supported transports by SignalR

SignalR connection starts as HTTP, and is then promoted to WebSocket connection if it is available. If WebSocket is not available it falls back to older transports.

HTML5 Transports
  • WebSocket
This is the ideal technology for SignalR because it uses server memory efficiently. It has the lowest latency and full duplex communication between client and server. But WebSocket requires Windows Server 2012 or Windows 8 and .NET framework 4.5. 

Basically to use WebSocket both client and server should support WebSocket.
  • Server Sent Events
Also known as EventSource. Does not support in IE. :-(

Comet Transports
Here browser or other client maintains a long-held HTTP request, which server can use to push data to client without client specifically requesting it. 
  • Forever Frame
For IE only. Creates a hidden IFrame which makes a request to an endpoint on server which does not complete. 

The server then continually sends script to the client which immediately executed, which provides one way real time connection from server to client. The connections server to client and client to server uses separate connections. A new connection is created for each piece of data that needs to be sent.
  • Ajax Long Polling
Does not create a persistent connection, instead polls the server with a request that stays open until the server responds, at which time the connection closes. and a new connection is established(requested) automatically. This may introduce some latency when connection gets resets


You can enable logging for hub's events in a browser using $.connection.hub.logging = true; command. 

If the client capabilities are known, transport can be specified when client connection is started using connection.start({ transport: 'longPolling' }); command. you can also specify fallback order like connection.start({ transport: ['webSockets','longPolling'] });

Connections and Hubs

SignalR has PersistentConnection and Hub connections. Persistent connection API provides direct access to low level communication protocols. A Hub is a more high level pipeline built on top of Connection API. 

Using Hubs also allows you to pass strongly typed parameters to methods, enabling model binding.

Self Hosting SignalR applications
Hosting SignalR is not restricted to IIS. Using SignalR Self Host library which is built on OWIN you can host SignalR on Console applications and Windows services. Check this article.

In the ASP.NET SignalR space there are lot of articles you can look into.


Here we limit client and server to a limited no. of times to be communicated (e.g: 25 times per second)




Resources:

Wednesday, July 17, 2013

Getting the most out of Global.asax

Global.asax is a class derived from HttpApplication class. This file is also called ASP.NET application file. Global.asax is responsible for handling application level events raised by ASP.NET and HTTPModules. This file is optional if you haven't created it, ASP.NET assumes you have not defined any application or session event handlers.

During the lifetime of your application, ASP.NET maintains pool of Global.asax derived HttpApplication instances. When the application receives an HTTP request, ASP.NET page framework assigns one of these HttpApplication instances to process the request. That instance is responsible for managing the request throughout its lifetime. When you see many number of requests coming to the application, many instances of HttpApplication instances is expected

Inside Global.asax file there are many methods you can use to make your lives easier when developing ASP.NET applications. This article will look at some of the methods you can use in your web applications.

ASP.NET automatically binds application events to handlers in Global.asax using 'Application_event' naming convention. (How to ASP.NET Application_Events Work - Rick Strahl and SO Question).

Before digging into Global.asax file you must understand the sequence of how each method is called. Below diagram extracted from stackoverflow shows the sequence.


Global.asax event sequence

Application_Start and Init (source)
Application_Start is a special method which doesn't represent HttpApplication events (Also Application_End). ASP.NET calls them once for the lifetime of the application, not for each HttpApplication instance. On the other hand, Init is called once for every instance of HttpApplication after all modules have been created.

Application_End
Application_End will fire when IIS Pool is recycled or the application is unloaded. (If a dependent file such as web.config gets changed, application will reload).

PreSendRequestHeaders (link)
Occurs just before ASP.NET sends HTTP headers to the client. 

BeginRequest
First event of the HTTP pipeline chain of execution when ASP.NET responds to a request

EndRequest
Occurs as the last event 

Error handling
Resources You can handle application errors inside Application_Error method


Accessing Session Data inside Global.asax
http://stackoverflow.com/questions/765054/whens-the-earliest-i-can-access-some-session-data-in-global-asax
http://stackoverflow.com/questions/5977285/set-session-variable-in-application-beginrequest?lq=1

Access Global.asax properties some outside (SO)
 
Resources
MSDN, TechRepublic, Application life cycle for IIS 5.0 and IIS 6.0, Application life cycle for IIS 7.0
Check Create Custom HTTP Modules

Saturday, July 6, 2013

Database Indexes

Database index is a data-structure which improves retrieval of data from database tables. Indexes are used to quickly locate data without having to go through every row in database table. 

Source : kindleyourbrain
If you create an index it'll create a data-structure with the field value in which you created the index and a pointer to the record in the original table.The values in an index is sorted.

The downside of creating indexes is it requires additional disk space. Also when you have many indexes data writing will be bit slower because you need add a record to index data structures as well.

You can use indexes to tune performance of the database. See how to work with SQL Server Indexes here

Check below video to learn more about indexes. Also you check database indexes videos in Youtube.

Clustered vs NonClustered indexes

A clustered index is a special kind of index means you're telling the database to store similar values close to one another on the disk. This is the reason why you can have only one clustered index for a table. This has the benefit of rapid retrieval of records. By default a column with a primary key already has a clustered index.

Index must knows
https://www.simple-talk.com/sql/performance/14-sql-server-indexing-questions-you-were-too-shy-to-ask/

You can have many nonclustered indexes.



Resources

Thursday, July 4, 2013

Storage options in HTML5

 This document is in draft version   

In this article we'll look into storage options available for HTML5. 

Web storage

  • Store data locally within user's browser. Earlier this was done using cookies. 
  • But Web Storage is secure and much faster. 
  • The data is not included with each server request. 
  • Possible to store large amounts of data without affecting site performance
  • Stored in key-value pairs
localStorage object stores the data with no expiration date. 

// Store
localStorage.setItem("lastname", "Smith");
// Retrieve
document.getElementById("result").innerHTML = localStorage.getItem("lastname"); 


sessionStorage object is like localStorage object but it stores data only for one session. The data will get deleted when user closes the browser window

if (sessionStorage.clickcount) {
    sessionStorage.clickcount = Number(sessionStorage.clickcount) + 1;
} else {
    sessionStorage.clickcount = 1;
}
document.getElementById("result").innerHTML = "You have clicked the button " +
sessionStorage.clickcount + " time(s) in this session.";
  

AppCache API

Cache the web application so that it is accessible without internet
  • Offline browsing - Use the application offline
  • Speed - Cached resources load faster
  • Reduced server load - Will only load updated/changed resources from server
AppCache API is supported from IE 10 onwards and other browsers. 

To enable app cache, you must include manifest attribute in documents <html> tag

 <!DOCTYPE HTML>
<html manifest="demo.appcache">
...
</html>


Every page with manifest attribute specified will be cached when the user visits it. The recommended file extension for manifest files is '.appcache'.

Geolocation API

Monday, April 22, 2013

Templating with Mustache JavaScript

Mustache can be used to deal with templating. Not only in JavaScript, Mustache is available for many languages including Nustache for .NET and mustache sharp for C#.

There are other client side templating options available, such as HandleBars an UnderscoreJS. 

Why use client side JavaScript templating?
http://www.smashingmagazine.com/2012/12/05/client-side-templating/
http://en.wikipedia.org/wiki/JavaScript_templating
https://www.google.lk/search?q=why%20use%20client%20side%20templating

Resources


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