Monday, August 29, 2011

Posted by SAMAJ SHEKHAR

0

Preventing CSRF using ASP.NET MVC’s Html.AntiForgeryToken() helper method.


How CSRF works

So, what’s it all about? All web application platforms are potentially vulnerable to CSRF, but in this post I’ll focus on ASP.NET MVC. Imagine you have a controller class as follows:

public class UserProfileController : Controller
{
    public ViewResult Edit() { return View(); }
 
    public ViewResult SubmitUpdate()
    {
        // Get the user's existing profile data (implementation omitted)
        ProfileData profile = GetLoggedInUserProfile();
 
        // Update the user object
        profile.EmailAddress = Request.Form["email"];
        profile.FavoriteHobby = Request.Form["hobby"];
        SaveUserProfile(profile);
 
        ViewData["message"] = "Your profile was updated.";
        return View();
    }
}

This is all very normal. First, the visitor goes to Edit(), which renders some form to let them change their user profile details. Secondly, they post that form to SubmitUpdate(), which saves the changes to their profile record in the database. There’s no XSS vulnerability here. Everything’s fine, right? We implement this sort of thing all the time…

Unfortunately, this innocent controller is an easy target for CSRF. Imagine that an attacker sets up the following HTML page and hosts it on some server of their own:
<body onload="document.getElementById('fm1').submit()">
    <form id="fm1" action="http://yoursite/UserProfile/SubmitUpdate" method="post">
        <input name="email" value="hacker@somewhere.evil" />
        <input name="hobby" value="Defacing websites" />
    </form>
</body>

Next, they somehow persuade a victim to visit this page (basic social engineering, look it up). When this HTML page loads, it submits a valid form post to /UserProfile/SubmitUpdate on your server.

Assuming you’re using Windows authentication or some kind of cookie-based authentication system such as Forms Authentication, the automated form post will be processed within the victim’s established authentication context, and will successfully update the victim’s email address to something under the attacker’s control. All the attacker has to do now is use your “forgotten password” facility, and they’re taken control of the victim’s account.

Of course, instead of changing an victim’s email address, they can perform any action that the victim can perform with a single POST request. For example, they might be able to grant administrative permissions to another account, or post something defamatory.

Ways to stop CSRF

There are two main ways to block CSRF:

  • Check that incoming requests have a Referer header referencing your domain. This will stop requests unwittingly submitted from a third-party domain. However, some people disable their browser’s Referer header for privacy reasons, and attackers can sometimes spoof that header if the victim has certain versions of Adobe Flash installed. This is a weak solution.
  • Put a user-specific token as a hidden field in legitimate forms, and check that the right value was submitted. If, for example, this token is the user’s password, then a third-party can’t forge a valid form post, because they don’t know each user’s password. However, don’t expose the user’s password this way: Instead, it’s better to use some random value (such as a GUID) which you’ve stored in the visitor’s Session collection or into a Cookie.

Using the AntiForgeryToken helpers

The core ASP.NET MVC package includes a set of helpers that give you a means to detect and block CSRF using the “user-specific tokens” technique.

To use these helpers to protect a particular form, put an Html.AntiForgeryToken() into the form, e.g.,

<% using(Html.Form("UserProfile", "SubmitUpdate")) { %>
    <%= Html.AntiForgeryToken() %>
    <!-- rest of form goes here -->
<% } %>

This will output something like the following:

<form action="/UserProfile/SubmitUpdate" method="post">
    <input name="__RequestVerificationToken" type="hidden" value="saTFWpkKN0BYazFtN6c4YbZAmsEwG0srqlUqqloi/fVgeV2ciIFVmelvzwRZpArs" />
    <!-- rest of form goes here -->
</form>

At the same time, Html.AntiForgeryToken() will give the visitor a cookie called __RequestVerificationToken, with the same value as the random hidden value shown above.

Next, to validate an incoming form post, add the [ValidateAntiForgeryToken] filter to your target action method. For example,

[ValidateAntiForgeryToken]
public ViewResult SubmitUpdate()
{
    // ... etc
}

This is an authorization filter that checks that:

  • The incoming request has a cookie called __RequestVerificationToken
  • The incoming request has a Request.Form entry called __RequestVerificationToken
  • These cookie and Request.Form values match

Assuming all is well, the request goes through as normal. But if not, boom!, there’s an authorization failure with message “A required anti-forgery token was not supplied or was invalid”.

This prevents CSRF because even if a potential victim has an __RequestVerificationToken cookie, an attacker can’t find out its value, so they can’t forge a valid form post with the same value in Request.Form. But legitimate users aren’t inconvenienced at all; the mechanism is totally silent.

Using salt

Salt? In case you want to protect multiple forms in your application independently of each other, you can use a “salt” value when you call Html.AntiForgeryToken(), e.g.,

<%= Html.AntiForgeryToken("someArbitraryString") %>

… and also in [ValidateAntiForgeryToken], e.g.,

[ValidateAntiForgeryToken(Salt="someArbitraryString")]
public ViewResult SubmitUpdate()
{
    // ... etc
}

Salt is just an arbitrary string. A different salt value means a different anti-forgery token will be generated. This means that even if an attacker manages to get hold of a valid token somehow, they can’t reuse it in other parts of the application where a different salt value is required.

Limitations of the Anti-Forgery helpers

ASP.NET MVC’s anti-CSRF helpers work very nicely, but you should be aware of a few limitations:

  • All legitimate visitors must accept cookies (otherwise, [ValidateAntiForgeryToken] will deny their form posts). Arguably this isn’t a limitation, because unless visitors allow cookies, you probably don’t have anything to protect anyway.
  • It only works with POST requests, not GET requests. Arguably this isn’t a limitation, because under the normal HTTP conventions, you shouldn’t be using GET requests for anything other than read-only operations.
  • It’s easily bypassed if you have any XSS holes on your domain. An XSS hole would allow an attacker to read a victim’s anti-forgery token value, then use it to forge valid posts. So, don’t have XSS holes!
  • It relies on the potential victim’s browser implementing cross-domain boundaries solidly. Browsers are supposed to stop foreign domains from reading your app’s response text and cookies, and are supposed to stop foreign domains from writing cookies to your domain. If an attacker manages to find a way around this, they can bypass [ValidateAntiForgeryToken]. Of course that’s not supposed to be possible. For the most part, modern browsers block this line of attack.

In conclusion, ASP.NET MVC’s anti-CSRF helpers are easy to use, and work very nicely

Contents taken from here
READ MORE - Preventing CSRF using ASP.NET MVC’s Html.AntiForgeryToken() helper method.

Friday, July 22, 2011

Posted by SAMAJ SHEKHAR

0

Introduction to HTML5 <Canvas>: Part 2 (Example)


This post is the sequel to my previous post of Introduction to HTML5 <Canvas>: Part 1 and shows a walkthrough example of using canvas for some static 2D drawing (for Introduction to animation wait for my next post). This is the second post to my “HTML5 <Canvas>” series.
In previous post we saw how <Canvas>'s context gives us an API with set of methods and properties to draw on its surface, now in this post we will use some of those methods to draw a logo of one of my favorite game PORTAL2.
Sorry, but your Browser Dosen't Support HTML5 <canvas>
Above is the actual completed art drawn on canvas, and below we will see how we draw that art piece by piece. And Let me tell you this article is just for introducing you to the use of various methods provided by canvas and may not show the best and efficient way of drawing on it. So keeping that in mind, let’s get started.

First things first

As you may know by now that before any drawing we need to have a handle on <Canvas> element to do manipulations, and that handle is the context object of the <Canvas>. The context of the <Canvas> element provides us all that API of methods to do drawing and manipulation on <Canvas>. To get the context we use "getContext()” method and pass in the string “2d” as parameter * . Also since we feel more natural using “degrees” for specifying angles but all functions of canvas context take clockwise “radians” as parameter, we’ll use following function to convert degree into anticlockwise* radians. Also note that it is recommended to use "save()” and “restore()” methods of context to save the current state of the context on the stack before any manipulation & transformation and restore it back to its previous state respectively.
*(for details check my previous post or w3c draft)
//context of the canvas
var ctx = document.getElementById("portalcanvas").getContext("2d"); 
//function to convert radians to degrees
var acDegToRad = function(deg){
		return deg* (-(Math.PI / 180.0));    
}

Drawing the “2”

We’ll start by drawing the number “2” on the <Canvas>. It consists of 3 pieces the base rectangle, a slant rectangle and an arc.
  • 2’s Base: The base rectangle is the easiest of all to draw, just set the “ fillStyle” property of the context to light gray color and use “fillRect( x, y, width, height)” method to draw the rectangle.
    ctx.save();
    ctx.fillStyle = "rgb(110,110,110)";
    ctx.fillRect(20,200,120,35);
    ctx.restore();
    
    If we want we could also draw above rectangle as a small horizontal line with line-width equal to the height of the above rectangle. But that would involve more steps like creating a path and then drawing the line along the path, which is more complicated for this primitive shape.
  • 2’s Slant: The slant rectangle is just a simple rectangle but elevated to an angle of 35 Degrees. So to create a slant rectangle first we will translate the origin of the coordinate space (i.e., the transformation matrix) to the top edge of 2’s base rectangle using “translate( newX, newY)” and then rotate the coordinate space by 35 degrees in anti-clockwise direction, taking new origin as the pivot/center, by using the “rotate(radians)” method and then simply draw the rectangle using fillRect( x, y, width, height).
    ctx.save();
    ctx.fillStyle = "rgb(110,110,110)";
    ctx.translate(20,200);
    ctx.rotate(acDegToRad(35));
    ctx.fillRect(0,0,100,35);
    ctx.restore();
    
    Also note that how we have used save() before any manipulation and then used restore() after drawing, this makes sure that the translation and rotation of coordinate space does not affect rest of drawings we are about do later on. This way context state of the canvas always remains in previous state, in this case, the Initial state. Remember save() and restore() doesn’t save/restore the contents on the canvas, it just save/restore the state of properties/attributes like “fillStyle”, “strokeStyle”, “lineWidth”, etc and coordinate space on the <Canvas>drawing context.
  • 2’s Arc: The top arc of number “2” cannot be drawn by rectangle methods but can be simply drawn like a line arc whose line-width is equal to the height of previous rectangles. For creating any line shape we first start a path by calling “beginPath()” method, then call any shape method like “rect()”, “arc()”, “lineTo()”, etc to add them to path and then optionally call “closePath()” method to complete the path and start new one. For this step we will start a new path and add an arc to the path by using “arc(x,y,radius, startAngle, endAngle)” method. So far we have only created the path, to actually draw the arc on canvas we will call “stroke()” method. But since stroke will draw with default color, so before calling “stroke()“ we will set “strokeStyle” property of context to light gray.
    ctx.save();
    ctx.lineWidth = 35;
    ctx.beginPath();
    ctx.arc(77,135,40,acDegToRad(-40),acDegToRad(180),true); 
    ctx.strokeStyle = "rgb(110,110,110)";
    ctx.stroke();
    ctx.restore();
    

Drawing the “blue guy”

The next thing to be drawn is that blue guy coming out of the wall. This art consists of a wall, blue guy’s head, his tummy and then this hand & legs.
  • Wall: The wall is the just a simple slim and tall blue rectangle.
    ctx.save();	
    ctx.fillStyle = "rgb(0,160,212)";
    ctx.fillRect(162,20,8,300);		
    ctx.restore();
    
  • Head: The blue guy’s head is also a simple circle, but since we not have a direct method like “fillCircle()”, we’ll need to use a similar trick as we did for “2’s” arc. We will start a new path, add a full 360 degree arc and fill it with color. For filling we will use “fill()” method accompanied by “fillStyle” property set to light blue color, to fill the path with blue color thereby creating a filled circle.
    ctx.save();
    ctx.fillStyle = "rgba(256,256,256,0.75)";
    ctx.fillRect(0,0,300,350);
    ctx.fillStyle = "rgb(0,160,212)";
    ctx.beginPath();
    ctx.arc(225,80,35,acDegToRad(0),acDegToRad(360));
    ctx.fill();		
    ctx.restore();
    
    A thing to note here is that when you create a path you have two options, either to call “stroke()” method to draw that path using current “strokeStyle”, as we did earlier and will do for hand and legs, or to call “fill()”method to fill the path with current “fillStyle”, as we did just now for head and will do for tummy. We also have an option of calling “clip()” method (discussed later).
  • Tummy: The tummy of the blue guy is also drawn by creating a triangle path and filling the triangle with blue color. To create the triangle path we first start a new path, move the initial drawing point from origin or any last position (lets it be O) to a point on the wall below the head using “moveTo(x, y)” method which moves the drawing point from current draw point to a new point (let it be A) without adding the line between O & A to the path, then use “lineTo( x, y)” method which moves the drawing point to a new point (let it be B) and also adds the line between A & B to the path. Similarly add the third point (let it be C) to complete the three points of the triangle. This will also add the line between B & C to the path. Now optionally you can use “lineTo( x, y)” method to go back to point A and add line between C & A to the path and thus closing the path but by default the “fill()” will automatically assume a line between opening and closing points and will fill the enclosed area.
    ctx.save();
    ctx.fillStyle = "rgb(0,160,212)";
    ctx.beginPath();
    ctx.moveTo(170,90);  //point A
    ctx.lineTo(230,140); //point B
    ctx.lineTo(170,210); //point C
    ctx.fill(); //fill area between ABC
    ctx.restore();
    
  • Hand: For hand we will simply create two lines as we did above. A to B for shoulder to elbow and B to C for forearm. But by default the line is 1px wide first we will set “lineWidth” property of context to 25px, then since line’s ends and joints (at B) are rectangular by default, we will set both “lineCap” property, for line ends and “lineJoin” property to “round”. And since we want lines to be drawn instead of filling the space between, we will call “stroke()” method of context.
    ctx.save();	
    ctx.lineWidth = 25;
    ctx.lineCap = "round";
    ctx.lineJoin = "round"; 
    ctx.strokeStyle = "rgb(0,160,212)";
    ctx.beginPath();
    ctx.moveTo(222,150);  //point A
    ctx.lineTo(230,190);  //point B
    ctx.lineTo(270,220);  //point C
    ctx.stroke();
    ctx.restore();
    
  • Leg: The leg can be drawn exactly as we drew the hand so code will be much same as above except for the coordinates.
    ctx.save();
    ctx.lineWidth = 25;
    ctx.lineCap = "round";
    ctx.lineJoin = "round";
    ctx.strokeStyle = "rgb(0,160,212)";
    ctx.moveTo(160,210);  //point A
    ctx.lineTo(195,260);  //point B
    ctx.lineTo(160,290);  //point C
    ctx.stroke();		
    ctx.restore();
    
    But there is a problem with above code, the result leg doesn’t look like what we want. Part of the leg is hidden in the wall, so we need to clip the extra piece of leg from the drawing.
  • Clip Leg: With above code we didn’t got what we wanted but fret not, “clip()” method comes to rescue. Clip is similar to fill method but instead of filling the area enclosed by the path with some color, it creates an enclosed invisible boundary (outline of triangle is drawn in figure only to highlight the clip area) where any drawing on it clipped if it does not lie in the clipping region and only the drawing lying in the clipping region is shown. So to clip legs protruding through the wall, we’ll first create a clipping region by creating a triangular path with one of its side coinciding with the wall and then draw the leg same as we drew the hand.
    ctx.save();
    //code for drawing clipping region
    ctx.beginPath();
    ctx.moveTo(170,200);  //point A
    ctx.lineTo(250,260);  //point B
    ctx.lineTo(170,320);  //point C
    ctx.lineTo(170,200);  //back to point A to close the path
    ctx.clip();           //set the above path for clipping region
    //code for drawing leg
    ctx.lineWidth = 25;
    ctx.lineCap = "round";
    ctx.strokeStyle = "rgb(0,160,212)";
    ctx.lineJoin = "round";
    ctx.beginPath();
    ctx.moveTo(160,210);
    ctx.lineTo(195,260);
    ctx.lineTo(160,290);
    ctx.stroke();		
    ctx.restore();
    
And that’s all we need to do to create the that Portal 2 Logo, Below is an animated canvas showing all the pieces we used to draw it (in fact every image in this article is actually drawn on the <Canvas> elements) accompanied by complete combined code I used to draw it. So I hope that you liked this article and stay tuned for my next post where I will discuss 2D animation on <Canvas>.

(Actual Source Code)


(function(){
    var ctx = document.getElementById("portalcanvas").getContext("2d");
	//function to convert deg to radian
    var acDegToRad = function(deg){
			return deg* (-(Math.PI / 180.0));    
		}

	//save the initial state of the context
	ctx.save();		
	//set fill color to gray
	ctx.fillStyle = "rgb(110,110,110)";
	//save the current state with fillcolor
	ctx.save();

	//draw 2's base rectangle
	ctx.fillRect(20,200,120,35);
	//bring origin to 2's base
	ctx.translate(20,200);
	//rotate the canvas 35 deg anti-clockwise
	ctx.rotate(acDegToRad(35));
	//draw 2's slant rectangle
	ctx.fillRect(0,0,100,35);
	//restore the canvas to reset transforms
	ctx.restore();
	//set stroke color width and draw the 2's top semi circle
	ctx.strokeStyle = "rgb(110,110,110)";
	ctx.lineWidth = 35;
	ctx.beginPath();
	ctx.arc(77,135,40,acDegToRad(-40),acDegToRad(180),true);
	ctx.stroke();

	//reset canvas transforms
	ctx.restore();

	//change color to blue
	ctx.fillStyle = "rgb(0,160,212)";
	//save current state of canvas
	ctx.save();
	//draw long dividing rectangle 
	ctx.fillRect(162,20,8,300);
	//draw player head circle
	ctx.beginPath();
	ctx.arc(225,80,35,acDegToRad(0),acDegToRad(360));
	ctx.fill();

	//start new path for tummy :)
	ctx.beginPath();
	ctx.moveTo(170,90);
	ctx.lineTo(230,140);
	ctx.lineTo(170,210);
	ctx.fill();

	//start new path for hand
	//set lineCap and lineJoin to "round", blue color 
	//for stroke, and width of 25px
	ctx.lineWidth = 25;
	ctx.lineCap = "round";
	ctx.strokeStyle = "rgb(0,160,212)";
	ctx.lineJoin = "round";
	ctx.beginPath();
	ctx.moveTo(222,150);
	ctx.lineTo(230,190);
	ctx.lineTo(270,220);
	ctx.stroke();

	ctx.beginPath();
	ctx.moveTo(170, 200);
	ctx.lineTo(250, 260);
	ctx.lineTo(170,320);
	ctx.clip();	

	//begin new path for drawing leg
	ctx.beginPath();
	ctx.moveTo(160,210);
	ctx.lineTo(195,260);
	ctx.lineTo(160,290);
	ctx.stroke();
	
	//restore the context back to its initial state
	ctx.restore();
})()
READ MORE - Introduction to HTML5 <Canvas>: Part 2 (Example)

Tuesday, May 10, 2011

Posted by SAMAJ SHEKHAR

0

How 'delete' works in JavaScript (by kangax)


Recently I was cheking out this question on StackOverflow which led me to a nice quizz to test your JavaScript knowledge. There, a question regarding delete made me think twice and so i googled up how delete works, and found this nice article i have posted (pasted ;) below.

NOTE: The contents below are taken from the Article "Understanding delete" written by Juriy Zaytsev. And from hereon "I" refers to him not me.

Contents

  1. Theory

  2. Firebug confusion

  3. Browsers compliance

  4. IE bugs
  5. Misconceptions
  6. `delete` and host objects
  7. ES5 strict mode
  8. Summary

A couple of weeks ago, I had a chance to glance through Stoyan Stefanov’s Object-Oriented Javascript. The book had an exceptionally high rating on Amazon (12 reviews with 5 stars), so I was curious to see if it was something worth recommending. I started reading through chapter on functions, and really enjoyed the way things were explained there; the flow of examples was structured in such nice, progressive way, it seemed even beginners would grasp it easily. However, almost immediately I stumbled upon an interesting misconception present throughout the entire chapter — deleting functions. There were some other mistakes (such as the difference between function declarations and function expressions), but we aren’t going to talk about them now.

The book claims that “function is treated as a normal variable—it can be copied to a different variable and even deleted.”. Following that explanation, there is this example:

  >>> var sum = function(a, b) {return a + b;}
  >>> var add = sum;
  >>> delete sum
  true
  >>> typeof sum;
  "undefined"

Ignoring a couple of missing semicolons, can you see what’s wrong with this snippet? The problem, of course, is that deleting sum variable should not be successful; delete statement should not evaluate to true and typeof sum should not result in “undefined”. All because it’s not possible to delete variables in Javascript. At least not when declared in such way.

So what’s going on in this example? Is it a typo? A diversion? Probably not. This whole snippet is actually a real output from the Firebug console, which Stoyan must have been using for quick testing. It’s almost as if Firebug follows some other rules of deletion. It is Firebug that has led Stoyan astray! So what is really going on here?

To answer this question, we need to understand how delete operator works in Javascript: what exactly can and cannot be deleted and why. Today I’ll try to explain this in details. We’ll take a look at Firebug’s “weird” behavior and realize that it’s not all that weird; we’ll delve into what’s going on behind the scenes when declaring variables, functions, assigning properties and deleting them; we’ll look at browsers’ compliance and some of the most notorious bugs; we’ll also talk about strict mode of 5th edition of ECMAScript, and how it changes delete operator behavior.

I’ll be using Javascript and ECMAScript interchangeable to really mean ECMAScript (unless explicitly talking about Mozilla’s JavaScript™ implementation).

Unsurprisingly, explanations of delete on the web are rather scarce. MDC article is probably the most comprehensive resource, but unfortunately misses few interesting details about the subject; Curiously, one of these forgotten things is the cause of Firebug’s tricky behavior. MSDN reference is practically useless.

Theory

So why is it that we can delete object properties:

  var o = { x: 1 };
  delete o.x; // true
  o.x; // undefined

but not variables, declared like this:

  var x = 1;
  delete x; // false
  x; // 1

or functions, declared like this:

  function x(){}
  delete x; // false
  typeof x; // "function"

Note that delete only returns false when a property can not be deleted.

To understand this, we need to first grasp such concepts as variable instantiation and property attributes — something that’s unfortunately rarely covered in books on Javascript. I’ll try go over these very concisely in the next few paragraphs. It’s not hard to understand them at all! If you don’t care about why things work the way they work, feel free to skip this chapter.

Type of code

There are 3 types of executable code in ECMAScript: Global code, Function code and Eval code. These types are somewhat self-descriptive, but here’s a short overview:

  1. When a source text is treated as a Program, it is executed in a global scope, and is considered a Global code. In a browser environment, content of SCRIPT elements is usually parsed as a Program, and is therefore evaluated as a Global code.
  2. Anything that’s executed directly within a function is, quite obviously, considered a Function code. In browsers, content of event attributes (e.g. <p onclick="...">) is usually parsed and treated as a Function code.
  3. Finally, text that’s supplied to a built-in eval function is parsed as Eval code. We will soon see why this type is special.

Execution context

When ECMAScript code executes, it always happens within certain execution context. Execution context is a somewhat abstract entity, which helps understand how scope and variable instantiation works. For each of three types of executable code, there’s an execution context. When a function is executed, it is said that control enters execution context for Function code; when Global code executes, control enters execution context for Global code, and so on.

As you can see, execution contexts can logically form a stack. First there might be Global code with its own execution context; that code might call a function, with its own execution context; that function could call another function, and so on and so forth. Even if function is calling itself recursively, a new execition context is being entered with every invocation.

Activation object / Variable object

Every execution context has a so-called Variable Object associated with it. Similarly to execution context, Variable object is an abstract entity, a mechanism to describe variable instantiation. Now, the interesing part is that variables and functions declared in a source text are actually added as properties of this Variable object.

When control enters execution context for Global code, a Global object is used as a Variable object. This is precisely why variables or functions declared globally become properties of a Global object:

  /* remember that `this` refers to global object when in global scope */
  var GLOBAL_OBJECT = this;

  var foo = 1;
  GLOBAL_OBJECT.foo; // 1
  foo === GLOBAL_OBJECT.foo; // true

  function bar(){}
  typeof GLOBAL_OBJECT.bar; // "function"
  GLOBAL_OBJECT.bar === bar; // true

Ok, so global variables become properties of Global object, but what happens with local variables — those declared in Function code? The behavior is actually very similar: they become properties of Variable object. The only difference is that when in Function code, a Variable object is not a Global object, but a so-called Activation object. Activation object is created every time execution context for Function code is entered.

Not only do variables and functions declared within Function code become properties of Activation object; this also happens with each of function arguments (under names corresponding to formal parameters) and a special Arguments object (under arguments name). Note that Activation object is an internal mechanism and is never really accessible by program code.

  (function(foo){

    var bar = 2;
    function baz(){}

    /*
    In abstract terms,

    Special `arguments` object becomes a property of containing function's Activation object:
      ACTIVATION_OBJECT.arguments; // Arguments object

    ...as well as argument `foo`:
      ACTIVATION_OBJECT.foo; // 1

    ...as well as variable `bar`:
      ACTIVATION_OBJECT.bar; // 2

    ...as well as function declared locally:
      typeof ACTIVATION_OBJECT.baz; // "function"
    */

  })(1);

Finally, variables declared within Eval code are created as properties of calling context’s Variable object. Eval code simply uses Variable object of the execution context that it’s being called within:

  var GLOBAL_OBJECT = this;

  /* `foo` is created as a property of calling context Variable object,
      which in this case is a Global object */

  eval('var foo = 1;');
  GLOBAL_OBJECT.foo; // 1

  (function(){

    /* `bar` is created as a property of calling context Variable object,
      which in this case is an Activation object of containing function */

    eval('var bar = 1;');

    /*
      In abstract terms,
      ACTIVATION_OBJECT.bar; // 1
    */

  })();

Property attributes

We are almost there. Now that it’s clear what happens with variables (they become properties), the only remaining concept to understand is property attributes. Every property can have zero or more attributes from the following set — ReadOnly, DontEnum, DontDelete and Internal. You can think of them as flags — an attribute can either exist on a property or not. For the purposes of today’s discussion, we are only interested in DontDelete.

When declared variables and functions become properties of a Variable object — either Activation object (for Function code), or Global object (for Global code), these properties are created with DontDelete attribute. However, any explicit (or implicit) property assignment creates property without DontDelete attribute. And this is essentialy why we can delete some properties, but not others:

  var GLOBAL_OBJECT = this;

  /*  `foo` is a property of a Global object.
      It is created via variable declaration and so has DontDelete attribute.
      This is why it can not be deleted. */

  var foo = 1;
  delete foo; // false
  typeof foo; // "number"

  /*  `bar` is a property of a Global object.
      It is created via function declaration and so has DontDelete attribute.
      This is why it can not be deleted either. */

  function bar(){}
  delete bar; // false
  typeof bar; // "function"

  /*  `baz` is also a property of a Global object.
      However, it is created via property assignment and so has no DontDelete attribute.
      This is why it can be deleted. */

  GLOBAL_OBJECT.baz = 'blah';
  delete GLOBAL_OBJECT.baz; // true
  typeof GLOBAL_OBJECT.baz; // "undefined"

Built-ins and DontDelete

So this is what it’s all about: a special attribute on a property that controls whether this property can be deleted or not. Note that some of the properties of built-in objects are specified to have DontDelete, and so can not be deleted. Special arguments variable (or, as we know now, a property of Activation object) has DontDelete. length property of any function instance has DontDelete as well:

  (function(){

    /* can't delete `arguments`, since it has DontDelete */

    delete arguments; // false
    typeof arguments; // "object"

    /* can't delete function's `length`; it also has DontDelete */

    function f(){}
    delete f.length; // false
    typeof f.length; // "number"

  })();

Properties corresponding to function arguments are created with DontDelete as well, and so can not be deleted either:

  (function(foo, bar){

    delete foo; // false
    foo; // 1

    delete bar; // false
    bar; // 'blah'

  })(1, 'blah');

Undeclared assignments

As you might remember, undeclared assignment creates a property on a global object. That is unless that property is found somewhere in the scope chain before global object. And now that we know the difference between property assignment and variable declaration — latter one sets DontDelete, whereas former one doesn’t — it should be clear why undeclared assignment creates a deletable property:

  var GLOBAL_OBJECT = this;

  /* create global property via variable declaration; property has DontDelete */
  var foo = 1;

  /* create global property via undeclared assignment; property has no DontDelete */
  bar = 2;

  delete foo; // false
  typeof foo; // "number"

  delete bar; // true
  typeof bar; // "undefined"

Note that it is during property creation that attributes are determined (i.e. none are set). Later assignments don’t modify attributes of existing property. It’s important to understand this distinction.

  /* `foo` is created as a property with DontDelete */
  function foo(){}

  /* Later assignments do not modify attributes. DontDelete is still there! */
  foo = 1;
  delete foo; // false
  typeof foo; // "number"

  /* But assigning to a property that doesn't exist,
     creates that property with empty attributes (and so without DontDelete) */

  this.bar = 1;
  delete bar; // true
  typeof bar; // "undefined"

Firebug confusion

So what happens in Firebug? Why is it that variables declared in console can be deleted, contrary to what we have just learned? Well, as I said before, Eval code has a special behavior when it comes to variable declaration. Variables declared within Eval code are actually created as properties without DontDelete:

  eval('var foo = 1;');
  foo; // 1
  delete foo; // true
  typeof foo; // "undefined"
  

and, similarly, when called within Function code:

  (function(){

    eval('var foo = 1;');
    foo; // 1
    delete foo; // true
    typeof foo; // "undefined"

  })();

And this is the gist of Firebug’s abnormal behavior. All the text in console seems to be parsed and executed as Eval code, not as a Global or Function one. Obviously, any declared variables end up as properties without DontDelete, and so can be easily deleted. Be aware of these differences between regular Global code and Firebug console.

Deleting variables via eval

This interesting eval behavior, coupled with another aspect of ECMAScript can technically allow us to delete non-deletable properties. The thing about function declarations is that they can overwrite same-named variables in the same execution context:

  function x(){ }
  var x;
  typeof x; // "function"

Note how function declaration takes precedence and overwrites same-named variable (or, in other words, same property of Variable object). This is because function declarations are instantiated after variable declarations, and are allowed to overwrite them. Not only does function declaration replaces previous value of a property, it also replaces that property attributes. If we declare function via eval, that function should also replace that property’s attributes with its own. And since variables declared from within eval create properties without DontDelete, instantiating this new function should essentially remove existing DontDelete attribute from the property in question, making that property deletable (and of course changing its value to reference newly created function).

  var x = 1;

  /* Can't delete, `x` has DontDelete */

  delete x; // false
  typeof x; // "number"

  eval('function x(){}');

  /* `x` property now references function, and should have no DontDelete */

  typeof x; // "function"
  delete x; // should be `true`
  typeof x; // should be "undefined"

Unfortunately, this kind of spoofing doesn’t work in any implementation I tried. I might be missing something here, or this behavior might simply be too obscure for implementors to pay attention to.

Browsers compliance

Knowing how things work in theory is useful, but practical implications are paramount. Do browsers follow standards when it comes to variable/property creation/deletion? For the most part, yes.

I wrote a simple test suite to check compliance of delete operator with Global code, Function code and Eval code. Test suite checks both — return value of delete operator, and whether properties are deleted (or not) as they are supposed to. delete return value is not as important as its actual results. It’s not very crucial if delete returns true instead of false, but it’s important that properties with DontDelete are not deleted and vice versa.

Modern browsers are generally pretty compliant. Besides this eval peculiarity I mentioned earlier, the following browsers pass test suite fully: Opera 7.54+, Firefox 1.0+, Safari 3.1.2+, Chrome 4+.

Safari 2.x and 3.0.4 have problems with deleting function arguments; those properties seem to be created without DontDelete, so it is possible to delete them. Safari 2.x has even more problems — deleting non-reference (e.g. delete 1) throws error; function declarations create deletable properties (but, strangely, not variable declarations); variable declarations in eval become non-deletable (but not function declarations).

Similar to Safari, Konqueror (3.5, but not 4.3) throws error when deleting non-reference (e.g. delete 1) and erroneously makes function arguments deletable.

Gecko DontDelete bug

Gecko 1.8.x browsers — Firefox 2.x, Camino 1.x, Seamonkey 1.x, etc. — exhibit an interesting bug where explicitly assigning to a property can remove its DontDelete attribite, even if that property was created via variable or function declaration:

    function foo(){}
    delete foo; // false (as expected)
    typeof foo; // "function" (as expected)

    /* now assign to a property explicitly */

    this.foo = 1; // erroneously clears DontDelete attribute
    delete foo; // true
    typeof foo; // "undefined"

    /* note that this doesn't happen when assigning property implicitly */

    function bar(){}
    bar = 1;
    delete bar; // false
    typeof bar; // "number" (although assignment replaced property)

Surprisingly, Internet Explorer 5.5 – 8 passes test suite fully except that deleting non-reference (e.g. delete 1) throws error (just like in older Safari). But there are actually more serious bugs in IE, that are not immediately apparent. These bugs are related to Global object.

IE bugs

The entire chapter just for bugs in Internet Explorer? How unexpected!

In IE (at least, 6-8), the following expression throws error (when evaluated in Global code):

    this.x = 1;
    delete x; // TypeError: Object doesn't support this action
  

and this one as well, but different exception, just to make things interesting:

    var x = 1;
    delete this.x; // TypeError: Cannot delete 'this.x'

It’s as if variable declarations in Global code do not create properties on Global object in IE. Creating property via assignment (this.x = 1) and then deleting it via delete x throws error. Creating property via declaration (var x = 1) and then deleting it via delete this.x throws another error.

But that’s not all. Creating property via explicit assignment actually always throws error on deletion. Not only is there an error, but created property appears to have DontDelete set on it, which of course it shouldn’t have:

    this.x = 1;

    delete this.x; // TypeError: Object doesn't support this action
    typeof x; // "number" (still exists, wasn't deleted as it should have been!)

    delete x; // TypeError: Object doesn't support this action
    typeof x; // "number" (wasn't deleted again)

Now, contrary to what one would think, undeclared assignments (those that should create a property on global object) do create deletable properties in IE:

    x = 1;
    delete x; // true
    typeof x; // "undefined"

But if you try to delete such property by referecing it via this in Global code (delete this.x), a familiar error pops up:

    x = 1;
    delete this.x; // TypeError: Cannot delete 'this.x'

If we were to generalize this behavior, it would appear that delete this.x from within Global code never succeeds. When property in question is created via explicit assignment (this.x = 1), delete throws one error; when property is created via undeclared assignment (x = 1) or via declaration (var x = 1), delete throws another error.

delete x, on the other hand, only throws error when property in question is created via explicit assignment — this.x = 1. If a property is created via declaration (var x = 1), deletion simply never occurs and delete correctly returns false. If a property is created via undeclared assignment (x = 1), deletion works as expected.

I was pondering about this issue back in September, and Garrett Smith suggested that in IE “The global variable object is implemented as a JScript object, and the global object is implemented by the host. Garrett used Eric Lippert’s blog entry as a reference.
We can somewhat confirm this theory by performing few tests. Note how this and window seem to reference same object (if we can believe === operator), but Variable object (the one on which function is declared) is different from whatever this references.

    /* in Global code */
    function getBase(){ return this; }

    getBase() === this.getBase(); // false
    this.getBase() === this.getBase(); // true
    window.getBase() === this.getBase(); // true
    window.getBase() === getBase(); // false

Misconceptions

The beauty of understanding why things work the way they work can not be underestimated. I’ve seen few misconceptions on the web related to misunderstanding of delete operator. For example, there’s this answer on Stackoverflow (with surprisingly high rating), confidently explaining how “delete is supposed to be no-op when target isn’t an object property”. Now that we understand the core of delete behavior, it becomes pretty clear that this answer is rather inaccurate. delete doesn’t differentiate between variables and properties (in fact, for delete, those are all References) and really only cares about DontDelete attribute (and property existence).

It’s also interesting to see how misconceptions bounce off of each other, where in the very same thread someone first suggests to just delete variable (which won’t work unless it’s declared from within eval), and another person provides a wrong correction how it’s possible to delete variables in Global code but not in Function one.

Be careful with Javascript explanations on the web, and ideally, always seek to understand the core of the issue ;)

`delete` and host objects

An algorithm for delete is specified roughtly like this:

  1. If operand is not a reference, return true
  2. If object has no direct property with such name, return true (where, as we now know, object can be Activation object or Global object)
  3. If property exists but has DontDelete, return false
  4. Otherwise, remove property and return true

However, behavior of delete operator with host objects can be rather unpredictable. And there’s actually nothing wrong with that: host objects are allowed (by specification) to implement any kind of behavior for operations such as read (internal [[Get]] method), write (internal [[Put]] method) or delete (internal [[Delete]] method), among few others. This allowance for custom [[Delete]] behavior is what makes host objects so chaotic.

We’ve already seen some IE oddities, where deleting certain objects (which are apparently implemented as host objects) throws errors. Some versions of Firefox throw when trying to delete window.location. You can’t trust return values of delete either, when it comes to host objects; take a look at what happens in Firefox:

    /* "alert" is a direct property of `window` (if we were to believe `hasOwnProperty`) */
    window.hasOwnProperty('alert'); // true

    delete window.alert; // true
    typeof window.alert; // "function"

Deleting window.alert returns true, even though there’s nothing about this property that should lead to such result. It resolves to a reference (so can’t return true on the first step). It’s a direct property of a window object (so can’t return true on a second step). The only way delete could return true is after reaching step 4 and actually deleting a property. Yet, property is never deleted.

The moral of the story is to never trust host objects.

ES5 strict mode

So what does strict mode of ECMAScript 5th edition bring to the table? Few restrictions are being introduced. SyntaxError is now thrown when expression in delete operator is a direct reference to a variable, function argument or function identifier. In addition, if property has internal [[Configurable]] == false, a TypeError is thrown:

  (function(foo){

    "use strict"; // enable strict mode within this function

    var bar;
    function baz(){}

    delete foo; // SyntaxError (when deleting argument)
    delete bar; // SyntaxError (when deleting variable)
    delete baz; // SyntaxError (when deleting variable created with function declaration)

    /* `length` of function instances has { [[Configurable]] : false } */

    delete (function(){}).length; // TypeError

  })();

In addition, deleting undeclared variable (or in other words, unresolved Referece) throws SyntaxError as well:

    "use strict";
    delete i_dont_exist; // SyntaxError

This is somewhat similar to the way undeclared assignment in strict mode behaves (except that ReferenceError is thrown instead of a SyntaxError):

    "use strict";
    i_dont_exist = 1; // ReferenceError

As you now understand, all these restrictions somewhat make sense, given how much confusion deleting variables, function declarations and arguments causes. Instead of silently ignoring deletion, strict mode takes more agressive and descriptive measures.

Summary

This post turned out to be quite lengthy, so I’m not going to talk about things like removing array items with delete and what the implications of it are. You can always refer to MDC article for that particular explanation (or read specs and experiment yourself).

Here’s a short summary of how deletion works in Javascript:

  • Variables and function declarations are properties of either Activation or Global objects.
  • Properties have attributes, one of which — DontDelete — is responsible for whether a property can be deleted.
  • Variable and function declarations in Global and Function code always create properties with DontDelete.
  • Function arguments are also properties of Activation object and are created with DontDelete.
  • Variable and function declarations in Eval code always create properties without DontDelete.
  • New properties are always created with empty attributes (and so without DontDelete).
  • Host objects are allowed to react to deletion however they want.

If you’d like to get more familiar with things described here, please refer to ECMA-262 3rd edition specification.

I hope you enjoyed this overview and learned something new. Any questions, suggestions and corrections are as always welcomed.

READ MORE - How 'delete' works in JavaScript (by kangax)

Monday, April 18, 2011

Posted by SAMAJ SHEKHAR

0

How to: Change Firefox 4's Default search from Bing to Google


Description

When you type something in plain text (i.e. not an address beginning www, etc) into the address bar in Mozilla Firefox it tends to perform a little bit of magic. After hitting enter you’ll usually end up either on a web page that’s quite relevant to what you typed, on the Google Search Results page with results of what you typed or else you’ll end up on Google search engines results with results of what you typed.

This Location Bar's Search feature is an Internet Keyword search where, if you enter text into the Location bar that is not a valid Internet address (URL), Firefox will try to direct you to the location you intended.

Internet Keyword search

The default behavior of Firefox (prior to Firefox 4) was to use an Internet Keyword search feature. Here, Firefox will first try to send your request to a keyword search service. By default, this service is Google's Browse by Name service (some articles on web says it uses Google's "I'm feeling Lucky" service but its not, see the table below). For example, If you type mozilla foundation into the Location bar, Firefox will submit a query to the Google Browse by Name service, since this is not a valid URL. The service will find its best match for your request, and direct you to http://www.mozilla.org. An entry without a clear match to a URL will display search results for the entry.

PS: Google’s “Browse By Name” is a cross between "I'm Feeling Lucky" and a normal Google search. "Browse By Name" acts like "I'm Feeling Lucky" if Google is certain that the first hit is correct, but otherwise returns a normal set of search results.

Service NameURL
I'm Feeling Luckyhttp://www.google.com/search?ie=UTF-8&btnI=&q=
Browse By Name http://www.google.com/search?ie=UTF-8&sourceid=navclient&gfns=1&q=
Google searchhttp://www.google.com/search?ie=UTF-8&q=

Solution

So anyway our concern is that now in Firefox 4 its been changed to use "Bing search" by default, its nice and "I Love Bing", but if you still want your results to be from Google, then you will need to change some configurations. There is an article on Google support forum, but that solution uses normal "Google Search" not the "Browse by name" service.

So Fear not, the instructions below give you a step by step solution to resetting the default behavior or you can choose to customize the behavior however you like.

  1. Open a new Firefox Windows (CTRL + N) or a new Tab (CTRL + T)
  2. In the address bar type about:config > press Enter
  3. If you get a very amusing warning from Firefox saying something like ‘Here Be The Dragons’ or 'This might void your warranty!' then click the I’ll be careful, I promise button and tell ‘em I sent ye
  4. In the filter text entry box at the top of the screen, type keyword will see only the preferences with the word keyword in them
  5. Now to reset Firefox to the default behaviour which is a Bing search, copy the following to your clipboard:
    http://www.google.com/search?ie=UTF-8&sourceid=navclient&gfns=1&q=
  6. Now double-click the keyword.URL configuration option and paste the above address over whatever is there
  7. Optionally, you can paste in your favorite search engine’s URL and that should work too. Like for yahoo use http://search.yahoo.com/search?p=
  8. Click OK and you’re done!
READ MORE - How to: Change Firefox 4's Default search from Bing to Google

Friday, April 1, 2011

Posted by SAMAJ SHEKHAR

0

Visual Studio 2010 Books on C#, Visual Basic, F#, VS IDE, and VS Extensibility


Note:Some of Contents below were originally taken from Lisa.Feigenbaum's MSDN Blog.
I have just edited and added few more links

People often ask for good VS 2010 book recommendations on the topics VS Pro is working on: C#, VB.NET, F#, VS IDE, VS Extensibility. Here are some recent titles to check out. You can also find a growing list on MSDN developer centers:

 

C# 2010:

 

VB 2010:

 

F# 2010:

 

Visual Studio IDE – Tips & Tricks:

 

Visual Studio Extensibility:

READ MORE - Visual Studio 2010 Books on C#, Visual Basic, F#, VS IDE, and VS Extensibility