JavaScript

Building Things Using Fusion 360 and JavaScript

I like making things.

I used to mostly just make things that show up on the computer screen - software things. Lately, however, I’ve been re-inspired to make real things. Things out of wood and things out of plastic and metal and fabric and string.

The way I see it, we design things either manually or generatively.

By manual I mean that I conceive an idea then design and build it step by step. I - the human - am involved every step of the process. Imperative code is manual. Here’s some pseudocode to describe what I’m talking about…

// step 1
// step 2
// if step 2 value is good then step 3
// else step 4 10 times

See what I mean?

I’m not arguing that this sort of code and likewise this sort of technique for building is not essential. It is. I am, however, going to propose that it’s often not altogether exciting or inspiring. The reason, IMO, is that the entire process is no greater than the individual or organization that implements it. An individual only has so many hours in the day and is even limited in ideas. An organization can grow rather large and put far more time and effort into a problem and obviously generate more extensive results. But the results are always linearly related to the effort input - not so exciting.

By generative I mean that instead of creating a thing, I create rules to make a thing. The rules may be non-deterministic and the results completely unexpected - even from one run to another. The results often end up looking very much like what we find in nature - the fractal patterns in leaves, the propagation of waves on the water, or the absolute beauty of ice crystals up close.

What’s exciting is when an individual or organization puts their time and effort into defining rules instead of defining steps. That is, after all, the way our own brains work, and in fact, that’s the way the rest of nature works too. It’s amazing and awesome and I would venture to say it’s even miraculous.

I think a lot of my ideas on the matter parallel and perhaps stem from Stephen Wolfram’s book A New Kind of Science.

Most of the book is about cellular automata. The simple way to understand these guys is to think back to Conway’s Game of Life. The game is basically a grid of cells that each have a finite number of states - often times two states: black and white. Initially, the cells in the grid are seeded with a value and then iterations are put into place that may change the state of the cells according to some rules.

The result is way more interesting than the explanation. The cell grid appears to come to life. The fascinating part is that the behavior of the system is usually not what the author intended - it’s something emergent. The creator is responsible for a) creating an initial state and b) creating some rules. The system handles the rest. It usually takes a lot of trial and error if the intention is to create something that serves some certain purpose.

Check out Wikipedia’s page on cellular automata, and specifically look at Gosper’s Glider Gun.

I don’t know about you, but I find that completely awesome.

Okay, so when are you going to get to the point of the blog post, codefoster?

Calm down. It’s called build up. :)

First, let me say that generating graphics in either 2D or 3D is nothing conceptually new. What I like about discovering and learning an API for CAD software, though, is that I can not only generate something that targets the screen, I can generate something that targets the 3D printer or the laser cutter. That’s all sorts of awesome!

The example I’m going to show you now is a simple one that I hope will just get your gears turning. You could, by the way, take that literally and generate some gears and get them turning.

If you don’t have Fusion 360, go to fusion360.autodesk.com and download it. If you’re a hobbyist, maker, student, startup type you can get it for free.

If you’re new to the program, let me suggest the learning material on their website. It’s great.

After you install Fusion 360, the first thing you need to do is launch the program. This API is attended. It requires that you open the program and launch the scripts. I have suggested to the team at Autodesk to research and consider implementing unattended scenarios as well.

Now launch the Scripts and Add-ins… option from the File menu…

Don’t be confused by the Add-Ins (Legacy) option in the same File menu. That’s for an old system that you don’t want to use anymore.

That should launch the Scripts and Add-Ins dialog…

There are two tabs - Scripts and Add-Ins. They’re the same thing except that Add-Ins can be run automatically when Fusion 360 starts and can provide commands that the user can see in their UI and invoke by hitting buttons. Add-Ins ask you to implement an interface of methods that get called at certain times. If you simply click the Create button on the Add-Ins page, it will make you a sample with most of that worked out for you already.

Let’s focus on the Scripts tab for now.

You’ll see a number of sample scripts in there. Some of them will have the JavaScript icon… …and others will have the Python icon…

The Fusion 360 API supports 3 languages: C++, Python, and JavaScript.

Above those, you’ll see the My Scripts area that contains any scripts you have written or imported.

It’s not entirely clear at first how this works. Let me explain. If you click Create at the bottom, you’ll get a new script written in a strange folder location. It’s good because it gives you the right files (a .js file, an .html file, and a .manifest), but it’s bad because it’s in such an awkward location. The best thing to do in my opinion is to hit create and get the sample code files and then move the files and their containing folder to wherever you keep your code. Then you can hit the little green plus and add code from wherever you want.

One more nuance of this dialog is that if you click the Edit button, Fusion 360 will launch an IDE of its choice. I think this is weird and should be configurable. If I edit a JavaScript file it launches Brackets. I don’t use Brackets. I use Visual Studio Code. It doesn’t end up being that much trouble, but it’s weird.

To edit my code, I just go to my command line to whatever directory I decided to put it in and I type…

code .

That launches Code with this directory as the root. Here’s what I see…

There you can see the .html, .js, and .manifest files.

I’m not going to take the screen real estate to walk you entirely through the code. You can see it all on GitHub. But I’ll attempt to show you what it’s doing at a high level.

Here’s the code…

<style type="text/css">.gist {width:700px !important;}
.gist-file
.gist-data {max-height: 500px;max-width: 700px;}
</style>
<script src="https://gist.github.com/codefoster/0b24212710319b681453.js"></script>

Let’s break that down some.

The createNewComponent function is just something I made. That’s not a special function the API is expecting or anything. The runfunction is, however, a special function. That’s the entry point.

Essentially, I’m creating a 20x20 grid, prompting the user to select a body, and then doing a 2D loop to copy the selected body. The position is all done using a transformation that shifts each body into place and then offsets it a certain amount in the Z direction. In this case, I’m just using a random number, but I could very well be feeding data in to this and doing something with more meaning.

Watch this short video as I create a cube and then invoke this script on it…

So, here is where you just have to sit back and stare at the ceiling and think about what’s possible - about all the things you could generate with code.

My example was a basic, linear iterator. Perhaps, however, you want to create something more organic - more generative?

Check out this example by Autodesk’s own Mike Aubry (@Michael_Aubry) where he uses Python code to persuade Fusion 360 to build a spiral using the API.

That has a bit more polish than my gray cubes!

If you build something, make sure you toss a picture my way on Twitter or something. I’d love to see it.

Top 5 Things C# Developers Hate About JavaScript

We’re called coders. We’re called software developers. But despite what we’re called and despite our primary function of turning human logic and scenarios into ones and zeros, not everything we do in these roles comes down to a programming language. The soft skills, in fact, end up being massively importance. I could elaborate in a separate blog post (and just may) about the centrality of grammar skills, technical writing skills, communication skills, diplomacy skills, and so on. I’m tempted to call on Napolean Dynamite to elaborate on the importance of various skills, but none of his examples actually work toward my point, so I’ll refrain.

Nevertheless, a good portion of our roles does end up as code, and our choice of language ends up being a significant and quite personal matter.

My experience has been dominated by C# and JavaScript. I don’t really want to revisit the other languages. That’s what counselling is for. And I love both of these languages. My experience spanning the two has given me some perspective on those that tend toward either one camp or the other. Perhaps my observations on why C# developers might get a bit worked up about the prospect of having to spend some time on a JavaScript project will entertain or even inform. I wouldn’t count on it, but that’s always the goal.

LINQless

First and possibly foremost among the reasons is the fact that a move from C# to JavaScript finds a developer sharply aware of his lack of LINQ.

If you don’t know, LINQ (Language Integrated Queries) is this amazing set of extension methods that affect lists in C# and extend even to external collections of things or persistent data. After a relatively short onramp, LINQ developers find themselves expressing just what they want in terse and very readable code.

LINQ is a beautiful thing and the first time you type .First() on a JavaScript collection and language services tells you you’re crazy for expecting to just be able to just do that, you do feel a sudden urge to put resumes out.

Resolution

I’d be mean if I didn’t offer what I know as far as resolution to this pain, so I’ll try.

While I can’t say that JavaScript does in fact have LINQ and you only have to type a using statement at the top of your code file, I can say that there are a number of roundabouts that heal most of the pain.

First, many still don’t know that ECMAScript5 defines and JavaScript in pretty much every browser worth it’s salt and your time implements a set of array functions that map pretty well to the common array functions. The lambda syntax isn’t quite as elegant, but there’s ECMAScript6 and TypeScript to remedy that. Instead of .Select() you get .map(), Instead of .Where() you get .filter(), and you always get .forEach() even without casting to a List first.

Second, JavaScript’s amazing set of open source libraries comes to the rescue with a number of suggested solutions such as LINQ for JavaScript on Codeplex, Underscore.js, and likely about a thousand more.

Finally, there’s the fact that most of the LINQ functionality is actually drop dead simple and I for one end up implementing functions on my own just for that code warrior feeling it gives me.

The Inequality of Equality

C# folks come out of their skin when they see the === sign. They assume it’s a typo and pull over long before the end of the explanation for its existence.

This one actually bothers me quite a bit, because as I see it, it offers a small convenience but costs a lot of clarity. Seldom does the convenience of type coercion benefit me more than the hassle of spending the 3 or so brain cycles it takes to choose. I’ve been told to save the cycles and just use === every time, but I’m not sure I’m convinced.

Resolution

None. Just live with it.

Weaknesses of Weak Typing

When you write an app in C#, you have to explicitly include definitions for every little thing. If you need a Customer with facial hair, you also need a CustomerFacialHairTypeEnumand a CustomerFacialHairTypeEnum.Goateevalue. Then a little way in, you end up having to write another class for a CustomerMapAttributeDifferentiatorFactoryGenerator or something like that. That’s what it feels like anyway when you write JavaScript for a week and then come back to a C# project.

But the result is veritable utopia of design-time tooling and near-iron-clad certainty that when your app builds, your app runs.

We don’t have this in JavaScript. In fact, JavaScript is practically defined by its lack of certainty, but if you give me a Customer I’ll give him a goatee in one short line. Then you ask me if my new object implements IFacialHairCustomer and I’ll just look blankly at you as if the answer is as unnecessary as the question.

Resolution

None necessary. No problem, no resolution.

Short Variables Names

JavaScript developers get used to such terse syntax and they just go crazy with it. You end up with…

var a = args.d.detail;

…and you end up with sleepless nights.

My personal rule on variable names in JavaScript is similar to my rule for variable names in C# actually. Use full, meaningful names, unless you’re inside a statement block brief enough to convey meaning better by way of its brevity.

In my opinion, the function…

customers.filter(function(c) { c.age > 21; })

loses more meaning than it gains when it’s expanded to…

customers.filter(function(customer) { customer.age > 21; })

Resolution

Stick to the same core philosophy with your JavaScript that surely you do with your C# - that is, think about the next guy that’s going to look at your code.

The Word Java

Finally, C# developers enjoy a few benefits of the language over Oracle’s Java, and the mere inclusion of the word Java in JavaScript is perhaps a deterrent.

As they say, however, Java is to JavaScript as Ham is to Hamburger, and the two have exactly 4 bytes in common and no more.

Resolution

Let go of nomenclature and get on with JavaScript

That’s all I’ll say on the matter. Thanks for listening.

Tapping Into Your Localized Resources Using JavaScript

Many developers (present parties included) are neglecting to take advantage of other cultures and are missing relatively easily earned revenue as a consequence.

Localizing your app by referencing resource strings is the first step and sets you up for easy translation to other languages. It’s simple enough to add your data-win-res in your HTML, but what about when you need to do the same thing from JavaScript?

There’s a quickstart on MSDN that will walk you all the way through the former, but if you run into a situation where you need to do the latter, you might find yourself in a pinch as there’s not nearly as much information online about it. It makes sense since it’s not an altogether common scenario.

The trick is to check out the Application Resources and Localization sample (also on MSDN) and look at scenario 11.

In it you’ll see that you can simply ask the ResourceManager for help. Let’s have a look in detail.

Create for yourself an empty Windows 8 blank app using JavaScript.

Now create a new folder called strings and in it a new folder with your culture name. Mine is en-US. If you don’t know the code for your culture name then you can look here.aspx). The table is very helpful if you speak English, but I wondered if MSDN has gone the extra mile and provided content in other languages.

A brief search turned up the button at the bottom of the page, but switching it to only provides me with…

Meaning, unfortunately, that this content is not available in your language, so here’s English. Bummer.

…and later on…

Meaning, _was this page helpful? _Well, not actually if you only speak French, but c’est la vie.

And that right there is the nature of technical content on the web. Information changes at lightning speed and it’s a wonder any of us can keep up with our apps or our documentation in anything but our own language.

But I got us sidetracked and you likely know your culture code anyway.

You should now have a string folder and a culture folder and inside the culture folder you create a resource file using a right click | Add | New Item… > Resources File (.resjson). So you should have this…

Open the resources.resjson file and you should see that it was prepopulated with…

{
"greeting": "Hello World!",
"_greeting.comment": "This is a comment to the localizer"
}

Great. Now you have the resource string. The word greeting there is what you use as your resource string identifier, but it doesn’t get shown to the user. The user sees Hello World! because that’s the value of that string.

Now, as I mentioned, utilizing this from your HTML is quite straightforward. you just add an attribute to whatever element you want to suck it into. If you want it to populate a div, you would use…

<div data-win-res="{textContent: 'greeting'}"></div>

In case you’re new to this, the data-win-res tag is so named for a few good reasons. The data- means it’s a valid HTML5 and will not trigger any syntax validators. The win- means it’s something provided by the WinJS library and makes it easier to distinguish from other libraries or from your own code. And the res obviously stands for resource, but you didn’t need me to tell you that.

Now comes the interesting part.

It may be that you are not laying this out so declaratively.

BTW, I can remember not knowing the difference between declarative code and a hole in a bucket, so I’m going to explain it here in case it helps.

There are two types of code (at least) as it pertains to UI. There’s declarative and imperative. Declarative code is the parts of your UI that exist because you explicitly wrote them into a UI description language like HTML, XAML, AXML, or whatever. Imperative code is the parts of your UI that come into being because you wrote code that told them to - usually based on some logic or action by the user.

If, for instance, you want to define a UI element that looks like a text box and prompts the user to enter their full name, you would likely be able to do that using declarative code. That likely means you’ll be writing HTML for it.

If, on the other hand, you need to get fancy with your UI and build it logically or if you need to ask the user something that you need to know before you can determine what kind of UI element to use, then you would likely be forced to use imperative code. It’s usually preferable to use declarative code when possible.

If, for instance, you need to figure out some information at runtime and use that to determine which string to use, then you need to load your resources imperatively. And I’m going to show you how.

Instead of tacking a data-win-res attribute on your div, simply give it an id attribute so you will be able to reference it from your JavaScript. Go ahead and do that in your default.html file replacing the existing <p>Content goes here</p>. Like this…

<div id="mydiv"></div>

Now, if you created this project from the blank template, then you’ll find a js folder with a default.js file in it. Open that and add the following method…

And that should work. Running the app (CTRL+F5) should result in a comforting Hello World in white text rendered on a black background.

Let me break down each of the five lines of that function, so you can see not only that it works but why.

Line 1: var resourceNS = Windows.ApplicationModel.Resources.Core;

This simply gives a shorter handle to the resources core which is built into the Windows application model. It’s a common practice to use this feature of JavaScript to shorten deeply embedded classes or even functions, and it does nothing more than keep your code shorter.

Line 2: var resourceMap = resourceNS.ResourceManager.current.mainResourceMap.getSubtree('Resources');

This is the first call to ResourceManager which handles the available resources in the current application. The getSubtree method is rather robust, but in this case it’s essentially allowing us to identify the file that our resources are in. In a large app, we may choose to separate our resources out topically for a better architecture.

Line 3: var context = resourceNS.ResourceContext.getForCurrentView();

The getForCurrentView method of the ResourceContext fetches the correct resource context for you. This is necessary because in Windows 8.1 resources can be customized for various scaling levels (which are determined by the screen resolution of the device your app is running on).

Line 4 (optional): context.languages = ['en-US'];

The fourth line is optional actually. If you don’t specify a language for the current context then your system’s current culture will be used. If you choose a language that you don’t have installed on the system then it will revert to whatever your system’s current culture is as well.

Line 5: mydiv.innerText = resourceMap.getValue('greeting', context).valueAsString;

Finally, you simply set the value of your UI element to the results of a call to the getValue method of your resource map.

That does it. Now, if you’re like me then you immediately start thinking about how you can wrap these 5 somewhat painful lines of code in a very elegant and semantic helper method to use anywhere within your app, and I’d say that’s a great idea.

7 Reasons I Still Love JavaScript

For many reasons, I still love developing Windows 8 apps using HTML, CSS, and JavaScript. I have extensive C# experience and always want to be able to say “I’m a C# developer”, but I’d like to add that “I’m a JavaScript developer” as well.

Some months ago I was a little pained to make even a short term commitment to write more JavaScript than C#. It felt a little like when I was learning French and found myself hesitant to start trying to think in French as if I would lose my English. Of course, that won’t happen, and we shouldn’t be afraid even of immersing ourselves in other languages. In fact, I’m a big advocate of the polyglot theory of intentionally moving into other languages spaces to expand our own scope, our value, and our perspective.

Becomes a way of thinking

I’m sure most development languages become a “way of thinking,” but I think JavaScript does even more so because it’s so dynamic and so light.

It’s the language of the web

Mashups are a breeze when you’re ingesting HTML and JSON data into and app that’s made with HTML and JavaScript. The WinJS.xhr() method can make web requests with a request type of “document” and then immediately act on the results just like it would any other in-app content. Blob images can be consumed and repurposed. JavaScript objects can be created instantly out of JSON data. Yada yada yada. It’s very convenient.

CSS selection of elements is great

Selectors are one huge strengths of the HTML/CSS that take advantage of the fact that HTML markup goes all the way to the client as XML-like syntax. Even on the client (at run-time) CSS can select very specific portions of the UI in order to affect it with styles or layout. JavaScript can take advantage of selectors too (using document.querySelector and .querySelectorAll) and that allows our logic to act on very specific portions of the UI.

One with the masses

There are a LOT of people writing JavaScript. A StackOverflow search on the [javascript] tag returns 300k+ questions on the matter (actually [c#] returns almost 400k!). It’s good to have camaraderie in writing code. It’s good to have employers looking for your skillset. It’s good to have others asking questions on StackOverflow that you can benefit from. It’s good to be one with the masses.

Standards driven

3JavaScript is broadly adopted and is broadly and inherently appealing because it’s based on web standards. The ECMAScript standard that is JavaScript, along with CSS and HTML, are governed by the World Wide Web Consortium (W3C) and that makes developers feel good. It’s very democratic and very social and has very high likelihood of moving forward and moving in good directions.

Don’t reinvent the wheel

There are a lot of JavaScript libraries out there. A lot. If you want to track faces or get fancy with date calculation or recognize touch gestures or implement IoC or pub/sub or manage Entity Framework data or edit images or any of a plethora of other things, there’s a JavaScript library waiting for you.

A full stack of script

When you write C#, you don’t usually just write C#. We find the client/server model everywhere and you don’t send server code to the client, but you can send script. Whether you’re writing an ASP.NET app or a client app, these days it seems you’re inevitably going to be interacting with some HTML or even some JSON somewhere… whether you’re using REST web services or scraping HTML screens. Having JavaScript on both the server end and the client end just tends to make you smile.

I like exploring languages. I am a veteran of VB. Like I have said, I’m a huge fan of C#. I have huge respect for C++ (though I haven’t knocked on that door since college). I am exploring Erlang. Nevertheless, today I am having a blast writing JavaScript, and if you’re writing JavaScript, I don’t think you’ll be hurting for work anytime soon!

Happy coding!

Using WinJS.xhr to Fetch This and That

You know the story. A call to a website used to be little more than a single request with its single response. But times have changed. The web is all grown up and any given visit to a website is often accompanied by multiple requests for more atomic bits of data.

The popular thing to do now, in fact, is to implement websites using a single page architecture where the user does one primary request and response to get the core document, and then the rest of his or her time spent in the app consists only of these tiny requests/response cycles that bring just what’s necessary.

This is how Windows 8 apps using HTML/JS work - they are single page apps. And to play in this sandbox, you need to get good at using WinJS.xhr(). WinJS.xhr() is not a fancy function. It doesn’t do a lot more than any of the other libraries do when they wrap the XmlHttpRequest. It makes for good, simple, elegant though and I like that.

Watch this screencast of the xhr() function in action and enjoy.

A JavaScript Library for Everything

Windows 8 is one of those environments that’s just fun and expressive to develop in. So is JavaScript. The convergence of the two is just rockin’.

One of the great things about JavaScript is the enormous amount of code that other people have already written and put up on the web for your consumption. Do you want to wrap local storage (store.js), detect faces (liuliu), implement lightweight pubsub (minpubsub), or load JavaScript asynchronously (include.js)? You can do it by simply including a library in your Windows 8 project.

To find a library, you can always Bing (did you know that Bing results are preferred to Google 2:1 in blind taste tests?) for the functionality you need or you can try something here…

Random Tile Colors

This tip is quite short and simple, but worth a post I think. If you want to colorize some tiles like the start screen does, here’s one simple way to do it.

var demos = [
{ key: "local", name: "Loading local data", group: "Data" },
{ key: "netflix", name: "Loading Netflix data", group: "Promises" },
{ key: "netflix10", name: "Loading Netflix data by 10", group: "Promises" },
{ key: "custom_promise", name: "Using custom promises", group: "Promises" },
{ key: "simple", name: "Simple data binding", group: "Data Binding" },
{ key: "properties", name: "Binding more properties", group: "Data Binding" },
{ key: "template", name: "Templates", group: "Data Binding" },
{ key: "share_simple", name: "Sharing text data", group: "Sharing"},
{ key: "datejs", name: "date.js", group: "Libraries"}
];
var colors = ["#0098ab", "#0070a9", "#d9532c", "#a400ac", "#009086", "#5838b4", "#ae193e", "#2c86ee", "#009c00"];
demos.forEach(function (i) {
i.tileColor = colors[Math.floor(Math.random() * colors.length)];
});

This is some code from a project I have that showcases some simple code demos, so I have an array of each of these objects. Then I create a quick array of some of the color codes used on the start screen. Finally, I simply do a forEach on the demos array adding a new tileColor property to each which is a randomly selected color from the color array.

This ability to just throw another property onto an object without mucking with the class and affecting all of the other instances, is in my opinion one of the nicest things about a dynamic language like JavaScript, and I take advantage of it quite a lot.

Now to actually use this color for the tiles, it’s a simple matter of adding it to the databinding statement like this…

<div id="itemTemplate" data-win-control="WinJS.Binding.Template">
<div class="tile" data-win-bind="onclick:click;style.backgroundColor:tileColor;">
<h3 data-win-bind="innerText:name;"></h3>
</div>
</div>

Notice the style.backgroundColor:tileColor term. That’s all it takes.

Using Promises

If you’re developing Windows 8 apps using JavaScript, then you’re likely familiar with the WinJS.Promise object. You can hardly get by without using one, because a lot of the API in WinJS and WinRT is asynchronous and for JavaScript apps they return a Promise.

I’m going to share with you what I have learned about promises so far in increasing order of sophistication.

Consuming a Promise

Everybody and their uncle is going to use this one. If you need to make a call to WinJS.xhr() for instance, you’re going to get a WinJS.Promise in return. They’re quite easy to deal with actually and you may already know this.

When you get a promise from a method, you simply hang a .then or a .done method off of it and provide a function that you want to run when the asynchronous method is complete.

WinJS.xhr({url:"http://someuri.com/service"})
.done(function(xhr) {
//do something here
});

The call to .xhr comes back really quickly and you and your code go about your day even though the service hasn’t responded yet. Then when the service finally does come back to you, everything inside the done method runs. The promise that .xhr returns contains a payload as well. That’s why we’re able to declare our done function with function(xhr) and then access whatever it is the service returned.

So this is super handy for keeping our UI fast and fluid. But let’s move past merely consuming promises and get a bit more advanced.

Passing a Promise

You’ve seen how to consume a promise so that you can avoid a blocking call to a relatively long running or potentially long running method call. Sometimes you want to write a method yourself that calls an asynchronous method and you want to give your method caller the ability to call it asynchronously.

In this case, all you have to do is return the promise given to you by the asynchronous method you’re calling. So, for example, let’s wrap the example call to .xhr above with our own method call…

function myMethodAsync() {
//may want to do some stuff here
return WinJS.xhr({url:"http://someuri.com/service"})
.done(function(xhr) {
//do something here
});
}

There we go. Now I can call myMethodAsync (and by the way, adding Async to the method name is a convention to indicate that it is an asynchronous method) like this…

myMethodAsync()
.done(function(xhr) {
// do something here
});

And notice that I can still specify the xhr parameter for my done function and access the payload.

That’s how we pass along a promise from one asynchronous method to another. Sometimes, however, you need to start from scratch and create your own promise.

Creating a Promise

If I want to create my own method and allow callers to call it asynchronously then I need to return to them a promise. That’s simply the pattern in JavaScript.

Creating a promise is pretty easy, but you need to understand the concept because sometimes things can start to feel messy and it’s really helpful to understand what’s going on (not that I do entirely yet).

In Windows 8 JavaScript development we have the WinJS.Promise. You create it like this…

new WinJS.Promise(function(c,e,p) {
//function body
});

The c, e, and p are parameters that are themselves functions. Within the function body, then, I can actually call c() when I want to complete the promise, call e() when I want to report an errant case, or call p() when I want to report progress.

Study this method I wrote that makes sure a file exists and if it doesn’t then it creates it…

function assureFileAsync() {
return new WinJS.Promise(function (c, e, p) {
if (fileExists("applicationData.json"))
c();
else
appdata.roamingFolder.createFileAsync("applicationData.json")
.then(function (file) {
return Windows.Storage.FileIO.writeTextAsync(
file, JSON.stringify(starterData)
);
})
.done(function () { c(); });
});
}

There are a few things going on here, so let’s dissect.

First, I did use the Async suffix to indicate to the caller that this is going to be an asynchronous method. I create and return a new WinJS.Promise and the bulk of the logic here exists in the function declaration for that promise.

If a file called applicationData.json exists (fileExists is another function I wrote), then we don’t need to do anything and this promise should be considered complete, so we simply call c(). If we wanted our promise to carry a payload (like the xhr method does), then we could put that here by calling c(myResult). In this case, however, we don’t need that.

If the file does not exist, then we want to create it. Notice that this creation is itself an asynchronous call and in the .then there’s even another one. Finally, after we have made certain the file exists and contains my starterData, then we call the c() to indicate that this promise is complete.

There’s plenty more insinuated by this, but I’m going to leave it there for now in the interest of simplicity.

Saving a Promise

Now this trick I just figured out recently and it’s very handy.

Let’s say that in one part of my code I want to do something (call it Action A) that may take some time, and then in another place I want to do something else (call it Action B) but Action B should not occur until Action A has successfully completed.

I could let Action B call Action A asynchronously because then I could hang the .then or .done on that call. Sometimes, though, I don’t want Action B to be the initiator.

Let’s look at a more concrete example. This is the case where I ended up discovering this pattern.

When my application loads I want to load all of the data from file. When you user lands on the home page, I want to show the loaded data. Obviously I can’t show the user the data until it’s loaded, but I want to initiate the data load in the app’s activated event not in the home page.

So here’s what we do. We initiate the data load from the app’s activated event and save the resulting promise somewhere where it will be accessible to the home page. I just added it dynamically onto the WinJS.Application object (not sure if that’s recommended or not, but it works great :) Then from the home page, we simply access that object and hang a .done on it. Easy.

Here’s the data load call from my app activated event…

WinJS.Application.dataLoadedPromise = Data.initializeAsync();

…and here’s where I want to start work on my home page data, but only after the data is loaded…

var hubItemsList = new WinJS.Binding.List();
WinJS.Application.dataLoadedPromise.done(function () {
getHubItemsAsync()
...

Now getHubItemsAsync (itself another asynchronous call, but that’s coincidental) will only get called once the dataLoadedPromise is complete.

Conclusion

There’s much more to promises that I didn’t include here - for brevity in part, but also because I haven’t discovered it yet, but keep an eye on this blog. As I turn over new leaves, I’ll post it here - I promise.

Page Navigation in Windows 8 JavaScript Apps

I’d like to talk a bit about navigating in Metro apps using HTML/JavaScript. There are a few options for doing so, and as you probably know whenever there’s more than one way to do things, then you the developer have power but not necessarily clarity. The latter is what I hope to offer here.

First of all, the HTML/JavaScript that Metro apps are based on are identical to the HTML/JavaScript that websites are based on. It is entirely based on the standards. This is good because proprietary things are bad - generally speaking. This means that you can navigate exactly like you do in websites, but don’t. I’ll explain why not.

So you could navigate from default.html to page2.html like this…

<a href="page2.html">link to page 2</a>

But again… you should usually do this. Doing so changes the “top level document location”. This navigation looks something like this…

Where the user is no longer on the default.html page. For websites, it’s just fine to jump around by navigating the top level like this because you’re usually not too concerned about state, but in a full-fledged application, you usually are concerned with state and you can make your life easier by using the built-in navigation features that are provided by the VS2012 templates.

When you use the navigation functionality, a navigation looks more like this…

Notice that the user is still on default.html, but the contents of the second page have simply been loaded into what is called the contenthost. Now, if you loaded a bunch of script and styles on default.html and even declared some variables and set some state, you still have all of that, even though to the user it appears that you’ve navigated to a second page.

Implementing this is pretty straight-forward. Follow these steps…

  1. Get the navigate.js script file that comes with the Navigation Application project template in VS2012. You can either start with the Navigation Application project template and notice that navigate.js is already in your js folder, or you can create a throw-away Nav project and steal that file.

  2. Reference the navigate.js from your default.html file…

  3. Add a contenthost to your default.html file

And that’s it. After this has been implemented, then you are free to do things in your JavaScript like this…

WinJS.Navigation.navigate("/pages/page2/page2.html");

And you have the chance to pass some parameters without having to resort to query string parameters which can be cumbersome and restricting. To do this, you can pass a second parameter to the navigate function like this…

WinJS.Navigation.navigate("/pages/page2/page2.html", myDoohicky);

…where myDoohicky can be any JavaScript object you want.

Now, when might we actually perform this navigation? Well, in many cases it will be on some user action. For instance, let’s say the user is going to click a button and we want to navigate them to page2.html. Let’s see what that would look like…

HTML

<button id="myButton">go to page2</button>

JavaScript

ready: function (element, options) {
document.querySelector("#myButton").onclick = function (args) {
WinJS.Navigation.navigate("/pages/page2/page2.html", "test value");
};
}

Now let’s look at a bit more pragmatic example. Let’s say we are working in a grid (WinJS.UI.ListView technically) and when the user touches one of the tiles, we want to navigate to a second page with more details about that element.

This can be wired up much like the simple button example above, but likely the elements in our grid are data bound from some list that we have. In that case, perhaps the easiest way to implement this is by adding a function to the list and then bind the click function just like any of the data elements are bound. Here’s an example of that…

HTML

<div id="headertemplate" data-win-control="WinJS.Binding.Template">
<div>
<p data-win-bind="innerText:firstLetter"></p>
</div>
</div>
<div id="template" data-win-control="WinJS.Binding.Template">
<div data-win-bind="onclick:clickFunction">
<img class="img" data-win-bind="src:imageUrl" />
<p class="name" data-win-bind="innerText:title"></p>
</div>
</div>
<div id="list" data-win-control="WinJS.UI.ListView"></div>

JavaScript

ready: function (element, options) {
var titlesListGrouped = new WinJS.Binding.List().createGrouped(
function (i) { return i.title.charAt(0).toUpperCase(); },
function (i) { return { firstLetter: i.title.charAt(0).toUpperCase() }; }
);
var list = q("#list").winControl;
list.itemDataSource = titlesListGrouped.dataSource;
list.itemTemplate = q("#template");
list.groupDataSource = titlesListGrouped.groups.dataSource;
list.groupHeaderTemplate = q("#headertemplate");
WinJS.xhr({ url: "http://odata.netflix.com/Catalog/Titles?$format=json&amp;$top=200" })
.then(function (xhr) {
var titles = JSON.parse(xhr.response).d;
titles.forEach(function (i) {
var item = {
title: i.ShortName,
imageUrl: i.BoxArt.LargeUrl,
clickFunction: function(args) { WinJS.Navigation.navigate("/pages/page2/page2.html", item); }
};
item.clickFunction.supportedForProcessing = true;
titlesListGrouped.push(item);
});
});
}

Now, there’s a lot going on in the JavaScript file there, so let me break it down for you. First of all, I pulled this example from another post I did on creating a Netflix browser app utilizing their OData feed. If you want to know what’s going on with the call and the data binding, go check that out.

I added to it though. I changed what happens in the forEach loop. The reason I did is to illustrate how to bind to a function like you bind any other data property. Look in the HTML at the div just below the one with the id of template. I’m binding the onclick attribute to the clickFunction. That clickFunction is what I created in the forEach loop of the JavaScript. Notice, though, that there’s one funny thing we need to do to it. Since we are using this in the HTML it could be exploited and so we turn on strictProcessing for our app and that requires us to set _supportedForProcessing_ on any functions that we are going to call from the HTML. So, we set that to true for our function and we’re good to go.

I hope this brings the concept home for you. If you have questions, leave a comment below and I’ll be glad to try to help.

I give you my word...

I’m excited about what I just implemented. I’m always excited when I figure something out or learn something big. This one is big for me. Hopefully this post will add some value to your life as well.

First the problem statement…

Here’s what I wanted to do. I am working on a Windows 8 Metro app using HTML/JavaScript.

I have a data.js file that represents (for now, until I put the data in the cloud) my data service. I am loading data up from a roaming file that contains simple JSON data. Actually, is “simply JSON” redundant. JSON just IS simple, right?

My hub page then needs to make sure that the application data is loaded and then it needs to request some. I can’t just directly request the data as is though because it needs to be massaged into the right shape to back the hub view. My application has items of Type A and Type B and I need to essentially flatten that into a super type that my hub will represent in different groups.

So I need to fetch some data and it needs to happen in an async fashion.

I’ve consumed objects that follow the Promise pattern plenty, but here I need to create my own Promise and get all custom about when it is considered complete and what it returns as its payload.

So I have two methods that I need to make asynchronous: loadAppDataAsync() and getHubItemsAsync(). The former is internal to my data.js function, but the latter is “exposed” to the rest of the app using a WinJS.Namespace called “data”.

loadAppDataAsync

This method, as I said, is “internal” to my data.js file. That is, it’s defined inside the modular function that encapsulates everything on my data.js file and thus is not available anywhere else in the application. The purpose of the function is to read the applicationData.json file and populate some arrays with the results. Here’s the method definition…

function loadAppDataAsync() {
return new WinJS.Promise(function (c, e, p) {
if (loaded) c();
else {
appdata.roamingFolder.getFileAsync("applicationData.json")
.then(function (file) {
Windows.Storage.FileIO.readTextAsync(file)
.then(function (content) {
//load the checklists
JSON.parse(content).checklists.forEach(function (i) {
checklists.push({
title: i.title,
template: i.template,
description: i.description,
backgroundImage: i.backgroundImage,
items: i.items,
type: "checklist"
});
});
//load the templates
JSON.parse(content).templates.forEach(function (i) {
templates.push({
title: i.title,
description: i.description,
backgroundImage: i.backgroundImage,
items: i.items,
type: "template"
});
});
})
.then(function () { c();});
});
}
});
}

I added the Async suffix to the method name because this method not only calls an async method, but also acts asynchronously itself. Here’s how that’s implemented.

If I just wanted to wrap up the getFileAsync method call, then I could simple return the result of that call, but I need to add a little bit of my own logic. I only want to make the getFileAsync call in the condition that my data has not already been loaded. So I return a new WinJS.Promise specifying its function (which receives complete, error, and progress attributes that I’ve called c, e, and p). In the function, if the data has already been loaded I call the complete method c (passing no attributes) immediately indicating that we’re done loading app data (because it’s already loaded). If the data has not been loaded, however, we have some work to do and we will not complete (by calling c) until we’re done with it (that’s why it’s in the .then).

This one is pretty simple. Let’s move on to the next method that we use to get the hub items after the application data has already been loaded. Here’s the code…

WinJS.Namespace.define("data", {
getChecklists: function () { },
getHubItemsAsync: function () {
var hubItems = [];
return new WinJS.Promise(function(c, e, p) {
loadAppDataAsync()
.then(function () {
checklists.forEach(function(cl) {
hubItems.push({
item: cl,
title: cl.title,
backgroundImage: cl.backgroundImage,
section: "My Checklists",
click: function (ev) {
WinJS.Navigation.navigate("/html/checklistPage.html", { item: cl });
},
get subtitle() {
return (cl.items.filter(function (i) { return i.checked; }).length / cl.items.length)
+ "% of " + cl.items.length + " items";
}
});
});
templates.forEach(function(t) {
hubItems.push({
item: t,
title: t.title,
backgroundImage: t.backgroundImage,
section: "My Templates",
click: function (ev) {
WinJS.Navigation.navigate("/html/template.html", { item: t });
},
get subtitle() { return t.items.length + " items"; }
});
});
})
.then(function () { c(hubItems); });
});
}
});

This one is defined in a Namespace so that we can call it from elsewhere in our app - namely from hub.js. What this method does is a little different from the former. Like before, we are returning a new Promise. Unlike before, after we populate our result (hubItems), we complete the promise with a result by calling c(hubItems).

Passing a value to the complete function makes that value available to the caller like this…

data.getHubItemsAsync().then(function(hubItems) {
hubItems.forEach(function(i) { hubItemList.push(i); });
});

Simple, eh? That’s the way it’s supposed to be. I want to get then items and then I want to push each of the results into my WinJS.Binding.List (here called hubItemList).

Now the grid on my hub is bound to a List that gets populated with data after the application data has been loaded and after the getHubItemsAsync method has projected the application data to look how we want it to look.

Phew! This JavaScript stuff is pretty crazy. It’s pretty awesome though.

Happy promise keeping!