AJAX File Uploads with HTML 5

I see on StackOverflow the question often how to upload a file via AJAX.  It turns out it is actually not that difficult. We utilize a solution using the Html 5 FileReader component. The idea is have the file reader read a PDF file contents, and transfer those contents to a hidden field (stored in the $hidden variable). A portion of the script we use is shown below.

$("#FileUpload").on('change', function (e) {
var $self = this;
var file = $self.files[0];

var fileReader = new FileReader();
fileReader.addEventListener('load', function () {
   var result = fileReader.result;
   $hidden.val(result);
});
fileReader.readAsDataURL(file);

$self.val('');
});

Once a file is read, it invokes the “load” event with the contents of the file; the contents of the file are then stored in a hidden field. Since the contents are in the HTML file, it’s possible then to send those HTML contents to the server, or be a part of a normal postback lifecycle.

The idea with “readAsDataURL” is it creates a URL like the following: “data:text/html,sdafadf34533543sefkafdsadf90809as8dfasdf90asdf9fsdf” where the contents of the PDF are really large. You’ll need to extend what is acceptable as a part of your content.

On the server side, the solution is as simple as splitting the contents after the first comma like:

//Strip off the "data:text/html," portion of the data URL posted back to the server
fileContents.Substring(fileContents.IndexOf(",") + 1);

This is one of many solutions; there are a wide variety of JQuery or other solutions out there.

Watch Your Scoping

I recently found a bug in a plugin and so I figured that would be a good time to offer a public service announcement as to why you have to be careful with scoping in JavaScript.  The plugin I’m featuring is just a quick example of the problem.  Suppose your had the following HTML snippet:


< div id="section1" class="section" >
First Button
< span id="sp1" >0< /span >
< /div >
< div id="section2" class="section" >
Second Button
< span id="sp2" >0< /span >
< /div >
< div id="section3" class="section" >
Third Button
< span id="sp3" >0< /span >
< /div >

Pretty simple. The idea of my plugin was to target the root DIV tag, and then parse down to the BUTTON and SPAN at an individual level. Now, as I think about writing this, the reality is of the situation, I should have considered the JQuery Widget API, as I think that would have been better situated for what I am about to do. I was under the gun to get this feature completed, and this solution was not optimal, but it worked and did get the job done. Anyway, the JQuery plugin is below:

$.fn.parse = function() {
  return this.each(function() {
    var spn = $(this).find("span");
    btn = $(this).find("button");
    
    btn.on("click", function(e) {
       var n = parseFloat(spn.html());
       n += 1;
       spn.html(n);
    
       btn.html(btn.html() + "(clicked)");
    });
  });
}

The idea is that the span and button are retrieved within the context of the root DIV, and when the button is clicked, both elements are updated to indicate that a click occurred. You’ll notice though, that while the span gets the proper update, the button does not (always targets the last). This is simply because the button doesn’t include “var” declaration. This means the button is scoped beyond the current context of the each() callback. Because of this, the last button was selected and thus the last button is represented in the query.

This produces the result:

jsscreenshot

Adding VAR was the immediate solution. Another reminder why you need to make sure you variables are scoped correctly.

Just to brainstorm, another solution could be to, using the current reference within the button click, access the button through the callback and even target the SPAN that way, rather than relying on variables.

You can view the Gist here.

Building a Windows 8 Required Validator Control

Coming from an ASP.NET background, I’ve been used to the way ASP.NET validates user input.  ASP.NET made validation easy; a developer simply dropped a RequiredFieldValidator onto a web form, linked it to the control to validate, supply a set of initialization parameters, and voila, validation problem solved.  Of course, you’d run into some common configuration problems, some easily solved by validation groups, while others solved by some manual method calls.  This worked from the concept of web development, and it has some practicality in a Windows world, and as such, this article is going to look at building a similar capability in WinJS.  Note that I never meant for this component to encompass all validation scenarios, so you may find some faults in my implementation (feel free to point them out in the comments).

To start, we need a class.  Classes have always varied in implementation in the JavaScript world.  The approach WinJS uses is nothing new, but may be a hybrid of existing techniques.  A class starts with a WinJS.Class.define method call.  Define has the following signature:

define(function() { /* constructor */, { /* instance methods */ }, { /* static methods */ }

In our required validator example, we need to define our class as such:

var requiredValidator = WinJS.Class.define(

function (element, options) {
this.element = element;
this.element.winControl = this;        this._errormessage = null;
this._isvalid = true;
this._mode = “text”;
this._targetID = null;
this._text = null;

WinJS.UI.setOptions(this, options || {});

this._buildVisualTree();

var list = window[“Validators”];

if (!list)
list = [];

list.push(this);

window[“Validators”] = list;

},

.

.

);

The first parameter of the define method is the constructor (which is also the only one visible here), which performs a variety of steps.  The first wo steps are common with WinJS controls; we first store the element in an instance field, followed by creating the winControl object reference common through all WinJS component in the framework.  Ever wondered how other windows controls worked when you saw this code: document.querySelector(“#idofwindowscontrol”).winControl?  The setting of the winControl property above establishes the linkage.  Our validator needs to store data in variables defined on the instance (hence the this._X references), and supply them with defaults.  These store the options of the control, and are exposed as properties (which we’ll see later on).  For instance, you probably have seen usage of the data-win-options properties on WinJS control.  Suppose our validator has a configuration of data-win-options=”{text:’$$’, targetID:’#target’}”; the control receives these values in the constructor (via the options parameter), and the values are supplied to the text and targetID values through the control’s properties.  The setOptions method is the way to make this all happen.

Note that the control adds itself to a collection in the windows object; this way, the entire page  can access all of the validators on the view, similar to how ASP.NET provides all of the validators through it’s Page.Validators property.

The next code sample begins our instance methods, or the body of the class.  Notice WinJS (and IE 10 which runs the WinJS application) has a notation for properties using “get:” and “set:”, something that was missing in previous implementations of IE.  The first set of methods are actually property definitions (which consist of getter and setter methods):

errormessage: {
get: function () {
  return this._errormessage;
},
set: function (value) {
  this._errormessage = value;
}
},isvalid: {
get: function () {
  return this._isvalid;
},set: function (value) {
  this._isvalid = value;
  this._changeVisibility();
}},

Each of these properties has a get and set method, interacting with the instance variables defined in the constructor.  Even though the define method has separate method calls, we’re constructing one class, and as such, this just works.

In the class definition, the required validator also defines instance methods.  The following method builds the UI via traditional means, and styles it appropriately.  Nothing special here; it really doesn’t have to be.

_buildVisualTree: function () {
var el = this.element;
el.innerHTML = this.text || this.errormessage;
el.style.display = “none”;WinJS.Utilities.addClass(el, “Validator”);
},

Finally, we get to the main highlight of the control, which is the process for validating the content. Our validator first checks that the input of the control has been provided, and our target element has a valid length string.

_getValue: function() {
    var el = document.getElementById(this.targetID);
    var val;

    if (typeof (el.value) !== “undefined”)
        val = el.value;
    else
        val = el.innerHTML;

    return val;
},

validate: function () {
    var val = this._getValue();
   
    this.isvalid = !!val;
    this._changeVisibility();

    this.dispatchEvent(“validated”, { value: val, isValid: this.isvalid });

    return this.isvalid;
}

We have our validator, of which we can define as many as we want on the page. In ASP.NET, a postback to the page, when the control has it’s CausesValidation property set to true, invokes the validation process. Since we don’t have that here, I added one additional class, whose responsibility it is to trigger the validation, which is something we’ll look at in the next post (including it in this post made the post too long).

Icenium: Mobile HTML 5 Development Offering from Telerik

If you have looked at Telerik’s product offering lately, you may have noticed a new listing for Icenium, a cross-platform hybrid mobile development solution.  Icenium is a toolset allowing developers to code applications using HTML 5, CSS, and JavaScript.  Using Apache Cordova (AKA PhoneGap), Icenium provides a common toolset and framework for developing applications.  It also includes and online and installable editor for developing such applications.  This framework has the ability to push the applications to many test devices at once, allowing for a USB deployment.  However, when it comes time to publish the application, Icenium uses a cloud environment for building the application in each environment (iOS, Android, etc.).

I’m really looking forward to see what Icenium has to offer, and if it is as good as it’s other products are, Icenium is going to be an excellent choice for mobile development.  You can read a more detailed introduction here: http://www.icenium.com/community/blog/icenium-team-blog/2012/10/22/introducing-icenium—an-integrated-cloud-environment-for-hybrid-mobile-app-development

HTML 5 Games With Lime JS, Part 1: The Start Method

To begin our test game, let’s take a look at the core objects that are defined within a Lime JS game.  Every app has a start function that is the main entry point for the application, which  gets called when the body of the document loads.  Within this method are a few common startup statements to initialize the application:

test.start = function(){
var director = new lime.Director(document.body,1024,768),
scene = new lime.Scene(),
target = new lime.Layer().setPosition(100,100);

scene.appendChild(target);
.
.
director.replaceScene(scene);
}

At the beginning, we create a new director object.  The director has many responsibilities;  for example, it manages the current viewport (which element it’s defined in and its size) and defines which  scene is displayed to the user, represented by the lime.Scene class.  Scenes are a container that’s rendered to the view, which contains one or many drawable objects that are appended to it.  Typically, a layer represents a set of drawable objects, similar to how a layer is defined in Photoshop.

Learning HTML 5 Games

You may be trying to plan to build a game, and wondering of your options. HTML 5 provides great capabilities to building games at your disposal.  This means that you can download or buy a framework you like and use it to build a game.  There are quite a few frameworks out there, so this requires some thorough research.  I’m not going to try to lean you toward a specific framework, but it’s definitely

Research a Framework That Supports the Capabilities You Need

Make sure the framework has build-in keyboard support (if building a game that’s not point and click) or at least has a capability to receive keyboard commands.  Look at the type of games that were built with the framework and evaluate for yourself.  Normally, on the framework’s site is a list of the games built with that framework.

Check Out Online Stores…

Like the Google Chrome Web Store.  A lot of HTML 5 games are deployed to the Chrome store.

Look for Games  Built With that Framework on Github and Other Providers

I found a few that were build with the framework I plan to use.  If you go to Github’s site and google the name of the framework you are using, there are bound to be hits.  You can research the games that others have built to see how some are put together.  While source code is always a work in progress, it may give you some ideas.

Blogs Online

There are a lot of blogs online that are created for gaming theory, not necessarily directly to HTML 5.  Doing some research over the theory of how different types of games can work is beneficial.  A lot of gaming technologies, even though different in language, are very similar in the way they work.  For instances, games are usually built with a looping mechanism, refreshing the screen frequently to manage the movement of objects and account for actions, etc.  It’s good to have a general understanding of how it works before jumping into a game.

HTML 5 Presentation Slide Show and Sample Code

On 7/17, I had given a presentation on HTML 5.  This presentation had provided a good introduction to the features that HTML 5 has to offer, and included an overview of how we can use HTML 5 to develop mobile applications and games.   The presentation I gave can be found on Skydrive with the PowerPoint and sample code: http://sdrv.ms/MAQShI

Some demos incorporated from other sites, which were the following:

Enjoy!