DXTREME Mobile for C# developers – Foundations

02 May 2013

We have just published a Release Candidate for DXTREME Mobile 13.1. There have been many changes for this particular release – even better Visual Studio integration, greater performance, better “native” look-and-feel, new Windows Phone 8 support, and so on – and I thought it would be a good idea to introduce how to write multi-device apps for this new version, especially as they’re written with HTML5 markup and JavaScript. I’ll do this introduction and tutorial over several blog posts, which may in turn become an official part of the documentation.

Lego built into 1, 2, 3First things first, let me lay down some ground rules. I shall assume you are a C# developer (or at least familiar with its syntax and grammar) and are using and are very familiar with Visual Studio 2012. Perhaps you know some HTML5 – or at least are familiar with basic HTML markup – and perhaps you know some JavaScript. That’s great if so, but I won’t assume you know too much in that area.

What I’ll do in this series of posts is to create a simple app for iPhone 5, iPad 3, and for the Kindle Fire HD tablet, all of which I have at hand and can test on. The app is going to be designed to help me in a momentous event later this year: I’m going to take the USCIS Naturalization Test to become a US Citizen. As part of this overall test, there is a sub-test on US civics, especially history, law, and government. The nice thing about this particular test is that all of the 100 possible questions are published and you have to answer 6 or more correctly of ten random ones that the USCIS Officer will ask you in order to pass. My goal is  100%. What we’ll do with this app is to load all 100 questions into some kind of database, and then ask the questions of the user one at a time, randomly. We’ll also explore how to process the answers: maybe by using multiple choice, or analyzing the reply for keywords, or whatever. I’ll also go through the process of compiling the app with PhoneGap and getting it into the relevant app stores.

Without further ado, let me provide a quick introduction to some basic JavaScript.

Introduction to JavaScript

JavaScript is a simple interpreted language designed explicitly for web pages. Nowadays, scripts are even compiled for even faster execution, but this need not worry you too much: just assume that the interpreter in your browser knows how to parse and execute JavaScript files.

JavaScript Types

JavaScript’s simplicity starts off with the type system – yes, no matter what you have heard, JavaScript does have types. Not many, but they’re there. There are six: number, string, boolean, object, null, and undefined. For now, just concentrate on the first four; we’ll introduce the others later on.

Number: in C# terms, this is the same as double. There is no equivalent to int unfortunately, so beware of issues with rounding errors during calculations. You enter constant values just the way you're used to in C#: 1, 2.3, etc. The typeof operator called on a variable containing a number will return "number".

String: for all intents and purposes, this is equivalent to C#'s string type, but do note that JavaScript's strings support 16-bit characters only; you cannot access characters on Unicode's higher planes. You enter constant values in the normal manner, however you can use either single or double quotes to do so: 'hello', "world". The typeof operator called on a variable containing a string will return "string".

Boolean: just like C#'s bool, a type that has just two values: true and false. The typeof operator called on a variable containing a boolean will return "boolean".

object: anything else, including arrays, dates, functions (yes, functions are objects too) and objects you create yourself. There is a special syntax to defining objects, which we'll get to in a moment.

Since JavaScript is a C-type language, you should easily understand the declarations of the following variables:

var e = 2.718281828;             // a number
console.log(typeof e);           // outputs "number" 
var name = "John O'Doe";         // a string
console.log(typeof name);        // outputs "string" 
var anotherName = 'Jane Doe';    // another string
console.log(typeof anotherName); // outputs "string" 
var isFamiliar = true;           // a boolean
console.log(typeof isFamiliar);  // outputs "boolean" 

One major difference to note: you do not declare anywhere the type of a variable. At the time a variable is used, JavaScript will work out what type the value has. Until then, it doesn't care. This means you can reuse variables as different types (please, don’t do this):

name = 42;            
console.log(typeof name); // outputs "number" 

Objects

There is no class system in JavaScript. Objects are rather more fluid than C#’s class model allows, and the inheritance scheme JavaScript uses is known as “prototypal inheritance”. Since it is so different from class inheritance, many people will implement a proto-class inheritance system. We’ll see some of this later. For now, just be aware that objects do not have a class definition behind them that describes what they look like.

An object in JavaScript is a container for named properties and methods. They are most often declared using an abbreviated syntax:

var ball = {
    color: red,
    bounce: function () {
        // code to make it bounce
    }
};

That is, ball is an object with two members: a color property with value red, and a method (a function) called bounce. In short, you declare an object with braces. Inside the braces, you can declare a set of comma-separated members of the object (if you don’t, the object is empty), where each member comprises a name followed by its value, separated by a colon.

The above code is equivalent to:

var ball = {};
ball.color = red;
ball.bounce = function () {
    // code to make it bounce
};

Notice that you can just add members to an object as we did here, or remove them or replace them. Objects are endlessly flexible in JavaScript.

Sometimes, objects are newed up, just like in C#. It’s not a constructor as we understand it in C#, just a special function with some built-in members. We’ll come across examples of this later, but for now here’s a simple example:

var startTime = new Date(); // get an object representing now
console.log(startTime.toTimeString()); // use built-in method

Functions

Functions are encapsulations of code. They’re objects and so can be passed around and manipulated in a functional manner, but they can also be called. We’ve seen a couple of them in use so far (console.log() is an example: log() is a function declared as a member of the console object, which is created by the browser under certain development/debugging scenarios).

Here’s an example that shows how you can create and pass around new functions on the fly:

var makeBracketedLogger = function (log) {
    return function (value) {
        log('[' + value + ']');
    };
};

var logAlert = makeBracketedLogger(alert);
logAlert(true); // displays [true] as an alert

var logConsole = makeBracketedLogger(console.log);
logConsole(42); // displays [42] on the console

Here we implement a function that creates logging functions. The functions it creates display the value they’re passed in between square brackets. I create two functions: one that uses the alert() function to display the value in an alert dialog box, and the other to display the value to the debugging console. This easily shows that functions can be created at run-time.

Scope and closures

This is one of the biggest differences between C# and JavaScript. In JavaScript the scope boundary for local variables is the nearest enclosing function, not just the nearest enclosing braces. Locals declared in an outer function are visible to inner functions within, too. Take a look at makeBracketedLogger() above. The log parameter is visible inside the function being returned as well (which is why the returned function works). However, note something else as well: the returned function forms a closure over the outer function so that it can still “get at” the log parameter, even after the outer function has completed execution. Closures are extremely important in JavaScript, so make sure you refresh your memory on what they are and how they work in C#. It’s the same in JavaScript, just with a simpler syntax.

Statements, expressions, and so on

…Are pretty much as they are in C#. There are a few wrinkles that you’ll need to understand, the main one being that the JavaScript interpreter will go to great lengths to coerce one variable to the type of another when you mix them, but we’ll cover those as we get to them.

There is one operator in JavaScript that is not known in C#, the identity operator, or triple-equals (===). This operator performs a comparison between two values, much like the equality operator (==) does in C#. JavaScript’s equality operator is a coercion operator: if the two sides are not of the same type, JavaScript will go through some gymnastics to coerce one value to the type of the other. Sometimes this can be convenient (for example: 1 == '1' evaluates as true), but sometimes it can seem downright capricious in its results. Best practices say, always use === (or, negated: !==), since the person reading the code after you will not get caught out by some coercion assumption you’ve made.

Onwards!

Anyway, that’s enough foundation for now. Let’s jump in next time with some DXTREME Mobile.

(If you want to explore more JavaScript syntax and grammar, please see my series on JavaScript for C# developers.)

2 comment(s)
softboy99

I'm keep watching this product. It's a great decision to open this new direction. My question is when your complex components like grid,treelist,pivot grid move to this platform. If this is done,it will greately change the enterprise development in the industry. And there are already have similar product for grid component in the market. Another question is the best way to prove the ability of this product is to build your own officioal website with this product. So that we have better experience for this website on PC and mobile devices.

Thanks a lot for your greate efforts.

5 May, 2013
Norman Kleinberg

I'd love to have a tool, similar to DXperience, to use to add mobile functionality to an ASP.NET MVC application. DXtreme seems to be it but without code samples and tutorials I can't decide if that's the way I want to go. I understand this is a new product but if you want people to shell out the extra money then they have to be able to work with it and most of us learn by example.

6 May, 2013

Please login or register to post comments.