CodeSchool courses on JavaScript Frameworks

CodeSchool is a great site for introductory programming courses. With all guides and practice exercises available right within the browser, it is a hassle-free way to start learning. The design of the site is also very pleasing which enhances the overall experience.

Recently, CodeSchool offered a free weekend pass to all their content. I took the opportunity to brush up my skills on the new version of Angular and also quickly went through the React course.


Course Link: Accelerating through Angular 2



Course Link: Powering Up with React


Review: Pixar in a box Tutorial by Khan Academy

Pixar is a box’ is an excellent tutorial at Khan Academy developed in collaboration with Pixar Animation Studios. It is about some of the Math concepts that we learn in school and how they apply to making animated movies. The content is meant for secondary school students (and above Smile).

Tutorial sketches a broad outline of the pipeline for producing animation, with each lesson digging deeper into a particular concept and its Mathematics.

1- Environment Modeling talks about representing curves (parabolic curves) using three points, rather than equations. It is more intuitive to work with three control points while designing and animating curves. This knowledge about curves is applied to create grass blade. A lot of grass blades are put together with randomness and animation offsets to create a natural looking grass field.

2- Character Modeling describes how polygons are used to start modeling shapes and subdivision algorithm is used to smoothen out the edges. 2D sketch of Human hand is designed using this technique without much effort. The crux of the lesson is the mathematics of subdivision and its application in 2D and 3D.

3- Animation lesson explains the role of Bezier curve in representing animation. A realistic bouncing ball animation is created in hands-on exercise.

4- Crowds are created by joining a number of parts in various combinations.  Lesson explores the concepts of permutations and apply it to calculating the number of possible combinations.

5- Sets & Staging deals with placing characters in the environment. Environment contains various objects which are placed around in the scene after scaling and rotating them as required. The lesson explains the mathematics behind these geometric transformations.

6- Rendering is a particularly exciting lesson which brings out the complexity of the whole process. While rendering we have to determine the color of each pixel in a frame taking into account all the light sources, camera position, all objects in the scene and how each object reflects or refracts light. This is done by casting rays out of the light sources and bouncing them off various surfaces. Diffuse and Specular properties of a surface determine how light will be reflected by it.

‘‘Pixar in a box’ is highly recommended as a fun way to learn.

Pixar in a box

Completed ‘Søren Kierkegaard – Subjectivity, Irony and the Crisis of Modernity’ from Coursera

Completed ‘Søren Kierkegaard – Subjectivity, Irony and the Crisis of Modernity‘ course taught by Associate Professor Jon Stewart from University of Copenhagen. The course is offered through Coursera platform and ran for 8 weeks from 6st October 2014 through 1st December 2014.

Course consisted of weekly reading assignments from the works of Kierkegaard, followed by video lectures where Professor Jon provided the background of the text and explained the key points. Video lectures are shot at various locations in Copenhagen which are associated with the life of Kierkegaard. The course concluded with an assignment to write a shot essay on a given topic related to Kierkegaard’s ideas.

My essay was on ‘What did Kierkegaard learn from his study of Socrates? Why is this connection between Socrates and Kierkegaard still relevant in the world today?’.

Coursera Soren Kierkegaard Certificate

Study Notes for Microsoft Exam: Developing ASP.NET MVC Web Applications (70-486)

Took Microsoft Exam 70-486 which part of MCSD certification. I spend about 2 weeks studying the material and took some notes which are posted here. Notes are not complete in the sense that they don’t cover the full syllabus – half of my notes are scattered in different places which will be incorporated here later (hopefully).

Code First Migrations:

Three step process (use Package Manager Console):

  1. enable-migrations -ContextTypeName MyProject.Models.StudentDBContext
    • Creates Configuration class with Seed method
    • Needs to be executed only once to setup migrations
  2. add-migration MyFirstMig
    • Creates {DateStamp}_MyFirstMig.cs in Migrations folder
    • Execute it after each change to model
  3. update-database
    • Execute it to apply changes to database

Data Annotations:

  • [Required]
  • [Range(5, 10)]
  • [StringLength(5)]
  • [DataType(DataType.Date)]         (enum DataType { CreditCard, Currency, Custom, Date, DateTime, Duration, EmailAddress, Html, ImageUrl, MultilineText, Password, PhoneNumber, PostalCode, Text, Time, Upload, Url, })
  • [DisplayFormat(DataFormatString = “{0:d}”)]

Model Validation:

  • In Controller’s Create or Edit action (server):
public ActionResult Create(Movie movie)
   if (ModelState.IsValid)
      return RedirectToAction("Index");

   return View(movie);
  • In view (browser):
<div class="editor-field">
   @Html.EditorFor(model => model.Title)     
   @Html.ValidationMessageFor(model => model.Title)

Cross Site Scripting Attack

  • Add @AntiForgeryToken() in view inside form element
  • Add [ValidateAntiForgeryToken] attribute on form post actions

Asynchronous Programming with async and await:


Bundling and Minification

  • Good Article: Link
  • Most browsers limit the number concurrent requests to the same domain to six
  • To disable
    <compilation debug="true" />
    <!-- Lines removed for clarity. -->
  • Can be overwritten in code
BundleTable.EnableOptimizations = true;
  • Creating script bundle
bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
  • Creating style bundle
bundles.Add(new StyleBundle("~/Content/themes/base/css").Include(
          "~/Content/themes/base/jquery.ui.accordion.css" ));
  • Adding reference to bundles in view
@Styles.Render("~/Content/themes/base/css", "~/Content/css")

<script src='@Scripts.Url("~/bundles/modernizr")' async> </script>


  • Can use ‘*’ wildcard and IncludeDirectory function
bundles.Add(new StyleBundle("~/jQueryUI/themes/baseAll")
    .IncludeDirectory("~/Content/themes/base", "*.css"));
  • .min files are selected for release (jquery-1.7.1.min.js)
  • -vsdoc files are ignored (they are for intellisense)
  • Bundle Transformation
    • Implement IBundleTransform
using System.Web.Optimization;

public class LessTransform : IBundleTransform
    public void Process(BundleContext context, BundleResponse response)
        response.Content = dotless.Core.Less.Parse(response.Content);
        response.ContentType = "text/css";
  • Add transformation
var lessBundle = new Bundle("~/My/Less").IncludeDirectory("~/My", "*.less");
lessBundle.Transforms.Add(new LessTransform());
lessBundle.Transforms.Add(new CssMinify());

Using OAuth providers with MVC:

  • Register your site with provider and Receive parameters (such as key or id, and secret)
  • Register your application as Provider’s client: RegisterFacebookClient(            appId: “111111111111111”,            appSecret: “a1a1aa111111111a111a111aaa111111”);

Interaction among View, Layout page (_Layout.cshtml) and other pages

@RenderBody() Called from _Layout.cshtml to render the body of the requested page at the right place within layout.
@RenderSection(“scripts”, required: false) Called from _Layout.cshtml to rendor a section if defined in the requested page.- Section definition is optional if required is false- Section definition on requested page

@section Scripts {



@RenderPage(“MyView.cshtml”, MyModel) Renders the specified page as part of the requested page. Similar to @Html.Partial(“MyView”)


WCF vs ASP.Net Web API



  • Don’t use HTTP GET request for delete, edit or create options as they open security holes (link)
  • Fiddler, a web debugging tool which logs all HTTP / HTTPS traffic. (


  • [Authorize(Roles=”Admin,PowerUser“, Users=”Mark“)]
    • Implements IAuthorizationFilter which has one method OnAuthorization
  • AuthorizeAttribute.AuthorizeCore method: When overridden, provides an entry point for custom authorization checks.
  • [AllowAnonymous] This attribute on Action will override the Authroize on Controller and wise versa


Browser / Feature Detection and Compatibility

  • Video tab with fall backs
<source src="video.mp4" type='video/mp4' />
<source src="video.webm" type='video/webm' />
<object type="application/x-silverlight-2">
<param name="source" value="http://url/player.xap">
<param name="initParams" value="m=http://url/video.mp4">
Download the video <a href="video.mp4">here</a>.


  • Display modes (by default we have regular mode and Mobile mode)
    • Mobile.cshtml will be used instead of Index.cshtml automatically when page is accessed through a mobile
    • Add new DefaultDisplayMode (WP7.cshtml)


DisplayModeProvider.Instance.Modes.Insert(0, new DefaultDisplayMode("WP7")
      ContextCondition = ctx => ctx.GetOverriddenUserAgent().Contains("Windows Phone OS")


  • Setting viewport to device width <meta name=”viewport” content=”width=device-width” />
  • CSS @media query


@media only screen and (max-width: 850px) {
    .site-title {
        color: #c8c8c8;

@media (min-width: 768px) and (max-width: 979px) and (orientation:portrait) {…


  • Check if user is on mobile device: Browser.IsMobileDevice
  • CSS Vendor Prefixes
    • -ms-, -mso- (Mircosoft); -moz- (Mozilla); -webkit- (Apple, Google); -o-, xv- (Opera)
    • Example: -moz-border-radius: 18px;


Razor View Templates


  • EditorFor template (used with @Html.EditorFor() helper)
    • Path: ~/Views/ControllerName/EditorTemplates/Article.cshtml


@model MyMVCApplication1.Article
@if (Model != null)
    @Html.TextBox("", Model.Title)
    @Html.TextBox("", Model.Body)
    @Html.TextBox("", string.Empty)
    @Html.TextBox("", string.Empty)


  • DisplayTemplate (used with @Html.DisplayFor() helper)
    • Path: ~/Views/ControllerName/DisplayTemplates/<Type Name>.cshtml


Action Filters


    • Authorization filters – Implements the IAuthorizationFilter attribute.
    • Action filters – Implements the IActionFilter attribute.
    • Result filters – Implements the IResultFilter attribute.
    • Exception filters – Implements the IExceptionFilter attribute.
  • Authorization filters are always executed before action filters
  • Filter’s Order parameter can be used to control the order in which filters of same type are executed
  • Filter’s AllowMultiple parameter can be used to run filter only once
  • ActionFilterAttributeimplements bothIActionFilter andIResultFilter and drives fromActionFilterAttribute
    • It has methods: OnActionExecuting, OnActionExecuted, OnResultExecuting, OnResultExecuted
  • Add filter globally to all actions Add(new RequireHttpsAttribute());
    • filters is GlobalFilters.Filters passed as parameter to FilterConfig
  • Useful Fitlers: HandlerError, OutputCache, Authorize


Web Accessibility Initiative-Accessible Rich Internet Applications (WAI-ARIA)

  • aria-labelledby=”name_label” This attribute on input field can an link it to the label which can deliver meaning otherwise delivered visually
  • aria-required defines a mandatory input field


Search Engine Optimization

  • txt file – create robot exclusion rules (list pages that should be indexed by search engine)
  • Have meaningful url. Rather than com/1, use<record title>



  • Accept-Language: en-US,en;q=0.8 (Request Header presented to server)
  • en is Language, US is Locale. Language is at a higher level than locale.
  • <globalization culture=”auto” uiculture=”auto” enableclientbasedculture=”true”/> (enable client based culture in Web.Config)
  • Thread.CurrentThread.CurrentUICulture (find current culture)
  • Use resource files
    • keeps strings in resource files (.resx)
    • create separate files for each language (MyResFile.resx,
    • access string using MyResFile.MyLabel1
  • An Alternative to resource files is to use localized views
  • There no way to determine culture in javascript (server has to send it back)
  • Setting culture for jQuery in browser (use anyone of the two)
    • <script>preferCulture(language);</script>
    • $.global.preferCulture(language)
  • Manually set culture on server (may be based on user selection)
    • CurrentThread.CurrentUICulture = new CultureInfo(“es-MX”);
  • Create satellite assemblies (dll) to separate culture specific resouces (only required resources are loaded in memory)


Action Attributes (other than filters and attributes covered in else where)

  • RequireHttps
  • ValidateInputTo exclude a field [ValidateInput(true, Exclude = “ArbitraryField”)]
  • AllowHtml
  • ActionName
  • ChildActionOnly (action can’t be accessed directly by client, has to be called from a view using @Html.Action(“MyView”) or RenderAction )


Error Handling

  • [HandleError(ExceptionType=typeof(NullReferenceException), View=”MyErrorView”)]
    • Action attribute for handling exception
    • Implements IExceptionFilter that has OnException method
    • By default MVC display ~/Views/Shared/Error
  • Application_Error method in global.asax class (for unhandled exception that makes through the stack)
  • IsCustomErrorEnabled

Action Results

  • All action results derive from ActionResult class
Action Result Type Action Helper method Comments
ViewResult View Renders Html, derive from ViewBaseResult
PartialViewResult PartialView Renders Html, derive from ViewBaseResult
JsonResult Json
JavaScriptResult JavaScript
RedirectResult Redirect
RedirectToRouteResult RedirectToActionRedirectToRoute
FileResult File
ContentResult Content Can be used to return pdf, xml etc.
EmptyResult N/A (return null)


  • A custom action result can be created by inheriting from ActionResult class and overriding void ExecuteResult(ControllerContext ctx) method

Model Binders

  • DefaultModelBinder Maps a browser request to a data object
  • LinqBinaryModelBinder Maps a browser request to a LINQ object
  • Creating a custom model binder
  • Implement IModelBinder interface with one method: public object BindModel(ControllerContextcontrollerContext,ModelBindingContextbindingContext)
  • Setting custom binder for a model class
public class MyModel
{       ...     }
  • Another way of doing it



  • Extending DefaultModelBinder class
    • public class MyBinder : DefaultModelBinder
  • Extend BindProperty method (loops through every model property one by one)
    • protected override void BindProperty(ControllerContext contContext, ModelBindingContext bindContext, PropertyDescriptor propDesc)
    • can be used to override default behavior for certain properties e.g. combine date and time from two fields into one property
    • call base.BindProperty for properties you want to bind using default binding
  • Registor the new binder

ModelBinders.Binders.DefaultBinder =newMyBinder();


  • Weakly typed model, all parameter with login prefix will map to LoginUser model

public ActionResult Login([Bind(Prefix=”login”)]LoginUser user)

  • Exclude / Include paramters for Bind

public ActionResult Save([Bind(Exclude = “Salary”)]Employee emp)


  • Four value providers: FormsValueProvider, QueryStringValueProvider, HttpFileCollectionValueProvider, RouteDataValueProvider
  • Three types of model binding: Strong, Weak and using ValueProvider.



  • Defining routes (IgnoreRoute should come before MapRoute)
public static void RegisterRoutes(RouteCollection routes)
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new
                controller = "Home",
                action = "Index",
                id = UrlParameter.Optional
            constraints: new { id = @"\d+" }


  • In case of Areas, providing a link to action

@Html.ActionLink(“Exam Detail”, “Exam”, “Detail”, new { area=”ExamSite”}, null)


  • Extending default MvcRouteHandler
    • public class MyCustomRouteHandler : MvcRouteHandler
    • Override protected override IHttpHandler GetHttpHandler(RequestContext reqContext)
    • Registering route handler
                new { controller = "Home", action = "Index" }
                ).RouteHandler = new MyCustomRouteHandler();
  • Implementing IRouteHandler (has one method GetHttpHandler)
    • Registration is bit different from above

Route customRoute = new Route(“custom/{name}”, new MyRouteHandler(“My Route”));

routes.Add(“route-name”, customRoute);


  • For custom controller factory, implement IControllerFactory which has three methods: CreateController, ReleaseController, and GetControllerSessionBehavior.
  • Register controller factory in the Global.asax Application_Start method: ControllerBuilder.Current.SetControllerFactory(typeof(MyControllerFactory());
  • Link: Deep Drive into IControllerFactory

View Engine

  • Both RazorViewEngine and Web Forms engine derive from VirtualPathProviderViewEngine which in turn implements IViewEngine
  • IViewEngine has three methods: FindView, FindPartialView and ReleaseView
  • The two find methods return ViewEngineResult object which contains IView
  • IView has one method public void Render(ViewContext viewContext, System.IO.TextWriter writer)

MVC Life Cycle

  • Request
  • UrlRoutingModule selects the Route object
  • Based on the route, UrlRoutingModule obtains an object that implements IRouteHandler (typically it is MvcRouteHandler)
  • MvcRouteHandler creates an instance of MvcHandler which implements IHttpHandler
  • MvcHandler obtains reference to IControllerFactory (typically DefaultControllerFactory)
  • MvcHandler create Controller instance by help of IControllerFactory
  • MvcHandler calls controller’s Execute method
  • ControllerActionInvoker object associated with Controller determines which action method to call
  • Response
  • Controller action create ViewResult
  • ViewResult calls ViewEngine
  • ViewEngine calls View
  • View renders the Response

HTTP Handlers

  • Implement IHttpHandler which has a method ProcessRequest and a property IsReusable
  • Register handler
          <add verb="*" path="" type="SampleHandler" />
          <add verb="*" path="*.SampleFileExtension" type="SampleHandler2 " />

Http Modules

        <add name="HelloWorldModule" type="HelloWorldModule"/>

Windows Identity Foundation

Took ‘A Brief History of Humankind’ from Coursera

Completed ‘A Brief History of Humankind’ course taught by Mr. Yuval Noah Harari from Hebrew University of Jerusalem. The course is offered through Coursera platform.

It is a big history course, giving bird eye view of evolution of humankind from hunter-gathers to present day knowledge workers. The course analyzes long periods of time and is divided into four sections:

Part 1: Cognitive Revolution (about 70,000 years ago)
Part 2: Agriculture Revolution (about 12,000 years ago)
Part 3: Unification of Humankind
Part 4: Scientific Revolution (last 500 years)

Each section has several lectures with the total of 17. The course ran from 10-Aug-2013 to 31-Dec-2013.

It is an highly opinionated account of history, full of contentious claims and ideas. I disagree with the Professor in many of the views expressed in the lectures, still it is a fascinating journey through history, albeit with a different perspective.

Coursera A Brief History of Humankind_01

Udacity’s ‘Introduction to Physics’ course

Took ‘Introduction to Physics’ course at Udacity. It is a beginner level course and I have skimmed through most of it. But what kept me going till the end is the extremely engaging way in which it is taught. Every lesson, you take one important Physics problem and try to solve it. You make progress in small steps by learning required techniques and mathematics. Interactive nature of the platform always makes you think by asking questions before introducing new concepts. On top that, all this is linked with the history of the problem, who solved it and how?

The course has 7 lectures:

Lecture # 1: Circumference of Earth

The Greek philosopher, Eratosthenes (276 BC – 195 BC), was the first person to calculate the circumference of earth with remarkable accuracy. He used geometry and trigonometry to figure this out.

He only needed to take following measurements for his calculation:

  • Length of the shadow cast by an object A at noon at location X.
  • Height of the object A.
  • Distance of location X to the nearest location where sun doesn’t cast any shadow at noon.

See the diagram and link below for details.

Method of Eratosthenes



Lecture # 2: Speed of freely falling object

Aristotle had following view on this:

  • Objects fall at constant speed.
  • Speed is directly proportional to mass of object.

It was Galileo who found that the distance covered by a falling object is directly proportional to the square of time it has been falling (i.e. objects fall with constant acceleration irrespective of their mass).


Lecture # 3: What causes motion?

The prevalent view before Galileo and Newton was Aristotelian. According to which there is one set of laws governing heavenly bodies and a different set for bodies on earth.

Newton through his laws of motion asserted that both heavens and the earth follow the same laws. And the apple falling from a tree or moon orbiting the earth do so under the influence of same force.


Lecture # 4: Keeping Holland Dry



This lecture is about Archimedes Screw and the basic principles behind its working. It builds on the understanding of force from previous lectures and introduces simple machines: Inclined Plane, Pulley and Lever. Simple machines enable us to trade off the force required to lift or move things with the distance. For example, using an inclined plane to move something to a higher level will require less force but we need to push it for a longer distance.

Next, the concepts of Work, Energy and Power are introduced.

  • Work = Force * Distance
  • Work = Change in Energy
  • Power = Work / Time
Work Energy Theorem 

Finally, the Law of Conservation of Energy is discussed with the example of roller coaster ride. During the ride, energy changes its form between kinetic and potential with some of the energy lost due to friction as heat.


Lecture # 5: Lost at Sea

Problem of this lecture is how to measure latitude and longitude?


Latitude is relatively easier to calculate while longitude is much trickier.

When sun is at the highest point in the sky and it is equinox, the latitude can be calculated as explained in the first lecture.

For calculating Longitude, we need to keep track of time. Galileo attempted to measure time by observing transit of Jupiter’s moon but the idea was not very fruitful due to the difficulties involved.

The answer lies in Simple Harmonic Motion.


Elastic Potential Energy


k = Spring Constant

Lecture discusses the discovery of Pendulum by Galileo and invention of Pendulum Clock by Christiaan Huygens.

Longitude can be measured by comparing the time on ship to the time of a known location. Pendulum clocks can be used to reliably measure time and hence calculate longitude.


Lecture # 6: Lightning Strikes



Lightning is an electrical phenomenon. This was not very clear in 18th century. The link between lightning and electricity was there in the literature but it was Benjamin Franklin (17-Jan-1706  to  17-Apr-1790) who emphasized this link and developed lightning rods which prevented buildings from burning due to lightning strikes.


This lecture talks about basics of electricity with particular focus on lightening rod and how it grounds the electric current keeping buildings safe.


Lecture # 7: Special Relativity

This is brief teaser to Special Relativity explaining the following two postulates of the theory and how they lead to bizarre conclusions like time dilation.

  • Laws of Physics are same in all inertial frame of reference
  • Speed of light constant regardless of the frame of reference

de Sitter double star experiment is explained as test of Special Relativity.


It concludes with a final exam where you can test your problem solving skills using the knowledge gained through the course. There are couple of bonus lectures also about ‘simple harmonic motion’ and ‘why can’t we open windows on an airplane’.

Completed ‘HTML5 Game Development’ course from Udacity

I have been taking Massively Open Online Courses at Coursera, but this is the first one at Udacity. The two platforms take different approaches… Coursera is more like a virtual classroom while Udacity feels like a very well designed interactive tutorial. Udacity is self-paced with very short video clips interspersed with questions and quick programming assignments. On the other hand, courses at Coursera start at specific dates and the assignments have deadlines. All students of a batch enroll in the class at the same time and discuss same topics on forums as the course progresses. This gives a more real university classroom like structure to Coursera.

The ‘HTML5 Game Development’ course teaches basic skills to get started with 2D game development. It does that by going through techniques and tools that were used to develop GRITS. GRITS can be downloaded from here. The overall quality of the course could be improved, particularly the grader bugs in some of the assignments were frustrating. Still I had a good time, mainly because Udacity as a platform is great and going by the posts in discussion forums, rest of the computer science courses at Udacity have excellent content. I would be hooked on Udacity for some time 🙂

Following are the tools used or recommended during the course:

Creating Sprite Sheets
Map Editor (Tiled)
Physics Engine
Audio Editor

HTML5 Game Development - Udacity-page-001

Completed ‘Software Engineering for SaaS’ from Coursera

Completed ‘Software Engineering for SaaS’ course offered by Dave Patterson and Armando Fox, Professors at University of California, Berkeley. This course was offered through

The course started on 13th July and the duration was 5 weeks. Course taught the best practices for developing software as a service. It included weekly coding assignments where a SaaS application was developed using the following technologies:

Server Side: Ruby on Rails (Model: ActiveRecord, MVC View: Haml)
Client Side: HTML, CSS and AJAX
Cloud: Heroku
Software Methodology: Agile
Behavior Driven Development tool: Cucumber, Capybara
Test Driven Development tool: RSpec