Friday, February 13, 2015

HTTP Fundamentals

Chapter 1 : HTTP Resources


- http://food.com/recipes/sandwich
  • URL scheme: (for e.g. "http://" in above address). Part before ://, it Defines how to access a particular resource. Other schemes are https,ftp and mailto(mailto://abhijeet.nagre@gmail.com). Everythinng after :// is specific to URL scheme.
  • Host: (for e.g. "host.com" in above address). DNS maps the host name to IP Address.
  • URL Path:(for e.g. "recipes/sandwich" in above address)

- http://food.com:80/recipes?type=breakfast
  • Port: (for e.g. "80" in above address). 80 is default for HTTP and 443 is default for HTTPS. This is the port at which Server is listening.
  • Query String: Preceded by "?" (for e.g. "type=breakfast" in above address). It is up to the host application to interpret this.  Mostly used to pass multiple name value pairs separated by &.
  • Fragment: Preceded by #. Not processed by server. Handled by client only. Identifies particular element in Html, which client should focus on.
- Having keywords in URL is a good Search engine optimization.

- URL Safe characters: URL can contain only safe characters.
Following are safe characters which cane appear is an URL.
            * Upper case and Lower case letters (a-z AND A-Z)
            * Numbers (0-9)
            * $_-.+*'(),

- URL Encoding:If URL contains unsafe character, it could be percentage (%) encoded (also know as URL Encoding). I.e. replace the character with "%{numeric code of the character in ASCII}". So ! could be sent as "%21" as 21 is it's ASCII code.

- Content Type of Resource: Server mentions type of the content to client. Thus client knows if the resource is image or video or text or something else. Content Types are specified as per MIME standard

- Content Negotiation: A resource represented by Single URL can have multiple representations. for e.g for multiple languages (for e.g. same recipe in French, English etc.) or in different formats like Html, MS Word or PDF etc. When client makes a request it can specify media types it can accept. Piece of code written in JavaScript can ask for JSON representation of a resource, whereas a piece of code written in C# can ask for representation in XML for the same resource with same URL.


Chapter 2 : HTTP Messages


- HTTP messages come in pairs (Request message and Response message). Information in the message is all in readable text.


- There are tools which give view of HTTP request coming and going from your computer. Fiddler is one such tool. Most browsers also provide such view.

- First line of the HTTP message (both Request and Response) is always explicit about its intent.

- HTTP Methods
 Method  Description
 GET Retrieve a Resource
 POST  Update Resource
 PUT  Store a Resource
 DELETE  Delete a Resource
 HEAD  Retrieve the header for a Resource        

- Even tough HTTP specification mentions above methods. GET and POST are mostly used methods others are rarely used.

- If you are writing a HTTP web service, you might want to use HTTP Put and Delete methods. Be careful, as there are few server side technologies and pieces of hardware who do not support these messages.

- POST method is used when browser needs to send some information to Server.

- There is part of HTTP specification which describes Safe and Unsafe methods.
- Safe methods let you read a resource from server. This method doesn't modify resources in Server. GET and HEAD fall in these category. Get operation should never have a side effect on Web Server.
- Unsafe methods are the ones which let you change resources on web server.
- If a Html page has Form and contents of the form are already Posted; then Browser will give warning if user Refreshes that page. PUT,POST and DELETE fall in this category.

- Post-Redirect-Get Pattern (aka PGT): When a Post request is processed by Server, the request is redirected to another Page (with HTTP Get command).

- FORM GET vs FORM POST
A Form is generally used with POST method. But it can be used with GET method as well. For e.g.
     
<form action="results.cshtml">
    <input name="q" placeholder="search" type="search" />
    <input type="submit" />
</form>

When above form is submitted a GET message is sent to Server at URL path results.cshtml. The value of input search will be appended to URL. URL will have query string with name q (input box's name). Whereas when contents of Form are sent to Server using POST message, values entered in the input boxes are sent as message and not as Query String.

- HTTP Status Code Categories


Method Description
100-199 Informational
200-299 Successful
300-399 Redirection
400-499 Client Error
500-599 Server Error

- Fiddler (fiddler2.com)



Chapter 3 : HTTP Connections


- Browser implement HTTP protocol. i.e. Browsers act as HTTP initiating agent and sends HTTP messages using (mostly) TCP.


- TCP: Does Flow control i.e. ensures that sender doesn't send messages too fast for the receiver to process them.

- WireShark : Could be used to do deeper analysis than what Fiddler does. Fiddler shows HTTP messages exchanged between browser and Web Server. WireShark even shows TCP handshakes,shows messages transferred between all the subsequent layers involved in the HTTP message transfer i.e. TCP, IP and Data Link layer.

- If a Web server doesn't allow persistent connections then it must include a header "Connection-Close" in Response. Shared Hosts would generally do this.



Chapter 4 : HTTP Architecture


- URL doesn't mention which HTTP method (GET,POST etc..) is to be used.


- All the information required to complete HTTP transaction is contained in HTTP messages.

- HTTP Proxy: 

Proxy server can
            * Act as Access Control device. e.g. Filter all traffic going to Facebook.com.
            * Strip out confidential data out of HTTP messages.
            * Create Audit Trail on Traffic          

- Forward Proxy: is closer to client than to Web Server.
            * Forward Proxy requires some configuration in client software or Browser.
            * Forward Proxy provides service to some limited set of users. e.g employees of company or users of ISP.

- Reverse Proxy: is closer to Server than to client
            * Completely transparent to client.
            * All the requests coming to the Web Server are coming though Reverse Proxy.
            * Proxy server can reduce load on the Web Server by providing services like Compression, HTTP message logging etc.

- Services provided by Web Proxy Server
            * Load balancing. Some Proxy Servers can look at how much CPU and Memory a server is using and distribute load based on that.
            * SSL acceleration: Encrypt and de-crypt HTTP messages
            * Security: Filter out dangerous HTTP Messages.
            * Caching Proxies: Cache HTTP Response Messages

- Fiddler works by installing itself as Proxy on the machine. Thus it can intercept all HTTP traffic.


- HTTP Headers for Caching 
            * Cache-Control:
            * Expires: Deprecated in HTTP 1.1 but used for backward compatibility
            * Pragma: Deprecated in HTTP 1.1 but used for backward compatibility

- Values for HTTP Cache-Control Header

            * Public: A response for everyone
            * Private: A response for specific user.
            * no-cache: Don't cache
            * no-store: You never saw this response (i.e. Delete message immediately)

- Caching
            * Public Cache: Shared among multiple users. Generally 
                  resides on Proxy Server
            * Private Cache: Web browsers cache HTTP messages marked
                  as Private Cache on users disk. 
                  Internet Explorer stores caches at "Windows\Temporary Internet Files" 
                  location.
                  Chrome's cache files could be found at "chrome://cache/"
            * HTTP GET message is safe message so could be considered for Caching
                  PUT,POST and DELETE are unsafe messages so are not considered for Caching.

- ASP.Net Cache Control Headers
            * Response.Cache.SetCacheability(..)
            * Response.Cache.SetExpires(..)

- Client sets "Last-Modified" header in HTTP messages to let Server know if the resource has changed since that. If resource has not changed, server sends HTTP response message with Status code 304. Which means client could use cached copy.



Chapter 5 : HTTP Security

- Some Load balancer's support Sticky Sessions. i.e. HTTP Requests belonging to a session are sent to same server.

- Stateless HTTP enables State management by using Cookies.

- Cookies: Server sends state information to browser using Set-Cookie header. Subsequent requests made by the browser contains this Cookie. 

- Session Cookie vs Persistent Cookie: Session cookie is discarded when Browser is closed whereas Persistent cookies are not discarded when Browser is closed. Persistent Cookie needs to have an Expires value.


- HTTP follows a Challenge Response format for authentication. When client asks for a secure resource, server returns a 401-Unauthorized response, Response also mentions which authentication protocol is used for Authentication. Client then asks credentials(username and password) to user and sends another request to server with credentials (Credentials are sent using WWW-Authentication header. All subsequent requests have WWW-Authentication header, which contains credentials.

- HTTP doesn't dictate how credentials are validated by Server.

- HTTP specification mentions two authentication protocols i.e. Basic and Digest.

- Basic Authentication: Sends username and password to server as Base 64 encoded string (via Authorization header). Thus this is very unsafe and rarely used.

- Digest Authentication: This is similar to Basic Authentication except client doesn't send plain text username and passwords to server. Client applies MD5 hash on username and password and sends result to server. Thus it is not possible for a sniffer to know username and password.

- Forms Authentication: Application has complete control over how authentication is managed.When client requests for a secure resource, Server redirects it to login page using HTTP 302 temporary Redirect. Login page lets user enter credentials, which are POSTed to server.  The response will also set a cookie indicating user is authenticated.

- In Forms Authentication Credentials are sent in plain text, So it is necessary to use HTTPS or Secure HTTP.

- Secure HTTP and HTTPS are same protocols also know as SSL or TLS(Transport Layer Security). Encrypts HTTP messages before they are sent. Uses https scheme in URL instead of regular http scheme. Default port for HTTP scheme is 80 and default port for HTTPS is 443.


- HTTPS adds a layer inbetween Application Layer and Transport Layer. HTTPS requires server to have a cryptographic certificate.This certificate is sent to client during setup of HTTPS connection. Certificate includes Server's host name. Certificates are provided by providers like Verisign. Certificates use public private keys. Administrators have to purchase certificates from certificate providers and install them on server.

- HTTPS encrypts HTTP messages except host name. Everything else (URL path,Cookies,headers, Body) is encrypted. Avoids Session hijacking as no eavesdropper can hijack Session cookie. Client can use certificate to validate(authenticate) host. HTTPS does not authenticate client.So some Authentication mechanism is required to authenticate client. HTTPS makes Client Authentication protocol secure as it encrypts username,password and authentication cookies in the Http messages. Clients cans authenticate by using Client side certificate, but this is rarely used.

- HTTPS Downsides: 
           * Performance: Large sites use specialized hardware called SSL accelerators.
           * Performance Connection setup is longer as additional hand shakes 
                  are required.
           * Can not be used as Public Cache however clients can cache them as 
                 private cache.

- OpenID: is a standard for decentralized authentication. Users do not have to create multiple passwords for various web sites. Also every web site doesn't have to manage authentication, it can delegate authentication management to identity provider. Identity provider stores and validates Identity.



Follow up 
Architectural Styles and the Design of Network-based Software Architectures
- Sticky Sessions

Friday, February 6, 2015

Play by Play: Scott Allen and Dan Wahlin


- Web Essentials is good plugin available for Visual Studio.
- Boot Strap components: http://getbootstrap.com/components
- Batarang: AngularJS plugin for Chrome

Thursday, February 5, 2015

Play by Play: Triage with Ayende Rahien

- As shown below a BaseController which is used as Base class by all Controllers. BaseController overrides two methods OnActionExecuting and OnActionExecuted, which run before and after each Action. OnActionExecuting is used for initializing session (For EF it is ObjectContext) and OnActionExecuted is used for disposing session. 



- Multi Threaded application. It is very difficult to debug any bug when logging is not done.So logging is very important when you are developing Multi Threaded applications.

Introduction to ASP.NET MVC 3

Chapter 1. Introduction to ASP.NET MVC 3

- Visual Studio: Web Developer FREE Edition
- ASP.Net MVC 3 is present in "Visual Studio 2010 SP1"
- ASPX View Engine: It is a legacy view engine and is present for Backward compatibility.
MVC Design Pattern
       * Separates responsibilities of components in UI Layer.
       * Doesn't dictate which DALayer is to be used.
       * Doesn't dictate how domain layer should look like.
       * Doesn't care if your application has Layers or not.
       * It is design pattern for building UI and nothing more.
       * View is just a presentation template.
       * Controllers are responsible for responding to UI events.

Goals of ASP.Net MVC
       * Embracing WEB:
       * Runs on top of ASP.Net. Thus Modules, handlers, caching and diagnostics are reused from ASP.Net
       * Extensible
       * Testable
 
- ViewBag is dynamic object
- @ sign tells Razor engine to consider subsequent text as code.
- It is not necessary to have Models in the Models folder. They can be anywhere. Including all the projects referenced by MVC Project.


- Strongly Typed Model:  By default View treats @Model as dynamic. One can make @Model strongly typed by providing a directive which specifies type of model.




Chapter 2. Controllers

- Routing: Routing returns first matched entry.
- All public methods in Controller class are Actions. So they could be reached by client. So be careful in marking methods in Controllers as public.
- Action Results
ActionName: This attribute could be applied to a Controller method to alias it's Action Name.
AcceptVerbs: This attribute specifies Http verbs which could be used to Reach that Action.
- Action Filters: apply pre and post processing logic to Controller action and its logic.
                 : are components which contain cross cutting logic








Chapter 3. Razor Views

Difference between Response.Write and @. @ Also html encodes text.
- If Razor engine is treating piece of text as code, whereas you want it to be treated as html then there are two ways. 1. Surround the text with tags OR 2. Prefix the text with @:
- Layout views are Master pages for Razor views
- @* : Acts as comments in the Razor
- Views\_ViewStart.cshtml: This file mentions which Layout file is to be used for current application
- _ViewStart.cshtml is hierarchical.
- Individual views can alter inherited Layout.
- Code Sample: 











Partial Views: This is similar to User controls in ASP.Net Web Forms
- ChildActionOnly: This attribute for a Controller Action ensures that attributed Controller Action isn't viewable by user directly by entering URL. 




Chapter 5. Working with Data (Part 2)


- Data Validation Attributes: System.ComponentModel.DataAnnotations defines Attributes for Data Validations. Following are commonly used validation attributes.          * Required
      * StringLength
      * Regex
      * Range

Custom Validation: There are two ways
          1.  Custom Attributes deriving from ValidationAttribute.


          2.  Model class can implement IValidatableObject.


Chapter 6. Ajax and Javascript with ASP.Net MVC 3



- Putting Script tags at the bottom of the Html Page helps performance.
Razor Helpers: Reusable logic could be put in Razor Helpers.
                            : A RazorHelper in a view is available in that view only. To make this RazorHelper available across multiple Views, move this RazorHelper to Extention Method of HtmlHelper OR by making a reusable RazorView by adding that RazorView to a class in AppCode
Ajax.ActionLink: Builds an anchor tag. When user clicks on this anchor tag, a Ajax request is sent to server. This request could be linked to Actions in the Controllers.
Unobtrusive Javascript: Only rule is "Html files do not contain any javascript code. All javascript code is contained in external file marked as script file.
- If you refer other javascript files from current javascript file as follows, Visual Studio will include functions defined in other javascript file in Intellisense.
            ///
- Custom Editor Template is a partial View.  When a Template for a type T is required, MVC searches for a template named T. So when Editor for DateTime is required MVC will search for template named DateTime.




Chapter 7. Security 


- MVC 3 provides two Types of Authentication out of box.
              1. Forms Authentication :
                             * For Public websites
                             * Customizable
                             * Typically relies on Cookies
                             * SSL is required to make web site secure.                          
               2. Windows Authentication (Integrated Authentication) : 
                          Good for Intranet Apps. Gives Single Sign On experience to users. 
                          Users need to be on same Windows Domain.
- Authorize attribute (without parameter) on Controller Action tells MVC that only authenticated users should be allowed to use this Action.  A role name could be sent to Authorize attribute and then that users in that role would only be allowed to use that Action.
ASP.Net Membership : Provides functionality for User Account Management. Default Provider is SQL Server, which saves User data in SQL Server. This Provider allows to create a user, Delete a user, Change Password etc.
aspnet_regsql: This utility adds/removes Membership Providers tables to a database.
- When using Windows Authentication, Roles map to groups created on server or Active Directory.
- Forms Authentication on Plain HTTP: Username password entered by user will be sent to Server as plain text. So if somebody is sniffing the network or capturing network traffic, he will be able to capture username and password. Solution to this is to use HTTPS, which encrypts username and password.
- This blog explains how to work with SSL at development time.
http://www.hanselman.com/blog/WorkingWithSSLAtDevelopmentTimeIsEasierWithIISExpress.aspx
XSS (Cross Site Scripting): Malicious user will use website to load malicious script or ActiveX Control or Html into user's browser. They will try to do this by getting to your site and trying to get your site to accept some input from a form input or a query string and have your site echo back that input into a page without proper encoding. 


- Microsoft provides AntiXSS library. It has Sanitizer.GetSafeHtmlFragment (body) method in it. This method has white list of allowed html tags. If input body contains any tag which is not part of this white list will be filtered by this method.




Chapter 8. ASP.Net Infrastructure for MVC


- Output Caching : Allows to store (cache) output of Controller Action in memory.
OutputCache attribute of Action : Use this attribute to Output cache result of Action.
- Best Practice : Do not enable Output Caching unless performance is monitored.
Localization : Two setting impact how application behaves under different cultures
        * Thread.CurrentCulture property impacts formatting (e.g. DateTime.Now.ToString())
        * Thread.CurrentUICulture impacts resource loading
 ASP.Net can set cultures according to HTTP headers
        * Http Header: Accept-Language
        * Use globalization section in web.config
- Logging Options
        * ASP.Net Health Monitoring
        * Log4Net
        * Microsoft Application Block: Logging
        * elmah (code.google.com/p/elmah)
- Machine wide web.config file contains section. Which tells how various health monitoring events should be treated. It contains following sections.
        * Where can a event be written.
        * Categories of Events


        * Specifies what events go to what event providers. Maps EventMapping to Providers.




Chapter 9. TDD and Unit Testing

TDD Cycle
        * Red: Write a Failing Test
        * Green: Write Code to Pass test
        * Refactor : Refactor code to improve design


- StrucutreMap-Mvc is IoC (Inversion of Control) Container for MVC.



Chapter 10. Configuration and Deployment

- The Views folders has local web.config
HandleErrorAttribute this filter ensures that Custom Error page is shown. This filter respects setting in web.config.
aspnet_regiis : utility registers ASP.Net with IIS. Exact command is "aspnet_regiis.exe -i". Working folder for this command needs to be .Net Folder.

Wednesday, December 3, 2014

AngularJS Fundamentals In 60-ish Minutes

AngularJS Fundamentals In 60-ish Minutes



- $Scope : Glue between Controller and View.
         : $Scope is ViewModel

- ViewModel : Data for the View or Model for View

- Controllers (in MVC) should not know about View as this makes it depend on View. This allows Controllers to be testable and Multiple Views are possible this way.

- Modules : are containers

- Routes : Maps View and Controller

Tuesday, December 2, 2014

Dependency Injection ( and Dependency Injection Container)

Video : http://www.youtube.com/watch?v=IKD2-MAkXyQ

Dependency : Dependency is has a relationship. Class A has class B. Class Cycle has Tyre.

Injecting Dependency : Dependency is pushed from outside to the class. So in above example Class Cycle instead of instantiating instance of class Tyre, gets an instance of Tyre from outside.

Principal Behind Dependency Injection : We should code to abstractions (interfaces).

Dependency Injection Container Pattern : Used to create dependencies for class\es.  Knows which class has which dependencies and how to instantiate those dependencies.


Tuesday, October 7, 2014

Utilizing SysteInternals (Channel 9 Course : http://channel9.msdn.com/Series/sysinternals/01)

Mod 1 : Introduction (http://channel9.msdn.com/Series/sysinternals/01)

  • Imp SysInternals tools 
  1. ProcessExplorer (Most Popular)
  2. ProcessMonitor  (Most Popular)
  3. PSTools
  4. AutoRuns

Could be used
  1. as Advance (IT Pro) version of Task Manager.
  2. to see all Threads associated with a Process
  3. to see Stack Trace, Number of Context Switches of a Thread
  4. to check which Process is having handle for a File.
  5. to check if a Process has open TCP-IP connections. Shows to which IP addresses current Process is connected to.
  6. Process Explorer (like many other SysInternals tools) can connect to a remote machine and show Process information for that machine.
  7. Process Explorer could be configured so that whenever user sees Process Explorer instead of System Task Manager.
  8. When an error message is shown and its source is not known. Bullet Eye functionality could be used  could be used to see which Process is associated with that message.
  9. SvcHost.exe is service host process. Process Explorer shows additional tab called Services in Properties window for Process Explorer. Process Explorer could be used to see which services are hosted by given instance of SvcHost.exe
  10. Good practice to Add columns Version, Integrity and Virtualized to Process Explorer.
  11. Microsoft doesn't Test Windows with disabling IPv6. So do not disable it without thorough testing.
  1. This tool is combination of FileMon (File Monitor) and RegMon(Registry Monitor).
  2. When to use Process Monitor : DLL corruptions, Configuration issues, Performance Diagnostics,
  3. By default Process Monitor displays Activities in Registry,File System, Processes (Process, Thread, DLL and Device Driver load operations) and Profiling (User and Kernal CPU time consumed, Number of context switches).  Networking (TCP and UDP network activity including source and destination address).
  4. 'Boot Monitoring' : Enabling this start Process Monitor on boot. Process Monitor will collect Trace since boot. 
  5. Process Activity Summary : 
"PSExec.exe \\RemotePC cmd" This command will start command prompt on remote machine named RemotePC. Subsequent commands entered in command propmt will actually be run against RemotePC.
  • PSInfo : Gives information of the system. Could be run remotely.
  • PSFile :
  • PSKill : Enables killing process on remote machines 
  • PSService : Displays Configuration,Dependencies and Status of Windows services.
  1. Very useful application to run automatically running application. Shows Applications which run on Logon, Services which run on Startup, Scheduled Tasks and many more.