Thursday, January 17, 2013

Javascript is a Free-For-All....

As part of a boot camp I am teaching this week, we decided to see how much insanity we could inject into Javascript before it would fail.  The group is made up of experienced C# programmers and we decided to experiment with blowing up the sort of structure and type restrictions we have all grown accustomed to in a structured language.  We created the following code block just to see how far we could push the 'undefined ' functionality, along with the variable typing being a basic free-for-all.


var arr = function()
{
  alert(arr['testB']);
}

arr['testA'] = true;
arr['testB'] = false;
arr['testC'] = true;
arr[arr[0]] = arr;

document.write(arr[arr[0]]);
document.write("<br/>");

document.write(arr['testC']);
document.write("<br/>");

document.write(arr[0]);
document.write("<br/>");

arr[arr[0]]();
document.write("<br/>");

document.write("foreach...<br/>");

for (var i in arr)
{
  document.write(arr[i]);
  document.write("<br/>");
}


This is not only viable syntax, but this code will run and output values consistent with the index resolution of the array (when it is an array and not a function, that is).  Interestingly, it appears to be a valid strategy to have an undefined value as a key in a key value pair.  My favorite aspect of this is declaring a function, array and key/value list as a single variable and have it act accordingly depending on how you reference it.  Even when you make one of the values within the key/value array the array itself.

Go home Javascript, you are drunk.

Friday, January 11, 2013

WebSockets

The web is based on the request/response paradigm of HTTP.  This pattern comes with inherent latency in communication by forcing a consumer of data to request all data to be consumed.  AJAX has really helped in making web application communication more dynamic than it had been historically; however, all HTTP communication is still completely driven by the client side of the equation.  This forces a developer to engage in user interaction or long-polling to create applications that, while they look and feel dynamic, are really still request/response in some fashion.  Push communication is loosely defined as the ability for a server to send data to its client without requiring the client to ask for it.  People have historically falsified a push application by engaging in long polling solutions.  A long polling solution requires that a client open a connection to the server so the server can keep it open until something is sent to the client.  At that point, the client deals with the data and then opens another long polling connection.  While enabling some dynamism, at the end of the day, it is a hack.  The new WebSocket technology defines an API for creating connections between a web browser and a server.  This allows the web client application to be notified from the server when and if the server has pertinent information for the client.

Walk-through

Following is a sample block of code using Javascript.  This will hit a WebSocket server and handle notifications based on listening to the events from the socket itself.  This sample was stolen verbatim from WebSocket.org and is a great example of a simple creation, connection and consumption mechanism.


var wsUri = "ws://echo.websocket.org/";
  var output;

  function init()
  {
    output = document.getElementById("output");
    testWebSocket();
  }

  function testWebSocket()
  {
    websocket = new WebSocket(wsUri);
    websocket.onopen = function(evt) { onOpen(evt) };
    websocket.onclose = function(evt) { onClose(evt) };
    websocket.onmessage = function(evt) { onMessage(evt) };
    websocket.onerror = function(evt) { onError(evt) };
  }

  function onOpen(evt)
  {
    writeToScreen("CONNECTED");
    doSend("WebSocket rocks");
  }

  function onClose(evt)
  {
    writeToScreen("DISCONNECTED");
  }

  function onMessage(evt)
  {
    writeToScreen('<span style="color: blue;">RESPONSE: ' + evt.data+'</span>');
    websocket.close();
  }

  function onError(evt)
  {
    writeToScreen('<span style="color: red;">ERROR:</span> ' + evt.data);
  }

  function doSend(message)
  {
    writeToScreen("SENT: " + message); 
    websocket.send(message);
  }

  function writeToScreen(message)
  {
    var pre = document.createElement("p");
    pre.style.wordWrap = "break-word";
    pre.innerHTML = message;
    output.appendChild(pre);
  }

  window.addEventListener("load", init, false);
 
You should try to use a WebSocket when you need low latency, real-time connections between the client and the server.  This technology can reduce your application chattiness and provide a truly dynamic experience for all of your users.  As more browsers move to support the WebSocket, this will push the envelope again on developing web based applications.  We will be able to provide the same kind of functionality we have grown used to in a net.tcp environment to distributed users of a web application.

Thursday, January 3, 2013

ASP.NET Web Tools 2012.2 Release Candidate

 Last Month, Microsoft released the ASP.NET and Web Tools 2012.2 update.  This release will extend the ASP.NET runtime a little bit and adds new tools to Visual Studio 2012. This update adds some new features and tools for all the flavors of ASP.NET (Web Forms, MVC, Web API, etc.).  I copied some of the highlights from the release marketing below.  It sounds pretty cool.

ASP.NET Enhancements
This update adds new ASP.NET templates and features, including:
  • New ASP.NET MVC templates.
    • Creating Facebook applications just became easier using the new Facebook Application template. In just a few easy steps you can create a Facebook application that gets data from logged in users and integrates with their friends.
    • A new Single Page Application template allows developers to build interactive client-side web apps using Knockout, jQuery, and ASP.NET Web API.
  • Real-time communication support with ASP.NET SignalR.  This enables you to easily take advantage of the new WebSocket support in .NET 4.5, while also automatically degrading to long-polling and other protocols for older clients.  If you haven’t tried SignalR yet you should – it is awesome.
  • New ASP.NET Web API functionality, including support for OData, integrated tracing, and automatically generating help page documentation for your API.
  • New ASP.NET Friendly URL functionality. This new feature makes it very easy for Web Forms developers to generate cleaner looking URLs (without the .aspx extension). The Friendly URLs feature also makes it easier for developers to add mobile support to their applications with support for mobile .ASPX pages and  supporting switching between desktop and mobile views.  It can be used with existing ASP.NET v4.0 applications.
  • Visual Studio 2012 Web publishing enhancements. Web site projects now have the same publish experience as web application projects (including to Windows Azure Web Sites), and you can selectively publish files, see the differences between local and remote files, and update local to remote files or vice versa.
  • Visual Studio 2012 Page Inspector enhancements. JavaScript selection mapping is now supported, and you can CSS updates in real-time.
  • Visual Studio 2012 editor support for Knockout IntelliSense and pasting JSON as a .NET class (which makes it even easier to consume Web APIs from others).
  • Visual Studio 2012 Project Template updates, including the latest versions of jQuery, jQuery UI, jQuery Validation, Modernirz, Knockout and more…
How it is delivered
You can download and install an integrated setup that contains the above enhancements today from http://www.asp.net/vnext.  The new runtime functionality is delivered to ASP.NET via additional NuGet packages. This means that installing this update does not make any changes to the existing ASP.NET binaries, and thus does not cause any compatibility issues with existing projects. New projects will contain the new functionality and existing projects can be updated with the new NuGet packages.

Summary
Web development is changing, and ASP.NET is rapidly delivering new capabilities to developers that help them take full advantage of new capabilities.  The ASP.NET and Web Tools 2012.2 update installs in minutes without altering the current ASP.NET run time components.  For a complete description see the Release Notes.

You can download and install the RC today: http://www.asp.net/vnext.

Wednesday, December 26, 2012

Javascript Extension Via Constructor

When using Javascript, there are a few ways to inherit or extend object definitions.  Depending on the choices you have made for your prototype declaration, some options make more sense than others.  For this discussion, let's focus on using a function to declare your prototype. This is a pretty common practice and does dictate some other direction if this is where you started.  Let's look at the following declaration:


function Vehicle(numWheels, motor)
{
     this.NumberOfWheels = numWheels;
     this.MotorType = motor;    
};


This is a pretty straightforward object.  We are simply creating a definition for a vehicle based on its number of wheels and the type of motor included.  If we want to extend this prototype and add a function allowing the vehicle to be driven, we would have two possible choices.  We could extend the prototype or simply update the original definition.  It may be best to extend the prototype in order to adhere to good design (e.g. the open/closed principle).  So, we will extend the prototype as follows:

Vehicle.prototype.Drive = function(){document.write("driving from the prototype!<br/>");}


Now our vehicle has the ability to drive via its extended prototype.  Our next step would be to extend the Vehicle object into another object based upon the definition of a Vehicle.  Again, assuming the use of constructor functions for object definitions, we would  start like this.

function MotorCycle(make, model)
{  
     Vehicle.call(this, 2,"V-Twin");
     this.Make = make;
     this.Model = model;
}


The line of code that is giving us the copy of properties is Vehicle.call(this, 2, "V-Twin"); This line is basically grabbing the properties from the Vehicle definition and extending them into the Motorcycle class.  If I were to create a new MotorCycle and output its definition to the document, it would look like this: {"NumberOfWheels":2,"MotorType":"V-Twin","Make":"Honda","Model":"VTX"}".  But, if I were to try to Drive() my new MotorCycle, what would happen?  Nothing.  The Motorcycle doesn't know how to drive since the definition from the prototype has not been applied to the MotorCycle.  In order to have the prototype functions attached to the new object, you have to explicitly set the MotorCycle prototype by default as follows:

MotorCycle.prototype = new Vehicle("2","V-Twin");
MotorCycle.prototype.constructor = MotorCycle;


This gives us access to the functions defined in the prototype of the Vehicle.  The second line appears to have no bearing upon the output or operation of the MotorCycle class.  While this is true at a glance, you have to focus on good design principles ensuring that behavior is what would be expected at every layer of inheritance, a.k.a., the Liskov Substitution Principle.  In Javascript, many people will do type-checking by performing a check against the constructor.  So, in the following statements, the MotorCycle.prototype.constructor = MotorCycle; statement would be the difference between a type check failing or passing.  Without getting into other ways to perform that check, let's just focus on the fact that people will do this:


if( cycle.constructor == Vehicle)
{
   document.write("type check says I am a vehicle");
}
else if( cycle.constructor == MotorCycle)
{
   document.write("type check says I am a motorcycle");
}


Many of the decisions made during the design of the prototype of an object will dictate direction when using the object itself.  In the following code, I have commented out all of the lines that have to do with possible methods of prototyping and extension.  As an exercise, it is interesting to choose varying methods and interact with the prototype by removing the comment from different lines and see how they interact.

function Vehicle(numWheels, motor)
{
     this.NumberOfWheels = numWheels;
     this.MotorType = motor;
//     this.Drive = function(){document.write("driving from the base<br/>");}
};

//Vehicle.prototype.Drive = function(){document.write("driving!<br/>");}


function MotorCycle(make, model)
{  
  //   Vehicle.call(this, 2,"V-Twin");
     this.Make = make;
     this.Model = model;
}


//MotorCycle.prototype = new Vehicle("2","V-Twin");
//MotorCycle.prototype.constructor = MotorCycle;

var cycle=new MotorCycle("Honda","VTX");
document.write(JSON.stringify(cycle)+"<br/>");
cycle.Drive();

if( cycle.constructor == Vehicle)
{
   document.write("old school type check says I am a vehicle");
}
else if( cycle.constructor == MotorCycle)
{
   document.write("old school type check says I am a motorcycle");
}


I have been an object-oriented developer for over 15 years on structured languages such as C++ and C#.  As I spend more time with Javascript, I keep flashing back to a certain meme that sums up my initial reaction to Javascript. 


That is until you really dig in and just spend time trying to break and fix things.  Then, it becomes at least a little bit more clear and can be related back to the knowledge you may already have.

Wednesday, December 19, 2012

HTML5 Canvas

Here is a cool little demo of the canvas element in HTML5.  This page will create an interactive gradient fill based on your mouse position within the canvas element.  It changes the color pattern based on the mouse moving and the control or shift key being held while moving.  It is a simple little demo illustrating the flexibility of this new element.  In Visual Studio 2012, create a new html page with the attached code sample.  It's a good learning exercise on uses for the canvas element.  You can take the same basic premise and make scribble pad out of the control. 

<!DOCTYPE html>
<html lang="en">
<head>
<title>Canvas Messing</title>
<style>
body 
{
  background: #fff;
}
canvas 
{
 
  height: 480px;
  width: 600px;
}
</style>
</head>
<body>
<canvas height="480" width="600"/>
<script>
    var canvas = document.getElementsByTagName('canvas')[0],
        ctx = null,
        grad = null,
        body = document.getElementsByTagName('body')[0],
        color = 255;

    if (canvas.getContext('2d'))
    {
        ctx = canvas.getContext('2d');
        ctx.clearRect(0, 0, 600, 480);
        ctx.save();
        // Create radial gradient
        grad = ctx.createRadialGradient(0, 0, 0, 0, 0, 480);
        grad.addColorStop(0, '#fff');
        grad.addColorStop(1, 'rgb(' + color + ', ' + color + ', ' + color + ')');

        // Assign gradients to fill
        ctx.fillStyle = grad;

        // Draw 600x480 fill
        ctx.fillRect(0, 0, 600, 480);
        ctx.save();

        body.onmousemove = function (event)
        {
            var width = 600,
                height = 480,
                x = event.clientX,
                y = event.clientY,
                rx = 480 * x / width,
                ry = 600 * y / height;

            var xc = Math.floor(256 * x / width);
            var yc = Math.floor(256 * y / height);
            if (event.shiftKey || event.ctrlKey)
            {
                grad = ctx.createRadialGradient(rx, ry, 0, rx, ry, 600);
                grad.addColorStop(0, '#000');
                grad.addColorStop(1, ['rgb(', xc, ', ', (255 - xc), ', ', yc, ')'].join(''));                
                ctx.fillStyle = grad;
                ctx.fillRect(0, 0, 600, 480);
                
            }
        };
    }
</script>
</body>
</html>

Wednesday, December 5, 2012

Windows Azure Mobile Services

The Azure Mobile Services platform has some great new functionality that works toward making this a total solution for a mobile / web application hosting environment.  Some of the new features include:
  • iOS support – enabling you to connect iPhone and iPad apps to mobile services
  • iOS Push Notifications via APNS (Apple Push Notification Services)
  • Facebook, Twitter, and Google authentication support with mobile services
  • Blob, Table, Queue, and Service Bus support from within your mobile service
  • Sending emails from your mobile service (in partnership with SendGrid)
  • Sending SMS messages from your mobile service (in partnership with Twilio)
  • Ability to deploy mobile services in the west US region
Scott Gu had an article on his blog this morning outlining the expanded support for iOS on the Windows Azure Mobile Services platform. This post runs through how to create a web service that sends push notifications to iOS devices using a native Objective-C SDK within Azure.

This will go a long way toward making Azure the gold standard platform for hosting a web application that interacts with all devices.  By combining this technology with the Windows 8 mobile platform to leverage your Azure-hosted RESTful services, you are able to offer a wide range of device support with a large amount of shared infrastructure and service instance.

If you would like to walk through a tutorial using the push notifications, Microsoft has published one that covers all of the basics. You can view the first tutorial here and follow it up with this one