Feeds:
Posts
Comments

Archive for the ‘Uncategorized’ Category

Async tips and best practices

Async/await is arguably one of the most important language improvement to ever come to C#. But with most great powers comes great responsibility. Designing APIs that leverage async/await can seem easy at first but if you don’t impose a few standards during the power dev phase of a project, when it comes time to support things like suspend/resume & robust navigation, you may quickly find yourself in a quagmire with a host of clean-up work to do. Here are a few tips me and my teams have come up with over the years to help start off on the right foot when building APIs.

Naming conventions

This is a simple and somewhat superficial one but worth mentioning. WinRT has defined a naming convention for async methods by always using the “Async” suffix at the end of a method name. This helps inform consumers of an API that it is asynchronous without having to look at the return type. It is also nice for auditing an app before shipping to ensure there are no hard to duplicate race conditions and that an app will suspend properly at any moment. More on these concerns later.

Should I add a cancellation token parameter?

Assuming you are returning a Task rather than IAsyncAction or IAsyncOperation (more on these later). Assume the answer is always yes. Async API take time to run. Maybe you already know that an async API will never take more than a few milliseconds, but this is an implementation detail that should never be imposed by the method signature. My advice is to always assume when designing an API that it might take many seconds and that the caller may want to abort the operation. This helps future proof your APIs in the following ways:

  1. Ultimately you may abstract your class and support different implementations that take longer than the original implementation.
  2. Some APIs like file system IO may always be quick in your dev bubble, but you never know when someone is loading from a network location or USB 1.0 thumb drive. Plan for the worst.

Furthermore, the consumer of the API should never need to care about how long an API will take to run. Consumers should always design with “what happens if this takes 2 seconds to run” in mind and having a consistent pattern to work with will help ensure this mind set.

WinRT compatibility: Cancellation tokens with IAsyncOperations and IAsyncActions

You should never need a cancellation token param when you are returning an IAsyncOperation or IAsyncAction. Note: These WinRT types that are required when exposing async operations from WinRT compatible components; Task is not permitted since it is a .NET specific type. The good news is, IAsyncOperation and IAsyncAction both provide cancellation token internally as part of the type. The easiest way IMO to build async WinRT components is to create a public method that returns the IAsync* type, and a private method that returns Task. Use the AsyncInfo static type to help convert a task into an IAsync* type AND supply the cancellation token. For example:

public IAsyncAction DoSomethingAsync()

{

return AsyncInfo.Run(c => DoSomethingAsync(c));

}

private async Task DoSomethingAsync(CancellationToken cancellationToken)

{

await Task.Delay(1000, cancellationToken);

}

The consumer of the public API should then always supply a cancellation token via the .AsTask(CancellationToken) extension method overload. For example:

await DoSomethingAsync().AsTask(myCancellationToken);

Optional parameters and cancellation tokens

Optional parameters can be convenient but the CancellationToken parameter should always be last. However, as you know, optional parameters cannot be followed by non-optional parameters. Fortunately, there’s a way to also make the CancellationToken parameter optional.

Don’t do this:

async Task DoSomethingAsync(CancellationToken cancellationToken, int waitTimeInSec = 1)

{

await Task.Delay(TimeSpan.FromSeconds(waitTimeInSec), cancellationToken);

}

Do this instead:

async Task DoSomethingAsync(int waitTimeInSec = 1, CancellationToken cancellationToken = default(CancellationToken))

{

await Task.Delay(TimeSpan.FromSeconds(waitTimeInSec), cancellationToken);

}

Note: this is getting pretty picky and you may chose to ignore this advice but it is my personal preference to stick with the established Microsoft convention by keeping CancellationToken at the end.

To throw or not to throw, that is the question.

This is the most important tip of all IMO. If your method accepts a cancellation token, it should always throw an OperationCancelledException if that token is cancelled during the operation. NEVER swallow that exception. If the consumer cancels the operation via the supplied cancellation token, assume they need to know and do this by throwing. The easiest way is to just let the exception bubble back up stream from any async methods you are calling. For example, here, we can assume Task.Delay will throw if the cancellation token is cancelled. We don’t need to do anything except not catch the exception.

async Task DoSomethingAsync(TimeSpan waitTime, CancellationToken cancellationToken)

{

await Task.Delay(waitTime, cancellationToken);

}

If you can’t rely on the async calls you are making internally within your method to throw or you need to handle cancellations manually such as in the case of transactions, simply call cancellationToken.ThrowIfCancellationRequested(). However, usually this is not required.

Should I throw even if the method finishes?

What if a method successfully completes but the cancellationToken is flagged after the last async operation? For example:

async Task<int> GetAverageGradeAsync(CancellationToken cancellationToken)

{

var allScores = await GetAllScoresAsync(cancellationToken);

int total = 0;

int sum = 0;

foreach (var score in allScores)

{

// SHOULD I THROW HERE?

total++;

// OR HERE?

sum += score;

}

// WHAT ABOUT HERE?

return sum / total;

}

This depends… is the method intended to be thread-safe? Does it take a long time to run?

In most cases, one can assume that the cancellation token will be flagged on the same thread as the loop is running on. If this is the case, there is no benefit to monitoring the cancellation token once the original async operation has completed. IF you can make these assumptions, there is no possible way that the cancellation token could even be set to a cancelled state in between these lines of code since everything is happening on the same thread. Yes, I know that ideally one would design an API to be thread-safe and not make assumptions about what thread the cancellation token is flagged from. However, there is a performance cost to checking the cancellation token and there’s a productivity and maintenance cost to inserting a bunch of ugly cancellationToken.ThrowIfCancellationRequested() calls in your code. My vote in most cases is to favor readability and leave out the calls to ThrowIfCancellationRequested.

That said, if you have a billion scores in the example above, ignoring the potential for an overflow, this could take a long time to calculate. In this case, you may want to run your calculation on another thread and handle cancellations during the calculation.

First, the best way to do this is on the same thread as the async operation. Creating new threads and hopping between synchronization contexts can be expensive. To prevent a new thread from being created, use Task’s ContinueWith method. This ensures that the same thread that the async operation was ran on is used for your subsequent code. Additionally, call cancellationToken.ThrowIfCancellationRequested() in your continuation code but call sparingly to improve performance. For example:

async Task<int> GetAverageGradeAsync(CancellationToken cancellationToken)

{

return await GetAllScoresAsync(cancellationToken).ContinueWith(t =>

{

int total = 0;

int sum = 0;

foreach (var score in t.Result)

{

total++;

sum += score;

if (total % 1000 == 0) cancellationToken.ThrowIfCancellationRequested();

}

cancellationToken.ThrowIfCancellationRequested();

return sum / total;

}, TaskContinuationOptions.OnlyOnRanToCompletion);

}

Please note that in the above example, it is possible that the cancellationToken was flagged as cancelled after the last call to cancellationToken.ThrowIfCancellationRequested was made but before or during sum / total was executed. This could result in your method successfully returning even though cancellationToken was set. This is OK and consumers of your API should expect that cancellation tokens are not always honored by async methods when dealing with multi-threaded scenarios.

Should I throw internal cancellation tokens?

No. If your async API creates and flags its own cancellation token, do not surface this to the consumer of your API by throwing an OperationCancelledException. A great example of this is for a timeout. Imagine you have an API that makes a web request with a 5 sec timeout. Also imagine that the timeout is something we want to handle internally within the API. A great way to impose timeouts is to create a CancellationTokenSource object and supply a timeout via the constructor. Build a linked cancellation token that marries the cancellation token supplied to the method with the timeout token created within the method and use during your web request operation. Then, check to see which one was cancelled and only bubble up OperationCancelledException if the token passed to your method was cancelled. Otherwise, throw a new exception type or handle as you see fit. For example:

static async Task<string> GetWebResponseAsync(Uri uri, CancellationToken cancellationToken)

{

// Adding a Cancellation token to time out the network request

CancellationTokenSource timeoutTokenSource = new CancellationTokenSource(TimeSpan.FromSeconds(5));

CancellationToken requestCancellationToken = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, timeoutTokenSource.Token).Token;

using (var httpClient = new HttpClient())

{

try

{

return await httpClient.GetStringAsync(uri).AsTask(requestCancellationToken);

}

catch (OperationCanceledException) when (timeoutTokenSource.IsCancellationRequested)

{

// request timed out

throw new TimeoutException();

}

}

}

What exception should be caught?

When catching cancellation exceptions, always catch OperationCanceledException, not TaskCanceledException. TaskCanceledException inherits OperationCanceledException but there are other exception types that can derive from it as well. OperationCanceledException is safer to catch unless you know you only want to TaskCanceledException.

How do I handle transactions?

If your async method throws an OperationCanceledException always be sure that your app’s state is not left broken. Either don’t throw at all and force the method to complete entirely or roll back your changes. A good example of this would be if you are writing 2 files to disk that both need to be completely written. In this case, if you threw an exception after writing 1 file but before writing the next, you would leave the app in a broken state. Tip: With C# 6 you can put additional async code in the catch block which makes it easier to roll back transactions if necessary.

To catch or not to catch

As mentioned earlier, you should always let OperationCanceledExceptions bubble up as long as they are the direct result of the CancellationToken supplied as a parameter being canceled. However, if you are creating or re-using a CancellationToken within your code and passing that to an async method, you should not throw OperationCanceledException from your method since the caller has an implicit guarantee that they are not responsible for cancelling the operation by virtue of not supplying a cancellation token. A simple scenario would be in the case of a button click event that needs to run an async operation. Here you might want to disable the button so it can’t get clicked again during the async operation, execute the async operation supplying it with a cancellation token of some kind (perhaps one that is set when the app suspends) and catch and ignore OperationCanceledException. In the finally clause you would restore the button state to ensure you always leave the app in a good state.

private async void Button_Click(object sender, RoutedEventArgs e)

{

var control = (Control)sender;

control.IsEnabled = false;

try

{

await DoSomethingAsync(((App)Application.Current).CancellationToken);

}

catch (OperationCanceledException) { /* ignore, suspending */ }

finally

{

control.IsEnabled = true;

}

}

Note, you may want to supply CancellationToken.None if there is never a scenario that should be captured. The async API will not need to be changed to support cancellations in other scenarios.

If you follow this guideline and the one from earlier about always accepting a CancellationToken parameter in your async APIs, you will have the net result of allowing cancellation tokens to be supplied at the highest level and also be caught at that same level. This gives you the greatest flexibility for code reuse. For example, you might have an API that is called from a button click and from a background task. The outcome of cancelling may be very different for these two scenarios. In the case of the button click, you may want to show the user an error. In the result of the background task you may want to just ignore it. Building your APIs in the ways described above gives your consumers the ability to choose how to handle cancellations.

async void

There are a lot of articles on the web that say “Don’t do it” so I won’t go into all the pitfalls here and completely agree as long as we’re talking about APIs that you are building. In other words, always return a Task (or IAsnycAction/Operation) if you have control over the signature of the method. The button click handler example above however is an example of one you don’t have control over and therefore can’t avoid on the other hand. Even if you never intend to await the task (e.g. you are building a method to be called from a constructor only), you should still return the task. Later you may want to call it from another place that you can await from or you may want to store the task object in a variable and await it later.

Async events

Awaiting an event handler is not something the language supports out of the box. All you can do is raise an event (without await) and carry on. However, there is a great pattern called “deferrables” that you can use in your own events to allow the code that raised the event to wait for an async operation that occurs in an event handler. To do this you need to create a custom EventArgs class that allows the event handler to request a deferral, perform its async operation and then signal back to the code that raised the event that it is complete. The code that raised the event can then await the collection of deferrals requested by one or more event handlers before continuing.

For a more detailed explanation and code samples, see my Custom async events in C# blog post.

Async properties

Async getters and setters are also not possible in C#. However, there are some tricks you can use to work around this as well. One approach is to simply get rid of the property and use Get and Set methods instead. However, this makes binding to a UI difficult. Another way that allows you to use the binding power of properties is to use the power of INotifiyPropertyChanged to your advantage.

For example, in a getter you could do something like this:

int? highScore;

public int HighScore

{

get

{

if (highScore.HasValue) return highScore.Value;

else

{

GetHighScoreAsync(CancellationToken.None).ContinueWith(t =>

{

highScore = t.Result;

PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(HighScore)));

}, TaskScheduler.FromCurrentSynchronizationContext());

return default(int);

}

}

}

In the case of a setter you can simply call an async method to set your value without awaiting the result.

In both cases, just be cognoscente about re-entrant scenarios where the getter or setter is called more than once before the internal async call returns. To help with this you can build a task queue in the case of the setter or store the active task in the case of a getter and do a null check first before continuing. For example:

int? highScore;

Task highScoreTask;

public int HighScore

{

get

{

if (highScore.HasValue) return highScore.Value;

else if (highScoreTask == null)

{

highScoreTask = UpdateHighScoreAsync(CancellationToken.None);

}

return default(int);

}

}

async Task UpdateHighScoreAsync(CancellationToken cancellationToken)

{

try

{

highScore = await GetHighScoreAsync(cancellationToken);

PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(HighScore)));

}

finally

{

highScoreTask = null;

}

}

Other resources

https://blogs.msdn.microsoft.com/andrewarnottms/2014/03/19/recommended-patterns-for-cancellationtoken/

https://programmerpayback.com/2015/09/03/custom-async-events-in-c/

Advertisement

Read Full Post »

Back at the dawn of .NET I wrote a useful little tool for myself called Seeker. Seeker is just a simple GUI Windows app that could search for text in your file system and optionally replace it with other text. To this day I still use this tool on a regular basis and have often thought about updating, open sourcing and sharing it with the world. Today’s the day!

screenshot

Install Seeker now

 

What does it do?

  • Search files of any type for text.
  • Optionally replace text found with different text.
  • Optionally use regular expressions.
  • Search for multiple entries in a file.
  • Control the encoding used to search and replace files. By default, encoding is automatically detected and preserved.

Aren’t there already other tools out there that do the same thing? Certainly, there are a number of great options out there already. Windows Explorer itself allows you to search for text in files and the first grep tool was probably invented before my time.

So why did I write yet another search and replace tool for Windows? A few reasons: 1) Way back in the day, it served a fun little weekend project to help me learn .NET 2) I needed all the features listed above and was having trouble finding a free version that did everything I needed. Yes, I’m cheap 😉 3) I wanted to be able to easily modify it if special needs arose.

Warning: Seeker is a very powerful tool and can be configured to change text in any file that you have permission to modify. Therefore, Be VERY careful when doing replace operations to ensure you don’t accidentally modify files you don’t intend to. There’s no ability to undo so use at your own risk.

Seeker is also 100% open source and can be found at seeker.codeplex.com.

Please post feedback either here or on CodePlex and enjoy!

Read Full Post »

The WinRT Genome Project

What is the hardest part about learning a new programming language? I’ve often argued that learning a new language is easy, it’s learning a new framework is can be time consuming.

In case you’ve been living under a rock lately, you probably already know that Windows 8 Metro style apps can be built with Xaml & C#. This means that .NET & Silverlight developers can leverage their existing skillset to easily build Win8 Metro Xaml style apps. But just how similar is Silverlight to WinRT?

In an effort to get some real numbers, I created a program to iterate over all the default assemblies included WinRT and compare with those found in Silverlight 5. Here’s what I found:

image

 

Of those 1,582 matching types, here is a look at the members (properties, method, & events) they have in common:

image

 

Comparison details for those interested:

  • I included all Silverlight 5 assemblies installed as part of the SDK. Other assemblies such as RIA services and the Silverlight Toolkit were not included.
  • The public Silverlight 5 RC was used. IMO it is highly unlikely any numbers will change once the final version is released.
  • Differences in namespaces, type accessibility, and base classes were still counted as a match. For example, I ignored differences such as a type being sealed or implementing ISerializable.
  • Similar liberties were taken with members.
  • Property get & set methods and event add & remove methods were not counted as unique members.

My key takeaways:

  • WinRT includes a ton of new types. Some of these are certainly for new features such as the marketplace, accelerometer support, …etc. Time to start learning!
  • Approximately 1/4 of the types in Silverlight are not present in WinRT. Some of these are no longer relevant like the types associated with the DOM bridge or Out of Browser support.
  • When comparing just the shared types, SL5 starts to look very close to an actual subset of WinRT. This is good news for Silverlight developers because it means most of your existing code should easily port.

Coming soon: I also have a side-by-side comparison of the entire WinRT and SL5 API so you can explore each and every difference in their respective APIs. Check back soon.

Update: Detail now available, here’s a complete comparison of every single public API in WinRT and Silverlight 5 and where they match.

Read Full Post »

BUILD

Today concludes the last day of the Microsoft Build conference (//build/) and after four days of sessions, keynotes, developing on the Win8 tablet, and countless conversations with other developers I have formed a number of opinions (both good and bad) about the new Windows 8 development stack and what it means to the world outside of Microsoft.

Disclaimer: If anyone tells you they’re objective, they’re not being objective. I’m biased in all kinds of ways and this is a summary of my personal thoughts and opinions. Whether you agree or disagree, hopefully this will invoke a few ideas and get you thinking about the changes we witnessed this week.

//build/targets…

 

/businesses

image

/brand_visibility

What do Best Buy, the Daily Show, and Hershey’s Chocolate have in common? They all have apps in the iPhone app store. But why wouldn’t these companies just build or improve their mobile websites? Would an app somehow be a better experience than a mobile website? Doubtful. OK, maybe Best Buy can use native phone APIs to help you find a store based on your current location and maybe you can build more touch-friendly features with Objective C, but the real reason is to show up to the party. Get listed in the app store or your customers may not be able to find you. But the app store is much more than the iOS yellow pages. Users actively go look for apps they think might be useful. This is very different from how consumers use the web. How many users open their shiny new iPhone and go browse the web for sites to add to their favorites list? None. Compare that with how many users instantly go look for cool apps to install. Like it or not, Windows 8 will be used on a daily basis by millions of users. Apple has already taught the world that there is an “app for everything” and users will be stoked to find one on their shiny new PC. Whether building a metro app for the new Windows 8 marketplace is justified as an opportunity or simply a precaution, most businesses can’t afford to stay home and miss the party.

/app_marketing

Ask any developer who’s built an awesome program that never made them rich what the hardest part about building successful software is. Answer: marketing. We developers have loads of ideas and talent but usually don’t know much about marketing or like learning how to do it right. At the same time, there are many profitable apps in the iOS app store by these same kinds of developer. Enough of them have been able to rake in the cash and barely lifted a finger to market their apps. The app store is a magical jolly fat man leaving presents for those who were simply good. Go to download.com and check out the thousands of non-mobile apps out there. I’d venture to say that very few have ever made a dime regardless of their popularity; now is their chance!

/cross_platform

There’s one huge story that Microsoft didn’t exactly mention but I believe they are willing to and perhaps even subtly encouraging people be misguided about. Yes, web developers can use their skills to build first class Windows 8 apps. Yes, web developers can build those apps faster if they have an existing app or website to port, but can you really share a common code base between a website and a Win8 app? Fat chance. Besides being inappropriate to design a metro app and a website identical to one another, the code just won’t port if you do it right… especially, if you use the all new and powerful Blend designer tool to build it. Blend is built for creating Win8 apps and although it generates HTML5 compliant HTML & CSS, it also uses Win8 specific controls and references js files that rely on the WinRT. Furthermore, it is highly doubtful that its output has ever been tested on anything but IE10. The bottom line: HTML and js may save you time, but mostly because of the skills of your developers, not the reusability of the code for other platforms.

 

/consumers

image

/tablets

Tablets are the real story with Win8. Will Win8 be better than Win7 for the non-touchscreen desktop or laptop? Probably. But is that difference compelling? Probably not. Tablets are clearly the primary target for Win8 and there are some good reasons to think Win8 could own the majority of the tablet market in due time. Here’s the difference between a Win8 tablet and the competition as of today: while iPads and Android tablets are hardly toys, they certainly aren’t workstations. Every single time I’ve traveled in the last year, I came packing both an iPad and my laptop. And each and every time I desperately tried to part with one or the other. While away for pleasure, I couldn’t part with my laptop in fear that I might need it to do something important. While away on business, taking the laptop was a given but I ultimately couldn’t part with my iPad so I could get my fix of Angry Birds on the airplane. Win8 tablets will be different. Once I load up my new Win8 tablet and learn to trust what the OS can do, I’m almost certain the only devices I’ll be traveling with will be my phone and tablet. Thank baby Jesus! OK, maybe this isn’t such a horrible burden to have: bringing 3 devices with you on vacation. But it demonstrates the problem pretty well. If I can travel with just a Win8 tablet, my mother-in-law can live with just a Win8 tablet. Bottom line: Microsoft is going to seriously raised the bar for the next generation of tablets.

/netbooks+laptops

While iPads may cannibalize netbooks and laptops today, Win8 tablets will bleed into the market and all devices will simply become portable PCs. Because Microsoft relies on others to build hardware, we can expect to see tablets of all different sizes and performance abilities. Some will have built in keyboards oozing with glutinous power and others will be wafer thin, glorified phones. Keeping with tradition, Microsoft will look to the plethora of hardware makers to innovate and fill every little nook and cranny of possible use-cases humans could have for portable computers. Netbooks and laptops won’t be cannibalized, they’ll be absorbed.

/desktop

I have my own ideas on the future of the desktop PC but it has much more to do with the Kinect than it does Win8; I’ll save those ideas for another blog post. For now, I don’t see any profound impact Win8 will have on the desktop PC J

/web

The web browser is dead. OK, I intentionally over-sensationalized that statement, but let’s be honest, apps and websites more and more are serving the same function. Because of the invention of the app store, apps are gaining popularity over websites for the widening areas where they overlap. Imagine you needed a stop watch on your iPad. Would you search the web or search the app store? I’ve actually asked this question to a number of iPad-owning friends and every one of them said without hesitation that they’d search the app store. The web browser is no longer the go-to tool to extend the features of your phone or tablet and soon the same will be true for your PC. Not long ago, it was inconceivable that a business would launch an app before building a website unless their only product was the app itself. Today, I can only assume that there are companies who have already built apps and will eventually get around to making a website. Is the web dead? Absolutely not. Apps need the web. Is the web browser dead? Hardly, the web browser will remain the go-to tool for content for a long time, but the role of the web browser is diminished and this is just the beginning.

/security

The other week, my colleague Justin Angel called out the Windows Phone AVG fake anti-virus app… how can you build an anti-virus app for a platform that doesn’t support viruses? Metro apps on Windows 8 won’t be as locked down as apps on the Windows Phone but a similar principal will be at work. Windows 8 requires all apps submitted to the app store to 1) run in a security sandbox, 2) be certified (and therefore subject to being pulled and publicly reviewed) and 3) be required to declare the various limited abilities they are allowed to perform at runtime. The user can therefore be guaranteed that when they install an app, it will do no more (in terms of security) than the app claims to do and they will have ample warning before installing that app. Unless users continue the soon-to-be antiquated practice of downloading and running exes from the internet instead of installing apps from the marketplace, they will be instantly granted incredible protections that only platforms like Win8 metro can provide.

/user_experience

While Windows 8 will still support Win32 apps, metro apps are where it’s at! Metro is a new design style that is beautiful, fluid and friendly to all forms of input devices including your fingers. Everyone I’ve talked to seems to love the new metro design paradigm, but even those that want overlapping windows with lots of chrome will be able to use the desktop/classic (Win7-like) mode if they prefer. In my opinion, Windows 8 metro is a leap forward in user experience and clearly sets a new bar for usability for apps and operating systems alike.

 

/developers

image

/silverlight+wpf

I’ve been asked this question more than any other at the conference: “What do you think the future of Silverlight is?” In case you’ve been living under a rock, this is the one question Microsoft promised to answer at the Build conference and unfortunately is one of the few questions they still refuse to address. I was expecting Steven Sinofsky himself to issue a very frank and straightforward statement about the future of Silverlight on day one… even if it risked boos from the crowd; we are owed that much. Unfortunately, Build is over and all we are left with is our own speculation. You might think that Silverlight has a bright future. After all, Silverlight 5 was released as a public RC only a week or so before the conference and for legions of Microsoft developers it is still the preferred choice for building web apps. So, what is “up” with Silverlight? As a Silverlight developer I have to grit my teeth a little when I profess my honest opinion that “Silverlight for the web is dead”. Ouch, that still stings a little.

The good news: managed code and Xaml is NOT dead. And managed code and Xaml of course is after all Silverlight or WPF without a name from the marketing department. In fact, although it remains to be seen, I think managed code could even become the predominant paradigm (over C++ and javascript) for building the next generation of Windows 8 apps. At the very least it will be a very popular choice. This is great news for Silverlight and WPF developers who want to build top-shelf metro apps for Windows 8. Additionally, Silverlight in browser and out-of-browser apps will continue to work as is for Windows classic/desktop mode.

The bad news: the build conference was NOT about the web browser or Win8 desktop mode. For all the IE pumping we’ve heard in the last year, I was left a bit surprised we didn’t hear more about IE. ‘The Gu’ gave us a quick peek at some new ASP.NET features and VS 2011 near the end of the 2nd day keynote but the content felt so out of place it was almost as if the respected ‘Gu’ was only there to appease the hordes of Microsoft developers (including myself) who he helped inspire during his tenure in the developer division at Microsoft. But it makes sense: Windows 8 and the future of the Microsoft dev stack are about metro and about metro apps.

The ugly news: Silverlight does not run in the metro browser and the metro browser will most likely be the main browser from now on in Windows. This makes some sense since Silverlight would need to be refactored to use the new WinRT controls and APIs under the hood in order to correctly support input and display the way a metro app should. Microsoft wants the metro experience to be pure and consistent across the board. This means that all apps that run in the metro environment must be using WinRT to do the heavy lifting – including web pages running through the metro browser. HTML & js based web pages can do this because IE10 uses WinRT under the hood to do all the rendering. Silverlight versions 1-5 do not. Could a special version of Silverlight for IE metro be rebuilt to use WinRT? Anything is possible. Will it be done? I wouldn’t hold your breath. At the same time, Silverlight out of browser apps are in a similar boat. Silverlight OoB apps won’t run in metro and are confined to the desktop/classic mode only.

OK, back to my “Silverlight is dead” comment: managed code and Xaml running in a web browser simply does not appear to be part of Microsoft’s long-term strategy. What caused this? While I’d love to speculate, I won’t in this post. Microsoft will continue to keep its foot in the door for web development using ASP.NET but in the end, Microsoft sells a little product called Windows and everything it does in some way needs be traced back to benefiting Windows. Web development in general is only important to Microsoft for two reasons: First, the traditional reason: Users use the web and want an awesome web browser. IE is a feature of Windows and Microsoft wants developers to be able to easily build web pages that work well in it. Second (and more importantly now than 1 week ago): Microsoft wants a great selection of apps in the Windows marketplace and they want the legions of web developers to help write those apps. It is a too large and talented pool of programmers to ignore any longer. .NET developers and HTML+js developers can now all partake. Silverlight for the web isn’t going anywhere but Silverlight will continue to lose reach as Windows 8 metro will now be added to the list of platforms that won’t support it. Sorry fellow Silverlight developers, we don’t have a choice; for the long term I suggest for you to start writing Windows apps or switch to HTML & js.

/C++

C++ developers must be peeing their pants from happiness. Finally, C++ lovers are first class citizens in the Windows world by being able to take advantage of many of the modern advances in programming that has transpired since the advent of .NET. Just like VB6 paved the way to NET, .NET paved the way to WinRT. Finally C++ programmers will be able to use Xaml and a rich object oriented runtime to build apps. It must feel good.

/winforms

If C++ programmers are peeing their pants from happiness, Winforms programmers are peeing their pants from agony. Buck up Winformers, you should have switched to WPF years ago and then at least you’d have the skillset to make the metro switch.

/html+js+css+svg

These developers are the real winners. Even if you don’t plan to write a sigle Win8 app, be happy knowing you could. 🙂 HTML5, CSS3, js & SVG are all first class citizens now with native access to the WinRT and killer performance of IE10 as your rendering engine.

/azure

The Build conference pretended to include Windows Azure but like ASP.NET, content was relegated to the hind quarter of the day 2 keynote and sessions were limited. For the most part, Windows 8 doesn’t really affect the story of the back-end; not significantly anyway. There are some new roaming features in Windows 8 which Azure will be well positioned to help out with and without a built in namespace for local database access from WinRT, connecting apps to the cloud will be more important than ever. However, at the same time, Microsoft is courting the web developers who are comfortable with non-Microsoft platforms. Microsoft wouldn’t dare make them use Windows Server or Windows Azure to easily build a Win8 app and therefore, for the time being, Azure takes a back seat in order to avoid polluting the message.

/asp.net

Build was clearly all about Windows on the client and by virtue of having an app store, starts to pave the way for reduced importance of applications hosted from within the web browser. ASP.NET came up near the end of the day 2 keynote and while there were some nice improvements to debugging and website optimization, there was very little content overall and almost zero sessions. HTML based Win8 apps have nothing to do with ASP.NET. They must ship as local, pre-made html & js packages and use AJAX if communication with the web is necessary. ASP.NET, Razor, MVC, and Webforms have no place in this world aside from providing one of many possible options for implementing web services.

/wp7

Windows Phone is very much part of Microsoft’s strategy. Yet it also played virtually no roll in the Build conference. Some have speculated that Windows Phone as we know it is merely a stop gap until Windows 8 (or 9) can be made to run on those devices. Windows 8 will only support the new Metro style apps on ARM based architecture and it is easy to see how it could be a good fit for running on even smaller form factors than the tablet in the near future. Windows Phone developers should expect someday to have the same paradigm choice for building apps that the Win8 platform now enjoys.

/xna

Surprise! There’s no XNA support in Windows 8 and no way to control DirectX from managed code. While I don’t have a shred of evidence to back this next statement up, I have a strong feeling this won’t be the last we hear of XNA. There are too many awesome games built on it and it is too useful to abandon. It would be a shame if Microsoft didn’t offer an XNA option or something similar soon. For now we’ll have to hold our breaths.

 

/competition

image

/apple

Apple has made a distinct choice that a tablet is more like a phone than a personal computer. Consumers have been more than willing to live with this difference because they haven’t known any different. Will consumers continue to accept this decision after seeing a Windows 8 tablet that offers the versatility of a laptop? I expect not but it remains to be seen. I believe it is inevitable that Apple will either make OSX more like iOS or will try to follow the Win8 lead and build a radical new hybrid OS. It will be interesting to see how the world’s favorite innovator reacts long-term to the innovations seen this week.

/google

Google should have serious reason for concern! While Android is rocking the Casbah, Google pays the bills with its advertising business. Windows Phone shows us just how irrelevant Google can be if the platform has it’s own built in search feature and provides its own simple advertising component for apps to use. Google needs to get used to it and should start fearing the worst in the long term. In fact, it probably already has. Android was probably not invented because Google has a passion for building a better OS, Android was a very smart and pro-active action on Google’s part to make sure their advertising and search platforms will continued to be used. I wouldn’t count Google out of the race by any means but their profitability clearly depends on Androids ability to out compete Windows.

/mozilla

Yikes, Firefox for Windows (Chrome, Opera, & Safari as well) had better hope Windows 8 metro is a failure. Even if they build a Windows 8 metro app, they will ultimately be building a layer on top of WinRT to render web pages instead of being part of WinRT like IE10 is. This would the equivalent of building a web browser to run inside a web browser. Performance will never be as good and they will always be 2nd in class compared to IE10 for mainstream users and geeks alike.

 

Special thanks to all the awesome people I met at Build for the 4 day collective learning session and great conversations. This blog post comes from your brains more than my own.

Read Full Post »