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