Marquee de Sells: Chris's insight outlet via ATOM 1.0 csells on twitter

You've reached the internet home of Chris Sells, who has a long history as a contributing member of the Windows developer community. He enjoys long walks on the beach and various computer technologies.




Moving My Site to Azure: ASP.NET MVC 2

In our last episode, I talked about the joy and wonder that is moving my site’s ISP-hosted SQL Server instance to SQL Azure. Once I had the data moved over and the site flipped to using the new database, I needed to move the site itself over, which brought joy and wonder all it’s own.

Moving to Visual Studio 2013

I haven’t had to do any major updates to my site since 2010 using Visual Studio 2010. At that time, the state of the art was ASP.NET MVC 2 and Entity Framework 4, which is what I used. And the combination was a pleasant experience, letting me rebuild my site from scratch quickly and producing a site that ran like the wind. In fact, it still runs like the wind. Unfortunately, Visual Studio 2012 stopped supporting MVC 2 (and no surprise, Visual Studio 2013 didn’t add MVC 2 support back). When I tried to load my web site project into Visual Studio 2013, it complained:

image

This version of Visual Studio is unable to open the following projects

 

This error message lets me know that there’s a problem and the migration report provides a handy link to upgrade from MVC 2 to MVC 3. The steps aren’t too bad and there’s even a tool to help, but had I followed them, loading the new MVC 3 version of my project into Visual Studio 2013 would’ve given me another error with another migration report and a link to another web page, this time helping me move from MVC 3 to MVC 4 because VS2013 doesn’t support MVC 3, either. And so now I’m thinking, halfway up to my elbows in the move to MVC 3 that Visual Studio 2013 doesn’t like, that maybe there’s another way.

It’s not that there aren’t benefits to move to MVC 4, but that’s not even the latest version. In fact, Microsoft is currently working on two versions of ASP.NET, ASP.NET MVC 5 and ASP.NET v.Next. Even if I do move my site forward two version of MVC, I’ll still be two versions behind. Of course, the new versions have new tools and new features and can walk my dog for me, but by dropping old versions on the floor, I’d left with the choices of running old versions of Visual Studio side-by-side with new ones, upgrading to new versions of MVC just to run the latest version of VS (even if I don’t need any of the new MVC features) or saying “screw it” and just re-writing my web site from scratch. This last option might seem like what Microsoft wants me to do so that they can stop supporting the old versions of MVC, but what’s to stop me from moving to AWS, Linux and Node instead of to ASP.NET v.Next? The real danger of dropping the old versions on the floor; not that I’ll move over to another platform, because I’m an Microsoft fanboy and my MSDN Subscription gives me the OS and the tools for free, but that large paying customers say “screw it” and move their web sites to something that their tools are going to support for more than a few years.

Luckily for me, there is another way: I can cheat. It turns out that if I want to load my MVC 2 project inside of Visual Studio 2013, all I have to do is remove a GUID from the csproj file inside the ProjectTypeGuids element. The GUID in question is listed on step 9 of Microsoft’s guide for upgrading from MVC 2 to MVC 3:

image

Removing {F85E285D-A4E0-4152-9332-AB1D724D3325} from your MVC 2 project so it will load in Visual Studio 2013

 

By removing this GUID, I give up some of the productivity tools inside Visual Studio, like easily adding a new controller. However, I’m familiar enough with MVC 2 that I no longer need those tools and being able to actually load my project into the latest version of Visual Studio is more than worth it. Andrew Steele provides more details about this hack in his most excellent StackOverflow post.

Now, to get my MVC 2 project to actually build and run, I needed a copy of the MVC 2 assemblies, which I got from NuGet:

image

Adding the MVC 2 NuGet package to my project inside Visual Studio 2013

 

With these changes, I could build my MVC 2 project inside Visual Studio 2013 and run on my local box against my SQL Azure instance. Now I just need to get it up on Azure.

Moving to Azure

Publishing my MVC 2 site to Azure was matter of right-clicking on my project and choosing the Publish option:

image

Publishing a web site to Azure using the Solution Explorer’s Publish option inside Visual Studio 2013

 

Selecting the Windows Azure Web Sites as the target and filling in the appropriate credentials was all it took to get my site running on Azure. I did some battle with the “Error to use a section registered as allowDefinition='MachineToApplication' beyond application level” bug in Visual Studio, but the only real issue I had was that Azure seemed to need the “Precompile during publishing” option set or it wasn’t able to run my MVC 2 views when I surfed to them:

 

image

Setting the “Precompile during publishing” option for Azure to run my MVC 2 views

 

With that setting in place, my Azure site just ran at the Azure URL I had requested: http://sellsbrothers.azurewebsites.net.

Where are we?

I’m a fan of the direction of ASP.NET v.Next. The order of magnitude reduction in working set, the open source development and the use of NuGet to designate pieces of the framework that you want are all great things. My objection is that I don’t want to be forced to move forward to new versions of a framework if I don’t need the features. If I am forced, then that’s just churn in working code that’s bound to introduce bugs.

Tune in next time and we’ll discuss the fun I had configuring the DNS settings to make Azure the destination for sellsbrothers.com and to add SSL to enable secure login for posting articles via AtomPub and Windows Live Writer.

0 comments




Moving My Site to Azure: The Database

In a world where the cloud is not longer the wave of the future, but the reality of the present, it seems pretty clear that it’s time to move sellsbrothers.com from my free ISP hosting (thanks securewebs.com!) to the cloud, specially Microsoft’s Azure. Of course, I’ve had an Azure account since its inception, but there has been lots of work to streamline the Azure development process in the last two years, so now should be the ideal time to jump in and see how blue the waters really are.

As with any modern web property, I’ve got three tiers: presentation, service and database. Since the presentation tier uses server-side generated UI and it’s implementation is bundled together with the service tier, there are two big pieces to move – the ASP.NET site implementation and the SQL Server database instance. I decided to move the database first with the idea that once I got it hosted on Azure, I can simply flip the connection string to point the existing site to the new instance while I was doing the work to move the site separately.

Deploy Database To Windows Azure SQL Database from SSMS

The database for my site does what you’d expect – it keeps track of the posts I make (like this one), the images that go along with each post, the comments that people make on each post, the writing and talks I give (shown on the writing page), book errata, some details about the navigation of the site, etc. In SQL Server Management Studio (SSMS), it looks pretty much like you’d expect:

image

sellsbrothers.com loaded into SQL Server Management Studio

 

However, before moving to Azure SQL Server, I needed a SQL Azure instance to move the data to, so I fired up the Azure portal and created one:

image

Creating a new SQL Azure database

 

In this case, I chose to create a new SQL Azure instance on a new machine, which Azure will spin up for us in a minute of two (and hence the wonder and beauty that is the cloud). I choose the Quick Create option instead of the Import option because the Import option required me to provide a .bacpac file, which was something I wasn’t familiar with. After creating the SQL Server instance and the corresponding server, clicking on the new server name (di5fa5p2lg in this case) gave me the properties of that server, including the Manage URL:

image

SQL Azure database properties

 

If you click on the Manage URL, you will have a web interface for interacting with your SQL Azure server, but more importantly for this exercise, the FQDN is what I needed to plug into SSMS so that I can connect to that server. I’ll need that in a minute, because in the meantime, I’d discovered what looked like the killer feature for my needs in the 2014 edition of SSMS:

image

Deploy Database to Windows Azure Database in SSMS 2014

 

By right-clicking on the database on my ISP in SSMS and choosing Tasks, I had the Deploy Database To Windows Azure SQL Database option. I was so happy to choose this option and see the Deployment Settings screen of the Deploy Database dialog:

Untitled-2

SSMS Deploy Database dialog

 

Notice the Server connection is filled in with the name of my new SQL Server instance on Azure. It started blank and I filled it in by pushing the Connect button:

Untitled-7

SSMS Connect to Server dialog

 

The Server name field of the Connect to Server dialog is where the FQDN we pulled from the Manage URL field of Azure database server properties screen earlier and the credentials are the same as I set when I created the database. However, filling in this dialog for the first time gave me some trouble:

Untitled-8

SQL Azure: Cannot open server ‘foo’ requested by the login

 

SQL Azure is doing the right thing here to keep your databases secure by disabling access to any machine that’s not itself managed by Azure. To enable access from your client, look for the “Set up Windows Azure firewall rules for this IP address” option on the SQL database properties page in your Azure portal. You’ll end up with a server firewall rule that looks like the following (and that you may want to remove when you’re done with it):

image

SQL Azure server firewall rules

 

Once the firewall has been configured, filling in the connection properties and starting the database deployment from my ISP to Azure was when my hopes and dreams were crushed:

image

SSMS Deploy Database: Operation Failed

 

Clicking on the Error links all reported the same thing:

Untitled-4

Error validating element dt_checkoutobject: Deprecated feature ‘String literals as column aliases’ is not supported by SQL Azure

 

At this point, all I could think was “what the heck is dt_checkoutobject” (it’s something that Microsoft added to my database), what does it mean for to use string literals as column aliases (it’s a deprecated feature that SQL Azure doesn’t support) and why would Microsoft deprecate a feature that they used themselves on a stored proc that they snuck into my database?! Unfortunately, we’ll never know the answer to that last question. However, my righteous indignation went away as I dug into my schema and found several more features that SQL Azure doesn’t support that I put into my own schema (primarily it was the lack of clustered indexes for primary keys, which SQL Azure requires to keep replicas of your database in the cloud). Even worse, I found one table that listed errata for my books that didn’t have a primary key at all and because no one was keeping track of data integrity, all of the data was in that table twice (I can’t blame THAT on Microsoft : ).

And just in case you think you can get around these requirements and sneak your database into SQL Azure w/o the updates, manually importing your data using a bacpac file is even harder, since you now have to make the changes to your database before you can create the bacpac file and you have to upload the file to Azure’s blob storage, which requires a whole other tool that Microsoft doesn’t even provide.

Making your Database SQL Azure-compatible using Visual Studio

To make my SQL database compatible with SQL Azure required changing the schema for my database. Since I didn’t want to change the schema for a running database on my ISP, I ended up copying the database from my ISP onto my local machine and making my schema changes there. Getting to point of SQL Azure-compatibility, however, required me to have the details of which SQL constructs SQL Azure supported and didn’t support. Microsoft provides overview guidance on the limitations of SQL Azure, but it’s not like having an automated tool that can check every line of your SQL. Luckily, Microsoft provides such a tool built into Visual Studio.

To bring Microsoft’ SQL compiler to bear to check for SQL Azure compatibility requires using VS to create a SQL Server Database Project and then pointing it at the database you’d like to import from (which is the one copied to my local machine from my ISP in my case). After you’ve imported your database’s schema, doing a build will check your SQL for you. To get VS to check your SQL for Azure-compatibility, simply bring up the project settings and choose Windows Azure SQL Database as the Target platform:

image

Visual Studio 2014: Setting Database Project Target Platform

 

With this setting in place, compiling your project will tell you what’s wrong with your SQL from an Azure point-of-view. Once you’ve fixed your schema (which may require fixing your data, too), then you can generate a change script that updates your database in-place to make it Azure-compatible. For more details, check out Bill Gibson’s excellent article Migrating a Database to SQL Azure using SSDT.

The Connection String

Once the database has been deployed and tested (SSMS or the Manage URL are both good ways to test that your data is hosted the way you think it should be), then it’s merely a matter of changing the connection string to point to the SQL Azure instance. You can compose the connection string yourself or you can choose the “View connection strings for ADO.NET, ODBC, PHP and JDBC” option from your database properties page on Azure:

image

SQL Azure: Connection Strings

 

You’ll notice that while I blocked out some of the details of the connection string in my paranoia, that Azure itself is too paranoid to show the password; don’t forget to insert it yourself and to put it into a .config file that doesn’t make it into the SCCS.

Where are we?

In porting sellsbrothers.com from an ISP to Azure, I started with the database. The tools are there (nice tools, in fact), but you’ll need to make sure that your database schema is SQL Azure-compatible, which can take some doing. In the next installment, I’ll talk about how I moved the implementation of the site itself, which was not trivial, as it is implemented in ASP.NET MVC 2, which has been long abandoned by Microsoft.

If you’d like to check out the final implementation in advance of my next post, you help yourself to the sellsbrothers.com project on github. Enjoy.

0 comments




Bringing The Popular Tech Meetups to Portland

pdx-tech-meetup-logoI’ve been watching the Portland startup scene for years. However, in the last 12 months, it’s really started to take off, so when I had an opportunity to mentor at the recent Portland Startup Weekend, I was all over it. I got to do and see all kinds of wonderful things at PDXSW, but one of the best was meeting Thubten Comerford and Tyler Phillipi. Between the three of us, we’re bringing the very popular Tech Meetup conference format to Portland.

The idea of a Tech Meetup is meant to be focused on pure tech. In fact, at the largest of the Tech Meetups in New York (33,000 members strong!), they have a rule where it’s actually rude to ask about the business model. The Tech Meetups are tech for tech’s sake. If you’re in a company big or small or if you’re just playing, cool tech always has a place at the Portland Tech Meetup.

The format is simple and if you’re familiar with the way they do things in Boulder or Seattle, you’re already familiar with it. Starting on January 20th, 2014, every 3rd Monday at 6pm, we’ll open the doors for some networking time, providing free food and drink to grease the skids. At 7pm, we’ll start the tech presentation portion of the evening, which should be at least five tiny talks from tech presenters of all kinds. After the talks, we’ll wrap up around 8pm and then head to the local water hold for the debrief.

If this sounds interesting to you, sign up right now!

If you’d like to present, drop me a line!

If you’d like to sponsor, let Thubten know.

We’re very excited about bringing this successful event to Portland, so don’t be shy about jumping in; the water is fine…

0 comments




The Party Is Just Getting Started At Snapflow!

snapflow logoThis has been my first week at Snapflow and what a week it’s been! I’ve already spend a good part of two days with actual customers that are excited about using Snapflow to build their web and mobile applications, started on a technical spike for one of those apps to be delivered on our platform in February and found the local Hawaiian teriyaki place.

As Chief Technical Officer at Snapflow, I’ll have influence over internal technology direction and external outreach, help to build our suite of products as well as growing the engineering team and work to understand our customers and make sure that they’re happy.

Snapflow’s customers are enterprise verticals building web sites and mobile apps. They want to build apps with global reach and cloud scale, but they don’t want to manage VMs for their databases, custom logic and REST APIs. With Snapflow, they get to configure their data model, design their custom logic with workflow and the REST API falls naturally from that. Further, because Snapflow provides enterprise-grade services, customers get top notch tools, security at the granularity they need, multi-tenancy to deal with app variations across groups or geographies, and guaranteed uptime. Our customers can then build their client apps however we want, but so far it’s been overwhelmingly HTML-based, so you’ll soon see tools from us to support that even more.

Technology-wise, we’ve got an amazing mix of AWS-based cloud hosting, Mongo DB and .NET on the server-side with HTML5-based tools and apps using Angular, Bootstrap and Kendo UI on the client-side.

And we’re hiring! Snapflow has more work than we can do right now and we’d love your help. I had other choices when it came to my next adventure, but Snapflow is that rare combination of people, technology and opportunity that I just couldn’t pass up. It’s the hot enterprise startup in Portland. Come join the party!

0 comments




TypeScript Templates for Windows 8

imageAs soon as I saw Anders’ talk on TypeScript, I fell in love. If you’re not familiar with it, TypeScript adds a lot of necessary features to JavaScript to make it suitable for building real apps, while still “compiling down” to JavaScript to maintain JS’s single biggest advantage: ubiquity. Further, TypeScript has tooling inside Visual Studio so that it works nicely with a wide variety of Windows projects, including Win8/JS projects.

However, while Microsoft has made a nice Win8/TS sample available, there are currently no Visual Studio project templates for building my own apps. Luckily, it was easy enough to build some:

image

You’ll notice three new templates: TypeScript versions of Blank App, Fixed Layout App and Navigation App. All three projects generate code that acts the same, except the code is in TypeScript instead of JavaScript (although the JavaScript is generated and very visible to your inspection).

I didn’t build the Grid App or Split App templates yet, since there is a lot of code there. I also haven’t ported any of the item templates. Now that I have the Navigation App template done (which includes an empty Page Control), the Grid and Split and other item templates will all flow from there (eventually : ).

JavaScript Patterns to TypeScript Constructs

Moving JavaScript to TypeScript involves two major pieces: porting the code from JS patterns to TS language constructs and bringing in references to the types that are used.

The first step, moving from JS patterns to TS language constructs, largely involved modules, classes and functions. For example, the navigator.js file defines the PageControlNavigator class in the Application namespace using JS patterns:

// navigator.js
(function () {
  "use strict";

  var appView = Windows.UI.ViewManagement.ApplicationView;
  var nav = WinJS.Navigation;

  WinJS.Namespace.define("Application", {
    PageControlNavigator: WinJS.Class.define(
        // Define the constructor function for the PageControlNavigator.
        function PageControlNavigator(element, options) {
          ...
          Application.navigator = this;
}, { home: "", /// <field domElement="true" /> _element: null, _lastNavigationPromise: WinJS.Promise.as(), _lastViewstate: 0, // This is the currently loaded Page object. pageControl: { get: function () { ... } }, ... } ) }); })();

The common pattern for a module that contains private and public parts is to use a self-executing anonymous function (which wraps all the code in navigator.js) to make everything private and then to use helpers to expose public parts explicitly (like the use of WinJS.Namespace.define). Further, to define a class is a matter of gathering up a constructor function with a set of member properties and functions, which is what the WinJS.Class.define helper does. Finally, right in the middle of that is the exposing of a namespace-wide property called Application.navigator, which makes it available to anyone using the Application namespace.

TypeScript provides actual language constructs for these patterns:

///<reference path='../declare/declare.ts' />
// navigator.ts
module Application {
    "use strict";

    var appView = Windows.UI.ViewManagement.ApplicationView;
    var nav = WinJS.Navigation;

    export var navigator: PageControlNavigator;

    interface PageControl {
        getAnimationElements: () => Element;
        updateLayout: (
            element: Element,
            viewState: Windows.UI.ViewManagement.ApplicationViewState,
            lastViewstate: Windows.UI.ViewManagement.ApplicationViewState) => void;
    }

    export class PageControlNavigator {
        home: string = "";
        _element: Element = null;
        _lastNavigationPromise: WinJS.Promise = WinJS.Promise.as();
        _lastViewstate: Windows.UI.ViewManagement.ApplicationViewState;

        constructor (element, options) {
            ...
        }

        // This is the currently loaded Page object.
        get pageControl(): PageControl { ... }

        // ...
    }
}

In this TypeScript code, you’ll see the module, export and class keywords that define the elements we were defining via patterns before. Further, the use of the interface keyword lets you define a contract for an argument or variable that the TypeScript compiler can check for you as it generates the corresponding JavaScript. Finally, notice the use of the type annotations after a colon, e.g. the PageControlNavigator type on the exported navigator variable, to give the TypeScript compiler more information. All of these constructs help you to be explicit about what you’re defining, which helps you track down errors and gives you better Intellisense as you code.

As I mentioned, TypeScript provides syntax on top of JavaScript, the idea being that all JavaScript code is already TypeScript code. Further, the TypeScript compiles produces JavaScript as it’s output. When you’re editing a TypeScript file in Visual Studio, you can see the corresponding JavaScript, which helps experienced JavaScript programmers bootstrap their way to TypeScript.

image

You’ll notice in this screenshot that TypeScript introduces shortcut syntax for function objects. For example, the following code from home.js:

WinJS.UI.Pages.define("/pages/home/home.html", {
  ready: function (element, options) {
    // TODO: Initialize the page here.
  }
});

can be written in TypeScript as follows:

WinJS.UI.Pages.define("/pages/home/home.html", {
  ready: (element, options) => {
    // TODO: Initialize the page here.
  },
});

The use of the TypeScript lambda syntax is both shorter and works better when it comes to your intuition of what the “this” keyword means.

The other thing to notice about most .ts files is one or more reference lines at the top that look like this:

///<reference path='../../declare/declare.ts' />

This is the TS way to do “include” or “import” of code from other TS files, instead of relying on an HTML container to pull in the right files.

TypeScript Declarations

A lot of the work porting the Win8/JS templates to TypeScript was replacing the use of JS patterns with TS constructs (which, ironically, generated back the same JS code I started with), but an equal amount of the work was in building TypeScript declaration files (*.d.ts files). The idea of a declaration file is that the JavaScript community has created a large number of libraries, none of which have associated TypeScript type information. TypeScript allows you to augment the type information for existing JavaScript libraries, e.g. jQuery, Knockout, WinJS, etc., with external files called declaration files.

The WinJS sample I mentioned earlier (Encyclopedia) provides a number of declaration files that provide type information for the HTML DOM, the WinRT object model, jQuery and for WinJS. Unfortunately, the one for WinJS is far from complete, which meant that a lot of the work I did to get the Win8/TS templates compiling without warnings was augmenting that file. All of the declarations files needed to make the templates compiled as generated are provided in the “declare” folder, but I’m sure there are holes that you’re going to run into as you add your own code. Of course, the authoritative winjs.d.ts file is part of the TypeScript distribution, so I’ll work with the nice folks on the TypeScript codeplex project to get my changes merged in.

Installing the Win8/TS Templates

To get started using the Win8/TS templates I’ve built, you’ll first need to install the TypeScript plug-in for Visual Studio 2012. Currently these templates have been tested under TS 0.8.1.1 only and the generated .jsproj files have this path hard-coded in. The web-based HTML Application with TypeScript template uses some trick to do away with hard-coded paths that I have yet to figure out.

You can download the Win8/TS samples from here, extract the three folders (blankts, blankfixedts and navts) into your VS2012 JavaScript project template folder, e.g. C:\Program Files (x86)\Microsoft Visual Studio 11.0\Common7\IDE\ProjectTemplates\JavaScript\Windows Store\1033. Once the files are there, shutdown all instances of Visual Studio 2012 and execute “devenv.exe /InstallVSTemplates” as admin. If you have multiple copies of Visual Studio installed, make sure you’re executing the one for VS2012.

Once you’ve completed those steps successfully, you should see three new TypeScript-based templates as shown in the very first figure of this blog post. Enjoy.

0 comments




Windows 8 and Visual Studio 2012 and Data Visualization, Oh My!

This month is a big one for Microsoft developers. Windows 8 will be generally available in stores on a variety of form factors starting on 10/26, with the BUILD conference following closely in the last week of October. This on top of the Visual Studio 2012 RTM earlier this summer and a Windows Phone 8 release coming soon, and there's a lot going on if you're a Windows developer.

If you've read my previous editor's notes this year, you already know that Telerik takes Windows 8 and Visual Studio 2012 very seriously. As of 10/17, we've officially released our set of XAML and HTML controls for building Windows Store apps on Windows 8, including data visualization controls like charts, gauges and bullet graphs. These controls aren't just ports from old platforms, but controls that have been re-imagined for the touch-centric mobile devices that Windows 8 will be shipping on. In addition, we've updated JustCode to support Windows Store project types, JustDecompile to decompile Windows Store and C# 5.0 apps and our JustTrace profiler to target Windows Store apps. If you'd like to see what our amazing customers have already done with all of this great Windows Store support, check out our Showcase Gallery.

Further, as the modern UI style becomes more popular, we’re continuing to push touch and metro UI themes into almost all of our suites, including ASP.NET AJAX, WPF and Silverlight. Also, these platforms including WinForms get a huge new control this Q: the PivotGrid, providing you with cutting edge data visualization for your custom apps.

In this Q, we've focused on Windows Store apps, Visual Studio 2012 and data visualization for desktop, web and mobile app development across the board, but that's not all! We've added Coded UI support to WinForms and WPF controls, full SharePoint compliance to our ASP.NET AJAX controls and complete storage of all of your Visual Studio settings in the cloud to JustCode! Check out our webinars the week of 10/22 so you can see just exactly what's new in your favorite Telerik products.

Chris Sells
VP, Developer Tools
@csells

P.S. And while the Developer Tools division has been hard at work, so has the rest of Telerik. For example, we've recently welcomed Eric Lawrence into our family with his excellent Fiddler tool, and the folks in our agile project management division TeamPulse have introduced Kanban boards and integration with TFS 2012 in their latest version.

0 comments




Telerik’s evolving platform guidance for .NET developers

Telerik often gets questions from its customers about which of the multitude of app frameworks that Microsoft provides for .NET developers that they should pick. WinForms? WPF? Silverlight? ASP.NET? What’s the right solution for their problem? The answer is always the same: it depends.

Unfortunately, that’s not very helpful, so last year a set of the best and brightest that Telerik has to offer sat down and figured out just what it depends on and whether we could offer clear, concise guidance for our customers. The answer was “yes we could,” so we did that in 2011.

However, it’s been a busy year that’s included two major events in the life of a .NET developer: Silverlight desktop and web have been shelved and Windows 8 has been born. So, with that in mind, we’ve updated the platform guidance to take those two important changes to the .NET developer landscape into account; you can read all about it in the Telerik’s 2012 platform guidance for .NET developers.

Or, if you’re already familiar with the 2011 guidance, the rest of this post will be about what’s changed in 2012.

Desktop Application

Desktop applications represent the range of applications from those supporting internal information workers to those delighting consumers. These applications typically involve richly interactive interfaces, either for heavy-duty data management or entertainment. They key characteristic of desktop apps is the need to take advantage of the full range of native capabilities of the platform.

Ideal .NET Platform: WPF

WPF provides the ideal platform for building desktop apps. With mature, rich tooling provided in Visual Studio and Expression Blend, readily available components that address the full range of app styles, a large developer community and ClickOnce deployment, WPF gives the .NET developer all of the power of building “native” Windows software with a simple deployment model.

Key Advantages of WPF:

[Special Silverlight Guidance Note: Silverlight is also a good candidate for building desktop apps, sharing many of the same characteristics of WPF. While it seems clear that Microsoft will not release a major version beyond the recently released Silverlight 5, their commitment to 10 more years of support as well as continued 3rd party vendor support means that it’s a viable alternative for WPF development for new or existing Silverlight projects.]

Tablet Application

The use of tablets and touch-centric apps within companies is on the rise, and tablet sales are expected to double in 2012 (Gartner). Unlike their mobile smartphone counterparts, which frequently complement existing desktop apps, analysts see the potential for tablets to be more disruptive, replacing certain types of desktop apps in the enterprise. For .NET developers, it is important to address this trend and pick a Microsoft platform that will deliver the best tablet experience. Many platforms available from Microsoft can be used to build touch-enabled apps, even WinForms, but Microsoft is providing clear guidance for modern, touch-first apps with the arrival of Windows 8.

Microsoft’s Windows 8 introduces a new model for building touch-enabled, tablet friendly apps that are meant to be content-focused, easy to use with no documentation, touch-centric and tailored to the device. These apps will run in a new dedicated environment only available in Windows 8.

Since Microsoft is making it clear that Windows 8 is their ideal platform for tablet apps, the bigger question developers must answer is how to develop tablet apps. Tablet apps can be built with either XAML/.NET or HTML/JavaScript. Both approaches have access to the full capabilities of the device and share a common Windows Runtime API.

Ideal Tablet Platform: XAML and .NET

When building Windows 8 tablet apps, choosing between XAML/.NET and HTML/JS largely depends on the kinds of existing assets within an organization and the skills of the developers, but we recommend XAML and .NET for most tablet app development. Tablet apps built with XAML and .NET not only offer the familiar .NET programming paradigms (and tools) that have been popularized over years of .NET and XAML development, but a large amount of the code, assets and skills carry over to Windows Phone 8 (WP8) app development. In contrast, it is not possible to leverage HTML/JS assets if you’re also building apps for WP8.

If supporting WP8 is not a key consideration for your tablet development, then it is important to know that Microsoft has worked to ensure the capabilities, tooling and run-time performance for both XAML and HTML tablet apps is as close to identical as possible. At that point, your choice between the two options is about the past and future technology strategy of your organization, not the capabilities of the platform.

So while we primarily recommend XAML and .NET for tablet app development, here are key advantages to both approaches that should be considered:

Key Advantages of XAML for building Metro-style apps:

Key Advantages of HTML for building Metro-style apps:

[Game support note: Both Windows Phone and Windows 8 provide access to DirectX for building high-performance “twitch” games. This access is provided via .NET XNA in Windows Phone 7 and via native DirectX in Windows 8. If you are planning on building high-performance games for these Microsoft platforms, we suggest this third option .]

Where are we?

It’s clear that Silverlight is in no sense “dead.” At Telerik, we still sell a large number of licenses to Silverlight developers, although from an engineering point-of-view, we spend more time making sure we’re taking the best advantage we can of WPF. Also, even if we don’t recommend starting new desktop or web deployment projects in Silverlight, it’s still alive and well on Windows Phone 7 & 8 and it provides an excellent springboard into XAML development on Windows 8. If you think of Silverlight as one of Microsoft’s implementations of XAML, along with WPF and the Windows 8 support, you’ll have the right mindset to move your Silverlight web and desktop apps, developers, skills and assets forward to WPF on the desktop, Silverlight on the phone and XAML on Windows 8.

0 comments




Telerik Loves Windows 8 and Visual Studio 2012 RTMs!

win8vs2012Yesterday’s release of Visual Studio 2012 and Blend for Visual Studio 2012 marks the beginning of a new era. In some ways, VS2012 and Blend are incremental releases, adding even better support for building enterprise and consumer apps and services for the desktop and the web. However, in one very important way, the release of VS2012 and Blend, together with the release of Windows 8 earlier this month, signals a whole new focus for the platform – that of touch-centric tablets – and with it, a whole new way to package and distribute apps for the Windows operating system – the Windows Store.

If Windows 8 sells even half of what Windows 7 has sold (which seems low, considering the support for a great number of new form factors), then that will represent 300 million customers all looking for new Windows 8 apps in the Store. Currently, that Store holds about 500 apps and even if Microsoft increases that number to 5,000 by general availability in October, that’s far short of the 500,000 apps that similar app stores have. In short, Windows 8 is going to have lots of users and those users are going to want to buy lots of apps. This is, of course, why Visual Studio 2012 and Blend are so important – they’re the tools you can use to design, develop and package your app for the Store and tap into those hundreds of millions of customers. Make no mistake – Windows 8 represents nothing short of a reboot of the Windows developer ecosystem and Visual Studio 2012 and Blend are the keys to that ecosystem.

Windows 8, Visual Studio 2012 and Blend are important to Windows developers, which makes it important to Telerik customers. Because of that, we’ve been on the cutting edge here since the BUILD conference in September, releasing metro themes that first week and supporting the Beta and RCs in our tools and controls. And now I’m happy to announce that we fully support Windows 8, Visual Studio 2012 and Blend across nearly all of our Windows developer products. And not only do we support them, but we take special advantage of their unique features in our products, as you can read in the following posts:

Of course, this is just the beginning of the tablet and mobile era for Windows developers, so count on Telerik to continue to push into Windows 8 and Windows Phone 8 for building touch-centric apps for both the Windows Store and the Windows Phone Store, as well as continuing to push our products to meet your needs on the desktop and on the web. Telerik’s been right there through the last decade of Windows development and you can expect us to be there for the next decade.

Chris Sells
VP, Developer Tools
@csells

0 comments




June, 2012, Florida: Best TechEd Ever!

This month in Florida is going to be my 2nd TechEd ever and I’m sure the best by far. The number of things I get to do is staggering:

I honestly can’t remember when I’ve looked forward to a conference more. I’ll see you there!

0 comments




Microsoft + ASP.NET + Open Source: This Time for Sure!

rocky-and-bullwinkleBullwinkle: “Hey Rocky! Watch me pull a rabbit out of a hat!”

Rocky: “Again? That trick never works!”

Bullwinkle: “This time for sure!”

In the last week or so, I’ve heard mixed reactions to Scott Hanselman’s eye-popping announcement that, in addition to ASP.NET MVC that is already open source, that Microsoft is releasing ASP.NET Web API and Razor as open source as well. Further, and this is the big deal:

Microsoft is going to take contributions on their open source ASP.NET components and ship those contributions in the box for future major releases.

Of course, this is big news on the face of it, but some folks aren’t convinced. Some more jaded members of the community look at the open sourcing of a Microsoft component as the beginning of the end for that component. “Look at IronPython!” they say. “That project was open sourced right before the team imploded.”

Another jaded point of voice is that Microsoft is open sourcing MVC so that they have a story when it’s killed: “You can add features to it all you want,” they claim Microsoft will say.

The funny thing about all of those points of view is that I hear people complain all the time when Microsoft cancels something, “I don’t care if they cancel my favorite project; just release the source to the community!” I find it ironic that when Microsoft does release the source for a dying project, people complain about that, too.

However, in this case, I don’t think that ASP.NET is going to be side-lined. In the previous cases, it was easy to see that Microsoft was moving on and to what, e.g. the C# dynamic keyword in the case of IronPython.

ASP.NET, on the other hand, is a huge part of the server-side story for Microsoft and MVC is clearly the thing they’re focusing on. It’s the common thread for custom servers for both UI and API on both Windows Server and the Cloud and a big focus in the tooling for VS11.

Further, Scott has a track record with making OSS work from Microsoft, including NuGet and the user contributions that it takes.

And finally, both Scott Hanselman and Phil Haack, respected, active community members, not only drove these projects but have endorsed them.

Those three things add up to Microsoft pulling the rabbit out of the hat for me.

0 comments




Building Windows 8 Apps with JavaScript

Brandon Satrom and I are writing a book on Metro/JS apps for Win8, with Don Box. All of the content on this page is subject to change.

winjs book cover

Read Online

Purchase

Table of Contents

Samples

Most of the chapters have several source code samples that accompany them, which you can download and use how you see fit. Enjoy!

0 comments




WinJS Promises: then and done

As of the Windows Consumer Preview (aka Win8 Beta), the WinJS promises object has a “done” method as well as a “then” method. The “done” method is just like “then” except that it turns unhandled errors into exceptions. If you read no further, know this:

Always call “done” as the last promise method in your promise chain.

Let’s say you have a promise implementation that makes failure a strong possibility:

  1. var prom = new WinJS.Promise(function (c, e, p) { e("#fail"); });

A fastidious developer will always pass in an error handler whenever then call the “then” method of a promise:

  1. prom.then(..., function (m) { content.innerText = "Handled: " + m; });

However, in the case that the developer doesn’t pass in a error handler function when calling “then”, the error will silently drop on the floor:

  1. prom.then(); // error? what error?

I realize that the web was built around the idea that page errors should just silently whistle into the wind, but as an app developer:

Errors should be loud.

So, I want my errors to be loud, I should default to using the “done” method on a promise instead:

  1. prom.done(); // error == BOOM!

When I call the “done” method and an unhandled error is detected, WinJS throws an error that not even a try-catch handler will stop from showing in the developer’s face:

image

Personally, I’d prefer to be able to catch such errors in try-catch blocks, but this behavior is far preferable to the error being ignored. Of course, if I care that much, I can provide an error handler function when calling done:

  1. prom.done(..., function (m) { content.innerText = "Handled: " + m; });

And finally, if I want to chain my promises, I just need to put the “then” methods in between so the errors flow, but the “done” method should always be last:

  1. var app = WinJS.Application;
  2. app.onactivated = function (eventObject) {
  3.   // start the download
  4.   downloadStatus.innerText = "downloading posts...";
  5.  
  6.   // process the declarative controls
  7.   WinJS.UI.processAll()
  8.   .then(function () {
  9.     // use the WinRT to download the RSS
  10.     var syn = new Windows.Web.Syndication.SyndicationClient();
  11.     var url = new Windows.Foundation.Uri("http://blogs.msdn.com/b/oldnewthing/rss.aspx");
  12.     return syn.retrieveFeedAsync(url);
  13.   })
  14.   .done(processPosts, downloadError);
  15. };

This is actual code from an app that pulls down an RSS feed after the processAll method is completed in the “then” method on line 8, which returns another promise on line 12. That promise is handled by the “done” method on line 14. If there had been an error in the download and as a developer, I’d forgotten to provide the “downloadError” error handler, I’d have gotten a giant exception dialog that would’ve encouraged me down a different path.

Thanks to Josh Williams from the WinJS team for reminding me of the “done” method.

0 comments




What’s New in the Beta Metro/JS Templates for VS11

The Consumer Preview of Windows 8 (aka the Win8 beta) is now available for download, along with the matching Visual Studio 11 beta. You can download them both from the Developer Center for Metro style Apps and at least when I did the downloading this morning, it was smooth and worked well. In case you’re interested, I downloaded the ISO, not the setup, and I am currently writing this blog entry in Windows Live Writer running inside a WMWare Workstation 8.0 virtual machine running on the Windows 7 host OS running inside Boot Camp on my MacBook Pro. As someone said to me this morning: “That’s a lot of VMs!” Maybe so, but the Win8 and VS11 betas are running surprisingly well inside of my Inception-box.

Metro/JS Templates for VS11 in BUILD

If you played around with the Metro/JS templates in VS11 from the BUILD conference in September, you’ll have noticed that the generated apps were compliant with the Windows 8 UX style guidelines, but that two of the templates – Grip and Split – generated large amounts of code. That’s because these are pretty much the biggest apps that Microsoft has ever shipped as templates. They each have multiples pages and they work hard at being simple but feature complete Metro style apps.

However, as well as the BUILD templates implemented the Win8 UX, their code wasn’t the greatest, for the following reasons:

All of these reasons meant that the functionality of the generate Grid and Split apps made for an instructional start to building your own Metro style apps, assuming you were willing to wade through a great deal of code. The new templates in the Win8 beta solve nearly all of these problems.

Get-VS-11-BetaMetro/JS Templates for VS11 Beta

Out of the box, the Metro/JS templates in the VS11 beta (made available today, Feb 29, 2012), get more betterer as they get more complex.Let’s start simple and work our way up.

image

Blank Application

The Blank Application template is almost the smallest Metro/JS app you can build, except that it includes a reference to the Microsoft Windows Library for JavaScript (aka WinJS):

image

And to be clear, this is a brand new feature. Including WinJS as a reference instead of dropping the code into each project means that MS can shipped a single shared implementation instead of every app in the store duplicating the code. If you want to duplicate the code into your project, you can do so, but you’ll also have to update the URL references to the JS and CSS files from your HTML files, like this snippet from the generated default.html:

default.html
  1. <!-- WinJS references -->
  2. <link href="//Microsoft.WinJS.0.6/css/ui-dark.css" rel="stylesheet">
  3. <script src="//Microsoft.WinJS.0.6/js/base.js"></script>
  4. <script src="//Microsoft.WinJS.0.6/js/ui.js"></script>

In addition to the new syntax with the leading double-slashes, that the number of WinJS files to include is a far smaller number in the Beta. Now it’s just base.js and ui.js, which makes it easy to decide which one(s) you want and in what order to include them, fixing a common problem in the BUILD bits.

One other thing that’s new in the Blank Application template is that there are stubs for implementing tomb-stoning to easily save and restore your app’s session state in the default.js:

default.js
  1. var app = WinJS.Application;
  2.  
  3. app.onactivated = function (eventObject) {
  4.     if (eventObject.detail.kind === Windows.ApplicationModel.Activation.ActivationKind.launch) {
  5.         if (eventObject.detail.previousExecutionState !== Windows.ApplicationModel.Activation.ApplicationExecutionState.terminated) {
  6.             // TODO: This application has been newly launched. Initialize
  7.             // your application here.
  8.         } else {
  9.             // TODO: This application has been reactivated from suspension.
  10.             // Restore application state here.
  11.         }
  12.         WinJS.UI.processAll();
  13.     }
  14. };
  15.  
  16. app.oncheckpoint = function (eventObject) {
  17.     // TODO: This application is about to be suspended. Save any state
  18.     // that needs to persist across suspensions here. You might use the
  19.     // WinJS.Application.sessionState object, which is automatically
  20.     // saved and restored across suspension. If you need to complete an
  21.     // asynchronous operation before your application is suspended, call
  22.     // eventObject.setPromise().
  23. };

The handling of the terminated state in the onactivated event on line 3 and the checkpoint event handler on like 16 are for reactivating and saving your app state respectively.

And finally, the handy TODO comments are something you’ll find sprinkled throughout the templates based on usability feedback conducted to determine what developers really need help with as they add their own functionality to the app.

Fixed Layout Application

Moving up the complexity scale, the Fixed Layout Application template is meant to do just what it says – provide a jumping off point for apps that are logically fixed layout. The crux of this code is the use of the ViewBox control in the default.html:

default.html
  1. <body>
  2.     <div data-win-control="WinJS.UI.ViewBox">
  3.         <div class="fixedlayout">
  4.             <p>Content goes here</p>
  5.         </div>
  6.     </div>
  7. </body>

Line 2 wraps the content of the app in a ViewBox control, which will scale everything inside of it to the size of the content, which is defined in the default.css file with the fixedLayout style:

default.css
  1. .fixedlayout {
  2.     -ms-grid-columns: 1fr;
  3.     -ms-grid-rows: 1fr;
  4.     display: -ms-grid;
  5.     height: 768px;
  6.     width: 1024px;
  7. }

You’ll see in lines 5 and 6 that the height and width of the div contained in the ViewBox is 768x1024, which means that the content can be created using absolute positioning and sizing. The job of the ViewBox is as the app is resized, either the computer’s resolution changes or more likely the app is moved between landscape, portrait, split and full sizes, the ViewBox will scale the content to take up as much room as possible, keeping the aspect ratio constant and scaling the content such that the app itself can think of itself as logically 768x1024 (or whatever the top-level div’s size is). This is very handy for building things like casual games where you want scaling, but generally not flowing – you want to control where the Scrabble tiles are or the tic-tac-toe pieces and it’s much easier to do that with a fixed size.

And now that I’ve described it, I’ll tell you that this template is the only one that’s structurally identical between BUILD and Beta. Still, it is useful.

Navigation Application

The next one up the ladder is the Navigation Application template, which is where we get the Back button and the support for moving HTML fragments into and out of the DOM just like the user was logically navigation page-to-page. In the BUILD bits, this navigation functionality was packaged in the default.js file, but in the Beta, default.js is just the same as the simpler templates. Instead, the navigation functionality is packaged into a new file: navigator.js. The reason this file is separate is to make it clear if you’d like to implement a different navigation policy, e.g. MVC, then this is the file to start with. Further, while this functionality would seem a shoe-in to be included in WinJS, it’s not quite “baked” enough, which means that MS hasn’t yet decided that this is “the way” to do navigation.

Still, it’s “a way” to do navigation in a Metro/JS app and a pretty useful one. Essential the way it works is that there is a singleton PageControlNavigator in the default.html file that holds the pages as they’re swapped in. The default.html is also where navigator.js is included:

default.html
  1. <script src="/js/navigator.js"></script>
  2. ...
  3. <div id="contenthost" data-win-control="Application7.PageControlNavigator" data-win-options="{home: '/html/homePage.html'}"></div>

The navigator.js file defines the PageControlNavigator control, which holds the logical pages as the user clicks around in the application. The home parameter is where to start the navigation. Navigation is to a Page, which is really a mapping between an HTML file and a set of events to handle over the lifetime of that Page:

homePage.js
  1. // This function is called whenever a user navigates to this page. It
  2. // populates the page elements with the app's data.
  3. function ready(element, options) {
  4.     // TODO: Initialize the fragment here.
  5. }
  6.  
  7. WinJS.UI.Pages.define("/html/homePage.html", {
  8.     ready: ready
  9. });

Of course, navigating to the home page is going to be rare compared to navigating between pages. The easiest way to get a new page to add to your app is to right-click on your project in the Solution Explorer and select Add | New Item:

image

The last item three item templates on the list are for shell contract implementations, which are beyond the scope of this blog post, but the first one is a Page Control, which gives us a triad of HTML, JS and CSS that fits exactly into the navigation model provided by the PageControlNavigator control:

page2.html
  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4.     <meta charset="utf-8">
  5.     <title>page2</title>
  6.  
  7.     <!-- WinJS references -->
  8.     <link href="//Microsoft.WinJS.0.6/css/ui-dark.css" rel="stylesheet">
  9.     <script src="//Microsoft.WinJS.0.6/js/base.js"></script>
  10.     <script src="//Microsoft.WinJS.0.6/js/ui.js"></script>
  11.    
  12.     <link href="page2.css" rel="stylesheet">
  13.     <script src="page2.js"></script>
  14. </head>
  15. <body>
  16.     <div class="page2 fragment">
  17.         <header aria-label="Header content" role="banner">
  18.             <button class="win-backbutton" aria-label="Back" disabled></button>
  19.             <h1 class="titlearea win-type-ellipsis">
  20.                 <span class="pagetitle">Welcome to page2</span>
  21.             </h1>
  22.         </header>
  23.         <section aria-label="Main content" role="main">
  24.             <p>Content goes here.</p>
  25.         </section>
  26.     </div>
  27. </body>
  28. </html>

 

page2.cs
  1. .page2 p {
  2.     margin-left: 120px;
  3. }

 

page2.js
  1. // This function is called whenever a user navigates to this page. It
  2. // populates the page elements with the app's data.
  3. function ready(element, options) {
  4.     // TODO: Initialize the fragment here.
  5. }
  6.  
  7. function updateLayout(element, viewState) {
  8.     // TODO: Respond to changes in viewState.
  9. }
  10.  
  11. WinJS.UI.Pages.define("/page2.html", {
  12.     ready: ready,
  13.     updateLayout: updateLayout
  14. });

Navigating to this new control defined by these files is a simple matter of calling the navigate method:

homePage.html
  1. <a onclick="WinJS.Navigation.navigate('/page2.html')">Page 2</a>

As far as the user is concerned, the anchor tag shows up as a link like any other:

image

Clicking on “Page 2” fires the onclick event, which calls the navigate method, passing in the path to the HTML file and causes the Page control defined in page2.html, page2.js and page2.css to be loaded:

image 

In addition to whatever content on your Page control, notice that the Back button shows up automatically. The Back button manages navigation via clicking, touching and the browser keys; Ctrl+Left Arrow and Ctrl+Right Arrow work as Back and Forward respectively.

Grid and Split Application

At this point, we’ve covered almost all of the core concepts that make up the Grid and Split applications: they bring in WinJS by reference, they use controls and they use navigation via the Page controls. In fact, even though the Grid app has three pages and the Split app has two, they’re really just the navigation template with the pages to implement the Grid and Split app patterns that MS decided were the major app patterns appropriate for Win8. However, the Grid and Split application templates do have two major features that the other templates don’t have: support for multiple view states and a centralized data model.

Multiple view state support means that as the app is moved between portrait, landscape, full and split, the app adjusts itself to look good in all states. The view state management is mostly handled with CSS styles associated with media modes, like in the Split App’s itemsPage.css:

itemsPage.css
  1. ...
  2. @media screen and (-ms-view-state: snapped) {
  3.     .itemspage .itemslist .win-vertical.win-viewport .win-surface {
  4.         margin-bottom: 30px;
  5.     }
  6. ...

In Metro/JS apps, MS has provided a media query predicate called -ms-view-state, which can be one of the four view states and the styles in the media query block will be applied when the app moves to that state. In addition, if you want to handle the view state change in JS, you can do so with updateLayout event in your Page control, like this snippet from itemsPage.js:

itemsPage.js
  1. // This function updates the page layout in response to viewState changes.
  2. updateLayout: function (element, viewState) {
  3.     var listView = element.querySelector(".itemslist").winControl;
  4.     if (viewState === Windows.UI.ViewManagement.ApplicationViewState.snapped) {
  5.         listView.layout = new ui.ListLayout();
  6.     } else {
  7.         listView.layout = new ui.GridLayout();
  8.     }
  9. }

In this case, the updateLayout event is called when the control is initially created and as the app moves through the view states so it can change the layout style for the ListView control showing the contents of the page:

imageimage

Landscape vs. Snapped view state layout for the itemsPage ListView control

The other major feature of the Grid and Split app templates – and this feature is new in the Beta bits – is the centralized data model, which is where the data for all pages comes from. This data model is defined in data.js and it contains the static group and item data as you just saw. The core of the data is exposed from data.js like so:

data.js
  1. WinJS.Namespace.define("data", {
  2.     items: groupedItems,
  3.     groups: groupedItems.groups,
  4.     getItemsFromGroup: getItemsFromGroup
  5. });

These three members of the data object are used throughout the templates, e.g. in the itemsPage.js ready event handler:

itemsPage.js
  1. // This function is called whenever a user navigates to this page. It
  2. // populates the page elements with the app's data.
  3. ready: function (element, options) {
  4.     var listView = element.querySelector(".itemslist").winControl;
  5.     ui.setOptions(listView, {
  6.         itemDataSource: data.groups.dataSource,
  7.         itemTemplate: element.querySelector(".itemtemplate"),
  8.         oniteminvoked: this.itemInvoked.bind(this),
  9.     });
  10.     this.updateLayout(element, Windows.UI.ViewManagement.ApplicationView.value);
  11. },

Notice that the data.groups property is used on line 6 to perform a data binding operation. That data binding is against the dataSource property of the object returned from data.groups, which itself is created by a method on the WinJS.Binding.List object that holds the grouped item data. It’s this binding list, a new feature in WinJS for the Beta, that makes it easy to move from the static data provided by the templates and dynamic data that your app defines.

The binding list is a binding data source, which means that as you add items to it, it notifies any control that happens to be bound to it. This is especially handy when your app starts up with zero data, but you need to initialize the ListViews such that as the data is available (perhaps from an asynchronous network call), it will be shown.

If you open up the data.js, you’ll see the static sample data:

static sample data
  1. // Each of these sample groups must have a unique key to be displayed
  2. // separately.
  3. var sampleGroups = [
  4.     { key: "group1", title: "Group Title: 1", subtitle: "Group Subtitle: 1", backgroundImage: darkGray, description: groupDescription },
  5.     ...
  6. ];
  7.  
  8. // Each of these sample items should have a reference to a particular
  9. // group.
  10. var sampleItems = [
  11.     { group: sampleGroups[0], title: "Item Title: 1", subtitle: "Item Subtitle: 1", description: itemDescription, content: itemContent, backgroundImage: lightGray },
  12.     ...
  13. ];

The group data has a unique key, a title, a subtitle, a background image and a description, which are all fields that the data templates used in the Split and Grid apps depend upon (although you can change them if you like). The item data has a reference to the group to which it belongs, a title, a subtitle, a description, a background image and the content for the item itself.

The code that populates the binding list with the sample data looks like this:

statically bound data
  1. var list = new WinJS.Binding.List();
  2. var groupedItems = list.createGrouped(groupKeySelector, groupDataSelector);
  3.  
  4. // TODO: Replace the data with your real data.
  5. // You can add data from asynchronous sources whenever it becomes available.
  6. sampleItems.forEach(function (item) {
  7.     list.push(item);
  8. });

As the comment makes clear, it’s this code you’re most likely to want to change. Instead of pulling in static data from the sampleItems array, we want to pull the items in asynchronously, perhaps from an RSS feed or two just like my earlier post:

dynamically bound data
  1. var list = new WinJS.Binding.List();
  2. var groupedItems = list.createGrouped(groupKeySelector, groupDataSelector);
  3.  
  4. // RSS feeds
  5. var feeds = [
  6.     { key: "feed1", title: "Scott Hanselman", subtitle: "a blog", backgroundImage: darkGray, description: "a blog", url: "http://feeds.feedburner.com/ScottHanselman" },
  7.  
  8.     { key: "feed2", title: "Raymond Chen", subtitle: "a blog", backgroundImage: lightGray, description: "a blog", url: "http://blogs.msdn.com/b/oldnewthing/rss.aspx" },
  9.  
  10.     { key: "feed3", title: "Chris Sells", subtitle: "a blog", backgroundImage: mediumGray, description: "a blog", url: "http://sellsbrothers.com/posts/?format=rss" },
  11. ];
  12.  
  13. feeds.forEach(function (feed) {
  14.     WinJS.xhr({ url: feed.url }).then(function (request) { processPosts(feed, request); });
  15. });
  16.  
  17. function processPosts(feed, request) {
  18.     // parse the RSS
  19.     var nodes = request.responseXML.selectNodes("//item");
  20.     for (var i = 0, len = nodes.length; i < len; i++) {
  21.         var node = nodes[i];
  22.         var item = {
  23.             group: feed,
  24.             title: node.selectNodes("title")[0].text,
  25.             subtitle: node.selectNodes("pubDate")[0].text,
  26.             description: "a post",
  27.             content: node.selectNodes("description")[0].text,
  28.             backgroundImage: feed.backgroundImage
  29.         };
  30.         list.push(item);
  31.     }
  32. }

In this case, our group data is a set of RSS feeds, being careful to continue to use the same group field names so I don’t have to update the data templates in the rest of the app. When the app loads, I still create a binding list, but instead of filling it directly, I start an async xhr call (the WinJS XMLHttpRequest wrapper) for each feed, creating an item for each RSS post I find upon a successful completion. Because I’ve left the data model alone and because I’m using the binding list, that’s all I have to change and now the entire app has been updated to support that data:

image

The items page with the set of feeds in the Split app template

image

The split page with the posts from the selected feed

Where Are We?

As you can see, the Metro/JS templates in the VS11 beta start simple and add features with navigation, pages with specific app pattern functionality, multiple view state support and a unified data model. The main difference is the Beta versions of this templates is that code has been simplified, beautified and pushed into WinJS as much as possible to make the inside of your app just as pretty and easy to use as the outside.

Translation

This article has been translated into Serbo-Croatian by Jovana Milutinovich. Enjoy.

0 comments




Editor’s Note, Telerik Newsletter, February 2012

Hello, all, and welcome to the February, 2012 edition of the Telerik newsletter! As the newest employee at Telerik, I’m still learning all of the good stuff we’re doing just in the area of developer tools.

For example, the features in JustCode that fix up my using statements (Ctrl+Shift+U) and show me a type’s shape and implementation via the JustDecompile integration (F12) are now ingrained into my fingertips, but I just learned (JustLearned!) that if I want to get completions on types that aren’t even listed in my using statements, I can use Ctrl+Alt+Space and keep right on coding, which is one of a ton of new features in the 2012 Q1 release. More new features in the Just family of tools include a new decompilation engine in JustDecompile to more completely handle new .NET constructs, a new “Largest Memory Retainer” view in JustTrace to find memory leakers and the ability write your very own JustCode extensions. And the Reporting and OpenAccess ORM tools have great new features coming, too!

On the controls side, for which Telerik is very well-known, we have new features in the ASP.NET AJAX and MVC suites, XAML Silverlight, WPF and Windows Phone 7 suites and even the WinForms suite. For example, one of the more amazing controls for me is that RadFileExplorer, which provides an entire logical way to explore files over the web, however you’d like to expose them, and is now updated with thumbnail image support. Plus, AJAX adds support for client-side data binding, exporting to Excel for RadTreeList and nearly complete support across the entire suite for OData. Further, MVC, Silverlight and WPF all get much enhanced data visualizations with charting and diagramming.

However, my favorite set of additions in the controls suite has to be focus on the end-to-end app building support from the WP7 team, including handling ratings, tooltips and the new Application Building Blocks, which includes components for sending diagnostic data back to the developer, implementing trial feature and app expirations and a helper for implementing LiveTiles. This set of components came directly out of the experience the WP7 team had in building and shipping the Tasks apps, which started as the ToDoLists sample. The WP7 team that working hard to make mobile developers happy, even providing guidance on how to build apps your customers will love and how you can make money on your apps.

All of this mobile experience is pouring directly into a whole new set of controls, tools and components that we’re building for Windows 8. Even today, JustCode already support the Visual Studio 11 and our controls have a Metro style theme built right in. Of course, we’re not going to stop there; we’re already spinning up a team dedicated to helping you build end-to-end mobile apps on Windows 8. We’re working closely with Microsoft to make sure we release our Visual Studio 12 extensions and support when VS12 ships, but you’ll see more from us even sooner than that. Stay tuned!

Really, there’s too much good stuff to list, so if I were you, I’d hang out on the Telerik blogs and on the @Telerik twitter feed to see what’s coming up. Even better, check out the upcoming webinars to see the new features in action and install the free trials. And, if you’re got questions, even with the trials, drop us a line on our support center and we’ll get you answers right away. Or, if you’d like to talk to me directly, feel free to drop me a line. We care deeply about making sure our customers get when they need, so keep those cards and letters coming!

0 comments




The Windows Libraries for JavaScript: Part I

DISCLAIMER: This post is targeted at the //build/ version of the Windows Developer Preview (aka Windows 8). Things are likely to change with future releases. On your head be it.

In the last post in this series, we looked at getting started building Metro style apps built using JavaScript (Metro/JS apps) with Microsoft Visual Studio 11 for the Windows Developer Preview (aka VS11) and Microsoft Expression Blend 5 Developer Preview (aka Blend).

In this installment, we’re going to take a look at the library that brings WinRT and the web platform together: the Windows Library for JavaScript (aka WinJS) and build an app while we’re doing it.

The Need for WinJS

While it is the case, as you’ll see, that a Metro/JS apps have the same access to the underlying Windows platform as any other language projection (like Metro/VB, Metro/C# and Metro/C++ apps), it’s also the case that HTML/JavaScript programmers have a certain style that they are used to programming in. In some cases, those habits need to change because Metro/JS apps aren’t web sites or even web applications; Metro/JS apps are native applications that happen to be built with HTML, JavaScript, CSS, SVG, etc.

However, in many cases, existing JavaScript habits are good ones and should be encouraged. Towards that end, Microsoft engineers have built the Windows Libraries for JavaScript (WinJS), which is a set of reusable JavaScript and CSS files which were created specifically to make it easier for you to build Metro/JS apps with the right Win8 “feel” to them.

The easiest way to bring WinJS into your project is to create an application using any of the Metro/JS project templates, since all of them include the WinJS files:

clip_image002

WinJS is defined by the files under the winjs folder. The Blank Application project template produces an application with an empty window, but it does it with style; specifically the style that makes a Metro/JS app look like a Win8 app. Of course, the styles alone can’t make everything right – you’ll also need the right layout, behavior, etc. As an example of how to build a Metro/JS apps that’s slightly more exciting than the one we’ve been looking at so far, let’s build one of the most famous members of the Windows team – Raymond Chen.

Mr. Chen is a developer on the Windows team that brought you the Windows Developer Preview (aka Win8). Further, he’s the author of the most excellent book “The Old New Thing” based on a blog of the same name:

clip_image004

Chen’s blog is famous for digging into the forgotten nooks and crannies of the Windows platform. And for our purposes, Chen’s blog is an excellent target for our sample because he’s chosen a blogging platform that exposes the full text of his posts in a programmatic form (both RSS and Atom) so that we can build a Win8 app to show them.

Any blog displayed in the browser is essentially the title, date and content from each of the latest blog posts. To start, we need to download the data for each of his posts. To do that, we first need to know where to put that code.

The WinJS.Application object

The Blank Application template-generated default.html loads a minimal set of WinJS JavaScript and CSS files:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>RssReader</title>
    <!-- WinJS references -->
    <link rel="stylesheet" href="/winjs/css/ui-dark.css" />
    <script src="/winjs/js/base.js"></script>
    <script src="/winjs/js/wwaapp.js"></script>
    <!-- RssReader references -->
    <link rel="stylesheet" href="/css/default.css" />
    <script src="/js/default.js"></script>
</head>
<body>
</body>
</html>

Updating the sample with some slightly more interesting HTML:

<!DOCTYPE html>
<html>
...
<body> <h1>The Old New Thing</h1> <div id="downloadStatus"></div> <div id="posts"></div> </body> </html>

Here we’re setting the header text of our app and creating two div elements as placeholders: one for the status of our RSS download and one for the data from the RSS when we get it. Also, let’s replace the contents of default.css with styles to match Chen’s blog:

body {
    background-color: #fff;
    color: #000;
    font-family: Verdana;
    padding: 8pt;
}

a:link, a:visited, a:active {
    color: #700;
    font-weight: inherit;
}

h1 {
    text-transform: none;
    font-family: inherit;
    font-size: 22pt;
}

#posts {
    width: 99%;
    height: 100%;
    overflow: auto;
}

.postTitle {
    color: #700;
    font-size: 1.2em;
    font-weight: bold;
}

.postDate {
    color: #666;
    font-size: 11pt;
}

.postContent {
    font-size: medium;
    line-height: 18px;
}

To support app lifetime, Win8 provides a set of app-level events. The generated default.js file subscribes to the app’s mainwindowactivated event and then starts the WinJS application:

(function () {
  'use strict';
  // Uncomment the following line to enable first chance exceptions.
  // Debug.enableFirstChanceException(true);

  WinJS.Application.onmainwindowactivated = function (e) {
    if (e.detail.kind ===
Windows.ApplicationModel.Activation.ActivationKind.launch) {


// TODO: startup code here } } WinJS.Application.start(); })();




  

The contents of the generated default.js file are contained within a self-executing anonymous function declaration (that is a mouthful – it’s fun to use a language with key concepts missing).

By default, any function or variable defined outside of a function in your JavaScript files is global across your Metro/JS app. Variables and functions defined within a function are only visible within that function. The template uses this outer function declaration to help you follow good JavaScript design patterns, ensuring that your functions and variables do not pollute the global namespace.

After grabbing the Application object from the WinJS namespace, the code subscribes to the event fired after the application and its resources (like default.html) have been loaded. This is a good place to do initialization, as we’ll see.

For any of the application events to fire, you need to let the application know you’re ready to receive them, which is what the call to the start method does.

The mainwindowactivated event handler is the perfect place for us to kick off the download of the data from Chen’s blog.

Async HTTP using WinJS.xhr

The xhr function in the WinJS namespaces provides a series of options for downloading data in both text and XML formats using HTTP. The name of the xhr function stands for XMLHttpRequest, which is the name of the object that sparked the AJAX/Web 2.0 revolution around 2005 (although the object has been part of Internet Explorer since version 5.0 released in 1999). The xhr function provided with WinJS is a wrapper that takes a number of options, including which HTTP verb to use (GET by default), which HTTP headers to include (none by default) and which URL to retrieve data from:

WinJS.Application.onmainwindowactivated = function (e) {
  // start the download
  var chen = "http://blogs.msdn.com/b/oldnewthing/rss.aspx";
  downloadStatus.innerText = "downloading posts...";
  WinJS.xhr({ url: chen }).then(processPosts, downloadError);
}

Instead of providing the option to retrieve the data synchronously or asynchronously the way the XMLHttpRequest object does, xhr forces an asynchronous call so that the UI will not be blocked while data is retrieved. You’ll see this all over the Win8 programming model as reflected into Metro/JS and it helps you make more responsive programs. In our case, because we don’t know how long the request is going to take, we’re setting the text content of the downloadStatus div to indicate progress.

Asynchronous functions from WinJS return an object called a promise, which represents results to be provided at some time in the future. The promise object exposes the then method, which takes an optional three functions, one for success, one for failure and one for progress.

The call to the xhr function returns the promise immediately, at which point we set the functions to call in the case of success or failure, ignoring progress:

function processPosts(request) {
  // clear the progress indicator
  downloadStatus.innerText = "";

  // parse the RSS
  var items = request.responseXML.selectNodes("//item");
  if (items.length == 0) {
    downloadStatus.innerText = "error downloading posts";
  }

  for (var i = 0, len = items.length; i < len; i++) {
    var item = items[i];

    // append data to #posts div
    var parent = document.createElement("div");
    appendDiv(parent, item.selectNodes("title")[0].text, "postTitle");
    appendDiv(parent, item.selectNodes("pubDate")[0].text, "postDate");
    appendDiv(parent, item.selectNodes("description")[0].text, "postContent");
    posts.appendChild(parent);
  }
}

function appendDiv(parent, html, className) {
  var div = document.createElement("div");
  div.innerHTML = html;
  div.className = className;
  parent.appendChild(div);
}

function downloadError() {
  downloadStatus.innerText = "error downloading posts";
}

When the xhr call has completed successfully, the processPosts function is called with a request object which has all the information as if we’d use the XMLHttpRequest object directly. The property we care about is responseXML, which contains the RSS data we requested. From the RSS, we use an XPath expression to select the set of item nodes, extracting the title, pubDate and description data to be used to create a div element per item, with div elements for each of the pieces of data we’re showing, styled appropriately.

For readers of The Old New Thing, the output should look pretty darn familiar:

clip_image006

At this point, you may worry about whether our use of the xhr function will actually work, since a page provided by a web server would fail. The reason this works is because Metro/JS apps run in a secure sandbox and are, by default, allowed the ability to make cross-domain HTTP requests even though web pages are not.

Actually, it’s not quite true that Metro apps are allowed access to the Internet by default – it’s just that Metro app project in VS11 are provided that access by default, as it’s such a common need.

Where Are We?

At this point, we’ve built a working Metro/JS app that does a real thing using WinJS. In the next installment, we’ll look at how WinJS provides features to make DOM manipulation better.

Portions Copyright © 2011 Microsoft Corporation. Reproduced with permission from Microsoft Corporation. All rights reserved.

0 comments




2623 older posts       No newer posts