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


Wednesday, March 27, 2013

ASP.NET MVC Context

HttpContext encapsulates all HTTP-specific information about an individual HTTP request. HttpContext resides in System.Web namespace which contains classes and interfaces for browser-server communication. HttpContext also implements IServiceProvider interface. You can access current context using HttpContext.Current property. 

Web API doesn't directly include HttpContext because REST API supposed to be completly stateless (other than cookies and other client-side state) but you can access it like in this example

Difference between System.Web.HttpContext.Current and Controller.Context (HttpContext vs. HttpContextBase) (link)
  • Both are usually identical
  • The type of HttpContext.Current is also HttpContext
  • The type of Controller.Context is HttpContextBase
  • Both implements IServiceProvider interface
  • When working on additional threads, System.Web.HttpContext.Current is threadstatic
    • Threadstatic means value is tied to the thread. In any additional thread, you cannot access HttpContext.Current
  • The context provided by the controller is mockable (for unit testing)
  • You can access System.Web.HttpContext.Current from any code inside the same application domain. But be careful to separate the layers
    • If you have a layered architecture its fine to access context from within web project but it is not a good practice to access it from a class library project (the project in which you keep your business logic).
  • In ASP.NET HttpApplication has a reference to HttpContext through its Context property. in ASP.NET MVC Controller class has Context property of type HttpContextBase. 
  • The idea behind introducing HttpContextBase abstract away dependencies to allow unit testing because HttpContextBase is an abstract class. (link)
  • Why HttpContext not derive from HttpContextBase (another link)
You can get HttpContext from HttpContextBase via.

HttpContext context = httpContextBase.ApplicationInstance.Context

Getting HttpContextBase from HttpContext

HttpContextBase abstractContext = new System.Web.HttpContextWrapper(context);
source (link1link2

Getting the HttpContext current inside ASP.NET MVC action (link)
Use System.Web.HttpContext.Current or this.HttpContext.ApplicationInstance.Context


Wednesday, February 6, 2013

ASP.NET Caching Complete Reference

One of the core concepts in web development is caching. Understanding why we need caching is important before digging into them.

Caching helps you to reduce traffic to web server by storing some of the 'data' website requires by storing it in some form of memory, than web server serving consequent requests for the same website from that client. This will reduce the web server from redoing everything for each and every request thereby improving the performance.

Caching can be roughly divided into
  • Output caching
  • Application state
  • Cache class
  • Static member variables

Output caching


Output caching has been available since first version of ASP.NET and is also available in ASP.NET MVC as an attribute. 

In ASP.NET you can add a outputcache directive for aspx page. (see example) then for the specified duration of the output cache duration setting the page will be cached.

In MVC you can decorate a action or a whole controller with outputCache attribute. (asp.net). 

Above what we have done is application output caching. There's another concept called proxy output caching. (Article includes good practical example of the usage)

Output Caching is extensible. You can use custom output cache providers. Usually these Custom providers derives from OutputCacheProvider type. You can do the required configurations in Web.config.

Application state 

You can store application level variables Application property of HttpContext. (link)

Cache class

Use cache class to to cache data in a ASP.NET Web application (for other types of applications you can use Memory Cache) sources: Object cache, Object caching 

Static Member variables

Use Static members to store application level attributes which do not change

Saturday, January 26, 2013

Execution Sequence of Entity Framework

When talking about Entity Framework its important to understand the operations happening,

Loading metadata
Happens only once in each application domain. Model and mapping metadata used by EF is loaded into MetadataWorkspace.

Opening the database connection
EF opens and closes database connection as needed. 

Generating views
This is usually a costly operation

Preparing the query

Executing the query

Loading and validating types

Tracking



Materializing the objects

Monday, January 14, 2013

Tuesday, January 1, 2013

Functional and Non Functional Requirements



Basically functional requirement is something specific the system should do. Functional requirement of a system could be,
  • Business rules
  • Administrative functions
  • Authentication and Authorization
  • Reporting
On the other hand non functional requirement describes how system works or how the system should behave. These can be,
  • Performance
  • Scalability
  • Capacity
  • Availability
  • Maintainability
  • Security 
  • Usability etc. 
Non functional requirements can be identified as quality attributes of a system. Non functional requirements are defined in terms of metrics (something that can be measured about the system).

Resources
http://reqtest.com/requirements-blog/functional-vs-non-functional-requirements/#conversion-0
http://stackoverflow.com/questions/16475979/what-is-functional-and-non-functional-requirement

image credit : http://www.steffen-zschaler.de/bibliographies/nfp/sommerville.png

Monday, December 31, 2012

Saturday, December 29, 2012

What you need to know about performance in Entity Framework


http://msdn.microsoft.com/en-us/data/hh949853.aspx 

Mapping Views
Mapping views are set of SQL statements that represents the database in an abstract way, which are also part of the metadata.
link1, link2

Query execution
Deferred vs. Immediate execution
Client side execution of LINQ queries
Query and mapping complexity
Mapping complexity
Query complexity
Relationships
Query paths
Saving changes
Distributed Transactions


Strategies for Performance improvement

Pre-generate views
Consider using NoTracking merge option for queries
Return the correct amount of data
Limit the scope of ObjectContext
Consider opening db connection manually.

Extra

  • In EF its best to understand how query execution happens 
  • Data Source is the one which provides connection pooling facility. Not the Entity Framework. The .NET provider for SQL Server provides support for Connection Pooling
  • In previous versions of EF (before 6) there was a performance problem when using Contains. This has been fixed now.

https://msdn.microsoft.com/en-us/data/hh949853.aspx
http://www.asp.net/web-forms/overview/older-versions-getting-started/continuing-with-ef/maximizing-performance-with-the-entity-framework-in-an-asp-net-web-application


http://www.asp.net/whitepapers/aspnet-data-access-content-map#gettingstarted


Saturday, December 8, 2012

Stuff you need to know about JavaScript

JavaScript has lot of concepts around it. There are things that you might miss out. Lets see some of them.

  • In JavaScript there are some variables starting as __ (__defineGetter, __defineSetter, __proto__). These are variables defined by the browser and are not defined by ECMAScript #convention (link2)
  •  Best practice to define libraries is to define one global variable (google, jquery) and define all your methods/variables within the scope of that object
  • JavaScript curry
  • Adding custom headers to JQuery AJAX request
  • Browser closing events
    • http://stackoverflow.com/questions/1119289/how-to-show-the-are-you-sure-you-want-to-navigate-away-from-this-page-when-ch
    • http://stackoverflow.com/questions/2076299/how-to-close-current-tab-in-a-browser-window
  • http://stackoverflow.com/questions/4869613/solutions-for-distributing-html5-applications-as-desktop-applications

Scope and Context in JavaScript

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