Tag Archives: Javascript

http://muaz-khan.github.com/UseMe/


Just designed a simplest project: UseMe

UseMe allows you to compare features side-by-side or search any feature as quickly and easily as possible!

Features are relevant to HTML5CSS3 and JavaScript specifications (also WebGL/SVG etc.)

Data has taken from +caniuse.com (awesome website!)

If I misused any feature; please let me know in the case.

I wanna make its design awesome using Canvas 2d API but my exams are about to starts (college exams) that’s why I’m early releasing a simplest version of UseMe.

Some individual features:
❶ http://muaz-khan.github.com/UseMe/#Canvas
❷ http://muaz-khan.github.com/UseMe/#WebGL
❸ http://muaz-khan.github.com/UseMe/#Video

Some features comparatively:
❶ http://muaz-khan.github.com/UseMe/#Canvas/vs/WebGL
❷ http://muaz-khan.github.com/UseMe/#Audio/vs/Video
❸ http://muaz-khan.github.com/UseMe/#requestAnimationFrame/vs/Canvas

https://github.com/muaz-khan/UseMe

Related: https://plus.google.com/100325991024054712503/posts/3A826CiDJzp

Dragging/Moving shapes smoothly using Canvas 2d APIs


Did you ever write code to drag or move shapes using Canvas 2d APIs? If you did, then didn’t you ever face a situation (an unexpected behaviour) when you drag or move a shape (e.g. circle, rectangle, image, Bezier cubic/quadratic curve, etc.)?

This post helps you write code to drag or move shapes as smoothly and accurately as possible using HTML5 Canvas 2d APIs.

Read full blog post

Dragging-or-Moving-Shapes-smoothly-using-HTML5-Canvas-2D-APIs

Curvature: HTML5 Canvas Curves Generator/Tool


Today I am happy to announce the release of Curvature: a tool lets you design curves using Canvas 2d APIs!

Curvature lets you draw unlimited Bezier curves and also generates exact code for you in two formats:

1) Absolute Coordinates

context.moveTo(200, 300);

context.bezierCurveTo(200, 300, 400, 500, 600, 700);

These are absolutely positioned points/coordinates.

Now let’s make an assumption: you had drawn one hundred (100) curves. Could you easily move all curves (as they are) on any portion of the screen?

The answer is: No, never. Not so easy!

Why it is not easy to move absolutely positioned coordinates on the screen?

You are drawing Bezier curves; not a simple line, arc or rectangle! For Bezier curves you have to understand its two control points and one ending point.

Canvas 2d API for Bezier curve looks like this:

CanvasRenderingContext2D.bezierCurveTo = function(cp1x, cp1y, cp2x, cp2y, x, y);

So what is the solution? The solution is relative positioned coordinates. If you had drawn hundreds of thousands of curves; no matter; Curvaturewill do all job for you!

2) Relative Coordinates

/* First curve where we set default values for x and y ! */

/* All subsequent curves will be extracted from these two objects! */

context.moveTo( x = 359, y = 319 );

context.bezierCurveTo( x + 25, y – 164, x + 191, y – 169, x + 285, y – 57 );

// Second Curve

context.moveTo( x , y  );

context.bezierCurveTo( x + 25, y – 164, x + 157, y + 51, x + 285, y – 57 );

// Third Curve

context.moveTo( x , y  );

context.bezierCurveTo( x + 25, y – 164, x + 234, y – 256, x + 285, y – 57 );

As you saw in the above code; when we call context.moveTo Canvas 2d API first time; we initialize default position for two variables or objects: x and y.

All subsequent values/points are relative to these two objects.

Changing them will affect all others accordingly.

How relative positioned coordinates can helps me?

Just copy auto generated code and you have to change only two points or coordinates or values:

x = e.pageX    // or whatever

y = e.pageY      // or whatever

Curvature auto-generates code for you! – Just copy and you are done!

Just draw more than one Bezier curves copy auto-generated code and you are done! Happy!!!

Try the tool:

https://canvature.appspot.com/

Just try! – Don’t hesitate to feedback! – You are most welcome!

You feedback may help me bring something better!

Cross-Origin requests and ASP.NET MVC


We can initiate cross-domain request in our webpage by creating either XMLHttpRequest object or XDomainRequest object. End user’s web-browser will request data from the domain’s server by sending an “Origin” header with the value of origin. If server responds with an “Access-Control-Allow-Origin:* | Origin” then we are permitted to access data; otherwise response will be unauthorized request.

Because we’ve to handle our server response for allowing cross-origin requests; we’ll use BeginRequest event handler in the Global.asax file for adding “Access-Control-Allow-Origin” header in our response.

HttpApplication.BeginRequest event occurs as the first event in the HTTP pipeline chain of execution when ASP.NET responds to a request. The BeginRequest event signals the creation of any given new request. This event is always raised and is always the first event to occur during the processing of a request.

protected void Application_BeginRequest(object sender, EventArgs e)
{
    HttpContext.Current.Response.AddHeader(
                "Access-Control-Allow-Origin", "*");    /* HttpContext.Current.Response.AddHeader(
      "Access-Control-Allow-Origin", 
      "http://AllowedDomain.com"); */
}

Asterisk (*) symbol indicates that request is public; however for the sake of security; we can allow a specific domain. In that case, the server will check whether request’s “Origin” header matches with domain-name that we allowed. So server will block unauthorized requests as soon as possible.

You can validate requests action-level by creating an attribute inherited to “ActionFilterAttribute” and allow only one action method to be accessible from cross-domains.

Support of Cross Browsers

Cross-Origin requests supported on IE8 (Windows 7 version),
Safari 4+
, Chrome and Firefox 3.5+ web-browsers. Preflight or Credential requests are supported on Firefox 3.5+Safari 4+ and Chrome web-browsers; IE8 doesn’t support them. You’ve to use XDomainRequest object for supporting IE8+ for cross-origin requests. IE6 and IE7 are not
supporting cross-origin requests.

For more details: please read Nicholas C. Zakas‘s article: Cross-domain Ajax with Cross-Origin Resource Sharing

Possible Attacks

Same origin used by web browsers
has a most significant protection again attack; however, cross origin requests are mostly vulnerable to attack.

  • CSRF attack: Cross-Site Request Forgery attack. CSRF interacts
    with user credentials and do malicious stuff on behalf of the user. It mostly applied to email accounts.
  • XSS attack: Cross-Site Scripting attack occurs to inject malicious
    data with POST/GET messages.
  • DNS Rebinding attack is interaction with DNS hostnames and networks address. Hacker injects malicious code and executes it; on the server side; server consider hacker’s request as authentic request because hostname matches.
  • Spoofing and re-direction attacks are mostly applied
    to cross-origin requests because server heavily relies upon HTTP headers to determine which site can access resources as well as what action they are permitted to do.

For cross-origin requests’ security: “Ensure user authority cannot be misused or compromised“.

A while ago, I wrote an article “ASP.NET MVC security and hacking: Defense-in-depth“, in which I talked about XSS and CSRF attacks. All of those attacking techniques also apply to cross-origin requests.

There is no definitive way to protect your cross-origin requests however; you can make your requests harder to attack by using some techniques as Google,
Twitter and Facebook are doing with their cross-origin APIs like Twitter‘s tweets APIs; Facebook‘s live stream and comments APIs.

Javascript and CSS3 only sliding up/down transition effects



First of all – View the Demo!

You’ve to apply following class to the element you want to slide up/down.

.sliding-effect
{
    -webkit-transition:     max-height .8s ease;
    -moz-transition:        max-height .8s ease;
    -o-transition:          max-height .8s ease;
    -ms-transition:         max-height .8s ease;
    transition:             max-height .8s ease;

    /* To hide by default, setting max-height 
          and opacity = 0 */
    max-height:     0;
    opacity:        0;
    overflow:       hidden;
}

/* <img src="/image.jpg" alt="" width="167" 
          height="186" />  */

By default: Above class is hiding the element; however, you can customize it.

You’ve to call two Javascript functions: 1) slideDown and 2) slideUp as shown here:

var element = document.getElementById( 'id' );

slideDown(element); /* show */
slideUp(element)    /* hide */

And slide up/down functions:

function slideDown( elem )
{
    elem.style.maxHeight = '600px';
    elem.style.opacity   = '1';
}

function slideUp( elem )
{
    elem.style.maxHeight = '0';
    once( 1, function ()
    {
        elem.style.opacity = '0';
    } );    
}

function once( seconds, callback ) /* Execute once after the specified interval */
{
    var counter = 0;
    var time = window.setInterval( function ()
    {
        counter++;
        if ( counter >= seconds )
        {
            callback();
            window.clearInterval( time );
        }
    }, 1000 );
}

We’re using a timer to set opacity = 0 because setting max-height = 0 doesn’t (completely) hide the element.

CSS3 transforms can be used for sliding up-down effects

Early in this article, we used CSS3 transition for sliding up and down effects; however we can use CSS3 transforms to make same sliding effect. One point you must remember is that CSS3 transforms are less supported than CSS3 transitions; especially on mobile web-browsers.

Let us create slide-down effect with keyframes of CSS3 transforms:

/* For WebKit web-browsers: Chrome/Safari */
@-webkit-keyframes slideDown {
    0%, 100% { -webkit-transform: translateY(-50px); }
    10%, 90% { -webkit-transform: translateY(0px); }
}/* For Gecko: Mozilla Firefox */
@-moz-keyframes slideDown {
    0%, 100% { -moz-transform: translateY(-50px); }
    10%, 90% { -moz-transform: translateY(0px); }
}

And here we are calling above keyframes:

.slide-Down /* Slide-Down effect */
{
    -webkit-transform: translateY(-50px);
    -webkit-animation: slideDown 2.5s 1.0s 1 ease forwards;    -moz-transform:    translateY(-50px);
    -moz-animation:    slideDown 2.5s 1.0s 1 ease forwards;
}

Chris Coyier of CSS-Tricks.com wrote an article Pop From Top Notification. The demo he created in the article is using CSS3 transforms for sliding-down effect. You can view his demo or download in zip format.

Security consideration when passing data through Ajax request in ASP.NET MVC


Note: Current blog-post is old. You can find latest/new blog post here:

ASP.NET MVC security and hacking: Defense-in-depth

Always be careful when passing data through JSON request because data will be visible to end user and in some cases, secure data can be exposed to end user.

  return Json(new dtweetDataContext().Users);

Above statement is passing the records of all users including users’ passwords.

“User” is a LINQ-to-SQL entity class as shown here:

public partial class User
{
  public string UserName    { get; set; }
  public string FullName    { get; set; }
  public string Password    { get; set; }
  public string Email       { get; set; }
}

Figure shows what happened and how secure data is visible to end user:

img27150

The best way is to pass a few fields of records by using IQueryable<type>.Select(..) extension method as shown here:

return Json(new dtweetDataContext().Users
     .Select(u => new { u.UserName, u.FullName }));

Now I am passing just two fields instead of whole user object:

  1. User name
  2. Full name

Figure shows that now our secure data is protected and also we reduced the size of JSON response:

img04741

Always know what’s happening behind the scene when you build something.

Using logical operators (&& and OR) in javascript


Note: Current blog-post is old. You can find latest/new blog post here:

Logical Operators in Javascript, an in-depth overview

Logical AND operator (&&)

For logical AND operator (&&) both operands should be true. Otherwise result will be false.

  1: console.log( true && true ) // true
  2: console.log( false && true ) // false

Unlike other strongly type languages, both operands are not necessarily Boolean in javascript.

  1: console.log( 'hello' && false ) // false
  2: console.log( false && 'hello' ) // hello

If one operand is object and other is Boolean then second operand is returned, as shown above. The same rule applies if both operands are objects.

The value produces by && or || operator is not necessarily of type Boolean. The value produces will always be the value of two operand expressions.

If either operand is null, null operand is returned.

  1: console.log( null && false ) // null
  2: console.log( +'23AB' && false ) // NAN
  3: console.log( undefined && false ) // undefined
  4: console.log( +'23AB' && null ) // NAN
  5: console.log( undefined && +'23AB' ) // undefined

In javascript, logical AND operator (&&) can be said to short-circuited operator because if first operand is false, then javascript engine did not execute second operator and simply skip it because result always false.

  1: console.log( false && +'23AB' ) // false
  2: console.log( false && undefined ) // false
  3: console.log( false && null ) // false

Logical OR operator (||)

For logical OR operator (||) one operand should be true for true result. Otherwise result will be false.

  1: console.log( false || false ) // false
  2: console.log( true || false ) // true

Unlike other strongly type languages, both operands are not necessarily Boolean in javascript.

  1: console.log( 'hello' || false ) // hello
  2: console.log( true || 'hello' ) // true

If one operand is object and other is Boolean then first operand is returned, as shown above. The same rule applied if both operands are objects.

  1: console.log( false || null ) // null
  2: console.log( false || +'23AB') // NAN
  3: console.log( false || undefined ) // undefined
  4: console.log( null || +'23AB') // NAN
  5: console.log( +'23AB' || undefined ) // undefined

In javascript, logical OR operator (||) can be said to short-circuited operator because if first operand is true, then javascript engine did not execute second operator and simply skip it because result always true.

  1: console.log( true || +'23AB' ) // true
  2: console.log( true  || undefined ) // true
  3: console.log( true  || null ) // true

Comparing && and || operator

&&

||

If one operand is object and other is Boolean then second operand

is returned. The same rule applies if both operands are objects.

If one operand is object and other is Boolean then first operand

is returned. The same rule applied if both operands are objects.

For logical AND operator (&&) both operands should be true.

Otherwise result will be false.

For logical OR operator (||) one operand should be true for true

result. Otherwise result will be false.

If either operand is null, null operand is returned.

  1: console.log( false || null ) // null
  2: console.log( true || null ) // true

Note: I tested all above examples in Firebug 1.7x.0a11 extension/add-ons.

ASP.NET MVC Razor – Separate JavaScript code while taking advantage of full link – as Url.Content() does


Note: Current blog-post is old. You can find latest/new blog post here:

Javascript absolute URL issues

If you are using a free hosting service like aspspider.com, then there is a lot of bad stuff will happen for you when you host your website!

The biggest problem I found when I hosted my website in a free hosting service was absolute URL problem.

In ASP.NET MVC view engine, we can use Url.Content(..) helper method for absolute URL but we cannot use it inside a javascript file.

I came up a solution for using same technique inside separate javascript file.

<script type="text/javascript">
      var domainName = '@HttpContext.Current.Request.Url.Scheme://@HttpContext.Current.Request.Url.Authority';
</script>

Just insert this code snippet inside ~/Views/_ViewStart.cshtml file and use it like this in separate javascript file.

[Note: _ViewStart.cshtml executes before any other views and merged with other views so you don’t have to place above code inside every view.]

Javascript.js [Separate javascript file]:

$.ajax( {
            url: domainName + '/Controller/Action',
            type: 'POST',
            success: {}
});