Aug 17, 2014

Understanding Execution Plan

Cluster Index Scan
If there is no WHERE clause or it is on column which is not indexed, then SQL Server scans the entire table. If table has a Clustered Index it will do a Clustered Index Scan otherwise it will do a Table Scan.

Cluster Index Seek
If where clause is on cluster index then it will do cluster index seek.

Non Cluster Index Seek

CREATE NONCLUSTERED INDEX [IX_sku]
ON [dbo].[Products] ([sku])
GO

In following case SQL Server will ideally do Non Cluster Index Seek

SELECT ID, SKU FROM [dbo].[Products] WHERE SKU = '123456'

Non Cluster Index Seek and Key Lookup on the clustered index
If where clause is on non-cluster index column and you are selecting * or columns other than the column on which table has non-cluster and cluster index , then SQL Server first does Index Seek (nonclustered) and then do a key lookup (clustered). The other operation which happens is Nested Loops which joins results from Index Seek and the Key Lookup. Included columns should be columns that you don't search on, but will return.

SELECT ID, SKU,Description FROM [dbo].[Products] WHERE SKU = '123456'

You can improve performance in above scenario by Creating a Covering Index or by Creating an Index with Included Columns. This way SQL Server doesn't have to do Key Lookup.

CREATE NONCLUSTERED INDEX [IX_LastName]
ON [dbo].[Products] ([sku],[Description])

Joining on non-like datatypes frequently causes table scan even when indexes are present

2005 introduced Dynamic Management Views (DMVs) which can be used to see how sql server uses index. This can also be used for  Identifying Unused Indexes.

DMV - sys.dm_db_index_operational_stats


SELECT 
 OBJECT_NAME(A.[OBJECT_ID]) AS [OBJECT NAME], 
 I.[NAME] AS [INDEX NAME], 
 A.LEAF_INSERT_COUNT, 
 A.LEAF_UPDATE_COUNT, 
 A.LEAF_DELETE_COUNT 
FROM   
 SYS.DM_DB_INDEX_OPERATIONAL_STATS (db_id(),NULL,NULL,NULL ) A 
INNER JOIN SYS.INDEXES AS I ON 
 I.[OBJECT_ID] = A.[OBJECT_ID] 
    AND I.INDEX_ID = A.INDEX_ID 
WHERE  
 OBJECTPROPERTY(A.[OBJECT_ID],'IsUserTable') = 1
 AND OBJECT_NAME(A.[OBJECT_ID]) = 'Products'

SYS.DM_DB_INDEX_USAGE_STATS


SELECT 
 OBJECT_NAME(S.[OBJECT_ID]) AS [OBJECT NAME], 
 I.[NAME] AS [INDEX NAME], 
 USER_SEEKS, 
 USER_SCANS, 
 USER_LOOKUPS, 
 USER_UPDATES 
FROM   
 SYS.DM_DB_INDEX_USAGE_STATS AS S 
INNER JOIN 
 SYS.INDEXES AS I 
 ON I.[OBJECT_ID] = S.[OBJECT_ID] 
 AND I.INDEX_ID = S.INDEX_ID 
WHERE  
 OBJECTPROPERTY(S.[OBJECT_ID],'IsUserTable') = 1
    AND S.database_id = DB_ID() 
 AND OBJECT_NAME(S.[OBJECT_ID]) = 'Products'  

  • The seeks refer to how many times an index seek occurred for that index.  A seek is the fastest way to access the data, so this is good.
  • The scans refers to how many times an index scan occurred for that index.  A scan is when multiple rows of data had to be searched to find the data.  Scans are something you want to try to avoid.
  • The lookups refer to how many times the query required data to be pulled from the clustered index or the heap (does not have a clustered index).  Lookups are also something you want to try to avoid.
  • The updates refers to how many times the index was updated due to data changes which should correspond to the first query above.

To manually remove a single plan or all plans from the cache, use DBCC FREEPROCCACHE
Reference:
https://www.simple-talk.com/sql/learn-sql-server/sql-server-index-basics/

Aug 14, 2014

Agile Methodology - Scrum, Kanban

Scrum
  • In scrum you have small team working on list of small, concrete deliverables. You divide big organization into small cross-functional and self-organizing teams.
  • It has fixed length iteration (usually 2 – 4 weeks) at the end of which you have shippable code. 
  • Each items in the iteration (sprint) are estimated and team commits on finishing it by the end of sprint.
  • At the beginning of iteration team pulls out items from the product backlog, based on the product owner’s priorities and how much the team thinks they can complete in one iteration. 
  • After each iteration the process is optimized by having retrospective.
  • Since you working on a small thing which is part of a large group, you integrate regularly to see the whole.
  • Scrum prescribes three roles: Product Owner (sets product vision & priorities), Team (implements the product) and Scrum Master (removes impediments and provides process leadership).
  • Scrum resistance change within the iteration, which means you typically don't add new item in the middle of iteration as team is commited with items pulled in the sprint.
  • Scrum prescribes estimation and velocity(per iteration how much hour of work a team can complete).
  • Burndown chart prescribed 
Kanban
  • Kanban leaves almost everything open. The only constraints are visualize your workflow and limit your WIP.
  • Split the work into pieces, write each item on a card and put on the wall 
  • Use named columns to illustrate where each item is in the workflow. 
  • Limit work in progress ( WIP), this way proper flow to finish line is always maintained.
  • Measure the lead time which is average time to complete one item.
  • It does not prescribe any roles but that doesn't mean you shouldn't have. You are free to add role(Product Owner) which make sense to your project. In a big project Project Manager role may be great idea, perhaps that’s the guy who helps multiple teams & product owners synchronize with each other. In a small project that role might be waste, or worse, might lead to suboptimization and micromanagement. 
  • Kanban board doesn't need to be reset or start over.
  • In Kanban, cross-functional teams are optional, and a board doesn’t need to be owned by one specific team. A board is related to one workflow, not necessarily one team. 
  • In Kanban, estimation is not prescribed. Uses Lead time as default metric for planning and process improvement. 

Lean Principals
  • Fail Fast, Learn Rapidly
  • Planning and Commitment are two different thing. Plan thoroughly and commit sparingly.
  • Think Big (Look at the whole Value Stream), Act Small
  • There is no process which cannot be improved. Continuous Improvement is never-ending.
  • Designs evolve, so do not waste time locking it down early.
  • Release Early, Release Often
  • Predictions of the future are always going to be inaccurate, by locking down designs, processes, requirements, etc., we lose our ability to respond to the inevitable unpredictability. Change is inevitable!
  • Build quality from the start -- don't rely on testing it in later. The job of testing is to prevent defects not find defects
  • Specify the most important things and deliver them fast, then take the next most important things. And repeat. We do not know what we do not know, so it is not possible to define everything (and have it remain unchanged) up-front. 
  • Everything not adding value to the customer is waste - stop doing it
  • Don't equate speed with hacking. A fast moving development team must have excellent reflexes and a well-disciplined "Stop the Line" culture.
  • Treat each other as our Customer. Find good people and let them do their job.
  • When a defect is found-Stop the Line, Find the Cause, Fix it

Aug 11, 2014

Asynchronous vs Synchronous Method

ASP.Net processes a request (http) by using a thread from thread pool. The processing thread cannot service any other request if its being processed synchronously. This can eventually result in condition known as thread starvation. After this condition server starts queuing up the request and if the queue becomes full server starts rejecting request with 503 status code - Server Too Busy.

In IIS you can set Threads Per Processor Limit and the Queue Length (IIS->Web Server(Feature View)->ASP)

Example of how you can write async action in MVC/Web api

 public async Task Create(Product product)
 {
                .   
                .
                .
var response = await client.PostAsJsonAsync(uri, product);
                .
                .  
}
In the above example, code will be executed synchronously until it hits await key word. The await keyword registers rest of the method as a callback on the task and then it immediately return. This will free up the processing thread. When the awaited task completes, it will invoke that callback to resume the execution of the method.

This is mostly helpful for I/O bound operations. For I/O intensive activity thread tells kernel what I/O it wants done, after which it continues on, rather than sitting and waiting for response from kernel. When kernel is done with I/O it callback so that rest of the processing can be done.

On the hand if the operation is primarily CPU intensive using asynchronous action will not provide any benefits rather it will make things worse because of its overhead.



http://msdn.microsoft.com/en-us/library/hh873177(v=vs.110).aspx

Aug 9, 2014

Protecting your Mvc page from CSRF

Adding @Html.AntiForgeryToken() to a view does following
 
 sets __RequestVerificationToken Cookie
 add hidden input __RequestVerificationToken to the page

And then you can add attribute ValidateAntiForgeryToken to the HttpPost action which will validate __RequestVerificationToken between cookie and posted hidden input value. This helps defend against cross-site request forgery. If any of the values are missing or the values does not match (it has some encryption logic so if you try to compare, the value it will not looksame), it will throw HttpAntiForgeryException.


With the absence of attribute ValidateAntiForgeryToken, your site can be easily prone to csrf. Refer to following for a quick way to create this condition


<body>
    <form name="badform" method="post" action="http://localhost/product-ui/Product/Create">
        <input type="hidden" name="sku" value="1234" />
        <input type="hidden" name="overview" value="something...." />
    </form>
    <script type="text/javascript">
        document.badform.submit();
    </script>
</body>

Jun 10, 2014

Cookie

Cookie is a small piece of data sent from a server and stored in the browser. Browser sends cookie back with each subsequent request based on set of rules. Few of the common examples

ASP.NET_SessionId is a cookie that ASP.NET uses to store a unique identifier for your session.

   Set-Cookie: ASP.NET_SessionId=huilln20biy333vr3smug2sb; path=/; HttpOnly


This is set only when user tries to store something to the session, for example in asp.net mvc if we add this code, then we should see this cookie.
ControllerContext.HttpContext.Session.Add("a",1);

.ASPXAUTH is a cookie that asp.net uses for form authentication.

     Set-Cookie: .ASPXAUTH=095F6C2AF0126AF84BD5A30AD2866328E06F61755EA6FCDEDAA5A79F9039FB38AC4812628A42C700B7E927B58CA6B50F831DA2143A06385AA422ED313CB39303C3C0DA75DCFE9BCF363B7969FCFC6B0114D362CE6C1A04C424C7B1D46A440170B1DABD47E6DD8C91D6EE64B74F5224B6; path=/; HttpOnly

A web server specifies a cookie to be stored by sending an HTTP header called Set-Cookie. This is how response header looks.

     Set-Cookie: value[; expires=date][; domain=domain][; path=path][; secure]
     Set-Cookie: MyCompany=SessionKey={some unique id}&UserName=MyName&UserId=MyId; domain=.somewhere.com; path=/

In asp.net mvc you can use following code in order to perform set this header

        var httpCookie = new HttpCookie("MyCompany", "SessionKey=something&UserName=MyName");
        httpCookie.Values["UserId"] = "MyId";
    
 httpCookie.Expires = DateTime.Today.AddDays(1);
 httpCookie.Domain = "bogus.com";
 httpCookie.Path = "/product";
 httpCookie.Secure = true;
 ControllerContext.HttpContext.Response.Cookies.Add(
  httpCookie
  );


Value is string in the format name=value. In the above example we have used subcookies in order to increase the number as there is limitation on number of cookie.

Value is sent to the server with each subsequent request if option allows

     Cookie: MyCompany=SessionKey={some unique id}&UserName=MyName&UserId=MyId;

Each of the options after cookie value are separated by semicolon and space.

Expires option indicates when the cookie expires and should not be sent back to the server. Without the expires option, a cookie has a lifespan of a single session as we saw in case of ASPXAUTH,ASP.NET_SessionId

Domain options indicates domains for which cookie should be sent. By default domain is set to the host name of the page setting the cookie. This is useful for case like mail.somewhere.com and finance.somewhere.com. By setting .somewhere.com cookie can be shared these sets of sites. Browser performs a trail comparison of this value and the host name to which a request is sent.

Path options is another way to control cookie. This comparison is done by comparing the option value character-by-character against the start of the request URL. If the characters match, then the Cookie header is sent.

If secure option is specified then cookie will only be sent to the server when a request is made using SSL and the HTTPS protocol.

Jun 9, 2014

Knockout

Knockout.js is a javascript library that allows two ways bindings between html elements and data model. This means any changes to data model can be automatically reflected in DOM and vice-versa. It simplifies dynamic javascript ui with MVVM pattern.

Observables are Functions
This was little confusing in beginning and probably I spend a lot of time in order to understand this.

var personModel = {
    firstName: ko.observable(''),
    lastName: ko.observable(''),
}

This is how you access and set these properties.

var firstName = personModel.firstName();
personModel.lastName('Raj');

Observable Arrays Track Arrays, Not the Items Within
An observableArray also has some extra methods added to it to perform basic array operations-pop, push, shift, unshift, reverse, sort, splice,remove,removeall.... Refer this for complete list

ko.toJS
You get a plain copy that contains only your data and no Knockout-related artifacts

ko.toJSON
This can be used for debugging too, something like this.
<hr />
<h2>Debug</h2>
<div data-bind="text: ko.toJSON(viewModelCart)"></div>

Manual Subscription
In typical scenarios you won't need manual subscription but sometimes it becomes handy. Consider an example where you have drop-down and based on the drop down selection, you want to make an ajax call, so you can write something like this.
viewModel.selectedItem.subscribe(function(newValue) {
    //make ajax call
});

knockout.mapping plugin.
Sometime using mapping plugin saves a lot of time. You can use ignore/include to have more control while mapping.

computedObservables

knockout.validation
Very handy in terms of applying validation logic.

Adding static text on data binding
This will not work
data-bind="text: '$' + Amount"

you have to use
data-bind="text: '$' + Amount()"
or 
data-bind="text: '$' + ko.utils.unwrapObservable(Amount)"

Jun 4, 2014

Sorting Algorithm

Linear
Divide and Conquer

Performance Measure
Number of swaps
Number of comparison

Bubble Sort
  • Compare each array item to it’s right neighbor
  • If the right neighbor is smaller then Swap right and left
  • Repeat for the remaining array items
  • At the end of first iteration you will have largest number at the end
  • For next iteration you don't have to consider last item for comparison, since it is already at the correct place.
  • Follow above step until you perform no swap.
  • Performance
    • Worst Case: O(n2) - Not suitable for large unsorted data
    • Average Case: O(n2) - Not suitable for large unsorted data
    • Best Case : O(n) - Works best for already sorted or nearly sorted data
    • Space Required: O(n)
  • Reference

Insertion Sort
  • Everything left of the current item being worked on is considered to be sorted
  • If current item is greater than the last item in the sorted part, then current item is at the correct position.
  • If above is not true then you find the correct position of the current item in the sorted part and then insert it at that location after shifting rest of shorted items by one towards right.
  • Follow above step until end.
  • Only one iteration
  • Performance
    • Worst Case: O(n2) - Not suitable for large unsorted data
    • Average Case: O(n2) - Not suitable for large unsorted data
    • Best Case : O(n) - Works best for already sorted or nearly sorted data
    • Space Required: O(n)
  • Reference

Selection Sort
  • Enumerate the array from the first unsorted item to the end
  • Identify the smallest item
  • Swap the smallest item with the first unsorted item
  • Performance
    • Worst Case: O(n2) - Not suitable for large unsorted data
    • Average Case: O(n2) - Not suitable for large unsorted data
    • Best Case : O(n2) - Not suitable for large unsorted data. This does a lot of comparison because of that this has worst performance in best case scenarios also.
    • Space Required: O(n)
  • Reference

Merge Sort
  • The dataset is recursively split in half until it contains one item.
  • It is then merged in sorted order
  • After this point sets are always sorted
  • This is called divide and conquer
  • Performance - This has predictable performance O(n log n) in all kind of scenarios which is different that other Linear sorting algorithm. This has also advantage of working in parallel.
    • Worst Case: O(n log n) - Suitable for large unsorted data
    • Average Case: O(n log n) - Suitable for large unsorted data
    • Best Case : O(n log n) - Suitable for large unsorted data
    • Space Required: O(n) - Merge can be, but is often not, performed in-place, meaning new data sets are created during split. These extra allocations increase the memory footprint required to sort data.
  • Reference

Quick Sort
  • Pick a pivot value
  • Move every item small than pivot item towards it left and item greater than pivot item toward its right.
  • At this point you know that pivot item is at the right location. 
  • Perform this operation on items on both side of the pivot until everything is sorted
  • Performance
    • Worst Case: O(n2) - Not suitable for large inverse sorted data
    • Average Case: O(n log n) - Suitable for average case
    • Best Case : O(n log n) - Works best for already sorted or nearly sorted data
    • Space Required: O(n)
  • Reference

May 23, 2014

Application Cache

HTML5 provides an application caching mechanism that lets web-based applications run offline. Browser (specially mobile) typically has small cache, so this provides additional control over the resource. This results in faster web pages, lower network bandwidth and lower web server load

Things to be aware when using Application Cache

Double Refresh Issue
1.Client Load the Page
2.Load Manifest File
3.Load Application Cache
4.Server update the page and Manifest file
5.Client reload the page which will come form clients Application cache
6.Client will fetch Manifest file
7.Since manifest file has been updated, page will be downloaded and application cache will be updated
8.Still user see page from old version of the cache, so client now has to reload the page.

The above situation may become little more confusing when there are few resources coming from Network (marked in NETWORK section), in which case some of the resources are fresh every time the page is viewed, where as others marked in Cache coming from application cache which was loaded last time the Page was viewed.

To get away with this situation you can write javascript code to reload page once application is cached (window.applicationCache.onupdateready event).

Asynchronous
If a manifest file is added to a HTML file, it forces all resources to be downloaded synchronously as soon as the manifest file is downloaded, which will mean resources that may not yet be required, such as JavaScript or an image below the fold, will be downloaded at the start of the page.The best way to reduce this problem is to be careful about the order of files listed in the manifest file. As a general rule the files should be in the following order CSS -> IMG -> JS.

Atomic
The only way to update application file is to modify manifest, even though resources are changed on the server, client will continue to see older cached version until manifest file is modified. Modifying manifest file will result in download of entire cache file even though only one changed.

Prevent Manifest File Caching
It is important to avoid caching the manifest file by ensuring the web server serves the manifest file with Cache-Control: no-store, no-cache and Expires: 0.

May 21, 2014

Browser Cach

Cache-Control
public-Means cached version can be saved by proxy and intermediate servers where evryone can see
private-Only user's private browser can cache it
no-cache-this is useful for cases where url is same but content may change

Max-Age
In specifies the max age (in seconds), until then resource is not considered stale. Until then no need to send request to server. Fiddler should not show any traffic and browser load page from the cache.

Expires
Absolute time until resource is not considered stale. The inclusion of just an Expires header with no Cache-Control header indicates that the content can be cached by both browsers and public/shared caches

Last-Modified
If response contains "Last-Modified" then browser sends following cache header in subsequent request to the same resource. Server can implement logic to verify if the resource has been modified since last modified sent by the browser and if it is not then it can send "304 Not Modified" status with no content.
If-Modified-Since: Mon, 19 May 2014 15:40:42 GMT

ETag
Its like a hash or fingerprint to a resource which server can send and in any subsequent request to the same resource browser can send this value as "If-None-Match". Based on this value server can decide if resource has been modified or not. Typically server will have this ETag and it will verify it with the If-None-Match value and if it is same then "304 Not Modified" can be responded.
If-None-Match: -1265215684

Cache With Refresh
Hitting refresh results in an “If-None-Match” header being sent to the origin web server for all content that is currently on the disk cache, independent of the expiration date of the cached content.

CTRL + Refresh or CTRL +F5 
Hitting CTRL and refresh (in Internet Explorer only) or CTRL and F5 (Internet Explorer and Firefox) will insert a “Cache-Control=no-cache” header in the request, resulting in all of the content being served directly from the origin servers with no content being delivered from the local browser cache. All objects will contain a response code of 200, indicating that all were served directly from the servers.

Browser Setting
Review browser setting to verify when the page is out of date (Every Visit/Never/Once per Session/When the page is out of date). Along with this check settings to enable/disable caching of SSL content.

Sample Cache related Http  Response Headers
Cache-Control: private, max-age=1000 (,s-maxage=0)
Expires: Mon, 19 May 2014 14:42:14 GMT
Last-Modified: Mon, 19 May 2014 15:40:42 GMT
ETag: -1265215684

HTML5 Application Cache
HTML5 provides an application caching mechanism that lets web-based applications run offline. Applications that are cached load and work correctly even if users click the refresh button when they are offline.

Mar 31, 2014

WinDbg

For 32bit process running on 64bit use WinDbg (x86)
For 64bit process use WinDbg (x64)

Look into task manager and if process has (*32), it means it's a 32 bit process running on 64 bit.

Dump
Task manager can be used to take dumps (Right click process and then create dump ). For 32 bit process use 32bit task manager which is located in C:\Windows\SysWOW64\taskmgr.exe.
Other tools like Debug Diagnostic Tool and ADPlus can also be used for taking dump.
Symbols
Symbol files with PDB extension allows the debugger to map code or data addresses to symbolic information that makes more sense to you when you debug. Some of the commands which are used around symbol files

.symfix = Set the symbol path to the public microsoft symbol server
.sympath = show/set the symbol path
.sympath + <symbol path> = append symbol path to existing symbol path
.reload = reloada all the symbol

SOS
SOS (Son of Strike) is one of the important extension which you will to use native debugging; you can use following command   to load SOS Debugging Extension.
.loadby sos clr

The above command means load sos.dll from the same location where clr is located.


Debugger commands
You can either attach process to the debugger or work with dump file.
Some of the important commands:

Managed Reference Types are created on Heap, which gets cleaned up by GC.

!DumHeap - Displays every single managed object which it finds.
                    Enumerates all the objects: Address,MethodTable, Size
                    Statistical view by categorizing object view by type: Method Table, count,size, class name; this is sorted by size, so the type which occupy maximum size will be shown in the bottom.

!DumHeap -stat

Analyzing size can give some clue in cased of troubleshooting memory leaks. Also comparing dumpheap stat between dumps taken after some interval can give some clue if any particular object is growing in size.

!DumpHeap -type System.Char[]

!DumpObjet(!do) - Dump singe reference objet
!DumpArray(!da) - Dump an array object
!thread - List all managed code thread running in the process, last exception thrown on any thread. In parenthesis it shows address of exception object so you can run !do on that to get more detail
!PrintException - shows exception information of specified exception
!clrstack -a - Managed code call stack; you can get address of local object and then do !do on those to get more details on that
!GCRoot - Reference chain of object, get address from !clrstack -a
~* e!clrstack - Displays all managed threads and call stack

Reference
http://vimeo.com/9936296

Feb 23, 2014

Backbone intorduction

Backbone is a JavaScript library for building rich web application. It's not a framework(like MVC or MVVM framework). The definition from the Backbone documentation: Backbone.js give structure to web applications by providing models with key-value binding and custom events, collections with a rich API of enumerable functions, views with declarative event handling, and connects it all to your existing API over a RESTful JSON.

In a typical client side application, the server's responsibility is to serve the initial page and then provide RESTful web services for the client-side models. The advantage is, its fast, just an initial cost of downloading and after that the network traffic is JSON models and that too asynchronous. The application is running on the client, so there is no round trip to process every single interaction. On the other hand client side application are not automatically indexed by search engine, relatively difficult to test. Also user of the application has source code so are free to modify code, this must be taken into consideration and security must be enforced by the server.

Single Page Application
In a single page application all the resources are loaded as a single page load and then it executes in a single web page, by using Ajax. In a typical server side application the performance suffers because of continuous regeneration of the page and retransmission over the network. SPA moves UI generation and logic to the client. SPA is a concept, not a strict definition. It often makes sense if your application to consist of a set of SPAs.

Model
Its contains application state as well as logic and behaviour. They can be validated, synchronized to some data source and can raise events for state change. Model attribute holds data, which can be accessed by Get,Set,Escape methods. Models have save, fetch, and destroy methods for synchronizing with the server. ToJSON converts a model's attributes to a JavaScript object.
 
 var Product = Backbone.Model.extend({
        prop1: '1',
        initialize: function () {
            console.log('product created');
            this.on('invalid', function (model, error) {
                console.log(error);
            });
        },
        dump: function () {
            console.log(JSON.stringify(this.toJSON()));
        },
        defaults: { // The default's property specifies default values to attributes.
            'name': 'backboan',
            'price': 'free'
        },
        validate: function (attrs) {
            var productIsValid = function(attrs) {
                if (!attrs.name) return false;
                if (!$.isNumeric(attrs.price)) return false;
                return true;
            };
            if (!productIsValid(attrs)) {
                return "please specify valid name and price ";
            }
        }
    });
  
 var p1 = new Product({
        name: 'car',
  price: 'bogus'
    });
 
 console.log(p1.isValid());  
 p1.set('price',10);
 console.log(p1.isValid());  
 console.log(p1.isValid());  
Inheriting Model
 
 var Product = Backbone.Model.extend({});
 var Electronic = Product.Model.extend({});
 
It is possible to define class properties by providing a second argument to extend, and that can be accessed as static method
  
 var Product = Backbone.Model.extend({},
    {
  callmedirectlyonclass: function() {
        return alert('i am static method');
    }

});

    Product.callmedirectlyonclass();
 
View

Routing
Client-side routes are a way to change browser URL which helps in generating a bookmarkable URL or to generate browser history that can be navigated backwards and forwards.Routes can be triggered in two ways:
1. When user enters the url,referesh,back button etc.In this case server process the request as any other request and when the response has been loaded in the browser, the backbone router will try it match it to a route. If a match is found route function will be called.
2. The other thing is client initiated request. These doesn't trigger server request.
 
    var AppRouter = Backbone.Router.extend({
        routes: {
            '': function () {

            },
            ':productName': function (productName) {
                detailProduct(productName);
            }
        }
    });

    appRouter = new AppRouter();
    
    Backbone.history.start();

Collection
Collections groups related models together. Like models it can publish events like model added, model removed, model changed, model destroyed, collection synchronized, collection reset and validation error. These also have lot of iterator methods like add,remove,reset,push,pop,slice,sort, where, findwhere, comparator etc. By default there is no comparator for a collection. If you define a comparator, it will be used to maintain the collection in sorted order.

Feb 20, 2014

Javascript Basics

A robust function can accept any number of parameters, whereas in normal function number of parameters accepted is preset, and cannot be altered.
 
 function addition(){
  var total =0;
  for (i=0;i>addition.arguments.length;i++)
  {
   total += addition.arguments[i];
  }
  return total;
 }

 console.log(summation(3,5));

By using named arguments in JavaScript functions you don't have to rely on order, but instead their name when passing into functions.
 
 function addition( oArg ){ 
  with(oArg){ 
   return  (typeof(number1)=="number"?number1 : 0) + (typeof(number2)=="number"?number2 : 0) ; 
  }
 }
 
 console.log(addition({number1:1,number2:2,number3:3}));

        //typeof returns: number,string,boolean,object,null,undefined

Creating Object Using Object Literals
In JavaScript, and I'm not talking specifically about the browser here, there's a default/global object. It's as if every code that we write which seems to be just "loose" inside your script (i.e. outside of any object declaration) is actually being written in the context of that global object. In our case, that function isn't just a loose "global" function, it's a method of the global object. Bringing ourselves back to the browser, the global object is mapped to the window object in this environment.
 
 function CreatingObjectUsingObjectLiterals(){
  person = new Object(); //or person = {};
  person.Name = "Name";
  person.SayYourName = function(){
   alert("My name is " + this.Name);
  }
  //In this case you don't need to (and cannot) create an instance of the class, it already exists. So you simply start using this instance.
  person.SayYourName();
 }
 
 //In this case you don't need to (and cannot) create an instance of the class, it already exists. So you simply start using this instance.
 var CreatingObjectUsingObjectLiterals1 = {
  name : {firstName : "first",lastName :"last"},
  gender : "Male",
  sayHello: hello
 } 
 
 function hello(arg){
  return "hello " + arg;
 }

 CreatingObjectUsingObjectLiterals();
 console.log(window.CreatingObjectUsingObjectLiterals1.sayHello("Test"));
 console.log(CreatingObjectUsingObjectLiterals1.name.firstName);
 console.log(window.hello("Test"));
//How do I loop through properties in an object?
 for(x in CreatingObjectUsingObjectLiterals1) alert(x + "-" + CreatingObjectUsingObjectLiterals1[ x ])

Use a function to define an object, then create new object instances.
 
 function DefineObjectUsingFunction(r){
  //To define properties and methods for an object created using function(), you use the this keyword
  this.radius=r,
  this.diameter=computeDiameter
 }

 var a = new DefineObjectUsingFunction(2);
 console.log(a.diameter());


Define Singleton Object Using Function
 
 //define a function (an anonymous constructor function) and invoke it with new.
 var defineSingletonObjectUsingFunction = new function DefineSingletonObjectUsingFunction(){
  //To define properties and methods for an object created using function(), you use the this keyword
  this.radius=0,
  this.diameter=computeDiameter
 }
 
 defineSingletonObjectUsingFunction.radius = 2;
 alert(defineSingletonObjectUsingFunction.diameter());


Prototype is a type of inheritance in JavaScript. We use it when we would like an object to inherit a method after it has been defined. Think of prototyping mentally as "attaching" a method to an object after it's been defined, in which all object instances then instantly share.
 
 function DefineObjectUsingFunction(r){
  //To define properties and methods for an object created using function(), you use the this keyword
  this.radius=r,
  this.diameter=computeDiameter
 } 
 
 var a = new DefineObjectUsingFunction(2);
 alert(a.diameter());
 
 DefineObjectUsingFunction.prototype.area = function(){return this.radius*this.radius*3.14;}
 alert(a.area());
 

Using prototype to extend pre-built string() object functionality
 
 function outputbackwards(){
  for (i=this.length-1;i>=0;i--)
  document.write(this.charAt(i))
 }
 String.prototype.writeback=outputbackwards
 var message1="Welcome to my site!";
 message1.writeback();
 

Jan 15, 2014

Cross Origin Resource Sharing

Cross-origin resource sharing (CORS) works by letting server indicate which origins are allowed to call them. When browser make a request to other domain it sends along an origin in the request header with the value of domain from where its coming from. If the server allows CORS, it will send response with header Access-Control-Allow-Origin which indicates if call is allowed. If this header is not present the the browser will not allow javascript to receive the response. In addition to the origin, CORS let server indicate which HTTP methods are allowed. CORS doesn’t prevent the call from being invoked on the server; rather, it prevents the calling JavaScript from receiving the results. 

Request Header
Origin:http://localhost:55724

Response Header
Access-Control-Allow-Origin: http://localhost:55724

Web API 2 supports CORS via NuGet package Microsoft.AspNet.WebApi.Cors. Here is how you can enable CORS for your api. This can done globally or at the controller level or at the action level.
 
 public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            //var cors = new EnableCorsAttribute("*", "*", "GET");
            config.EnableCors();
    
    
  [EnableCors("http://localhost:55725", "*", "GET")]
  public class ProductController : ApiController

Preflight Requests
For some CORS requests, the browser sends an additional request, called a “preflight request”, before it sends the actual request for the resource. The pre-flight request uses the HTTP OPTIONS method. If the preflight request succeeds, the browser sends the actual request.

Jan 10, 2014

IHttpActionResult

This is new feature to WebApi 2.0 In many ways this is similar to action result in asp.net mvc. There are some build in action result like mvc controller has view result, json result etc. Web api has OkResult, NotFoundResult, ExceptionResult,UnauthorizedResult,BadRequestResult, ConflictResult,RedirectResult,InvalidModelStateResult.
 
  public IHttpActionResult GetDetails(string name)
        {
            Product product = _productService.GetProduct(name);
            if (product == null)
                return NotFound();
            return Ok(product);
        }
This simplifies unit test, for example if you are using request object to create http response object then you need to do setup to unit test controller.

Routing With Attribute


This allows routing with Attribute on any action. This works for both Api as well as mvc controller. You can have multiple route to an action. This can also be applied at the controller level

[Route("Api/Product/{name:alpha}/Reviews")]
[Route("Api/Product/{id:int:min(1)}/Reviews")]
        public HttpResponseMessage GetReviews(int id)

[RoutePrefix("Api/Product")] : This will apply to all the routes in the controller

Following configuration change need to happen to make attribute route work
public static void Register(HttpConfiguration config)
        {
            config.MapHttpAttributeRoutes();
            config.Routes.MapHttpRoute("DefaultApi", "api/{controller}/{name}", new {name = RouteParameter.Optional});

Notice MapHttpAttributeRoutes is before default route, this give opportunity for attribute route to be applied before default route.

Web Api Help Page

Install-Package Microsoft.AspNet.WebApi.HelpPage -Version 5.0.0

This will add following to the package config
<package id="Microsoft.AspNet.WebApi.HelpPage" version="5.0.0" targetFramework="net45" />

This install will not add any new assembly to the reference, but this will add Area HelpPage, with controller,model and view which will provide help page.

Documentation:
Update Project Property, build tab to check Xml Documentation file.
Open Areas->HelpPage->AppStart->HelpPageConfig file and uncomment
config.SetDocumentationProvider
Make sure it refers the same xml documentation file


Now open .../Help url