Tuesday, October 30, 2012

Building Windows 8 Apps with C# and XAML is Here!

“Jeremy builds real apps for real customers. That’s why I can heartily recommend this book. Go out and write some great apps … and keep this book handy.” – from the forward by Jeff Prosise.

WP_000097When my wife stuck her head in the office and said, “Honey, there’s a UPS truck in front of the house” I knew exactly what it was. I ran downstairs and practically kicked down the door to grab my box that contained the initial copies of my latest book, Building Windows Apps with C# and XAML.This is my third full-length book and it is still amazing to see the final result. I pitched the project back in October of 2011 on the heels of the first //BUILD conference. I started with the idea of pushing out a comprehensive reference manual but quickly realized that project would take way too long to deliver in time for the official release of Windows 8. Therefore, I decided instead to focus on the core story necessary to go from an idea to a complete app successfully accepted in the Windows Store. I’m happy I did because I was able to cover all of the key areas in what I believe is an easy to read narrative that gives you everything you need to get started, while connecting to other resources and references to “go deeper” when and where needed.

 

If you’re curious about just what is covered, here is the detailed table of contents:

  1. The New Windows Runtime
    1. Looking Back: Win32 and .NET
    2. Looking Forward: Rise of the NUI
    3. Introducing the Windows Store Application
      1. Windows 8 Design
      2. Fast and Fluid
      3. Snap and Scale
      4. Use of Right Contracts
      5. Great Tiles
      6. Connected and Alive
      7. Embrace Windows 8 Design Principles
    4. Windows 8 Tools of the Trade
      1. Blend for Visual Studio
      2. HTML5 and JavaScript
      3. C++ and XAML
      4. VB/C# and XAML
      5. Behind the Scenes of WinRT
      6. WPF, Silverlight, and the Blue Stack
    5. Summary
  2. Getting Started
    1. Setting Up Your Environment
      1. Windows 8
      2. Visual Studio 2012
      3. Blend
    2. Hello, Windows 8
      1. Creating Your First Windows 8 Application
      2. Templates
    3. The ImageHelper Application
      1. Under the Covers
    4. Summary
  3. Extensible Application Markup Language (XAML)
    1. Declaring the UI
      1. The Visual Tree
      2. Dependency Properties
      3. Attached Properties
      4. Data-Binding
      5. Value Converters
    2. Storyboards
    3. Styles and Resources
    4. Layout
      1. Canvas
      2. Grid
      3. StackPanel
      4. VirtualizingPanel and VirtualizingStackPanel
      5. WrapGrid
      6. VariableSizedWrapGrid
      7. ContentControl
      8. ItemsControl
      9. ScrollViewer
      10. ViewBox
      11. GridView
      12. ListView
      13. FlipView
      14. ListBox
    5. Common Controls
    6. Summary
  4. Windows 8 Applications
    1. Layouts and Views
      1. The Simulator
      2. The Visual State Manager
      3. Semantic Zoom
    2. Handling User Input
      1. Pointer Events
      2. Manipulation Events
      3. Mouse Support
      4. Keyboard Support
      5. Visual Feedback
      6. Targeting
      7. Context Menus
    3. The Application Bar
    4. Icons and Splash Screens
    5. About Page
    6. Sensors
      1. Accelerometer
      2. Compass
      3. Geolocation
      4. Gyrometer
      5. Inclinometer
      6. Light Sensor
      7. Orientation Sensor
    7. Summary
  5. Application Lifecycle
    1. Process Lifetime Management (PLM)
      1. Activation
      2. Suspension
      3. Termination
      4. Resume
      5. Navigation
      6. Application Data API
    2. Connected and Alive
    3. Custom Splash Screen
    4. Summary
  6. Data
    1. Application Settings
    2. Accessing and Saving Data
      1. The Need for Speed and Threading
      2. Understanding async and await
      3. Lambda Expressions
      4. IO Helpers
      5. Embedded Resources
    3. Collections
      1. Language Integrated Query (LINQ)
    4. Web Content
    5. Syndicated Content
    6. Streams, Buffers, and Byte Arrays
    7. Compressing Data
    8. Encrypting and Signing Data
    9. Web Services
      1. OData Support
    10. Summary
  7. Tiles and Toasts
    1. Basic Tiles
    2. Live Tiles
    3. Badges
    4. Secondary Tiles
    5. Toast Notifications
    6. Windows Notification Service
    7. Summary
  8. Giving Your Application Charm
    1. Searching
    2. Sharing
      1. Sourcing Content for Sharing
      2. Receiving Content as a Share Target
    3. Settings
    4. Summary
  9. MVVM and Testing
    1. UI Design Patterns
      1. The Model
      2. The View
      3. The View Model
    2. The Portable Class Library
    3. Why Test?
      1. Testing Eliminates Assumptions
      2. Testing Kills Bugs at the Source
      3. Testing Helps Document Code
      4. Testing Makes Extending and Maintaining Applications Easier
      5. Testing Improves Architecture and Design
      6. Testing Makes Better Developers
      7. Conclusion: Write Those Unit Tests!
    4. Unit Tests
      1. Windows Store Unit Testing Framework
      2. Mocks and Stubs
    5. Summary
  10. Packing and Deploying
    1. The Windows Store
      1. Discovery
      2. Reach
      3. Business Models
      4. Advertising
      5. Preparing Your App for the Store
      6. The Process
      7. The Windows App Certification Kit (WACK)
      8. What to Expect
    2. Side-Loading
    3. Summary

Of course, you can also download and check out the source code from all chapters - it's available free as an open source project at http://Windows8Applications.CodePlex.com.

My publisher did a great job pulling together the content, including the dozens of figures and screenshots I included to illustrate every step of the process. Besides your local book store (and if they don’t have it, be sure to let them know they need to fill a shelf with copies), where can you pick this up? There are several options available and various sites will be running different specials and discounts, so check them out:

Thanks again for all of your support!

Wednesday, October 24, 2012

Windows 8 Hands-On Videos from Engadget Round-Up

With the launch of Windows 8 right around the corner, OEMs are releasing a ton of exciting hardware. In fact, there are so many options for Windows 8 machines that it is causing information overload. I thought I’d help simplify things by pulling together some of the hands-on videos I’ve watched over the past few weeks from one of my favorite technology sources, Engadget. This should help pull together the Windows 8 experience in one place. Here, in alphabetical order, are a slew of videos to help get you started.

Weigh in with comments at the bottom, and if I missed a hands-on you think belongs here, let me know!

Note: if you are not seeing embedded videos, try going to the original site for this article by clicking here.

Acer Iconia W510 and W700

ASUS VivoTab RT

Dell XPS 12 Windows 8 Convertible (Link, no video)

Follow this link to see the hands-on write-up.

Fujitsu Lifebook UH75

Fujitsu Stylistic Q702 and LifeBook T902 Convertibles

Kupa UltraNote Modular Tablet

Lenovo ThinkPad Tablet

Check out the video “The Pursuit.

Microsoft Surface

Panasonic AX series Ultrabook

Samsung Series 5 and Series 7

Samsung Windows RT ATIV

ZTE V98 Windows 8 Slate (Link, no video)

Follow this link to see the hands-on write-up.

Thursday, October 18, 2012

How to Play DVDs on Windows 8 (Even on your tablet that doesn’t have a DVD Player)

I recently picked up a new DVD that I wanted to watch … only I was hoping I could tap into the convenience of my tablet and take it with me. Of course, the tablet doesn’t have the form factor to host a DVD player. Compound that with the problem that Windows 8 doesn’t ship with DVD support, and it could have been a major issue.

Only, it wasn’t.

Getting support to play DVDs on Windows 8 is easy. Just download a copy of VLC media player (click on the text for the link). This is a free, open-source multimedia player that handles almost any protocol you can think of. With the software, it’s easy to pop in a disc and start playing it, and it renders beautifully on my Windows 8 laptop.

But what happens when I want to watch in another room? That’s easy enough. I install a copy on my slate device as well, and then perform a few easy steps.

First, I open the disc.

vlc1

Next, I tick the mark for “No disc menus” and choose the “Stream” option.

vlc2

The first dialog just sources the disc – you can click next to set up the destination. Here, choose HTTP and click the Add button.

vlc3

You can select a port and an optional path … here I’m using the default 8080 port with no path. Remember that you must have the port opened on your firewall (the first time you launch, you should get a dialog prompting you to allow that firewall access).

vlc3a

Under the profile, you can pick the type of stream. I had to experiment on my local network but VP80 + Voris (Webm) seemed to work best for me.

vlc4

I click Next and then on the final screen I simply leave the defaults and click the “Stream” button at the lower right of the dialog. Once it starts streaming, I open VLC on my tablet. I choose the option to open a network stream:

vlc5

I enter the name of my host computer (the one that is playing the DVD) and the port, then click play:

vlc6

Now I have streaming goodness, and can watch the DVD from anywhere in the house using my tablet. I’d show you a screen cap of Spartacus playing but I’m pretty sure that image would be under copyright.

Of course, there are other more advanced options with controls that will be available through media center, XBox and Smartglass, but for now that is a quick and dirty solution that works well for me.

Wednesday, October 17, 2012

The Microsoft Surface and Apple iPad 3 Head to Head

I was in a recent discussion about the Microsoft Surface and how it will be received by the consumer market. Obviously there are a lot of emotional reactions. Everyone is speculating about the price points, comparing features, and wondering if average consumers will even care. I would argue that there is a technical aspect to this that does make sense to discuss and debate … after all, you can compare screen resolutions or count apps in the app store … but then there is a purely marketing aspect that overrides any technical considerations. No, it doesn’t mean the specs don’t matter, but it does mean that you can have poor specs and great marketing and still succeed, and the best specs in the world won’t fix a poor marketing campaign.

All of the discussion and speculation got me wondering, how does this offering compare to the iPad? I can’t offer an objective opinion because I’m not an iPad user. I have a Samsung Series 7 slate that I purchased to write my book, and have been using Windows 8 on it since the Developer Preview. I love it. It does exactly what I want. When I am heads down writing prose or code, I’m on my dual screen monitors with a big external keyboard. When I’m casually browsing emails, participating in social networks, editing or commenting on manuscripts or watching videos, I’ve got my slate in hand. The battery lasts a long time (I enjoy watching movies any time I’m flying from Atlanta to Seattle, and always have plenty of battery left over) and the experience is just nice.

That, however, doesn’t mean it is not lacking or inferior. Of course this is a full version of Windows 8 on a Pentium chip that requires a fan to cool it so it is a lot thicker than an iPad. I have friends with iPads who love it. It’s thin. It’s easy to carry around. It is fast, snappy, and does the trick … so from that perspective, it’s tough for me to say one really “wins” over the other. The people used to the iPad, love it, the ones used to the Windows 8 slate, love it. Having said that, I was a former iPhone user and switched to Windows Phone 7 and had no desire to go back (no, didn’t receive anything from Microsoft for that statement, either, I truly had the choice and ended up turning it over to my daughter because I loved the Windows Phone so much).

OK, enough about speculation, let’s see what we can be objective about. Here’s a technical comparison that I believe accurately reflects the two models. Disclaimer: this is what I’ve gathered to the best of my ability by examining the data available online. I do not warrant the accuracy here and I welcome all feedback and updates. The specs here do not represent any official statement or correspondence from either Microsoft nor Apple. Here’s what I came up with:

 

iPad $499

Surface $499

iPad $599

Surface $599

iPad $699

Surface $699

Storage

16 GB

32 GB

32 GB

32 GB

64 GB

64 GB

Display

2048x1536

1366x768

2048x1536

1366x768

2048x1536

1366x768

Camera

1080p

720p

1080p

720p

1080p

720p

Back Camera

720p

720p

720p

720p

720p

720p

Weight

1.44 lbs

1.5 lbs

1.44 lbs

1.5 lbs

1.44 lbs

1.5 lbs

Thickness

9.4mm

9.4mm

9.4mm

9.4mm

9.4mm

9.4mm

Includes keyboard?

No

No

No

Yes

No

Yes

RAM

1 GB

2 GB

1 GB

2 GB

1 GB

2 GB

CPU

2-core 1 GHz

4-core 1.5 GHz

2-core 1 GHz

4-core 1.5 GHz

2-core 1 GHz

4-core 1.5 GHz

Battery

10 hours

8 hours

10 hours

8 hours

10 hours

8 hours

HD Video out?

Yes

Yes

Yes

Yes

Yes

Yes

USB 2.0?

No

Yes

No

Yes

No

Yes

Ambient light?

Yes

Yes

Yes

Yes

Yes

Yes

Accelerometer?

Yes

Yes

Yes

Yes

Yes

Yes

Gyroscope?

Yes

Yes

Yes

Yes

Yes

Yes

Compass?

Yes

Yes

Yes

Yes

Yes

Yes

Microsoft Office?

No

Yes

No

Yes

No

Yes

Again, I welcome any corrections or updates if I’m off. Let’s take a look line by line:

Storage

This one was interesting to me. The entry level model for Surface actually has twice the storage of it’s counterpart, and other models are on par with the price.

Display and Cameras

Clearly the iPad3 wins in this category. With a super high resolution display it blows the Surface out of the water, and has a higher resolution front camera to boot. I would have to really hold two of these devices side by side to determine how much of a difference that makes – the video really doesn’t concern me, I am perfectly fine with 720p, but the display is something that can make a major difference if you are staring at the tablet all day long.

Weight and Thickness

These appear to be so close that you can’t really declare a winner. Right on par in both aspects.

CPU and RAM

Unless my information is off, it looks like all price points of the Surface are double RAM of the iPad3 (2 GB vs. 1 GB). The CPU is a quad core NVidia T30 that clocks up to 1.5 GHz compared to a dual-core A5x that clocks up to 1.0 GHz but I wouldn’t read that as a win for one over the other – regardless of cores or clock (which changes, by the way, to preserve battery) we’d have to see head-to-head bench marks to determine if the CPUs are really being utilized in a way that makes one truly faster than the other.

Battery

These are all based on claims and not actual data, so it’s tough to say the 2 hour difference is significant. Microsoft may be conservative or they may be off – you’d have to set up an experiment with comparable streaming video, browsing, or other “high cost” activities on both devices to truly compare. It looks like on paper the batteries should be comparable.

Peripheral Support

To me the Surface wins hands-down here. If you don’t care, it’s a moot point, but I like my USB drives and other peripherals and the fact that the Surface has a USB 2.0 port I can plug them right into.

Sensors

The systems appear to have a similar array of sensors.

Microsoft Office

This is to me hands-down the most important comparison. This is not based on my personal bias, but practical experience. My Samsung slate is often mistaken for an iPad on planes just because it’s a tablet and Apple has certainly marketed their product well enough to make it seem that all tablets are iPads. What gets interesting, however, is when I’m editing PowerPoint presentations, book manuscripts in Word, or catching up on Outlook emails on my device. That’s when people lean over and go, “Oh, wow, how did you get Office on there?” When I explain it’s the Windows version on a Windows machine, I consistently get “oohs” and “ahhhs.” Of course, I have mixed feelings about this one. WindowsRT will be limited to Windows Store apps, which include Office, so that’s good … but the next thing I typically say, which is “Yeah, I can run ALL of my Windows 7 software on this” simply won’t hold true for Surface until the Pro version comes out later next year.

First Windows 8 ad:

First Surface ad:

So what’s the bottom line?

I think this appears to be a very innovative product that I’m excited to try out. I just may get one for my wife or daughter and see how they enjoy it and whether or not they feel limited by the available apps. Whether we decide it’s awesome and far better than the iPad3 doesn’t really matter, however. Sure, it makes a difference, but what will determine overall success is how well Microsoft markets the product … and that’s still up in the air, although the hype is now beginning for both Windows 8 and Surface.

What do you think about the recent announcements? What are your thoughts on features, specifications, and price points? How about all of the other manufacturers releasing their line of Windows 8 products … is any particular model standing out as a clear leader in innovation, design, and, yes, I’ll say it, ability to kick iPad’s ass?

Comment below.

Wednesday, October 10, 2012

Windows Runtime Components in a .NET World

The new type of program known as a Windows Store app—optimized to run on Windows 8 devices—has a default view with a full-screen window and no distracting chrome, so the content is the focal point. Windows Store apps support fluid layouts that adapt and scale to a variety of screen sizes and resolutions. They provide a touch-first experience while providing full support for the traditional keyboard and mouse.

MSDN recently released a special Windows 8 issue that covers Windows Store apps. It includes an article I contributed about creating managed Windows Runtime (WinRT) components that can be consumed by Windows Store apps written using any of the available language options, including C++ and HTML/JavaScript. Learn about the requirements needed to create a Windows Runtime Component in C#, how to reference and use it, and how it impacts other language selections when developing Windows Store apps.

The article includes a full example for creating a special component that generates thumbnails and is consumed by C#, C++, and a HTML/JavaScript application as well. The team at Microsoft also provided a VB version.

Read the full article online at Windows Runtime Components in a .NET World.

Jeremy Likness

Saturday, October 6, 2012

A Tiny Portable Inversion of Control Container for Multiple Windows Platforms

As part of the cross-platform example in my book, I built a tiny IOC container mainly to avoid having to reference and explain MEF, Unity, or any of the other choices. This is not a full-fledged container with tons of services like injection. It is simply an easy way to create things that depend on other things and manage their lifetime.

The "portable" part is evident in the targets. You can reference the exact same DLL from any Windows Phone, .NET Framework 4.x, Windows Store (Windows 8), or Silverlight 4+ project to use the container. That's it - completely portable, no recompiling necessary, and you now get to keep the same API on your view models when you're wiring dependencies (yes, I'm looking at providing a simple portable MVVM implementation too, but a portable Sterling will probably be my next focus since I get so many requests for it on Windows 8).

If you are dubious about what is possible across platforms, download the Chapter 9 source code from Windows8Applications.CodePlex.com (it's free, regardless of whether or not you get the book) and look at the Wintellog example. This is a full blown RSS feed reader implemented for both WPF and Windows Store (Windows 8) that uses most of the same code (even part of the networking stack). It includes a very basic version of the container that I used in the book.

The container is less than 200 lines of code. Many of the lines are there for design-by-contract checks and some thread-safety mechanisms to ensure unregistering and resolving from separate threads doesn't clobber the container.

It has a few features:

  • Uses a simple lambda expression to describe how to create implementations for types
  • Passes itself to the instance delegates so they can recursively resolve other references
  • Provides labels so you can segregate different definitions (or consider everything under a "label" as a different "container"
  • Allows you to unregister a definition (and register it as something different, though I can't imagine why you'd do that)
  • Allows you receive a shared or a non-shared instance (lifetime management
  • Allows you to destroy the shared instance and generate a new one
  • Provides a TryResolve to test and resolve in one operation

The use of it is fairly straightforward and can be inferred from the tests:

[TestInitialize]
public void TestInitialize()
{
    _target = new PortableIoc();
}

Register and resolve:

[TestMethod]
public void GivenTypeRegisteredWhenRequestedThenShouldReturnInstance()
{
    var expected = new SimpleBar();
    _target.Register<IBar>(ioc => expected);
    var actual = _target.Resolve<IBar>();
    Assert.AreSame(expected, actual, "Test failed: same instance was not returned.");
}

Test that you can resolve it:

[TestMethod]
public void GivenTypeRegisteredWhenCanResolveCalledThenShouldReturnTrue()
{
    _target.Register<IBar>(ioc => new SimpleBar());
    Assert.IsTrue(_target.CanResolve<IBar>(),
                    "Test failed: can resolve should return true when the type is registered.");
}

Try to resolve it:

[TestMethod]
public void GivenTypeIsNotRegisteredWhenTryResolveCalledThenShouldReturnFalse()
{
    IBar barInstance;
    var result = _target.TryResolve(out barInstance);
    Assert.IsNull(barInstance, "Test failed: bar instance should be null when type is not registered");
    Assert.IsFalse(result, "Test failed: result should be false when type is not registered.");
}

Generate a non-shared instance:

[TestMethod]
public void GivenTypeIsRegisteredWhenNewInstanceIsRequestedThenShouldReturnNewInstance()
{
    _target.Register<IBar>(ioc => new SimpleBar());
    var actual1 = _target.Resolve<IBar>();
    var actual2 = _target.Resolve<IBar>(true);
    Assert.AreNotSame(actual1, actual2, "Test failed: create new should not return the same shared instance.");
}

Use constructor injection:

target.Register<IBar>(ioc => new SimpleBar());            
_target.Register<IFoo>(ioc => new SimpleFoo(ioc.Resolve<IBar>()));

Or property injection:

target.Register<IBar>(ioc => new SimpleBar());            
_target.Register<IFoo>(ioc => new SimpleFoo { Bar = ioc.Resolve<IBar>() });

That's about it - you can grab the source and/or binary (sorry, no NuGet package yet) over at PortableIoC.CodePlex.com. Now let's get some work done on Sterling ...

Jeremy Likness

Tuesday, October 2, 2012

Building Backbone Applications with TypeScript

Hot off the press, TypeScript was announced earlier this week and has resulted in an explosion of commentary over Twitter and various blogs. The language claims to be tailored for application-scale development using JavaScript by providing a typed superset. It compiles to JavaScript so it will work in any browser. The promise is to make it easier to organize and structure code, as well as get rid of those annoying errors that leave users hunting through hundreds of lines of code seeking out an errant comma or issue with case sensitivity.

Ironically, I was speaking with an attendee at our Devscovery conference about the future of JavaScript right before TypeScript was announced. It’s obvious that JavaScript is here to stay, and it’s not going to get any better. It may get better parts, but backwards compatibility is going to force the bad parts to remain for a long time. What’s worse, there is nothing that convinces me browser vendors will play nice with the specifications when we’ve had a standard for almost 20 years and it is still implemented differently in different browsers. My take having come from a heavy JavaScript background before I was spoiled for several years by the ease of writing solid Silverlight business applications is that if we have to deal with it, we need to tackle it on three fronts:

  1. Education: JavaScript is a dynamic language where functions, not classes, rule. Developers need to stop trying to play object-oriented developer in the client space and learn how to play by the client rules.
  2. Moderation: Having said that, there are features that simply make it far too easy to shoot yourself in the foot. While there are decent solutions to address this like running JSHint/JSLint, I personally welcome an approach to catch issues at compile (or even better, development) time and keep us all honest. Bugs are easier to fix the closer to the source and the earlier in the process you are. One of the things I mentioned was that something like CoffeeScript should be implemented that helps protect us from the bad parts as we develop, but still generates to that friendly backwards-compatible JavaScript all of the browsers love.
  3. Better Glue. Yes, I said it. Silverlight developers know what I’m talking about *cough* RIA Services *cough* … now that we have very standard ways of exposing APIs, there should be easier ways to glue the client to the server so that developers are working on “what’s different” and not spending 75% of their time building controller methods and writing AJAX calls on the client.

I believe TypeScript is a tool that preserves the first item (it honors JavaScript and doesn’t try to hide the dynamic and flexible nature) and addresses the second item (it allows us to declare intent far more clearly and then have feedback right away) and probably does nothing for the last item.

Instead of debating whether or not we need another language or if it is good or bad (and hey, I love C#, and I loved TurboPascal, so the fact that it was developed by Anders Hejlsberg doesn’t hurt) I would rather jump into using it so I can start to get a feel for how it helps or hurts. Tomorrow I’ll be speaking for three hours on this specific topic (how to leverage libraries in JavaScript development to help scale for large projects and with large teams) so I decided to grab an example I created with Backbone.JS to see what it would take to port over. Here we go!

Step one was simply implementing the VS 2012 plug-in. I’m sure I failed miserably at this. I get syntax highlighting but no template to add a new TypeScript file, no automatic compilation and no effective IntelliSense. I’m sure it’s operator error so stay tuned. You can grab whatever you need (or I should say, “Whatever is available”) from the TypeScript downloads link. Next, I added a JavaScript file and renamed it to have a .ts extension and added a post-build script to compile it:

tsc $(ProjectDir)/Scripts/app.ts

Next, I grabbed the language specification and went to work. First, I found I had to declare some variables to allow for external modules:

declare var $: any;
declare var _: any;

That was easy! Using Backbone however was a little more complicated. I cheated by taking a look at the existing TodoMVC sample from the TypeScript site. To allow Backbone to play nicely with TypeScript, I have to define a module and export classes that describe the API. It doesn’t have to be the full API, but can focus on the pieces I’ll be using. Here’s an example of exporting the Backbone Model object as a class:

declare module Backbone {   
   
    export class Model {
        constructor (attr? , opts? );
        get(name: string): any;
        set(name: string, val: any): void;
        set(obj: any): void;
        save(attr? , opts? ): void;
        destroy(): void;
        bind(ev: string, f: Function, ctx?: any): void;
        toJSON(): any;
    }
}

Notice that I have optional parameters in the constructor. I can declare intention by providing a type for named parameters and the return type of the function. Pretty cool. I like to use Backbone.Events as well, and TypeScript allows me to define interfaces. Here is the interface for events specifying the signature for “on” and “off” (register and unregister):

interface HasEvents {
    on: (event: string, callback: (parms?: any, moreParms?: any) => any) => any;
    off: (event: string) => any;
}

The easiest way to read this in my opinion is right to left. A function that returns any type takes the parameters of, well, in the case of the first one, a function that has two optional parameters and returns any type, and the first parameter is a string. I also made an interface for the simple version of a contact to make it clear when I am expecting an instance of this:

interface ContactInterface {
    id?: number;
    firstName: string;
    lastName: string;
    email: string;
    address: string;
    city: string;
    state: string;           
};

You can also declare static properties on classes, so I created a template class just to hold the compiled templates I am using:

class Templates {
    static contact: (json: any) => string;
    static editContact: (json: any) => string;
    static contacts: (json: any) => string;
};

Note that the compiled template takes any type of object and returns a string. Finally, I created a global object to host cross-cutting events in lieu of using a pub/sub library like Postal. Note the implementation of the HasEvents interface.

class AppEvents implements HasEvents
{
    on: (event: string, callback: (model: Contact, error: any) => any) => any;
    off: (event: string) => any; 
    trigger: (event: string, data: any) => any; 
};

Finally, you get to see some plain JavaScript – I create the object and extend it to have events:

var appEvents = new AppEvents();
_.extend(appEvents, Backbone.Events);


So now let’s tackle how we did it the “old way” vs. “the new way.” Here is the old way I defined my contact model:

App.Models.Contact = Backbone.Model.extend({
    initialize: function () {
        console.log("Contact init.");
    },   
    defaults: function () {
        return {
            id: null,
            firstName: '',
            lastName: '',
            email: '',
            address: '',
            city: '',
            state: ''
        };
    },   
    validate: function (attrs) {
        if (_.isEmpty(attrs.firstName)) {
            return "First name is required.";
        }
        if (_.isEmpty(attrs.lastName)) {
            return "Last name is required.";
        }
        if (_.isEmpty(attrs.email)) {
            return "Email is required.";
        }
        if (attrs.email.indexOf("@") < 1 ||
        attrs.email.indexOf(".") < 1) {
            return "The email address appears to be invalid.";
        }
        return "";
    }
});


Basically I’m logging something to the console, providing a template for a contact instance, and declaring my validations. Notice that there is no way to guarantee what I return from the function (I could just as easily send back { foo: “bar” }) and that the attributes for the validation could be anything as well. With TypeScript, I can be more specific and even generate development-time (and compile-time) errors if I’m not doing what I expect:

class Contact extends Backbone.Model implements HasEvents {
    on: (event: string, callback: (model: Contact, error: any) => any) => any;
   
off: (event: string) => any;   
    isValid: () => bool;   
    initialize() {
        console.log("Contact init.");
    };
    defaults() : ContactInterface {
       return {
            id: null,
            firstName: '',
            lastName: '',
            email: '',
            address: '',
            city: '',
            state: ''
        };
    };
    validate(attrs: ContactInterface) {      
       if (_.isEmpty(attrs.firstName)) {
            return "First name is required.";
       }      
       if (_.isEmpty(attrs.lastName)) {
            return "Last name is required.";
       }      
       if (_.isEmpty(attrs.email)) {
            return "Email is required.";
       }      
       if (attrs.email.indexOf("@") < 1 ||
        attrs.email.indexOf(".") < 1) {
            return "The email address appears to be invalid.";
       }      
       return "";
    }
};

Notice that I implement the events in a more specific way, providing a detailed signature for the callback. Functions are simply declared similar to how they are defined on C# classes and I don’t have to worry about exposing the property name. Finally, I can type the return value and the parameters for the various functions. Pretty cool, no? I’m still using JavaScript and the object can still be dynamic, but I can at least constrain it to the specific interface I’m going to use within my method.

Here’s the old definition for the collection, passing in the options to configure it to point to the REST API on my server:

App.Collections.Contacts = Backbone.Collection.extend({
    model: App.Models.Contact,
    url: "/api/Contacts",
    initialize: function () {
        console.log("Contacts init.");
    }
});


Here’s the new definition that derives from the base class and uses a constructor instead. I also make it very clear I’m using events on the collection as well, which isn’t evident in the original JavaScript.

class Contacts extends Backbone.Collection implements HasEvents {   
    on: (event: string, callback: (parms?: any, moreParms?: any) => any) => any;   
    off: (event: string) => any;
    url: string;  
    model: Contact;       
    initialize() {
        console.log("Contacts init.");
    }
    constructor(options?: any) {
        this.url = "/api/Contacts";   
        super(options);       
    };
};

Another cool feature is that I can declare types and then cast calls that aren’t apparent to a type. For example, I haven’t informed TypeScript that jQuery can return a DOM element, but on my declaration for views I do use the HTMLElement type. To reconcile this, I can simply cast the result like this:

this.el = <HTMLElement>$("#contact");          

I know, it looks like an HTML tag but that is because it’s not a true cast, only a tip that this is the return type we expect. After several more models and views, I define an overall application object that spins up the initial collection in the constructor. Note how I also set the static template properties – very straightforward syntax. Creating the object kicks off the application:

class Application {
       
    public static editContactView: EditContactView;

    constructor() {
        Templates.contact = _.template($("#contactTemplate").html());
        Templates.editContact = _.template($("#editContactTemplate").html());
        Templates.contacts = _.template($("#contactsTemplate").html());
        var contacts = new Contacts();
        contacts.fetch();
        var contactsView = new ContactList({
            collection: contacts
        });       
        contactsView.render();
    };
};

// host container
var App = new Application();

The application demonstrates CRUD with a list that populates a form with validation where the user can edit, delete, and add new contacts.

backbonetypescriptexample

The build process compiles the TypeScript to a JavaScript file that is actually referenced from the MVC view. You won’t see interfaces or definitions because those help enforce things at development and compile time. What does the output look like? Here’s the compiled application-wide event object I created:

var AppEvents = (function () {
    function AppEvents() { }
    return AppEvents;
})();
; ;
var appEvents = new AppEvents();
_.extend(appEvents, Backbone.Events);

Here is the contact model definition – note how the Backbone Model is passed in for extension:

var Contact = (function (_super) {
    __extends(Contact, _super);
    function Contact() {
        _super.apply(this, arguments);

    }
    Contact.prototype.initialize = function () {
        console.log("Contact init.");
    };
    Contact.prototype.defaults = function () {
        return {
            id: null,
            firstName: '',
            lastName: '',
            email: '',
            address: '',
            city: '',
            state: ''
        };
    };
    Contact.prototype.validate = function (attrs) {
        if(_.isEmpty(attrs.firstName)) {
            return "First name is required.";
        }
        if(_.isEmpty(attrs.lastName)) {
            return "Last name is required.";
        }
        if(_.isEmpty(attrs.email)) {
            return "Email is required.";
        }
        if(attrs.email.indexOf("@") < 1 || attrs.email.indexOf(".") < 1) {
            return "The email address appears to be invalid.";
        }
        return "";
    };
    return Contact;
})(Backbone.Model);

Jeremy, where’s the full download? Sorry, right now the project is reserved for attendees at Devscovery – I may have a full project to make available after this week, but for now you can take a look at the full TypeScript source (this is the entire client application) by clicking here.

Thanks! What do I think? So far my thoughts are very positive. I see this being a useful tool that enables teams to write the code they are used to, with options to add safeguards and types where necessary to avoid errors and make the code easier to organize, read, and comprehend. I’ll have to use it some more but this short project of converting an application over has me raising both thumbs up.