PhoneGap, Kendo, and MVVM by Example

I’ve been looking into developing PhoneGap applications. PhoneGap is an excellent tool for getting an application into the app store for iOS, Android, Windows 8/Phone 8, and many other platforms. Since it’s HTML 5 and JavaScript-Based, running on the web browser of the target platform, PhoneGap requires only a single codebase (however, there can be some quirks with the various features, as described in the PhoneGap documentation). Since it’s HTML; you can virtually have whatever design you would like.

However, to go with a minimalist design would not be very user friendly. It’s often best to use a framework like JQuery Mobile, Sensa Touch, or others to handle the look and feel for you. These frameworks provide you with a header and footer similar to apps you would see in the application store, and provide enhanced UI input and layout elements. This is why I chose a framework to lay out the markup for me, and this is also why I chose to use Kendo UI, from Telerik. Kendo UI provides a mobile application framework that supplies a templated UI to the user that completely resembles a mobile application. It also provides a series of input widgets perfect for capturing user input that’s much more appealing ot the user than the standard HTML controlset. It also provides an MVVM framework, and a Single Page Application framework for managing your application’s interaction between the view and model. Note that Kendo comes in three different frameworks: kendo UI web for web controls, Kendo UI Mobile for mobile web applications and PhoneGap, and Kendo UI DataViz, or data visualization components (charting, etc.).

The sample application is the shell we are going to plant into a phonegap application (discussed in a later post). To start, we are going to build is an application containing two views, using data that’s bound to the view via the MVVM framework. In all of my searching on the internet, I had trouble finding a simple example incorporating these exact features, so I hope the following example is a benefit to you. I’ll also describe the Kendo UI framework as I go. To begin, we need to create an HTML page and add some core script definitions to it.

<link href="../../css/kendo.common.min.css" rel="stylesheet" />
<link href="../../css/kendo.bootstrap.min.css" rel="stylesheet" />
<link href="../../css/kendo.mobile.all.min.css" rel="stylesheet" />

<script src="../../js/jquery.js"></script>
<script src="../../js/jquery.migrate.min.js"></script>
<script src="../../js/kendo.all.min.js"></script>

I’ve included the Common, Bootstrap (as in bootstrap theme, not Twitter Bootstrap), and the mobile CSS files. All of these provided allows you to use the Kendo UI web and mobile controls. Additionally, I’ve included JQuery (a requirement of Kendo), which is the latest. The migrate JS file is an add-on that ensures backward compatibility between older versions of JQuery (as of the time of writing, this example used JQuery 1.9.1, but Kendo requires 1.8.2). Additionally, the kendo all JS file contains all of the scripts for the web, mobile, and dataviz frameworks.

Now that we have our references setup, let’s flesh out the UI. To begin, let’s setup the views and the layout, as the following:

<div id="newview" data-role="view" data-title="New Contact" 
  data-layout="viewlayout" data-model="newViewModel">
	.
	.
</div>

<div id="existingview" data-role="view" data-title="Existing Contacts" 
  data-layout="viewlayout" data-model="existingViewModel">
	.
	.
</div>

<div data-role="layout" data-id="viewlayout">
	<header data-role="header">
		<div data-role="navbar">
			<a class="nav-button" data-align="left" data-role="backbutton">Back</a>
			<span data-role="view-title"></span>
		</div>
	</header>

	<footer data-role="footer">

		<div id="footertabs" data-role="tabstrip">
			<a href="#newview" data-icon="add">New</a>
			<a href="#existingview" data-icon="contacts">Contacts</a>
		</div>

	</footer>
</div>

To begin, we have two views, a new view and an existing view. A view is the container for what the user sees, defined by a data-role value of “view”; the user only sees one view at a time, starting with the new view. A view has a header and footer. The header contains the header title bar, plus any buttons used for navigation. The footer bar contains additional footer options, which is a set of tabs to navigate between the two views. Notice that the header and footer are defined an element with a data-role attribute value of “layout”. Layouts are a convenient way to reuse the header and footer across all views. This layout above is used for the new and existing view. Now we have the views defined, and the navigation between views using the tabstrip component. But if you viewed this page in the browser, it wouldn’t be very useful. For instance, the tabscript would not work as it currently stands. We need to enable a JavaScript widget that Kendo uses to provide the tabbing feature. Kendo uses a JQuery UI widget-like capability for enabling these behaviors. For instance, to enable the tabstrip programmatically, one would do:

$("#footertabs").kendoMobileTabStrip({ /* options */ });

However, Kendo made this even easier through it’s application class; by adding the following line, the entire view is wired up to it’s related JavaScript widget, all linked together through the data-role attribute, and related “data-” configurations.

var kendoApp = new kendo.mobile.Application(document.body, {
	loading: "Loading..."
});

Now that our views are wired up and our components are linked to their JavaScript counterpart, the next task needing performed is to define the MVVM data models. Before we fully get into that, let’s look again at the complete view.

<div id="newview" data-role="view" data-title="New Contact" data-layout="viewlayout" data-model="newViewModel">
	<form action="" method="post">
		<ul id="newformlist" data-role="listview">
			<li>
				<label>Name:</label>
				<input type="text" id="Name" data-bind="value:newName" />
			</li>
			<li>
				<label>Suffix:</label>
				<input type="text" id="Suffix" name="Suffix" data-bind="value:newSuffix" />
			</li>
			<li>
				<label>Email:</label>
				<input type="email" id="Email" name="Email" data-bind="value:newEmail" />
			</li>
			<li>
				<label>Phone:</label>
				<input type="tel" id="Phone" name="Phone" data-bind="value:newPhone" />
			</li>
		</ul>
	</form>
</div>

<div id="existingview" data-role="view" data-title="Existing Contacts" data-layout="viewlayout" data-model="existingViewModel">
	<ul id="existinglist" data-role="listview" data-bind="source:contacts" data-template="contacttemplate">
	</ul>
</div>

Here we ahve our two views. The first container a form, and the last contains a list. Both use the listview component, a mobile-specific component that binds data similar to a grid, or can be used as shown above for representing a form. Both views define certain attributes; they define a title that will appear in the layout’s title bar. The views also define the layout to use (as we saw above) and the data model to bind to. Within eaach view is an HTML element that defines what to bind to. For instance, in our form, each textbox is bound, using the data-bind attribute, to some specified value (newName, newEmail, etc). The “value:” prefix specifies the type of bindings to use. There are quite a few bindings available; for know, now that the value binding links the value from the view model to the “value” attribute of the element. In future posts, I’ll talk about some of the other attributes available. These bindings link the model (newViewModel) to an attribute of that model. This makes it very easy to bind the data in a two-way fashion from some backend model to the user interface, and vice versa.

Our listview that displays a list of contacts defines a source, or the array of data to bind to, and specifies a template to use. Templates are script element defining the UI to define for the item of the list. The following is the attached template the listview uses to show the name, phone, and email for each contact. Note that templates use a #= # or #: # convention for binding, and can even accept javascript statements like the “if” statement below.

<script type="text/x-kendo-template" id="contacttemplate">
	<h3>
		#= Name#
		# if (Suffix != null && Suffix.length > 0) { #
			#= Suffix #
		# } #
	</h3>
	<div>
		#= Phone #
	</div>
	<div>
		#= Email #
	</div>
</script>

To wire up these views, we need some data. This is where the view models come into play. Kendo defines a view model using the observable method; note that this approach is different than what other MVVM frameworks use (like Knockout JS for one). Kendo transforms the basic model definition into an object with observable properties to provide the two-way binding.

var newViewModel = kendo.observable({
	newName: "ABC",
	
	newSuffix: "",
	
	newPhone: "",
	
	newEmail: ""
});

var existingViewModel = kendo.observable({
	contactsLoaded: true,
	
	contacts: [
		{ Name: "Ted Person", Suffix: "", Email: "ted.person@fake.com", Phone: "555-555-5555" },
		{ Name: "Amu Person", Suffix: null, Email: "amy.person@fake.com", Phone: "555-555-5555" },
		{ Name: "Bob Person", Suffix: "Jr", Email: "bob.person@fake.com", Phone: "555-555-5555" }
	]
});

And voila, this is all that you need to define multiple views, binding them to an MVVM model. I’ve created a JS fiddle with the scripts; it’s not fully working correctly, which is something I have to contact Telerik about. But you can get the contents and scripts here (which work great locally), or the full example here.

Working with CheckBoxList

I know the content of this post is outdated for most users, as most users have moved on to something other than ASP.NET Web Forms. But for those of you still using web forms, and even for those using MVC, I have some code I’m about to remove (as the requirements changed), and as such, want to post it in case it helps someone else.

There are times when a series of options are presented in a CheckBoxList, such as a list of rows. For this, typically what’s used is the CheckBoxList control, which renders a table. In each cell of the table is a checkbox defined as <input type=”checkbox” />. Each of these checkboxes represented a role; however, to add to the speciality of the situation, the first item displays an “All” item. This “All” item represents all of the items in the list, but does not check the other items. Instead, it’s a manually inserted item with no entry from the database, nothing from the underlying Roles table. To start, here is the CheckBoxList control:

<asp:CheckBoxList ID="RolesList" runat="server" 
   DataTextField="RoleName" DataValueField="RoleKey"
   RepeatLayout="Table" RepeatColumns="3" 
   RepeatDirection="Horizontal" />

To show the all item in the list, the following code was used. Noticed the CSS class used.

Dim item As New ListItem("All", "")
item.Attributes("class") = "AllItem"

In script, we grab all of the inner checkboxes, and do it in a way we don’t have to understand the underlying markup (as server controls hide the underlying client markup in this case). The :checkbox pseudo selector grabs all of the checkboxes generically as shown below:

var roles = $("#RolesList").find(":checkbox");

With this list, we can attach to the clicking of all the items. The first item of the list is the “All” item (note that the trick I used to identify this special item was to add an AllItem class definition). If the “All” item was checked, the handler removed checkboxes from all of the other checkboxes. Otherwise, when checking another item that’s not the “All” item, the handler removes the check from the first item. How it was done is shown below:

roles.click(function () {
	var allItem = $(this).parent().hasClass("AllItem");

	if (allItem) {
		if (this.checked == true) {
			roles.not(":first").attr("checked", false);
		}
	}
	else {
		roles.eq(0).attr("checked", false);
	}
});

To begin, we check if the current checkbox has the AllItem; the CheckBoxList control attaches the AllItem class to the parent SPAN element above the INPUT element, which is why the parent() method is used. To set the checked on the first item, I used the .eq(0) method, or finding the first item in the list of roles, as checked (which happens to be our “All” item). Otherwise, the not() method is used to remove all but the All checkbox and clear those check marks.

And voila, we have list with a special “All” item as the first designated item.

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

Resolving an Uncommon Eclipse Startup Error

I recently downloaded the Android development tools for Windows 8, using the Eclipse environment for app developmen. In the latest download, the Android developer tools already come with Eclipse, the popular tool for Android and Java development. After some time, though, I got the following error below. It’s rather large so I’ll cut to the chase now. The fix for me was to run the eclipse.exe -clean command. Note, if you are running a virtual environment, such as using Hyper-V or VirtualBox, you may need to run the command as an administrator.

!SESSION 2013-02-16 21:58:12.331 ———————————————–
eclipse.buildId=v21.0.1-543035
java.version=1.7.0_13
java.vendor=Oracle Corporation
BootLoader constants: OS=win32, ARCH=x86_64, WS=win32, NL=en_US
Framework arguments: -product com.android.ide.eclipse.adt.package.product
Command-line arguments: -os win32 -ws win32 -arch x86_64 -product com.android.ide.eclipse.adt.package.product

!ENTRY org.eclipse.osgi 4 0 2013-02-16 21:58:13.223
!MESSAGE FrameworkEvent ERROR
!STACK 0
org.osgi.framework.BundleException: Exception in org.eclipse.osgi.framework.internal.core.SystemBundleActivator.start() of bundle org.eclipse.osgi.
at org.eclipse.osgi.framework.internal.core.BundleContextImpl.startActivator(BundleContextImpl.java:734)
at org.eclipse.osgi.framework.internal.core.BundleContextImpl.start(BundleContextImpl.java:683)
at org.eclipse.osgi.framework.internal.core.InternalSystemBundle.resume(InternalSystemBundle.java:225)
at org.eclipse.osgi.framework.internal.core.Framework.launch(Framework.java:657)
at org.eclipse.core.runtime.adaptor.EclipseStarter.startup(EclipseStarter.java:274)
at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:176)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:629)
at org.eclipse.equinox.launcher.Main.basicRun(Main.java:584)
at org.eclipse.equinox.launcher.Main.run(Main.java:1438)
at org.eclipse.equinox.launcher.Main.main(Main.java:1414)
Caused by: java.lang.IllegalStateException: Expected to find an object at table index: 357
at org.eclipse.osgi.internal.resolver.StateReader.getFromObjectTable(StateReader.java:83)
at org.eclipse.osgi.internal.resolver.StateReader.readGenericDescription(StateReader.java:600)
at org.eclipse.osgi.internal.resolver.StateReader.readBundleDescriptionLazyData(StateReader.java:350)
at org.eclipse.osgi.internal.resolver.StateReader.fullyLoad(StateReader.java:823)
at org.eclipse.osgi.internal.resolver.BundleDescriptionImpl.loadLazyData(BundleDescriptionImpl.java:662)
at org.eclipse.osgi.internal.resolver.BundleDescriptionImpl.getExportPackages(BundleDescriptionImpl.java:160)
at org.eclipse.osgi.framework.internal.core.PackageAdminImpl.setFrameworkVersion(PackageAdminImpl.java:706)
at org.eclipse.osgi.framework.internal.core.PackageAdminImpl.setResolvedBundles(PackageAdminImpl.java:656)
at org.eclipse.osgi.framework.internal.core.SystemBundleActivator.start(SystemBundleActivator.java:67)
at org.eclipse.osgi.framework.internal.core.BundleContextImpl$1.run(BundleContextImpl.java:711)
at java.security.AccessController.doPrivileged(Native Method)
at org.eclipse.osgi.framework.internal.core.BundleContextImpl.startActivator(BundleContextImpl.java:702)

Using the Telerik RadDropDownList Control for Windows Store Apps (HTML/JavaScript)

I previously wrote about using the Telerik RadAutoCompleteBox control for Windows Store apps. We’re going to look at another control, which is the RadDropDownList control. This control is as simple as the RadAutoCompleteBox, and I’m going to include some additional steps not mentioned previously. So let’s get started. To begin, we need to add a reference to the Telerik.UI.DLL, which is available once you downloaded and installed the Windows 8 components.  Once installed, you can add a reference to it by right-clicking references, selecting “Add reference”.  It should appear in the extensions list.

Once you have this, we need to add some references to scripts and styles, as shown next:

<link href=”///Telerik.UI/css/common.css” rel=”stylesheet” />
<link href=”///Telerik.UI/css/dark.css” rel=”stylesheet” />
<script src=”///Telerik.UI/js/jquery.js”></script>
<script src=”///Telerik.UI/js/ui.js”></script>

Notice the triple slash at the beginning of the script.  This is the assembly notation.  This signals to the Windows framework to look in Telerik.UI.dll for the associated CSS and JS files, similar to how we pull out embedded references in the ASP.NET AJAX framework.

Next, we need to add a reference to the control in the page:

<span id=”Group” data-win-control=”Telerik.UI.RadDropDownList”
data-win-options=”{dataTextField:’GroupName’,dataValueField:’GroupUserName’,autoBind:false}”></span>

Here we create a new RadDropDownList and initialize the field names, which are pointers to fields in the objects bound to the list.  Next, the autoBind feature signals not to automatically bind on load.  This is because, in this example, we’re going to programmatically bind the grid.  I do so first by making a call to a backend service:

WinJS.xhr({
type:”get”,
url: “..”,
headers: { “content-type”: “application/json” }

})
.then(

function(d) {

var data = JSON.parse(d.response);
var dataSource = new Telerik.Data.DataSource(data);

var group = document.querySelector(“#Group”).winControl;
group.dataSource = dataSource;

}
);

Using the xhr function to make an XML HTTP request, the established JSON data returned from the backend service is passed to the Telerik data source and bound to the control.  Instead of binding from code, we can also bind data inline, as illustrated in the following example.  Below is a snapshot of an example created in the telerik sample documents.

<span id=”Span1″ data-win-control=”Telerik.UI.RadDropDownList” data-win-options=”{
dataSource: [
{ category: 'Green', color: '#7AD36A', border: '#3A7E2B' },
{ category: 'Interesting', color: '#9CB6E7', border: '#28518E' },
{ category: 'Orange', color: '#F9BA89', border: '#B14F0C' },
{ category: 'Purple', color: '#B6A2E3', border: '#4C318E' },
{ category: 'Red', color: '#E6A0A1', border: '#A61C22' },
{ category: 'Yellow', color: '#FCFA90', border: '#A0981D' }
]
}”></span>

I hope this was a good illustration of the Telerik RadDropDownList control, and how easy it is to use in your projects.

Using Telerik RadAutoCompleteBox for Windows 8 (HTML)

In this post, we’re going to look and see how ridiculously easy it is to add auto complete behavior functionality, as demonstrated in the sample application built for the Windows 8 controls. If you haven’t done so already, download the RadControls for Windows 8 sample demo available in the Windows Store. This sample application comes with control demonstrations and sample code, which is also available when you download the source control.

First, we need an input element, as shown below.

<input class=”Member” type=”text” data-win-control=”Telerik.UI.RadAutoCompleteBox” />

Technically, we don’t need an input control, as we could also use a span element. The more important factor of this element definition is the data-win-control property, which specifies that it is a RadAutoCompleteBox control. This is a standard Windows 8 declaration of a control. Microsoft includes a variety of other types of data properties for specifying other settings, like data-win-bind for binding data to the view, data-win-options for providing initialization options, and much more.

Using the data-win-options property, the RadAutoCompleteBox control allows us to supply several properties directly in the markup. For instance, my control could have used the following setup, taken from the Telerik examples:

data-win-options=”{
dataSource: {data: Telerik.QSF.HTML.Examples.AutoCompleteBox.Configurator.countries},
height: 330,
minLength: 2,
dataTextField: ‘title’
}”

These additional examples save us from supplying additional information in code. However, if we need that finer control, the RadAutoCompleteBox has a server-side API. For instance, to bind a collection of JSON objects to the autocomplete, all we need to do is the following.

var members = items.querySelector(“.Member”).winControl; //find the control by CSS class
var _members = new Telerik.Data.DataSource( .. );
member.dataSource = _members.dataSource;

Similar to how Windows Store Apps use a WinJS.Binding.List for it’s binding purposes, Telerik also has it’s own binding list, which is a DataSource control. JSON that was streamed from the database server is sent to the client, wrapped in a DataSource object, and linked to the control.

And that is it; that’s all that it takes to wire up the AutoComplete control.

Using JQuery FullCalendar with ASP.NET MVC and Entity Framework

I had a need to use a calendar component in my application. Calendars are hard to come by, that also act as a scheduling component. In comes JQuery FullCalendar, a plugin that renders a calendar with event components.

To set this up

1. Create an Entity Framework model with all of the AdventureWorks entities.  Choose whatever template you like. Leave the context name as the default “AdventureWorksEntities”.

2. Create a new MVC project. Add a new controller named OrderHistoryController. The OrderHistoryController that I used is defined as the following:

public class OrderHistoryController : Controller
{
//
// GET: /OrderHistory/
public ActionResult Index()
{
return View();
}

[HttpPost]
public ActionResult List(long start, long end)
{
var epoch = new DateTime(1970, 1, 1);
var startDate = epoch.AddMilliseconds(start);
var endDate = epoch.AddMilliseconds(end);

var ctx = new AdventureWorksEntities();
var data = ctx.SalesOrderHeaders
.Where(i => startDate <= i.OrderDate && i.OrderDate <= endDate)
.GroupBy(i => i.OrderDate)
.Select(i => new { OrderDate = i.Key, Sales = i.FirstOrDefault()}).Take(20).ToList();

return Json(data.Select(i => new
{
title = (i.Sales.Customer != null) ? i.Sales.Customer.AccountNumber : “Untitled”,
start = i.OrderDate.ToShortDateString(),
allDay = true
}));
}

}

The Index action serves up the view.  Once the view is loaded, an AJAX request is made back to the server, looking for any orders.  Using LINQ, we load up some of those records.  I used a GroupBy statement so that I could get one record back per date for a given month, as a way to test with a single record per day.

JSON is the preferred mechanism to return to the client.  We’ll need to massage the data a little bit in order to work with the full calendar.   For instance, we’ll have to convert the date appropriately.  For simplicity, I used ToShortDateString to get the date and parse it in JavaScript.  However, it would have been more appropriate to convert the date to Epoch time (time since 1/1/197o).

3.  Download JQuery FullCalendar from the following URL: http://arshaw.com/fullcalendar/download/.  Copy the JS and CSS files to your project, in the Content and Scripts folder (or whatever folder structure you are using).  The files includes are:

  • fullcalendar.css – the core CSS file
  • fullcalendar.print.css – the CSS stylesheet for printing a calendar
  • fullcalendar.js – the core JS file
  • fullcalendar.min.js – the minified JS file
  • gcal.js – Google calendar integration

4.  Add scripts to your page

Rather than adding all the scripts to every page, I added the scripts to the OrderHistory view.  To do this, I started by creating a bundle.  Open up Bundle.config and add the following:

bundles.Add(new ScriptBundle(“~/bundles/calendar”).Include(

#if DEBUG

“~/Scripts/fullcalendar.js”

#else

“~/Scripts/fullcalendar.min.js”

#endif

));bundles.Add(new StyleBundle(“~/Content/calendar”).Include(

“~/Content/fullcalendar.css”,

“~/Content/fullcalendar.print.css”

));

We use these bundles within the view. To setup the calendar, all that we need to do is add a DIV to a page with an ID, like <div id=”container”></div>. The FullCalendar plugin simply attaches to

$(“#calendar”).fullCalendar({
    header: {
        left: ‘prev,next today’,
        center: ‘title’,
        right: ‘month,agendaWeek,agendaDay’
    },
    editable: true,
    eventClick: function(i, evt, view) {
               
    },
    events: function (start, end, callback) {
        $.ajax({
            type: “post”,
            url: ‘@Url.Action(“List”, “OrderHistory”)?start=’ + start.getTime().toString() + “&end=” + end.getTime().toString(),
            success: function (d) {
                var list = [];
                for (var i = 0, len = d.length; i < len; i++) {
                    var item = d[i];
                    item.start = new Date(item.start);

                    list.push(item);
                }

                callback(list);
            },
            error: function (e) {
                debugger;
            }
        });
    }

});

The plugin supports a variety of members defined in the documentation that can be specified at initialization time. The key is the events property, which defines the source of the events. The source can be a static list, a pointer to a page or web service, or even a function callback. The latter option gives you the most flexibility, and I’ve demonstrated it’s usage in this example. The callback gets a start and end parameter. These parameters are dates, converted to epoch time (in milliseconds) as they are sent to the server. JQuery is used to make the call to the server, and as the results come back, the process does some massaging first. For instance, a date is coming back to the client in string form, and converts the date back to a date form.

Once our final list is complete, and to load them into the calendar, they are passed to the callback. The plugin handles all of the loading of data into the calendar. Remember from the MVC controller, it returned a title, start (date), and an allDay indicator. Using this data is what the FullCalendar plugin uses as the data source. More parameters

Building JQuery Widgets Part 2

In this article, we’re going to look at some of the finer aspects of the plugin we last build a little bit ago.  Let’s start by looking again at the _init method.  As I mentioned previously, this method runs when the plugin is initialized, after the _create method runs (if there is one).  On init, we have this definition.

_init: function() {

this.options = $.extend({

title: “Interactive Help”,

buttonText: “OK”,

alertIfHidden: true,

beforeShowCallback: null,

afterShowCallback: null,

nextCallback: null,

startingCallback: null,

finishCallback: null

}, this.options);    this._elements = [];

this._currentIndex = 0;

this._total = 0;

this._buildUI();

},

Notice the use of the $.extend method; this method is very handy for establishing default values.  The method takes the values passed into the first parameter, and passes it to the second object, only if a value doesn’t already exist.  This is a great way to ensure a field exists, and helps you from having to write a lot of code that checks for a property’s existence.  What I mean by that is if you didn’t use the extend method, if your plugin tries to use this.options.startingCallback, when startingCallback was never supplied in the options, then an startingCallback is undefined an an exception is the result.  Our implementation of extend above ensures a title, buttonText, etc. field exists on the options object, so we don’t have to do that type check.

Notice that we have some options with a “callback” extension; these are the equivalent to an event in .NET or some other object-oriented language.  An event in an object-oriented language is defined explicitly, allowing the consumer of that event to attach to it and receive notification when the event occurs.  Widgets have the same functionality, in a different way.  We can attach to the event handler by supplying a JavaScript function, and then invoke that function at the appropriate time At various points in the plugin, we’ll invoke the callback by doing the following:

if (!!this.options.nextCallback)

this.options.nextCallback(this, { index: this._currentIndex, total: this._total });

We invoke the method, if it exists, and pass in any additional parameters.  Another important point to note is that you as a developer can interact with the consumer through these callbacks.  For instance, take a look at the code below.

var args = $.extend({
oldElement: el,
oldLeft: (!!pos && !!pos.left) ? pos.left : null,
oldTop: (!!pos && !!pos.top) ? pos.top : null,
element: null,
selectorFunction: null,
left: null,
top: null
}, def);if (!!this.options.beforeShowCallback)
this.options.beforeShowCallback(this, args);

if (!!args.element)
{
el = args.element;

if (!el && typeof(args.selectorFunction) !== “undefined”)
el = args.selectorFunction({ element: this.element });
if (!!el) {
pos = this._getElementPosition(el);
}
}

In this example, we construct an event argument that has specific parameters.  These parameters are passed to the beforeShow event, through the beforeShowCallback (notice the use of extend to ensure certain parameters exist).  After it’s called, the widget interrogates the argument object for any changes the user may have made.  For instance, the user may have supplied an element, or even a function for selecting the element.  In this way, users can provide the widget input at the time the event has executed, something we also have the ability to do in object-oriented languages.

When creating widgets that others on your development team, or possibly the world if  you release your widget to the public, the difficulty comes with how to let them know how to use your plugin, what parameters are available for each callback, and other aspects requiring documentation.  Without good documentation, that supply the parameters being passed in at initialization time or supplied by a callback, the consumer of the widget will have difficulty using it.  While we don’t always like documentation, providing it is key to your widget’s success.  Sure, the above average developer will read the source, but the rest of your audience will be left in the dark without good direction.

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.