Check out Part 3 of 4 in my blog series for Magenic featuring Windows Store App Using HTML5 – Asynchronous Data Template Functions. In this article, I introduce asynchronous data template functions. The nature of Windows Store apps is asynchronous. To follow along with this asynchronous nature (as Windows Store app developers should), this article will detail asynchronous template functions.
Asynchronous template functions provide enhanced usability by allowing a user to interact with the app during information retrieval while keeping the user aware of incoming information. This is essential in providing the user with an optimal experience.
When projecting a WinRT Component object to WinJS, I kept running into an exception saying that the WinRT object could not be extended. This post will briefly describe how I got around this issue.
There are a few things known that helped come to this solution:
I didn’t need to worry about differences between one-way/two-way binding. All I had to do was present the object onto the screen.
Average JavaScript objects are bindable with WinJS
JavaScript objects are essentially associative arrays
If a member does not exist when referenced in an assignment operation, it is first created, then assigned.
I can essentially “clone” objects by iteratively copying members using array syntax.
This last item is exactly what I did! Let me elaborate: It is simple. At this point, we can’t bind to WinRT Objects therefore we need to make them bindable ourselves. The code snippet below shows this.
function _makeBindable(obj) {
var o = new Object();
for (m in obj) {
o[m] = obj[m];
}
return o;
}
var winrtObj = Projection.getWinRTObject();
// cannot bind winrtObj
var bindableWinRTObj = _makeBindable(winrtObj);
// use bindableWinRTObj for data-binding scenarios
Lets look at _makeBindable in a little more detail.
First, the function takes an object as a parameter. This object is the WinRT object that is causing issues. Then, a local variable is created assigned to a new Object.
The next part is very important – iterating over the members of the WinRT object. Using a for-in loop, cloning an object is quite easy. In this case, “m” represents the current member name as a string. Since JavaScript objects are essentially associative arrays, “m” can be used to access the current WinRT object’s member using array syntax. The member name is also used to assign to the local variable that was previously created. This effectively copied the current member from the WinRT object to the local variable.
Once all of the members are copied, the local variable is returned for use in data-binding scenarios.CodeProject
Check out Part 2 of 4 in my blog series for Magenic featuring Windows Store App Using HTML5 – Basic Nested Data Templates. In this article, I introduce data template functions. The potential of data template functions easily stretches beyond added scalability. They give the developer complete control over the presentation of each data object. By taking template functions into account when designing Windows Store Apps, the app will have the potential of a very powerful data presentation layer.
Debugging JavaScript can be a nightmare… Unless of course, you know how to effectively use Web Inspector.
Below is a video from Tom Dale (co-author of the JavaScript MVC Framework Ember.js (http://emberjs.com/). He first details debugging JavaScript using Web Inspector.
Check out Part 1 of 4 in my blog series for Magenic featuring Windows Store App Using HTML5 – Basic Nested Data Templates. In this article, I introduce nested data templates where data templates have data templates! Like basic templates, there are four necessary components when working with nested templates: Template, Data Source, Binding, and Render Target. Building off basic templates, nested templates provide further flexibility by adding more levels of control over the presentation of data. Using the methods described will allow the potential for indefinite levels of nesting. This greatly increases the flexibility of data presentation. Please note that this article will only go as far as a single nested template.
Intellisense is a beautiful thing. Viewing hints, documentation, and available overloads as you type is simply awesome. This is very common in C# and VB but what about JavaScript? Ever wish you had these same rich experiences while writing your JavaScript code? With Visual Studio 2012, you can! Below is an excellent video by Scott Hanselman explaining how this is possible:
I am writing an app for Windows 8 and need a maintainable set of values I can use in JavaScript. My first attempt included creating a Constants object that contained the values I needed. This soon became unmanageable as the number of constants increased. To fix this, something like an ASP.Net web.config file would be great. The problem is I do not want the restriction of accessing it through a sort of “AppSettings” property as with ASP.Net websites. My preference would be a JavaScript object that contains the properties I need but from a configuration file. How would I do this?
The Solution
What would solve my problem is a JavaScript object created at runtime that includes properties and values based on an XML file. A few things known about JavaScript make this solution viable:
JavaScript is a highly dynamic language. Considering this fact, creating an object during runtime should be like Eddie Van Halen playing a guitar.
Object properties can be accessed and manipulated using normal array syntax.
Server data is accessible from JavaScript. AJAX is the acronym.
Since an XML file is obtained, it can be parsed no differently than an average HTML document.
Combining the implementation of these four facts will enable me to create an object at runtime using the data of an XML file. The next section will explain how this is done.
The Implementation
There are three basic steps to implementing this. The mechanisms accessible from WinJS will help tremendously. First, the XML file needs to be obtained. This can be done using the WinJS.xhr function. More information on this function can be found on MSDN: “WinJS.xhr function (Windows)”. The next step is to parse the XML file and then to create the Constants object based on the data retrieved from the file. These steps will be explained in more detail in the following sections.
The Configuration File
To consume the file, the file will need to be created. Below is the sample content in the file:
As can be seen, this is nothing more than an average XML file. There are various nested nodes and attributes to show some of the possible node structures supported by this solution. For this article, the name of the file is “config.xml” and the root node is “Configuration”.
The Data
The WinJS.xhr function is used to get the XML file. This function takes an object used to configure the request and returns a Promise. This is shown below:
WinJS.xhr({
url: "config.xml",
headers: {
"If-Modified-Since": "Wed, 2 Feb 2000 11:11:11 GMT"
},
responseType: "document"
}).done(function(result) {
if (result.status === 200) {
var data = result.responseXML;
var root = data.querySelector("Configuration");
WinJS.Namespace.define("ST.Constants");
iterate(root, ST.Constants);
} else {
/* … Handle missing document … */
}
});
The xhr function is called, taking an object used to configure the XMLHttpRequest. “url” is the only required property. Other optional properties can be used to further configure the XMLHttpRequest. This is much like jQuery’s ajax method but, in this case, a Promise object is returned. The “done” method of the returned Promise is used to process the returned XML document.
The parameter passed to the xhr function is an object. This object is used to configure the XMLHttpRequest as mentioned previously. Here the “url” is set to the path to the XML file. Then, the “headers” property is used which includes the “If-Modified-Since” date. This ensures the XML file is obtained. The last property is “responseType” which is used to make sure the result of this call is a document able to be parsed by JavaScript.
Processing the XML File
.done(function(result) {
if (result.status === 200) {
var data = result.responseXML;
var root = data.querySelector("Configuration");
WinJS.Namespace.define("ST.Constants");
iterate(root, ST.Constants);
} else {
/* … Handle missing document … */
}
});
The next step is to process the returned XML file. The xhr function returns a Promise object. This object contains a “done” method that can be used for processing the results of the xhr function call. As with the average use of XMLHttpRequests, the first step is to make sure it succeeded. Using the result passed into the done handler, the status of the request can be determined. This result object is the XMLHttpRequest. It contains useful properties among these being “status” and “responseXML”. A successful status is 200. If the status is 200, the function proceeds with processing the results by first getting the responeXML from the result object. Since the responseType was set to “document”, the content of responseXML is the XML document that can be parsed by JavaScript. The iteration of this document will be described in more detail below but there are two more steps to do first. The iteration method takes two parameters. The first parameter is the node to process. To begin, the root node needs to be processed so this is what is retrieved. The second parameter is the object to process with the node. The object is meant to be static so the WinJS.Namespace.define method is used to create this. The two parameters are passed to the iterate method. The next section provides more detail.
The Iteration
There is hair, teeth, flesh, and bones but the iteration method is the meat. Within this method is the traversal of the XML file along with the additions to the Constants object. Below is the implementation:
function iterate(node, ns) {
if (node && node.childNodes) {
if (node.childNodes.length > 0) {
var nodes = node.childNodes;
var len = nodes.length;
for (var i = 0; i < len; i++) {
var sub = nodes[i];
if (sub.nodeType === sub.ELEMENT_NODE) {
var name = sub.nodeName;
if (sub.childNodes.length > 0) {
ns[name] = {};
iterate(sub, ns[name]);
} else {
var attName = sub.getAttribute("name");
var attValue = sub.getAttribute("value");
if (attName && attValue) {
// key/value attribute
ns[attName] = attValue;
} else if (attValue && node.nodeName && !attName) {
// node name/value
ns[name] = attValue;
} else {
/* handle data not available */
}
}
}
}
} else if (node) {
var name = node.nodeName;
var attName = node.getAttribute("name");
var attValue = node.getAttribute("value"); //Key/Value Attribute
if (attName && attValue) {
ns[attName] = attValue; //Node Name/Value
} else if (attValue && node.nodeName && !attName) {
ns[name] = attValue; //Log Warning
} else {
/* handle data not available */
}
}
}
}
Above is the implementation of the iteration method. This method has various validation checks for the current node, child nodes, and attributes. There is also room for handling missing data.
Handling No Children
The method begins by checking whether the given node and its children exist. If any children exist, it continues processing the child nodes. If there are no children, the method checks to make sure there is a node and upon success attempts to get the name and value attributes. This is shown below:
else if (node) {
var name = node.nodeName;
var attName = node.getAttribute("name");
var attValue = node.getAttribute("value");
if (attName && attValue) {
// key/value attribute
ns[attName] = attValue;
} else if (attValue && node.nodeName && !attName) {
// node name/value
ns[name] = attValue;
} else {
/* handle data not available */
}
}
There are three possible paths than can be taken here:
If both the name and value attributes exist, the Constants object is updated. A new property is added to the object. This part takes advantage of the fact JavaScript object properties can be accessed and manipulated by using normal array syntax. The new property is created with the value of the “name” attribute and is assigned the value of the “value” attribute.
If the value attribute and node name exist but not the name attribute, the Constants object is updated using the node name. The name of the new property is the name of the node. The value of this new property is the value of the value attribute.
If neither of the above two cases exist, there is no data available as this solution is currently implemented. This is a good place to handle such a case by either logging the occurrence, adding default data, or any other way that is necessary.
Handling with Children
If the given node exists with children, the iterate method proceeds by processing the child nodes. The snippet below shows this:
if (node.childNodes.length > 0) {
var nodes = node.childNodes;
var len = nodes.length;
for (var i = 0; i < len; i++) {
var sub = nodes[i];
if (sub.nodeType === sub.ELEMENT_NODE) {
var name = sub.nodeName;
if (sub.childNodes.length > 0) {
ns[name] = {};
iterate(sub, ns[name]);
} else {
var attName = sub.getAttribute("name");
var attValue = sub.getAttribute("value");
if (attName && attValue) {
// key/value attribute
ns[attName] = attValue;
} else if (attValue && node.nodeName && !attName) {
// node name/value
ns[name] = attValue;
} else {
/* handle data not available */
}
}
}
}
}
The node is checked to make sure it has child nodes. If it does, each child node is processed in a simple for loop. The current child node is stored and then a check is done to be sure it is an element node. If so, the method checks this node’s children. If they exist, the name of the sub node is used to create a new property of the given Constants object. Then the iterate method is called again this time passing in the current child node and the new property of the Constants object. This provides the support needed to add nested nodes in the XML file.
If the current child node does not have any children, it is processed in the same way as what was described in the previous section “Handling No Children”.
The Outcome
As you are probably aware by now, this solution creates an object at runtime. Using the Watch window while debugging the structure of the object can be seen:
This shows that the structure of the Constants object mirrors the structure of the XML file.
Originally Perceived Enhancements
Using this solution offers numerous benefits. It is flexible, scalable, and performs well. It provides practically infinite levels of nesting in the xml file (barring any call stack limitations when the prototype chain is created). There is also no performance hit from going across a network since the configuration file is local to the app. Among these strengths, there are still improvements that can be made.
Attribute Values
So far, the values of the constants are set as the attribute values in the XML file. Node values could be used as well.
Data Types
Not every value is appropriate as a string. Additional logic could be added to the iteration to have values of appropriate data types (e.g. If the value is meant to be an Integer, make it an Integer; if the value is meant to be a Date, make it a Date).
Caching
This creates an object at runtime. Don’t create the same object every time the app is started. When the object is first created, store it. Then, retrieve it from storage when the app loads again. Only create this object when a change has been made.
Conclusion
This article presented a way to create objects that are easily configurable by updating values in an XML file. As with most things, there are pros and cons to this solution but it does the job and does the job well. Needless to say, the band is happy and the object has been brought to life.
Windows Library for JavaScript (WinJS) provides convenient ways to format and display data. Here we focus on templates and a few ways of implementing them in a Metro app. Templates provide a way to present multiple instances of object data to the user with a high degree of control while maintaining ease of implementation. Templates can be used with ListViews, other controls provided for Metro app development, and can even be used without a predefined view.
In this article, three ways of using templates will be described, beginning with template basics. This section will provide an overview of templates and what roles HTML and WinJS play. The second section will describe item templates and how they can be used to display a list of items. Then, building off the second section, the third section will employ item templates with the ListView control. Finally, more advanced topics will be discussed, including nested templates and object-oriented CSS. A usable solution that contains a functional version of the code snippets provided is available at the end of the post. General data-binding experience is assumed.
Above is an example of the extension method in use. First, the regex pattern is stored. This pattern is used to match particular phone number formats. The raw data for the phone number is then stored. The raw data of the phone number cannot be used in its entirety to make a valid phone call therefore, it must be scrubbed. This occurs with the call to phoneRaw.ToString(phoneRegex). This call returns the string “011-122-2333”. Using the extension method, the phone number went from a raw, unusable form, to a valid format using a single method call.
Implementation Details
The ToString extension method created above uses the Regex class. This class provides various methods for retrieving information regarding the Regex’s anatomy such as groups, group numbers, and pattern matches. The ToString extension method uses two of these: IsMatch, and Match.
Regex.IsMatch
This is a static method returning a Boolean value indicating whether a match is found in the specified string using the specified regular expression. In the extension method created above, this is used to decide whether to proceed with returning the value of Regex.Match, or simply return null.
Regex.Match
This is a static method returning a Match object containing information about the first occurrence of the specified regular expression in the specified string. The extension method created above uses this to return the Value of the match. This value contains the string representation of the matched substring found in the input string.
Originally Perceived Enhancements
There are a few improvements that can be made to the original extension method. One, in particular, is the use of the static method Matches. This returns all of the successful matches of a regular expression in a given string. The user can then determine which match to use. Below is an example:
public static string ToString(
this string @this,
string regexPattern,
int matchIndex)
{
var matches = Regex.Matches(@this, regexPattern);
return
(matches.Count > matchIndex ? matches[matchIndex].Value : null);
}
Above is another version of the ToString extension method that accepts a RegEx pattern and a match index. The method retrieves all of the matches and, if valid, returns the desired match’s value. This way, the user is able to do this:
Above shows the enhanced version of the ToString extension method. It is used to obtain the area code “011” of the phone number by retrieving the first occurrence of 3 consecutive digits.
Conclusion
The two versions of the ToString extension method created above allow, with just a few lines of code, the ability to do all sorts of string manipulation and input validation using regular expressions. CodeProject
This entry will focus on extending System.IConvertible objects to retrieve its binary form as a String. Basic knowledge of programming in C# and creating extension methods is assumed.
Converting from one data type to another (Casting) is quite commonplace in computer programming. In C# this can be done in various ways:
The list above will be described in the following three sections.
Implicit Casting
This is one of the most basic forms. When one variable of one data type is assigned to another with a different yet compatible data type, they can be implicitly cast. Here is an example:
long lngValue = 9223372036854775806L;
int intValue = 2147483646;
lngValue = intValue;
Above is an example of implicit casting. A long (Int64) variable occupies 64 bits (or 8 bytes, or 16 nibbles). An int (Int32) variable occupies 32 bits (or 4 bytes, or 8 nibbles). Since Int32 memory space can easily fit within Int64 memory space (as depicted below), an implicit conversion can be applied from Int32 to Int64. An explicit cast must be performed when converting the opposite direction (Int64 to Int32) where truncation will occur.
Above is a visual comparison between Int32 and Int64 memory space (Int32 to Int64 cast).
Explicit Casting
This is another basic form of casting. Here is an example:
long lngValue = 2147483646L;
int intValue = 0;
intValue = (int)lngValue;
Above is an example of explicit casting. Since a 64-bit variable does not completely fit within a 32-bit memory space, we must use explicit casting while accepting the fact truncation may occur (possibly loss of data). Truncation is depicted below (an Int64 to Int32 cast):
Using System.Convert
System.Convert contains many methods meant to convert from one base data type to another. There are methods such as ToInt64, ToByte, ToDateTime, etc. Here is an example:
int intValue = 2147483646;
long value = Convert.ToInt64(intValue);
Above is an example using the ToInt64 method of System.Convert. The method accepts the Int32 value we initialized and converts it to Int64. This particular method simply wraps an explicit cast: (long)value. Others are dependent on an object’s implementation of the System.IConvertible interface as shown in the implementation of the Convert.ToInt64(object) method:
public static long ToInt64(object value)
{
if (value != null)
{
return ((IConvertible) value).ToInt64(null);
}
return 0L;
}
Above is the implementation of Convert.ToInt64(object). The ToInt64 method of value is called after converting it to System.IConvertible proving its dependence on System.IConvertible objects.
The Extension
Now that we have gone over the basics of casting and the dependency on System.IConvertible objects, the extension method can be created. Below is the implementation:
public static class IConvertibleToBinaryString
{
public static string ToBinaryString(this IConvertible @this)
{
long value = Convert.ToInt64(@this, CultureInfo.InvariantCulture);
string converted = Convert.ToString(value, 2);
return converted;
}
}
Above is the implementation of the extension method to convert objects deriving from System.IConvertible to their binary form as a String. First, the object is converted to long. This must be done to be able to specify the base for the Convert.ToString method that follows. The culture information provided is optional. Convert.ToString accepts a value to convert of type long and an integer specifying the base. This is important. Base 2 is binary, therefore, calling Convert.ToString(lngValue, base) with 2 as the base indicates a conversion to the binary form of the long value. There are other bases that can be used as well to created methods such as:
ToHexString (use base 16)
ToOctetString (use base 8)
ToDecimalString (use base 10)
Proving Binary Validity
How does one know that the method actually works? Unit-testing is how! Below is a basic method testing four uses of the extension method previously created. This uses MSTest:
public void</span> ToBinaryFromLong()
{
long lv = 10L;
Assert.AreEqual("1010", lv.ToBinaryString());
short sv = 2;
Assert.AreEqual("10", sv.ToBinaryString());
Boolean bln = true;
Assert.AreEqual("1", bln.ToBinaryString());
bln = false;
Assert.AreEqual("0", bln.ToBinaryString());
}
Running the code above should pass. This means the binary form is retrieved as expected.
Conclusion
This entry provided a look at a combination of System.Convert, System.IConvertable, and extension methods. Please note: This entry demonstrated extending System.IConvertible objects. It is not to suggest a String of binary numbers has common relevant uses. This is an enjoyable entry meant to prove it can be done.CodeProject