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.

Advertisements

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.

ASP.NET MVC And Client Side Lists with Kendo

In this post, I’m going to illustrate a very simple way to create client-side list-based UI’s in ASP.NET MVC. The idea with this example is to allow the ability to add a bulk number of list items that doesn’t require constantly posting back to add additional items. In this example, we’ll use Kendo UI Core framework templating capabilities, although any templating framework will do.

To start, let’s look at a very simple model:

public  class SystemTestModel
{
   public List Entities { get; set; }
}

public class SystemListEntity
{
   public string Name { get; set; }
   public string Value { get; set; }
   public bool IsDeleted { get; set; }
}

Here we have a View Model that has a list of child items. Very simple. Notice the entity has 2 properties, and an IsDeleted property, which will be illustrated later. For this example, the controller setup is simple; it reads the form posted values and rebuilds the non-deleted ones:

public ActionResult List()
{
   var model = new SystemTestModel { Entities = new List() };
   return View(model);
}

[HttpPost]
public ActionResult List(SystemTestModel model)
{
   //Remove non-deleted records - deleted from  client
   var entities = model.Entities.Where(i => i.IsDeleted == false);

   //Save entities to DB or other work
   //Reload UI
   return View(new SystemTestModel { Entities = entities.ToList() });
}

Within the view, the Name/Value pairs are rendered

<tbody id="Grid" data-last-index="@(Model.Entities.Count - 1)">
   @for (var i = 0; i < Model.Entities.Count; i++) {
     <tr>
         <td>
            <input type="text" name="@Html.NameFor(m => m.Entities[i].Name)" value="@Model.Entities[i].Name" />
            <input type="hidden" name="@Html.NameFor(m => m.Entities[i].IsDeleted)" value="@Model.Entities[i].IsDeleted" />
         </td>
         <td>
            <input type="text" name="@Html.NameFor(m => m.Entities[i].Value)" value="@Model.Entities[i].Value" />
         </td>
      </tr>
   }
</tbody>

Each server-side item is rendered using the collection-based naming syntax that MVC uses to identify collections. The name for a collection-based item looks like the server-side equivalent: Entities[X].[Field] (ie. Entities[0].Name). This is important because our client-side HTML template must do the same thing:


   <tr>
      <td>
          
          <input type="hidden" name="@Html.NameFor(m => m.Entities[-99].IsDeleted)" value="@Boolean.FalseString" />
      </td>
      <td>
          <input type="text" value="#= Value #" name="@Html.NameFor(m => m.Entities[-99].Value)" />
      </td>
   </tr>

Notice in the template the -99; the really neat thing about the NameFor helper is that the expression doesn’t need to be valid; -99 works and literally renders to the HTML as “Entities[-99].Name”. Notice that the script block is the same equivalent above, but will be used to render client-side additional elements. The HTML between the two doesn’t need to be exact, but similar. The view will use this template when the “Add” button is clicked.

What that really means is that the server may have rendered 2 name/value items, and the client can render additional pairs. Our approach is to ensure that we render the pairs in sequential order whether created from server or client, preserving that sequential order.

The view has an add button. The add button triggers the templating capability of kendo. The idea with the template is to get the HTML for the entry and replace the “-99” with the actual index. So if the server-side rendering produced 2 elements (using indexes 0 and 1), the client-side “Add” button generates items starting from index “2” and greater.

$(function () {
   //http://docs.telerik.com/kendo-ui/framework/templates/overview
   $("#NewButton").on("click", function (e) {
      var html = $("#ItemTemplate").html();
      //Get the last index, add 1 because we are adding an item at the new index
      var index = $("#Grid").data("last-index") + 1;
      $("#Grid").data("last-index", index);

      //Replace -99 with the new Index
      html = html.replace(/-99/g, index);

      //Can be used to apply data values from JS
      var template = kendo.template(html);
      var data = {}; //For now, not doing any template binding
      var content = template(data);
            
      $("#Grid").append(content);
   });
});

The first step here is get the templated HTML, and update the current index appropriately. When this UI posts back, the updated index sequence posts back the new items correctly at positions 2 and greater. When the UI reloads, we now have server-side items created from the new index, and new items can be added again.

You may have noticed the IsDeleted property; this can be used to indicate items as deleted. The UI can have a delete button, which can trigger JavaScript that can hide the entire TR tag of the item from view and update the hidden field. When posted back, a permanent delete can happen (purge from the DB if it was originally persisted).

The main goal of this approach is bulk entry of lists without having to postback to add each item, like web forms used to do.

Here is the entire View (assumes JQuery and Kendo scripts included):

@model SystemTestModel

<form action="" method="post">

   <div class="row">
      <div class="col-md-12">

         <table class="table table-bordered table-hover">
            <thead>
               <tr>
                  <th>Name
                  <th>Value
               </tr>
            </thead>
            <tbody id="Grid">
               @for (var i = 0; i < Model.Entities.Length; i++)
               {
                    <tr>
                      <td>
                         <input type="text" name="@Html.NameFor(m => m.Entities[i].Name)" value="@Model.Entities[i].Name" />
                          <input type="hidden" name="@Html.NameFor(m => m.Entities[i].IsDeleted)" value="@Model.Entities[i].IsDeleted" />
                        </td>
                         <td>
                             <input type="text" name="@Html.NameFor(m => m.Entities[i].Value)" value="@Model.Entities[i].Value" />
                           </td>
                          </tr>

               }
            </tbody>
         </table>

      </div>
   

   <div class="row">
      <div class="col-md-12">

         <button type="submit" name="Action" value="SAVE" class="btn btn-primary">
             Save 
         </button>
         <button type="button" name="Action" value="NEW" class="btn btn-default">
             New
         </button>

      </div>
   </div>

</form>

@section scripts {
   
      <script type="text/x-kendo-template">
               <tr>
                    <td>
                        <input type="text" value="#= Name #" name="@Html.NameFor(m => m.Entities[-99].Name)" />
                        <input type="hidden" name="@Html.NameFor(m => m.Entities[-99].IsDeleted)" value="@Boolean.FalseString" />
                    </td>
                     <td>
                        <input type="text" value="#= Value #" name="@Html.NameFor(m => m.Entities[-99].Value)" />
                     </td>
              </tr>
      </script>

<script type="text/javascript">
      $(function () {

         //http://docs.telerik.com/kendo-ui/framework/templates/overview
         $("#NewButton").on("click", function (e) {
            var html = $("#ItemTemplate").html();
            //Get the last index, add 1 because we are adding an item at the new index
            var index = $("#Grid").data("last-index") + 1;
            $("#Grid").data("last-index", index);

            //Replace -99 with the new Index
            html = html.replace(/-99/g, index);

            //Can be used to apply data values from JS
            var template = kendo.template(html);
            var data = {}; //For now, not doing any template binding
            var content = template(data);
            
            $("#Grid").append(content);
         });

      });
   </script>

}

And Controller:

public class SystemListEntity
   {
      public string Name { get; set; }

      public string Value { get; set; }

      public bool IsDeleted { get; set; }

   }


    public class SystemController : BaseController
    {

         public ActionResult List()
         {
            var model = new SystemTestModel { 
                          Entities = new List<SystemListEntity>() };

            return View(model);
         }

         [HttpPost]
         public ActionResult List(SystemTestModel model)
         {
            var entities = model.Entities.Where(i => i.IsDeleted == false);

            //Save entities

            //Reload UI
            return View(new SystemTestModel { Entities = entities.ToList() });
         }
}

Dynamic Script Registering Component in ASP.NET MVC

One of the performance enhancements recommended in tools like YSlow and others is to put your JavaScript script files at the bottom of the page. The great difficulty in a web forms or MVC web application with doing that is scripts at the bottom of the page are typically added in the master page. Any pages or views can make use of a special section just for scripts, but partial views or user controls can’t take advantage of that.

I’m about to illustrate a solution that will do just that. It’s setup for MVC, but could be easily adapted for web forms by making the helpers as controls. You have to understand that MVC is a top down structure. So as views or partials render, they render their contents in place. The common approach is to have a section for scripts:

site.master:


  // master page common scripts


@* for any custom scripts in the view *@
@RenderSection("scripts", false)

The view can add a @section scripts { } to take advantage of this, but the partial view cannot. Additionally, everything is rendered in top down format; if a partial view at the top of your page has a script like:


$(function() { alert("In the partial view"); });

The problem with this script is that the final rendered view (when scripts are defined at the bottom) will look like:


$(function() { alert("In the partial view"); });


.
.
.
view content
. . // master page common scripts // view scripts

Since it’s top down, it’s also dependent on order, so scripts defined have no dependency (lacking a dependency feature like angular or script JS).

The following solution was meant to give more control over placement of defined scripts. Scripts are defined in a wrapper, and queued up for later rendering. The solution I’m providing is simple, but easily enhanced to add dependencies in scripts, custom ordering, and more features.

To give an idea of what we need to do, the system will achieve something like the following:

view.cshtml:

@Html.AddScript("ViewInit", () => @$(function() { .. }));

partial view:

@Helper Script()
{
   
     ..
   
}

@Html.AddScript("PartialInit", (m) => Script());

master:

@Html.PlaceScripts()

The idea is to add scripts via a method, which queues them up to be rendered, and writes them out at the point the PlaceScripts method is called. Note that for partial views, I’m using a little trick I noted earlier, whereby using a helper is the only way to circumvent exceptions that occur when using the action-based approach.

AddScript essentially adds the definitions to the HttpContext.Items collection, a common trick for storing singleton-like data elements that are available across the application. Since HttpContext.Items is available to add and then render scripts, it’s a great place to share content. The AddScript method shoves in data:

public void AddScript(HtmlHelper html, string key, Action fn)
{
    var http = html.ViewContext.HttpContext;
	var list = http.Items["_Scripts"] as Dictionary;
	
	if (list == null)
		list = new Dictionary();
	
	list[key] = fn;
	
	http.Items["_Scripts"] = list;
}

This method checks to see if we have a dictionary in the items collection; if not, it creates it, pushes in our item, and updates the collection. Similar, our other method, which takes a helper result, uses another overload to store the string result for easy rendering:

public void AddScript(this HtmlHelper html, string key, HelperResult fn)
{
	this.AddScript(html, key, fn(html.ViewData.Model).ToHtmlString());
}

public void AddScript(this HtmlHelper html, string key, string script)
{
    var http = html.ViewContext.HttpContext;
	var list = http.Items["_Scripts"] as Dictionary;
	
	if (list == null)
		list = new Dictionary();
	
	list[key] = script;
	
	http.Items["_Scripts"] = list;
}

We could easily add dependencies and ordering requirements to this solution if we needed; for now, let’s finish this out by showing how to grab the contents and render them:

public void PlaceScripts(this HtmlHelper html)
{
var http = html.ViewContext.HttpContext;
var list = http.Items[“_Scripts”] as Dictionary;

if (list == null)
return;

using writer = new HtmlTextWriter(html.ViewContext.Writer)
{
foreach (var entry in list)
{
if (typeof(entry.Value) is string) {
writer.WriteLine(entry.Value);
}
else {
//This is an action; the action will be
//rendered in the current output stream, and
//do not need to be directly written
entry.Value(html.ViewData.Model);
}
}
}

}

This would need greatly enhanced for dependencies and sorting; right now, we take the list in order and render it out. For HTML results or just plain string definitions, it gets rendered to the current response stream. Actions get processed the same way, but MVC handles that internally, rather than your code.

And voila, we are done; now we can define scripts in the view and partial views and expect them to be rendered where we want them placed, and have a component that can be easily enhanced to do much more.

Kendo MaskedTextBox Custom Rules

The Kendo UI MaskedTextBox plugin is great for limiting the input entered into a textbox. For instance, to validate a phone number, you could do the following:

$("#tb").kendoMaskedTextBox({
    mask: "(000) 000-0000"
});

The value zero ensures only numbers are entered. The masked text box also has these placeholders as well:

9 – 0 to 9 plus space
# – 0 to 9, space, plus, minus
L – a-z, A-Z
? – a-z, A-Z, space
& – any character
C – any character, space
A – letters, digits
a – letters, digits, space
. – Decimal
, – Thousands placeholder
$ – Currency

Outside of these rules, it’s possible to add your own, such as the following:

$("#tb").kendoMaskedTextBox({
    mask: "~A-00-000",
    rules: {
       "~": /[3-9]/,
       "*": /[ASDF]/
    }
});

The “~” and the “*” are the mask placeholder, whereas the /[3-9]/ and /[ASDF]/ define the range of acceptable values. This way, you can create a range to be whatever you desire.

Kendo UI Lists and Twitter Bootstrap Simplified

Bootstrap is a great CSS layout framework for setting up the user interface of your application. Bootstrap provides a grid system, whereby content can be structured into a grouping of columns up to a maximum of 12 total. This works great for laying out content, and can also be useful for layout out content in grids too. The following is an example of defining a template. Kendo uses templates to define the item view for the list. The following is a row within the eventual list rendered vertically:

<script type="text/x-kendo-template">
  <div class="row">
    <div class="col-md-3">
      #: FirstName #
    </div>
    <div class="col-md-4">
      #: LastName #
    </div>
    <div class="col-md-2">
      #: State #
    </div>
    <div class="col-md-3">
      <a href='@Url.Action("Where", "Some")/#=ID#'>
        View
      </a>
    </div>
  </div>
</script>

Next, we need to use the template, which we would supply to the kendo listview initialization plugin. Below is the initialization of the list, as well as the passing of the template to the list:

<div id="listview"></div>

  $(function() {
    $("#listview").kendoListView({
       autoBind: false,
       dataSource: new kendo.data.DataSource(..),
       template: kendo.template($("#template").html())
    });
  });

Notice our listview doesn’t need to define anything special; it gets built up by the kendoListView widget. The initialization properties passed are disabling auto binding on init (manual binding occurs later, which is good for views that need the user to interact with a form first). It also defines a data source and supplies our template.

The listview then binds the data, grabbing each record and generating a collection of <div class=”row”> objects, one for each record of data. That’s all that it takes to use the listview to bind a collection of rows using the bootstrap styles. Now when the screen collapses, each cell also collapses into it’s own row.

Custom Validator Execution in Windows Store Apps, Part 2

In part 1, we looked at the creation of a Windows 8 required validator control by constructing a WinJS class. In order to create a more full-fledge validation feature (but the final version of this will not as feature complete as the ASP.NET validation system, as it didn’t need to be), I had to use some additional components, which I will outlay in this blog post.

Each validator manages itself, validating the control it’s supposed to and registering itself with teh window object, using a window[“Validators”] collection. This is very similar to the Page.Validators collection in ASP.NET. ASP.NET also uses the page to trigger validation; this didn’t quite work for my scenario. Instead, I included the following component to handle validation.

var valExecutor = WinJS.Class.define(
	function (element, options) {
		this.element = element;
		this.element.winControl = this;

		this._isvalid = true;

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

		clear: function () {
			var list = window["Validators"] || [];

			for (var i = 0, len = list.length; i < len; i++) {
				var item = list[i];
				item.isvalid = true;
			}
		},

		isValid: function() {
			return this._isvalid;
		},

		validate: function () {
			this._isvalid = true;
			var list = window["Validators"] || [];

			for (var i = 0, len = list.length; i < len; i++) {
				var item = list[i];
				item.validate();

				if (!item.isvalid)
					this._isvalid = false;
			}

			this.dispatchEvent("validated", { isValid: this._isvalid });

			return this._isvalid;
		}

	}
);

This is a control that you would put in the view. The executor picks up the list of validators in the windows collection, loops through them all, checks for validity, and then performs some cleanup work. We can then simply call validate() on this control to validate all of the validators, instead of each control individually (but you can do that too if you like).

This control could very easily have acted like a validation summary, putting a message in a list and displaying the list of results to the user. It could have added the useful validation groups feature too, but again, that was overkill for my needs at the moment. I didn’t have that need at the moment, but it could be very easily done. We can use our control in a view like:

<div id="valexec" 
   data-win-control="PrayerLink.UI.ValidationExecutor" 
   style="display:none"></div>

And invoke validation via:

var val = document.querySelector("#valexec").winControl;
val.validate();

if (!val.isValid()) {
	/* do something */
}

The validation occurs, we can check whether the object is valid and do something about it. And that’s all that it takes to create a simple validation control in Windows 8 store apps using HTML and JavaScript.

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).

Intro to Windows 8 Store Apps Using JavaScript and HTML

Windows 8 is the next great operating system for Microsoft. I detailed the changes that the operating system is bringing to the common consumer. As you can see, it comes with quite a few user interface changes. However, for the developer, the focus on development shifts away from developing traditional windows applications, and moves toward developing a windows store application. This is a big paradigm shift that has an interesting twist. Applications that were previously only for mobile devices are now able to be installed on a laptop or desktop computer too. It brings about a lot of interesting possibilities.

Interestingly enough, Windows 8 or RT development supports both XAML and HTML/JavaScript. Each has it’s pros and cons, which I really don’t want to get into here. I’ve decided to use JavaScript templates for application development for this blog series. I’m choosing HTML and JavaScript for several reasons; it’s easy to layout and style, it’s easy to work with and I can personally develop an application rather quickly. It’s familiar to me as an ASP.NET and web developer, and it resembles building an application with PhoneGap. PhoneGap is another HTML/JavaScript framework that supports Windows 8 and other platforms. Transitioning from an HTML/JavaScript Windows 8 application to a PhoneGap application will be easier.

To create a new application, go into Visual Studio 2012 (within Windows 8) and select add a new project. Navigate to the JavaScript category, then Windows Store. Select one of the 5 existing templates to choose from, depending on the layout you need. Each template comes with a different set of files already defined for you; however, if you want to start from scratch, choose the Blank Template.

When you create your application, there are a few items to note. In the root of the application is default.html, the default page of that application that is the root container page for the single page application (SPA) template. This is the page always loaded into the application. With a single page application template, content can be loaded within the page, similar to an include file or a user control in ASP.NET. Page content consists of the following file types: .html, .js, and .css. The HTML file is the view that presents the content, whereas the JS file is the controller of sorts, similar to an MVC pattern implementation, leaving the CSS file to manage the user presentation. Each of the pages typically resides in the pages folder.

Let’s take a look at a sample application’s page. Below is a Login page that I used for an application. The easiest part to start is the HTML of our login page.  To create a new page, select Add > New Item > Page Control.  This creates the HTML, CSS, and JavaScript for you.  I’ve modified the default to look as the following:

<html>
<head>
<meta charset=“utf-8” />
<title>Login</title>
<link href=“//Microsoft.WinJS.1.0/css/ui-dark.css” rel=“stylesheet” />
<script src=“//Microsoft.WinJS.1.0/js/base.js”></script>
<script src=“//Microsoft.WinJS.1.0/js/ui.js”></script><link href=“Login.css” rel=“stylesheet” />
<script src=“Login.js”></script>
</head>
<body>
  <div class=“Login fragment”>
<header aria-label=“Header content” role=“banner”>    <button class=“win-backbutton” aria-label=“Back” disabled type=“button”></button>
    <h1 class=“titlearea win-type-ellipsis”>
      <span class=“pagetitle”>Login to PrayerLink</span>
    </h1>
  </header>
<section aria-label=“Main content” role=“main”>    <table>
     <thead></thead>
     <tbody>
<tr>
<td>
User Name:
        </td>
<td>
<input type=“text” id=“UserName” name=“UserName” />
</td>
</tr>       <tr>
<td>
Password:
</td>
<td>
<input type=“password” id=“Password” name=“Password” />
</td>
</tr>
<tr>
<td colspan=“2”>
<button id=“LoginSubmit”>Login</button>
</td>
</tr>
</tbody>
</table>

  </section>
</div>
</body>
</html>

A lot of this code sample is provided standard from Microsoft.  The header and core wrapper is automatically provided for you.  Even within the page’s content, you can see it defines all of the styles and CSS content the page uses.  Notice it provides the header of the page using pre-defined styles defined in the ui-dark.css stylesheet, and some other core wrapping content.

All of the login’s custom content is within the section element, with the role of main (for you JQuery enthusiasts, that would be “section[role=’main’]” :-D). Notice I have a form with standard input elements. The Windows 8 framework styles these components to have a much better appearance than the standard textbox.

WinJS.UI.Pages.define(“/pages/Login/Login.html”, {// This function is called whenever a user navigates to this page. It// populates the page elements with the app’s data.ready: function (element, options) {

var btn = element.querySelector(“#LoginSubmit”);

btn.addEventListener(“click”, hnd);

},    unload: function () {

// TODO: Respond to navigations away from this page.

},

updateLayout: function (element, viewState, lastViewState) {

///

// TODO: Respond to changes in viewState.

}

});

The page class defines certain event handlers such as ready, similar to JQuery’s ready event; unload, which runs when the page is unloaded; and updateLayout, a method that runs when the layout needs to be updated as the view changes modes between full screen to snapped to landscape, etc.

As developers, we are used to defining events in markup that point to an event handler. Rather than using this approach, it’s advisable to use the addEventHandler method on the element, which can attach an event handler using a defined method, or with a dynamic function, like the following example:

var btn = element.querySelector(“#LoginSubmit”);btn.addEventListener(“click”, hnd);

Here the “hnd” function fires when the button is clicked. On click of the button

var hnd = function (sender, e) {var user = document.querySelector(“#UserName”).value;var pwd = document.querySelector(“#Password”).value;.

.

}

In this example, the handler of the button grabs the reference to the elements using document.querySelector, using a CSS syntax for finding the elements by it’s ID. Once the element is retrieved from the DOM, we can then access the input element’s value via the value property.

This is a brief intro to windows 8 apps; I plan to go into more detail in future blog posts.