Creating an Observable Object in Windows 8 JavaScript

Living in the JavaScript world for a while will help you to appreciate the offerings of C# for sure. Many concepts like classes, inheritance, observable collections, list extensions (LINQ) are simply absent and so a creative alternative has been created either in WinJS or just in recommended practice.

One of these is in the area of data binding.

First of all, I recommend Stephen Walther’s excellent article on Metro: Declarative Data Binding. He’s much more thorough than I intend to be here. I only want to relay my experience with following the instructions on dev.windows.com – specifically the article entitled How to bind a complex object, and following the sample project entitled Programmatic binding sample. If you want to learn a lot more about Windows 8 development using HTML and JavaScript, you can check out Stephen’s book Windows 8.1 Apps with HTML5 and JavaScript.

Here are the steps I took to get a very simple object to bind well.

  • Write a simple class
  • Add an _initObservable method
  • Mix it
  • Instantiate it
  • Bind the properties
  • Change a property to test

That’s it. I’ll elaborate a bit on each point.

Write a simple class

Here’s the rocket science class I wrote. It has a single property – name.

var Widget = WinJS.Class.define(
function (name) {
this.name = name;
}
);

Add an _initObservable method

var Widget = WinJS.Class.define(
function (name) {
this._initObservable();
this.name = name;
}
);

This is necessary so that “the observablility implementation is completed properly”.

Mix it

WinJS.Class.mix(Widget,
WinJS.Binding.mixin,
WinJS.Binding.expandProperties(Widget)
);

This adds the necessary bindability to your custom class. If you only want a select few of your properties, you can specify a subset of properties in the parameter for the expandProperties method call. See the Programmatic binding sample to see what I mean.

Instantiate it

Now you’re ready to instantiate your object.

var widget = new Widget("Widget1");

Bind the properties

What you’re doing in the binding is specifying a function that you want to run whenever a property is changed.

widget.bind("name", function (newValue, oldValue) {
var foo = document.querySelector("#foo");
foo.innerText = newValue;
});

Change a property to test

Now, somewhere in your code, change value of that property like this…

widget.setProperty("name", "Hi, Mom!");

And there you have it. The simplest possible example I could come up with for data binding a complex object by turning it into the JavaScript version of an observable object.

Happy binding!

Design Before You Develop

It has never been a good idea to jump right into development without putting time into the design of your project. It’s tempting to attribute your progress to the time when you’re actually typing the code into the computer, but application design like never before is more than fluff. It scopes and directs your efforts and saves you from real hours spent on divergent, throw-away work.

This is still true in Windows 8 development, but a lot of work has already been done to support application developers in creating Metro style applications. There’s a lot of design philosophy in the platform. The effort of which is to create an application ecosystem that has some consistency and thus some predictability and thus user joy.

Here’s a video I recorded that will walk you through the design philosophy – the 8 traits of Metro style design. Enjoy. Happy designing.

Design Before You Develop.wmv

Save New Projects When Created

Do you occasionally write a one-off project in Visual Studio that you know is not going to go anywhere?

I used to have a console application that I called Sandbox that I had a shortcut to. I could open it, write some code, and then close without caring what it’s state was when it closed. The bummer was when I opened it, sometimes I had to do a little cleanup to get it ready for fresh code. It wasn’t ideal and I abandoned the practice a long time ago.

There’s a better way though. It seems there always is.

If you go to Tools | Options | Projects and Solutions in Visual Studio…

…and uncheck the Save new projects when created, Visual Studio makes the above scenario very nice.

The New Project dialog quits asking for a file path. What it actually does behind the scenes is create the project in your temporary files. Only when you try to close or save the project does it actually decide you need to specify a name and path for the project. The dialog actually gives you the option to either Save your project or Discard it.

Discarding eliminates it without a trace and leaves you about your merry way. I like this feature a lot.

Snippets Overview in VS11 and ReSharper

Following is an overview of getting started with Snippets. This will be the overview from 30,000 feet. If you want to get into the nitty gritty how-to then follow my links. As with all of my posts these days, this one will reference VS11 which is still in beta. Most of the concepts are the same for VS2010.

I would like to convince you that climbing the snippet learning curve is worth it because the view from the top is spectacular. In order to be convinced, you’re going to have to believe that you’ll save time. Here’s a brief comparison to help you believe…

<table border="0" cellpadding="2" cellspacing="0" style="width: 561px;">
<colgroup>
<col style="width: 300px;" />
<col style="width: 100px;" />
<col style="width: 100px;" />
</colgroup>
<thead>
<tr style="font-weight: bold;">
<td valign="bottom">Operation</td>
<td valign="bottom">Keystrokes (Typing)</td>
<td valign="bottom">Keystrokes (Template)</td>
</tr>
</thead>
<tbody>
<tr>
<td valign="top">Create a new hyperlink (HTML)</td>
<td valign="top">15</td>
<td valign="top">6</td>
</tr>
<tr>
<td valign="top">Create a simple one cell table (HTML)</td>
<td valign="top">40</td>
<td valign="top">5</td>
</tr>
<tr>
<td valign="top">Empty using statement (C#)</td>
<td valign="top">13</td>
<td valign="top">2</td>
</tr>
<tr>
<td valign="top">Try catch block</td>
<td valign="top">30</td>
<td valign="top">4</td>
</tr>
</tbody>
</table>

I’m not exactly sure why Snippets in Visual Studio are so daunting for so many, but they are. I personally put off using them for a long time because creating and using them wasn’t just a “bam bam done” deal.

First, there’s the fact that the snippets are XML files, so you have to figure out the schema and what elements are expected. Then there’s the idea that Snippets are particular to languages. Then they need to be saved into a certain folder (C:\Users\\Documents\Visual Studio 11\Code Snippets\Visual C#\My Code Snippets).

But once I took a few minutes to dig in and see how they work, I realized that they’re not difficult, and although the learning curve is steep, it’s also short and I think the power and configurability of Snippets necessitates it.

Let’s start off with some facts:

  • Snippets are a way of saving typing and thus time (they also encourage more consistent code)
  • Visual Studio offers Snippets
  • ReSharper offers Live Templates which use a completely different technology to solve the same exact problem
  • If ReSharper is installed and configured for IntelliSense then you can use both VS Snippets and R# Live Templates… this is my recommended configuration *
  • Snippet Designer is a free plug-in for Visual Studio that helps you write Snippets
  • Snippet Designer does not yet work in VS11 Beta

  • in HTML/XML files, VS automatically creates closing tags for opening tags that you type. You can turn this off by going to Tools | Options | Text Editor | HTML | Formatting | Auto insert close tag.

Visual Studio – Snippets

Snippet functionality in VS is robust for certain. If it lacks anything, it’s ease of use and even that’s subjective. The process is to create a code snippet file – that is an XML file with a .snippet extension, drop it in the My Code Snippets folder, and then go to town with it. I obviously skipped over some details though, so just look at the _Walkthro__ugh – Creating a Code Snippet _link below for more.

Snippet Designer

I would say that if you want to or have to (because maybe your employer is cheap and doesn’t want to spring for R# licenses) stick with native snippets, you should at least go get the Snippet Designer. It’s free, so if your employer doesn’t have a group policy against installing free tools, then go get it from the link below, and if they do then consider a new employer or send them my way and I’ll give them some financial justification with my 100 level economics that they won’t be able to argue against.

Snippet Designer is a free plug-in for Visual Studio that makes it easier to create and modify your code snippets. One of the best features is the ability to just highlight a block of code you’ve already written by conventional means, right click it, and choose to turn it into a snippet.

You can create or edit a snippet in Snippet Designer by either opening a .snippet file or by choosing New File in Visual Studio. It uses a custom editor in VS so you can stay in the same environment. Behind the scenes, Snippet Designer is just editing the snippet XML.

The bummer is that Snippet Designer doesn’t work in VS11 yet. Sheesh, you’d think we’re still in beta or something!

ReSharper – Live Templates

R# extends and enhances the Snippets in VS. If you allow R# to handle your IntelliSense (recommended), then you get the best of bot world – VS snippets and R# templates.

The two biggest advantages to R# templates over VS snippets are:

  • the “macros” you can attach to place holders in templates and
  • the ease with which you can save your templates in the solution (for you only), in the solution (for everyone that uses the solution), or on your computer (to be used across multiple solutions)

For in-depth help with templates see ReSharper Templates in ReSharper’s online documentation.

Resources

Walkthrough- Creating a Code Snippet.aspx “Walkthrough- Creating a Code Snippet”)

Visual C# Code Snippets.aspx)

Best Practices for Using Code Snippets.aspx)

Code Snippets Schema Reference.aspx)

Snippet Designer

ReSharper Templates

Visual Studio 11 Ninja Skills

This post is taken from a local presentation I did on April 2, or rather my presentation was taken from this post. One or the other is true, and so is the other.

As developers, we all aspire to be proverbial ninjas and we all love our tooling. If you don’t fit in those categories, then ask yourself whether you’re a developer or just on your way to project management.

This post and presentation are going to be highly distilled [I’m a big whisky fan]. In the distillation process, a mixture containing alcohol is heated until the pure alcohol turns to gas, rises, and is captured. I consider technology distillation a huge part of my job, so let’s boil out the pure essence and capture it. In fact, I’ll use the word essence or essential quite a lot.

I’ll walk you first through some essential Windows keyboard shortcuts that no power user in my opinion can live without. Then I’ll take you on a highlighted walk through Visual Studio 11 (Beta) – again, just the essence. And finally, I’ll do the same thing with ReSharper 7 (EAP) from JetBrains.

Essential Windows Shortcuts

First, I’m going to share with you some essential Windows shortcuts. These are the ones that I think you must have in your pocket. Even if you’re a Visual Studio rock star, if you don’t have these Windows shortcuts, you’re inhibited.

[WIN + SHIFT + LEFT/RIGHT] Move current window to an alternate monitor

[WIN + LEFT/RIGHT] Move current window to left/right half of the current screen

[WIN + 0-9] Launch the corresponding application from your task bar or switch to or flip through instances of the application

[WIN + SHIFT + 0-9] Launch a new instance of the corresponding application

[WIN + ALT + 0-9] Reveal the context menu and jump list for the corresponding application

[MIDDLE MOUSE (WHEEL) CLICK] Close a tab or launch a hyperlink in new tab. The tab close functionality becomes very handy and is supported in most tabbed applications.

[WIN + C] (Windows 8) Opens the Charms bar on the right allowing you to search, share, etc. There are many Windows 8 shortcuts for doing each of the functions in the Charms bar, but if you remember this one shortcut you can access most all of them.

See – essence – you don’t need to be overwhelmed with shortcut keys. You only need a few and you should have some pretty good window management skills. You can launch Visual Studio or launch a second instance of Visual Studio or launch the jump list for your Windows Explorer application so you can choose your development folder with all your projects. Okay, let’s move on.

Practice the keyboard shortcuts in this post. Actually practice them. You’re naturally blind to your own areas of poor keyboarding skills and productivity. Practice will reveal and improve them and save you time and real money.

There’s a lot of information about this already out on the web, so I’ll just offer highlights and some consolidation via links. Here are the biggest and most relevant features IMHO:

Some of those links to go training courses on MSDN… not documentation… training courses. In my experience, it’s easy to read documentation, but you take home a lot more of the information if you take the time to walk through a tutorial or a lab or a training course.

You can find more VS11 training courses here.

Visual Studio Navigation

[CTRL + ALT + L] Open the Solution Explorer – face it, you need to get to that Solution Explorer rather often. Do it with a keystroke instead of a click.

[CTRL + ,] Navigate To… – the grand daddy of all keyboard shortcuts in VS if I can be so bold. Looking for something in your solution? You’ll likely find it here. Navigate to searches for all code symbols and file names and it uses a “contains” string search pattern and camel case. So CTRL + , and then “WL” will find you the WriteLine method you were looking for as well as the WLFoo.cs file.

[CTRL + ;] Search Solution Explorer – filters the files and symbols that appear in Solution explorer by your query. It should be called Filter Solution Explorer because it doesn’t take you off to some search results. It just hides everything from SE that doesn’t match your query.

[CTRL + Q] Quick Launch – if you’re looking for a command that you know is somewhere in the vast see of commands in the Tools | Options dialog, try CTRL + Q. Try “line numbers” for example.

[CTRL + F] Find – this one grew up from the incremental search that jumped you directly to the next query result on your current page. Now it’s all grown up and can do just about everything that the Find in Files dialog does. The only exception is that CTRL + F always just highlights and navigates you to your results, whereas (see next shortcut)…

[CTRL + SHIFT + F] Find in Files – …as I was saying. Whereas Find in Files actually gives you your results in the Find Results pane.

[CTRL + SHIFT + UP/DOWN] Find more instances in file – another winner in my book. This is an easy one to type. Use it when your mind says, “I wonder where else on the page I used this variable.” I like that it not only finds the other symbols for you, but it highlights them as well.

[F8 / SHIFT + F8] Find next search result, error, reference, etc. – it’s slow to mouse down to the find results or to your build errors and double click on each one. Instead just hit F8 and blaze through them. Use F8 to back up when you miss your exit (don’t try this on the interstate).

[CTRL + - / CTRL + SHIFT + -] Navigate back and forward – “Where was that code? I was just looking at it.”

Editing

[SHIFT + ALT + ENTER] Full screen – don’t forget this one. Now you can set up all of the supporting windows you want in VS, and when you want them all to go away so you can concentrate on your code, BAM!

[SHIFT + ALT + ARROWS] Block editing – this one never fails to surprise a few near-ninjas. I think it’s because they say, “Oh yeah, I know what block highlighting is, “ and they miss the latest greatest part. Not only can you hold ALT and select a block of text (to delete it for instance), but try this. Try just putting your cursor at the beginning of a line, holding SHIFT and ALT, and then pressing the down arrow a few times. Your cursor extends down. Now type. You can type on all of the lines at once. This works in the middle of a block of code too. You can paste something into there from the clipboard too.

[CTRL + SHIFT + V] Paste from clipboard ring – copy something, copy something else, copy something else. In most of Windows, your first and second somethings are gone – replaced by the last thing you copied right? Not so in VS. Now hit CTRL + SHIFT + V three times and you’ll see how this one works.

[CTRL + SHIFT + L] Delete current line – I have seen developers use all kinds of antics to delete an entire line. Most are quite a waste of precious seconds and some are downright silly. CTRL + SHIFT + L does it in a snap regardless of where on the line(s) your cursor happens to be. See the next shortcut for a follow on.

[SHIFT + DEL] Cut current line – this one is like the former except it’s FAR easier to reach on the keyboard and it puts the deleted line(s) on the clipboard. I changed this shortcut to do the same as CTRL + SHIFT + L.

ReSharper (aka R#)

The Uber Essential

[CTRL + SHIFT + R] Refactor this – this one is used for all kinds of stuff. You can extract a method, inline variables, or convert a method to a property. Spend some time placing your cursor on methods, properties, classes, etc. and hit this shortcut to bring up a list of all of the possible ways to refactor it.

[ALT + ENTER] Quick Fix – when R# has highlighted something either with a squiggly underline or by some other means and you have placed your cursor on it, hitting ALT + ENTER brings up the quick fix menu which is the recommended way to resolve the issue. Choosing the recommendation obviously puts it into effect.

[ALT + ` ] Navigate To – this is R#’s version of Navigate To (unlike VS’s CTRL + ,) This one navigates to symbols related to one one you’re on. If you’re on a class and hit this, you will have the option to navigate to its base type or derived types for instance. Most or all of the options in the list have a shortcut of their own, but if you can remember this one shortcut for navigating then you can get to any of them.

The Merely Essential

[ALT + PGUP/PGDN] Go to previous / next highlight - when R# suggests things, it draws a colored marker in the small bar that is rendered just right of your scroll bar. Each of these is a highlight. You can configure what sorts of things appear here and what their severity is. This shortcut jumps from one to the next or previous. Using ALT + PGDN and ALT + ENTER is a really fast way to go through all of the issues in your page and correct or ignore them.

[CTRL + SHIFT + ENTER] Complete Statement (aka Smart Enter) – this one is useful when you know you’re done with your line of code, but you haven’t yet typed all of the smiles and mustaches or the closing semicolon. It enters all of these for you and returns to the next line.

[CTRL + R, R] Rename – this one is available under the CTRL + SHIFT + R menu as well. It’s similar to Visual Studio’s built in ability to smart rename, but it goes a bit further and it’s really good at suggesting symbol names. It’s even able to find references to the symbol you’re renaming in code comments and ask you if you want them to be changes as well.

[ALT + INS] Insert code – depending on your context this shortcut inserts code for you. If you’re in a class and you hit it for instance, one of the options will be to insert a constructor for that class. The dialog boxes that pop up are full of great options, but you can also blaze by them to elect for default functionality.

[CTRL + T, CTRL + SHIFT + T, SHIFT + ALT + T] Go to Type, File, Symbol – I mention it here because it has it’s place, but I like VS’s built in [CTRL + ,] better than these. It’s hard to remember whether what I’m looking for is a filename or a symbol and hard to remember which shortcut to use. The pause to remember is too much for me and I usually go for the comma.

[SHIFT + ALT + L] Locate in Solution Explorer – this is a wonderful shortcut that accompanies [CTRL + ALT + L] which is the VS native shortcut to focus on your Solution Explorer. This one locates the current file in the Solution Explorer though. There is an option to always have the Solution Explorer track which file you’re on, but this is disorienting to me and I’d rather just jump to it when I want it. I use this one all the time.

[ALT + DOWN/UP] Go to next/previous member – great for when you’re just getting the lay of the land, this one allows you to jump one method at a time sort of like how the CTRL key jumps by one word at a time. It’s faster than reaching for the scroll wheel in most cases.

[ALT + HOME / END] Go to Base / Derived Types – use this to traverse the inheritance tree in both directions. If you’re headed down the tree and there are multiple derived types then a quick menu pops up and lets you pick which one you’re interested in. This is very fast and helpful.

[SHIFT + ALT + F12] Go to Usage – this appears to duplicate the functionality of the VS native SHIFT + F12 command which finds references, but there are some strong differences. First, it’s finding usages instead of references which plays great with TDD (Test Driven Development). This means that if I’ve used a type somewhere then it will appear even if I haven’t defined that type yet. Another strong difference is that the results appear in a context menu instead of in the Find References pane of VS making it much faster to choose your target.

Editing

[CTRL + ALT + LEFT/RIGHT] Extend/Shrink Selection – I’d love to buy a beer for the guy that made this one. Selecting text with the mouse is one of the slowest things I see developers do. Using the CTRL and SHIFT keys is much quicker, but even that will cause significant delays. Wherever the cursor is, if I “extend” the selection, it will modify the selection to the next logical level. Perhaps something like: the variable, the statements right side, the entire statement, the entire method body the statement is in, the entire method including declaration, etc. And of course “shrinking” does the converse. This in combination with some quick CTRL + X, CTRL + C, CTRL + V (tell me you know those ones!!) makes for some lightning fast editing.

[CTRL + SHIFT + ALT + UP/DOWN] Move code up/down – holding down the whole suite of modifier keys (CTRL, SHIFT , and ALT) might require a few fingers, but remember – the mouse takes your whole hand! Combine them with an up, down, left, or right, and you can move the selected code around on the screen in a very intelligent way. You’ll have to try it to see what I mean.

That’s all for now. There are a billion more, but this is just the essence. Practice and advance beyond your samurai skills to full on ninja!

Creating a Timer in Windows 8 (C#)

Ready for the shortest blog post in history?

Looking for a time in Windows 8? Look no further. Just drop this code into the App constructor on the App.xaml.cs page…

var d = new DispatcherTimer();
d.Start();
d.Tick += (sender, o) => { Debug.WriteLine('tick'); };

Now go take a look at Visual Studio’s Output pane and watch it tick.

Insert Formatted Code into OneNote

NoteHighLight on CodePlex

If you haven’t started using OneNote, you might want to consider it. You can create a notebook a free instance of SkyDrive and it makes note taking, collaboration, and sharing all very easy. The part I couldn’t live without is my ability to just hit [WIN + N] from anywhere in Windows and instantly get a new note. I don’t have to worry about saving it either. By default, it lands in my Unfiled Notes (in my SkyDrive notebook). I can move it to another location later for more organization if I want to, but honestly the searching in OneNote is so good, that I usually don’t bother. As long as I give it a good title, I’m always able to find it later. Actually, even if you paste images into your note, the indexer recognizes the text in your image and will even search on that!

On my Windows Phone 7, I can do the same thing. I pin a “New Note” tile to my start page and I can just hit that to create an unfiled note. The great thing is that both notes land in the same place… on my SkyDrive. So if I jot a note from the field, it’s available to me in Windows on my laptop later. Nice.

But I’m a software developer and I write a lot of code. Sometimes I just jot down little pieces of code. So I went looking for a syntax highlighter that worked in OneNote. I found it. It’s called NoteHighLight and it’s on CodePlex (here). The installer is in an asian font, so it was a blind install for me, but just choosing the default button on each page of the install wizard worked fine.

It installs into OneNote as its own tab. I decided I’d rather have it in the Insert menu, so I customized it like this…

Hitting Insert and then choosing one of these will get you a dialog like the following…

…and give you a nice way of typing or pasting in your code, and after completion, you’ll have something like this…

Happy note taking!

So Many Ways to Search in Visual Studio 11

There’s more than one way to skin a cat and more than one way to do a search in Visual Studio. There are 5 (that I know of, comment if you know of another) to be precise.

Search for a file, object, object member, etc. anywhere in your project. For instance, if you know that you have something in your app called Widget, but it’s just too much to think about where exactly you put it, then just hit CTRL + , and type “widget” and you’ll get results for the class itself along with any other members with the word widget and any object members.

Search in Solution (CTRL + ;)

This one is new to VS11 (actually, you may have used it with the Productivity Power Tools in VS2010) and allows you to filter your Solution Explorer to show only files that match your query. It’s especially helpful in my opinion for filtering out anything except for a certain file type. Querying for “.js” for instance will get rid of anything except for JavaScript files.

Quick Launch (CTRL + Q)

This one was in previous releases of Visual Studio, but it wasn’t as prominent and was often overlooked. I use Quick Launch to quickly find that option that’s buried somewhere in Tools | Options but I know it’s going to take me about 4 minutes and 25 seconds to find exactly where. Take line numbers for instance. Now why line numbers are not turned on my default is absolutely beyond me, but turning them in used to be an arduous process on a normal day and all but impossible at the end of the day, or on Monday, or before coffee, or with a slight headache. Now you just hit CTRL + Q and type “line numbers” and you’re in good shape.

Find (CTRL + F)

Also introduced with Productivity Power Tools and then brought native into VS11, Find is best used for finding text in the current file (although it will search multiple files as well). It’s a quick way to search and has the added benefit of highlighting all results for you.

Find in Files (CTRL + SHIFT + F)

Although able to search only in the context of the current document, this command is most often used for finding files across the solution or project. I like to dock this dialog in the lower right pane with Properties so that I always know where it’s going to be and I can keep it up across multiple searches.

Metro on an Alternate Monitor?!

You know those sonic noise guns that you can shoot at people and they supposedly just stop in their tracks because it’s physically disorienting? I felt like I got hit with one when I ran across this little nugget.

Want to move your Metro experience from your primary monitor to another screen - say your second (or fourth) monitor or even to the projector for a show? I’ve been told that the start menu appears on the primary monitor (without resorting to the simulator). Period. But that’s not the case! look up thank God

If you press WIN + PGUP/PGDN, you can change which monitor the start menu and all Metro apps appears on. Now that’s awesome! Until now, I was resorting to the simulator for getting my icons on my second monitor or projector to show people. News must spread. Tell everyone.

ReSharper 7 EAP in Visual Studio 11

I used to think that Visual Studio had an incredible set of keyboard shortcuts and productivity features. Then I installed ReSharper. Now a vanilla install of Visual Studio feels a bit vanilla.

Sure all of the refactorings are awesome, but what I end up missing when I’m missing R# is the little stuff. It’s the extend and shrink selection (Ctrl + Alt + Right Arrow/Left Arrow). It’s the next and previous member (Alt + Up/Down Arrow).

With R# 7 EAP, as with the Windows 8 Consumer Preview, I installed it the same day it was available. I was thrilled at first too – ready to blaze through my Windows 8 projects at the speed of sharp. But I discovered shortly that my IntelliSense was not working. For JavaScript behind Metro apps, I got an IntelliSense menu, but the entries were all wrong. And an acquaintance had the same issue. This was a deal breaker and I sadly uninstalled R# from my machine.

Today I tried again and low and behold everything works! So my mood swing is back at its acme and I’m ready to blaze through the code again.

Here’s the link to the EAP: http://bit.ly/resharper7eap