Sponsored By Aspose - File Format APIs for .NET

Aspose are the market leader of .NET APIs for file business formats – natively work with DOCX, XLSX, PPT, PDF, MSG, MPP, images formats and many more!

Drafting problems with confcodeofconduct.com and other thoughts

Much has been written about Codes of Conduct recently. In my previous blog post, I mentioned the problems with many of the Codes of Conduct used today. The first thing everyone needs to understand is that while there is a moral basis articulated for why these codes should exist, they are nevertheless legal documents. At least, they should be treated and DRAFTED as such.
To demonstrate that, I’m going to analyze the model Code of Conduct at confcodeofconduct.com. Let’s begin:

All attendees, speakers, sponsors and volunteers at our conference are required to agree with the following code of conduct. Organisers will enforce this code throughout the event. We are expecting cooperation from all participants to help ensuring a safe environment for everybody.

How about guests? It is possible that there is some other class of person that could be missed here? What about a spouse of an attendee? Right off the bat, this document is in trouble. One of the things you will notice is the lack of defined terms in the document. In a legal document, a defined term’s first characters are always capitalized, regardless of whether they appear as the first word in the sentence or somewhere else.

The Quick Version
Our conference is dedicated to providing a harassment-free conference experience for everyone, regardless of gender, age, sexual orientation, disability, physical appearance, body size, race, or religion. We do not tolerate harassment of conference participants in any form. Sexual language and imagery is not appropriate for any conference venue, including talks, workshops, parties, Twitter and other online media. Conference participants violating these rules may be sanctioned or expelled from the conference without a refund at the discretion of the conference organisers.

What is “harassment” for purposes of this document? It gets more confusing because in the second sentence, other terms are used (Sexual language and imagery). Are these additional words meant to imply something different from “harassment”? Or, are these words meant to define or further define what harassment means for purposes of this document? The good news is that in the absence of a definition, a court may take judicial notice of a common definition. The problem is the additional words could still imply that sexual language and imagery are something different than harassment. Are they more or less serious? Are they to be treated the same? Much of this can be sorted out – but somebody other than the drafter. That’s the point here – that there is an intent which is attempted to be expressed here. Remember this too, ambiguities in a legal document are construed against the drafter. In other words, you as the drafter, the one whose intent your document is supposed to reflect, won’t get the benefit of the doubt.

The Less Quick Version
Harassment includes offensive verbal comments related to gender, sexual orientation, disability, physical appearance, body size, race, religion, sexual images in public spaces, deliberate intimidation, stalking, following, harassing photography or recording, sustained disruption of talks or other events, inappropriate physical contact, and unwelcome sexual attention.

Here, in the less quick version, there is an attempt to define harassment. What if somebody is doing something that is not included in this finite list that another feels is harassment? Guess what, they are out of luck. When you have a finite list like this, they become words of limitation. As to the photography element, the word harassing appears. Always a problem to have the word used inside the definition for that word. That’s bad legal drafting as it makes for a lack of clarity. Typically, you will see a list of things in a legal document. This is often used as a guide for understanding. A well written document would include the phrase “including, but not limited to..” That way, you don’t have to keep amending your document when another type of activity could be covered.

Participants asked to stop any harassing behavior are expected to comply immediately.

This statement is bad on a number of levels. First, the phrase participants is used without any definition. It is capitalized as the first word in the sentence. With a conference however, the phrase participant likely means something, such as the word attendee. The other problem with this sentence is that it places a condition precedent on the offending behavior. If they are not asked to stop, they don’t have to “comply immediately?” I know that is not the intent of the document, but that is what these words say. Accordingly, statements like this are really meaningless in a legal sense. To the lay person who wrote it, it means something. But you are not writing this document for you per se. Rather, you are writing this for somebody else and for it to be enforceable.

Sponsors are also subject to the anti-harassment policy. In particular, sponsors should not use sexualised images, activities, or other material. Booth staff (including volunteers) should not use sexualised clothing/uniforms/costumes, or otherwise create a sexualised environment.

Right off the bat, we now know that Sponsors and Participants could be two separate classes. While participants and sponsors are covered by this code, it still leaves the possibility that perhaps, they are to be treated differently and that perhaps, there are multiple standards, express or implied in the document.

What does “sexualized” clothing mean? We all know what the term “Booth Bunny” means. What if the person working in the booth happens to be an attractive woman who wears clothing that somebody thinks is “sexualized”? Does the sponsor’s employee not have rights? Does the sponsor have to get a clothing check with the conference ahead of time?
This is an example of where somebody has tried to be specific. In that effort however, the attempt at specificity, ambiguities and more questions arise. Remember the thing about ambiguities in a document. They are construed AGAINST the drafter. All benefits of the doubt would go to a sponsor in this case.
And what about attendees? Since this statement only appears to apply to sponsors, are attendees exempt? The text in this code of conduct suggests yes, they are. Was that the intent? Likely no, but that’s what you get when you have poorly drafted legal documents.

If a participant engages in harassing behavior, the conference organisers may take any action they deem appropriate, including warning the offender or expulsion from the conference with no refund.

A few problems here. Notice that participant is not defined. Who is actually covered in that class? Yes, several groups of people are covered under the code. But in this statement, a specific class appears to be carved out. Think of it as a local variable within a module that is shielded from the broader context. Also, what if a sponsor engages in “harassing behavior?” They seem to be exempt here because of the presence of the word “participant” – which is undefined and which is different from the word “sponsor”. And of course, what about volunteers, spouses, etc?

The other thing here is the one thing that many in the Code of Conduct Pledge movement seem to rally against – giving too much discretion to the conference. Here, the conference may do something or may not do something. Also, what if the conference is at a hotel? The “offender” can still stay on prem as the conference has no jurisdiction on that.

If you are being harassed, notice that someone else is being harassed, or have any other concerns, please contact a member of conference staff immediately. Conference staff can be identified as they’ll be wearing branded t-shirts.

First, who is “you”? Do they mean to say that if I’m reading this, I’m covered regardless of whether I’m part of the conference? Other concerns? Is this a catch all?

Conference staff will be happy to help participants contact hotel/venue security or local law enforcement, provide escorts, or otherwise assist those experiencing harassment to feel safe for the duration of the conference. We value your attendance.

Other than the fact that participants are not defined, what does it mean to “feel safe?” As a conference, you are making a warranty here of sorts. It is interesting to note that while there is expulsion for the offender – with no refund, what about the victim? Why doesn’t he or she get a refund? This is getting into the public policy issue here, but it is something that should be discussed. Why should the conference be allowed to profit from both the offender and the victim?

Here’s a news flash, you can’t really help people feel one way or the other – in a legal document. That’s more the stuff of therapy – which the typical conference won’t have trained staff. All you can hope to do is deal with the situation by stopping it and preventing any other harm.

We expect participants to follow these rules at conference and workshop venues and conference-related social events.

Who is “we?” The conference? The people who run the conference as individuals? And what are “these rules?” What is a workshop? What is a conference-related event? Again, the scourge of a lack of defined terms.

Put it this way, if I were representing somebody who was kicked out of a show on the strength of this document, without due process (under some level of due process and other protections of consumer commerce related statutes, etc) – along with the ambiguities, I’d feel very confident about prevailing. Further, there is the strong possibility of a defamation suit due to somebody at the conference saying something. Typically, a conference is not equipped to investigate, provide counsel, etc. Also, I’d be suing the conference as an organization as well the organizers individually. The words of this model code of conduct appear to open them up.

What’s the best advice for a conference? Decide first if part of your business is going involve policing people? If it is, then I suggest you not have the conference. It’s not a good business model. If you are confronted with something that on its face is a crime, then bring in the police and then let them handle it from there. That’s what they do. That’s what they are trained for.
What if what you are confronted with is conduct that is bad for your conference business? Deal with it. If you have to expel somebody, do it. Just be sure you have things documented in case you find yourself getting sued by the expelled party. Indeed, a conference has a right to protect ITS INTERESTS – which are not necessarily and totally aligned with the alleged victim’s interests. And I say alleged because the burden of proof is on the accuser. I know, this isn’t a court of law, etc. But guess what. As a conference, if you don’t afford the accused some level of due process and protection, you could have a tainted process such that you open yourself up for liability.

Finally, as a conference, if you want to have a general statement of expectations for those who participate, go for it. Just make sure it is well drafted and comports with your intent. Make sure it is workable and doesn’t have the unintended consequences of creating additional problems and liability. Above all, don’t rely on the model on confcodeofconduct.com or anything that is related or derives from it.

As a general matter, people have a reasonable expectation that when going to a conference or any event, they can do so with quiet enjoyment – without interference. The 18th amendment of the US Constitution through the Volstead Act in 1921 tried a similar social experiment. Not only didn’t it work – it was a massive failure due to its unintended consequences. Why? For one thing, it wasn’t workable. You can’t legislate morality. Forever, governments and people have tried. Doesn’t work. Bad actors will be bad actors. We rely on social norms and self-policing for the most part. There is in fact a common code of decency. It isn’t written, it’s implied. It is the bedrock of what makes a society. And for every society, it’s a bit different.

Those who hawk prescriptive solutions typically have an agenda. Often, it’s a personal agenda. It can also be a business agenda as well. Well, with all due respect, I choose not to be governed or ruled by your personal agenda. At the same time, I respect a conference’s right to do business as it sees fit. If it wants to have a code of conduct, fine by me. I couldn’t care less. As I said before, I don’t see a conference’s fortunes rise or fall on the presence of a code of conduct. Rather, I evaluate conferences based on factors such as how they operate, the sessions, the speakers, the venue, customer service, price, etc. I think I’m in good company here. And for the few that would eschew a conference for not having a code, I suspect there are people to take their place.

Every conference is different. Each is its own society. How I view DevConnections is far and away different than how I view CodeStock. Love them both, but each are different. Some of the best conferences I’ve attended don’t have Codes of Conduct. And by the same token, some of the so-so ones have Codes of Conduct. I ascribe no causation or correlation to the code or a lack of code. For me, the Code of Conduct insofar as MY evaluation of conference is a meaningless data point. Others may have a different view and while I don’t hold those same views, I respect those views nevertheless just as I respect a conferences prerogative to have a code of conduct or not have a code of conduct.

But if you choose to have one, make sure it is well drafted and you don’t sign up for more than you bargained for. Also, make sure an attorney reviews it.

One other thing. Companies like Heroku that have policies like this: https://www.heroku.com/policy/events. If you are at an event that Heroku sponsors, you be sure to enlist their help in the conference’s enforcement of the Code of Conduct. Not sure if the Heroku folks realized or not, but they put themselves front and center on the policing of these codes. In a very real way, Heroku is warranting that a conference is “safe.” If you happen to be an aggrieved individual and Heroku sponsored the event, talk to your lawyer. You may have a potential second defendant in your cause of action should it come to that. By the way, Heroku’s parent is Salesforce.com.

I think Heroku’s stance is an honorable one and I respect their right to do what they please. Doesn’t affect me one way or the other. I get the idea. By companies doing this sort of thing, it could have the effect of putting economic pressure for conferences to have codes of conduct. Guess what, won’t have a widespread effect. WWDC, SXSW, TechEd, BUILD, Oracle Open, and a slew of other big shows don’t have them for reasons that have nothing to do with wanting people to feel safe. These are big time businesses that have a vested interest in attendee’s safety and satisfaction. If you don’t think that is paramount to them, then you really have no business sense whatsoever. And, if you are the kind of person who needs to have a Code of Conduct in place for you to feel safe, govern your actions and other actions, it really doesn’t say much about how much you value the notion of personal responsibility. If you really think a Code of Conduct is the thing that makes you safe like a bullet proof vest or a panic room, I have a bridge in Brooklyn I’d like to sell you.

Posted in Uncategorized | Tagged , | Leave a comment

Codes of Conduct – a call for calm, clarity and common sense

Much has been discussed recently on Twitter, blogs and other outlets about the need for all conferences to have a code of conduct. As a general matter, I avoid any conclusion that states a specific prescriptive device is suitable in all situations. I view conferences as businesses and I respect their right to run their business as they see fit. As consumers, we can vote with our feet if we feel that there isn’t a good value proposition of if there is something morally objectionable with a conference. As with all things, this is an intensively personal decision. Conferences however, have to be allowed some flexibility. And let’s be candid, just as not all men are pigs, not a single conference I’m aware of, regardless of whether they have a code of conduct or not, solicits bad behavior from its participants. Forget the moral issues – that would just be bad business.

As a general matter, let me put my cards on the table. I don’t believe a conference’s worth rises or falls on the presence of a code of conduct. Such a code is merely made of words on a page. The real question is whether there is a culture of mutual respect and consideration. You don’t need a code of conduct for that.

A recent case is the Columbus, OH conference StirTrek. This conference has gone on for years, successfully – without incident. They do their best to be inclusive. As for female representation amongst speakers, I think StirTrek is well above average. There have been no incidents ala PyCon. And guess what, StirTrek as of today, doesn’t have a code of conduct. StirTrek has something much more important – a dedicated board that fosters a culture of respect. The same goes for my friend Mike Eaton’s KalamazooX conference that focuses on soft skills. With that background, I ask folks to keep a level head about this issue and not paint all conferences and all people with the same brush.

As some of you know, I’m a software developer and a lawyer. I’ve seen many of the codes of conduct and I find the longer, more verbose ones are largely unworkable. They miss important items and contradict in some areas. The longer ones fall into the trap of being more than codes. They stray into the area of regulation. Keep in mind that no code or legal document is perfect. We also have to be mindful of the fact that conferences are put on by dedicated volunteers for the benefit of the community. Yes, we often pay hundreds of dollars to attend, but if we continually attend the same show, we must be recognizing the value. And in fact, we often ascribe the value of a conference to the conduct of its leadership. I ask that people remember that – the people that run a show and their conduct over years of running a show. Does it really matter whether or not a code of conduct exists or existed? I respect the right of people to expect a code of conduct. I also respect the right of conferences to have or not have a stated code of conduct. People, you have a remedy – don’t attend a conference if it is morally objectionable. Where you step over the line is when you demand, to the point of publically bullying conferences to have codes of conduct. Out of fear, some conferences may oblige. But is that what you really want? Don’t you want to change hearts and minds? The irony is that many of the public bullying we see is the type of conduct these same people would find objectionable under their ideal code of conduct.

And finally, how many of you that are demanding codes of conduct would be willing to forgo alcohol at a conference? How many of you attend the all too famous GitHub Drink-Ups. The fact is, alcohol is often a major part of the problem. The other part of the problem is either people who cannot, for one reason or another, handle the situation and get out of control. I’ve been around long enough to know the last thing on anybody’s mind when at a conference social function is whether there is a code of conduct and whether we are in compliance with such document.
OK.. To that, I offer this simple paragraph as a model code. It is small and it balances the equities between conferences and participants. It is merely a statement of expected behavior with a nod to enforcement. Don’t look for details of enforcement. Every situation is different. You’re all adults. You learned right from wrong early on (at least, you were supposed to). You don’t need a piece of paper to empower you. That said, I can understand why there is a feeling that perhaps, there should be an affirmative statement by conferences as to what is acceptable behavior. Personally, I don’t need it, but it is a personal decision and others may differ in their views. Keep this in mind as well – the longer and more specific you make things, the more maintenance it requires. It’s kind of like software!! I think the words below work and provide the kind of assurances any reasonable person would want. Then again, I wrote it and I may be a bit biased!! Note – I don’t get wrapped up in distinctions between attendees, sponsors, volunteers, etc. The code below applies to EVERYONE at the show. That includes staff. Another thing – if a violation amounts to a crime, call the police. Or, contact the venue. The last sentence clarifies that. What is “good conduct”? It’s kind of like pornography. Justice Potter Stewart 50 years ago said: “I shall not today attempt further to define the kinds of material I understand to be embraced within that shorthand description [“hard-core pornography”]; and perhaps I could never succeed in intelligibly doing so. But I know it when I see it, and the motion picture involved in this case is not that.”

Anyone affiliated with this Conference (The “Participant”) is expected to conduct themselves in a civil manner & treat any other Participant with mutual respect and consideration. (The “Standard of Conduct”). The Standard of Conduct is defined by what is deemed to be generally accepted by the Conference; the Venue; the Venue’s own standards of conduct, rules and regulations; and any legal authority of which the Venue or Participant is subject. Only timely and directly reported violations of the Standards of Conduct with sufficient factual details of the violation to the Conference, upon investigation if warranted, may result in sanctions including, but not limited to expulsion of the offending party/parties without recourse. Sanctions imposed under this paragraph shall be adjudicated and determined in the sole discretion of the Conference. Nothing in this paragraph should be interpreted to interfere or discourage with a Participant’s right to contact the Venue and/or Law Enforcement directly and in such a case, the Conference shall fully cooperate with the Venue and Law Enforcement.

Posted in Uncategorized | Tagged , | 1 Comment

Before you grab that content, think…

Recently, I’ve been asked about copyright matters and fair use. I thought I’d take a few minutes and post here and hopefully, begin posting here on a regular basis!!

Whenever you take an image or somebody else’s content, unless there are provisions that state otherwise, you are infringing on a copyright….period. It some cases, content may be in the public domain or licensed under Creative Commons are some other open licensing scheme. If you copy and incorporate somebody else’s content without permission, you may get a very unwelcome inquiry in the form a cease and desist letter and an outright demand for payment. Here’s some free advice for you – when you get a C&D letter, take the content down – at least temporarily. The person or entity asserting ownership still has the burden of proving ownership. When you receive that letter, assuming you have indeed taken somebody else’s content, the only thing you know for sure is that you don’t own the copyright. Whether the person or entity sending you the letter owns the content is not the issue.

Right now, the phrase you may be thinking of is the Doctrine of Fair Use. The issue is much more complicated as different countries and confederations have their own copyright laws. A good resource for you to review is this link: http://www.rightsdirect.com/content/rd/en/toolbar/copyright_education/International_Copyright_Basics.html

Remember, the country you are domiciled in is likely a signatory to one or more treaties that you are subject to.

Getting back to Fair Use. For purposes here, I’ll limit the discussion to the doctrine in the USA. Legal doctrines are things created over years of case law. Through time, they change. What typically results from cases and their facts are things we refer to as multi-factor tests. These tests are stated in absolute terms. How they shake out in a particular case is by no means absolute because they application of these tests is fact intensive.

Fair Use is an affirmative defense – meaning that you readily admit that you are infringing on somebody else’s copyright, but it is permissible because of Fair Use.

Why have the doctrine in the first place? Perhaps you wish to comment upon and critique something? Perhaps the original work is political and you wish to voice an opposing point of view. Hard to do that without referencing and perhaps copying at least some portion of the original work. Perhaps the nature of your use is educational or news reporting in nature. A good read is this link: http://www.cmsimpact.org/journalism.

In the USA, Fair Use is based on a 4 factor test:

  • The purpose and character of your use
  • The nature of the copyrighted work
  • The amount and substantiality of the portion taken
  • The effect of the use upon the potential market

Absent your specific facts and how courts have held, these 4 factors don’t mean much and don’t help to resolve one way or the other whether it is likely or not that your use of somebody else’s work constitutes Fair Use. The only way you will ever get a definitive answer is to have a case litigated in a US Federal Court. The likelihood of that is almost nil as very few cases are brought to court, much less tried and even lesser, reach a verdict. Most cases we read about come from the Supreme Court as the stakes in those cases are great or the facts represent a novel twist that could add color to how the law should be applied.

What can the monetary damages be in the US? For starters, you can be compelled to pay the other side’s legal fees. Then there, are the other monetary damages such as lost revenue for the right’s holder. Whatever revenue you derived through use of the work will be disgorged. Then of course there are your own legal fees. Not exactly what you bargained for when you grabbed somebody else’s work!!

A few tips for you to consider:

  • When searching for images, use the licensing filter option. Both Google and Bing make it easy to filter on license type. If the images and content are public domain you can use them straight away. Here’s the key to remember, others can take it from you as well. Best for you to be clear that such content is in the public domain. Take note of where you took the content. You never know, some troll may try to represent it as his. If the content is subject to something like Creative Commons, take heed in those requirements. You typically have to disclaim ownership and note that the content is subject to a CC license. Not doing so puts you in violation of CC. Never forget, CC and other licenses are just that – licenses with terms and conditions you have to comply with. They are not public domain.
  • Make sure on your site you have a disclaimer that rights as to content and images from others are held by others. There are numerous examples. Your site and blog should have at least some rudimentary terms of service. Chance are, the place you copied things from does… :-)
  • If there is content you want to use, ask the owner. You may be surprised that they may say yes – under some conditions. The key is to attribute ownership of that work to make it clear A – it’s not your work and B – whose work it is. Being reasonable can go a long way.
  • You may have to consider paying a license fee for use of the work. This is a business decision you will have to make. It’s important to note that the law demands copyright owners take affirmative acts to protect their work. When you get a C&D letter, it’s not due to the rights holder being a jerk. Courts expect rights owners to not sit on their hands.
  • And finally, establish a relationship with a lawyer in your jurisdiction. Don’t try to be your own lawyer – even if you happen to be a lawyer!
Posted in Copyright, Intellectual Property, Law | Tagged , | Leave a comment

A simple jQuery Qunit-based JavaScript Unit Test Project Template

UPDATE: I just updated the template. You can download it here.

Next week, I’m giving a talk on JavaScript Unit Testing at Codestock. I think this is my 5th year. Always a great show and am looking forward to seeing everyone in Knoxville, TN. The talk is going to be divided into 3 parts: 1 – recognizing and implementing testable JavaScript code, 2 – JavaScript Unit Testing fundamentals and 3 – Visual Studio integration. It is the 3rd part that I want to discuss right now. I’ve just uploaded a new JavaScript unit test project template to the Visual Studio Gallery.


There is a need for a simple unit test project that is devoted to JavaScript unit testing. For this template, I chose the jQuery QUnit project. To make full use of the template, you will also need the Chutzpah JavaScript Unit Test Runner installed. Chutzpah integrates your JavaScript Unit tests.

Once the extension is installed, the add-in will be available:

(Yes, I know the project type reads as Visual C#… When I created the template, I decided to start with a class library project – like any other unit test project. I could have hosted this in a Windows Store JavaScript project – but that would have left folks out that have not upgraded to Windows 8 yet. )


To get up and running, I added a simple Hello World QUnit JavaScript unit test. The following example shows the template in action:

Consider the following solution structure:


This solution has 3 projects: ASP.NET MVC, MVC Unit Test and a JavaScript Unit Test Project. To illustrate how to put your web project’s js code under test, I created a myFunctionTests.js file –  which corresponds to the myFunctions.js file in the UnitTesting.Web MVC Project. Here is the code for myFunction.js:

var myFunctions = (function () {
    var _functions = {};

    _functions.add = function (items) {
        var total = 0;
        for (var i in items)
            total += items[i];
        return total;

    return _functions;

A very simple function that takes an array of numbers and adds them together. Here’s the test in the JavaScript Unit Test Project:
(Take note of how to reference the js file that hosts the function under test.)

/// <reference path="../../../unittesting.web/scripts/myfunctions.js" />

test("My Function Add Test", function () {
    var result = myFunctions.add([1, 2, 3]);
    var expected = 6;

    ok(result == expected, "Result: " + result  + ", expected: " + expected);

In addition, there is also a standard unit test project which was added when the MVC project was created. The following figure shows the Visual Studio Test Explorer running all of our tests (in my Test Explorer settings, I’ve opted to organize the tests by project):


If I was to alter the test by changing the expected value to 5 and saved the file, the affected tests will run again. The following figure shows our unit test in a failed state:




Posted in Javascript, jQuery, QUnit, Unit Testing | Tagged , , , | Leave a comment

Pre-Process your images with promises

For this post, I’m using Windows 8 WinJS as the vehicle. However, this approach is applicable by any method that implements an XMLHttpRequest.

Here’s the scenario: you have an application with several images and those images are stored on a remote server. The sources of each image is something like http://someserver.com/myimage.png.

Looking at a Windows 8 store app as an example, the good news is that your page will display immediately. Your images may display immediately. Or more likely, they will begin to display after the page has loaded. You may see the images incrementally appearing. This does not make for a good user experience.

The good news is that WinJS implements the Promise Pattern and XMLHttpRequest via the WinJS.xhr object. This means we can pre-fetch images and resolve them to blob URL’s and then bind our UI to the blob URL instead of the raw image url.

Using a stock WinJS Navigation Project, the following code is placed in the app.addEventListener(“activated”, function (args) {} handler:

var promises = [];

//Load the blob for the default image in the event a specified image URL does not work.
WinJS.xhr({ url: "images/no-available-image.png", responseType: "blob" }).done(function 
(data) {
 var noImageBlob = URL.createObjectURL(data.response);
  //The imageResults.json file is a static result from the Bing Images API.
  WinJS.xhr({ url: "js/imageResults.json" }).done(function (data) {
     var results = JSON.parse(data.responseText);
     //Loop through the results to create the promise array.
     results.d.results[0].Image.forEach(function (element, index, array) {
     promises[index] = WinJS.xhr({ url: element.MediaUrl, responseType: "blob" })
        .then(function (e) {
           //When the promise executes, an imageBlob property is created
           //holding the image blob URL
           results.d.results[0].Image[index].imageBlob = URL.createObjectURL(e.response);
        }, function error(e) {
           //If an error occurs when trying to retrieve the image
           //the No Image BLob URL created on line 28 is used instead
           results.d.results[0].Image[index].imageBlob = noImageBlob;
     //The join method kicks off the promises handed to it.
     //The promises can run in any order and finish at any time. 
     //The done event for the join method fires after all of the promises
     //in the promise array have been fulfilled.
     WinJS.Promise.join(promises).done(function (e) {
        //Need to create a global namespace to hold a reference
        //to the images array. To facilitate data binding, 
        //the WinJS.BindingList method is invoked, passing the 
        //image array.
              Images: new WinJS.Binding.List(results.d.results[0].Image)
           //Now that all of the pre-processing has occurred, we can now
           //navigate to the home page that displays the images.
           if (app.sessionState.history) {
              nav.history = app.sessionState.history;
           args.setPromise(WinJS.UI.processAll().then(function () {
              if (nav.location) {
                 nav.history.current.initialPlaceholder = true;
               return nav.navigate(nav.location, nav.state);
           else {
                return nav.navigate(Application.navigator.home);

JavasScript, being a dynamic language, we can simply augment the object from the parsed JSON. In this example, I used a static file from the Bing Image Search API. You will have to conform the object references to the specific API you are working with. In the previous code, we wait until all of the images have been fetch. In an async world, this can be a challenge. We don’t know what order the requests will be processed. In some cases, a server status 500 could result. This approach affords us an opportunity to handle that error with a place holder image. If on the other hand, you deal with the raw URL’s directly, you have no such opportunity to intercept errors.

On the HTML markup side, I have this code to bind an image tag’s src to the newly created imageBlob property. For this example, the raw URL that is returned in the response is MediaUrl.

<section aria-label="Main content" role="main">
   <div id="ImagesTemplate" data-win-control="WinJS.Binding.Template">
      <div style="width: 150px; height: 100px;">
          <img src="#" style="width: 60px; height: 60px;" 
              data-win-bind="alt: MediaUrl; src: imageBlob" />
       <h4 data-win-bind="innerText: MediaUrl"></h4>
<div id="ImageListView" 
   data-win-options="{itemDataSource : ImageList.Images.dataSource, 
                      itemTemplate: select('#ImagesTemplate')}">

In the markup, I have a WinJS ListView control that uses the ImageList.Images.dataSource as its datasource. The ListView also references a simple template to display the output.

Here is the result (looks a bit skewed due to this page’s dimensions):


When the page displays, because the images have already been pre-fetched, they will immediately display as well. This makes for a more pleasant user experience.

Looking at the first image, it has a raw URL of:


When pre-fetched, the blob URL is:


Posted in Windows 8, WinJS | Tagged | Leave a comment