AJ’s blog

August 14, 2011

RIA with Silverlight–The Business Perspective

If you read this, chances are that you are a developer and that you like Silverlight. And why not? Exciting platform, great features, outstanding tooling. But! If you’re a corporate developer, have you sold it to your management yet? If not, this post is for you.

Silverlight is for RIA, and the domain of RIA applications is largely intranet or closed/controlled extranet user groups. This again is what is usually found in larger enterprise companies. Companies that usually have a vested interest in controlling their environment. And in terms of bringing software into production and of operations and maintenance afterwards, every new platform is one platform to many.

So, the odd developer comes along and talks about this great new technology. Does the management care? Probably not. What does it care about? Simple. Money! Money, as in costs for deployment and user support, hardware and licenses to get the stuff up and running, operations and developer training, maintenance. And money as in savings in the respective areas and – the cornerstone, as the business usually pays the bill – impact on the business. All usually subsumed under the term ROI.

About a year ago, I finished an analysis looking into RIA with Silverlight, conducted for a major customer. Not from the point of view of the developer, but that of business people, operations, and IT management:

So, let’s look briefly at each aspect…

User/Business perspective…

The business doesn’t exactly care for the platform Silverlight itself; it cares for its business benefits. Benefits as in improved user experience, streamlined business workflows, office integration, and so on. And since we had some lighthouse projects with Silverlight we were able to collect some customers’ voices:

“This [streamlining with Silverlight] would reduce a [...] business process [...] from ~10 min to less than a minute.”

“Advanced user experience of Silverlight UI helps raising acceptance of new CRM system in business units”

“I was very impressed of the prototype implementation […] with Silverlight 3. Having analyzed the benefits of this technology I came to the conclusion that I want the […] development team to start using Silverlight as soon as possible. [...]”

This is also confirmed by the typical research companies, like Gartner or Forrester:

“Firms that measure the business impact of their RIAs say that rich applications meet or exceed their goals” (Forrester)

Operations perspective…

In production, the benefit of Silverlight applications (compared with respective conventional web based applications) is reduced server and network utilization.

For example, we had a (small but none-trivial) reference application at our disposal, which was implemented in ASP.NET as well as Silverlight (as part of an analysis to check the feasibility of Silverlight for LOB applications). We measured a particular use case with both implementations – starting the application and going through 10 steps, including navigation, searches, and selections. Both applications were used after a warm-up phase, meaning that the .xap file, as well as images and other static files had already been cached.

The particular numbers don’t matter, what matters is the difference between the amount of data that has been exchanged for each step (in case of navigations none at all for Silverlight). For the single steps:

And accumulated over time:

A ratio of roughly a tenth of the network utilization is quite some achievement – considering that the Silverlight application wasn’t even optimized to use local session state and caching, it should be even higher.

This should have a direct impact on the number of machines you need in your web farm. Add the fact that session state management on the client drastically reduces the demand for ASP.NET session state – usually realized with a SQL Server (Cluster) – there is yet another entry on the savings list.

On the down side is the deployment of the Silverlight plugin. For managed clients – especially if outsourcing the infrastructure comes into play – this may very well become a showstopper.

IT Management perspective…

With respect to development and maintenance, what IT Management should care about includes things like ability to deliver the business demands, development productivity, bug rates in production, costs for developer training, and so on.

Actually all areas in which Silverlight can shine, compared with other RIA technologies, and with the typical mix of web technologies as well:

  • Rich, consistent, homogenous platform
    • .NET Framework (client and server), Visual Studio, Debugger, C#
    • Reduced technology mix, less technology gaps, less broad skill demands
  • Improved code correctness and quality…
    • compiler checks, unit testing, code coverage, debugging, static code analysis, in-source-documentation, …
  • Improved architecture and code
    • Clean concepts, coding patterns, clear separation of client code, lead to better architectures
    • Powerful abstractions lead to less code (up to 50% in one project), less complexity, less errors

Customers’ voices in this area:

“between our desktop app and the website, we estimate 50% re-use of code”

“a .NET developer can pretty much be dropped into a SL project. […] This is a huge deal […]”

“As alternative for Silverlight we considered Flash. […] only Silverlight could provide a consistent development platform (.NET/C#). […]”

 

Conclusion…

Taking all this together, and considering that enterprise companies usually have the tooling and test environments (well…) readily available, this all adds up to something like the following bill:

RIA Return on Invest

Whether the bill looks the same for your company or for one particular project, of course, depends on many things. Especially nowadays with all the hubbub around HTML5 and mobile applications (without any relevant Silverlight support). But if RIA is what you need, the Silverlight will quite often yield far more benefits than any other option.

Still, you need to do your own evaluation. However, I hope to have given you some hints on what you might focus on, if you want to sell technology to the people who make platform decisions in your company.

The actual analysis was fairly detailed and customer specific. But we also prepared a neutralized/anonymized version, which we just made available for download (pdf). (Also directly at SDX.)

That’s all for now folks,
AJ.NET

kick it on DotNetKicks.com

March 12, 2011

HTML5 – Part III: The Limits

Filed under: HTML5, Silverlight, Software Architecture — ajdotnet @ 5:26 pm

Alternative title: HTML5 – Still HTML, not a RIA platform

The last post was about the chances and benefits of HTML5. But there are also some exaggerated expectations that HTML5 cannot fulfill. Mainly this concerns the term “RIA”, and the effect HTML5 will have in this area.

Or as someone wrote:

“Will HTML 5 one day make Flash, Silverlight and other plug-in technologies obsolete?” (link)

Actually this is a very regular question I have to answer. (Often enough it doesn’t come as question, but as statement. Or accusation. Sic!)

I already detailed how HTML5’s video and canvas will take over tasks that have formerly been solved by other technologies, namely Flash. And some people seem to infer that if Flash is a RIA technology, and HTML5 obsoletes Flash, then HTML5 must obviously make RIA technologies obsolete in general.

Quite wrong. Actually the fact that Flash is used for video and 2D graphics has nothing to do with Flash being a RIA technology. Flash simply happened to be able to delivering these features, both in terms of technical capability as well as broad availability. That it also happens to be a RIA technology is more or less happenstance.

But before moving on we need to clarify the terms “RIA” and “RIA technology”…

My personal definition of RIA technologies relates to the following attributes: Stateful programming model, with some kind of page model, for applications running in a browser sandbox. This includes Flash, JavaFx, Silverlight as a browser plugin (but not in its WP7-platform variation).

Wikipedia applies the terms to Flash, Java (not JavaFx! Sic!), and Silverlight. Sill, this is debatable, and a year ago even Wikipedia had a far broader definition, but in my experience this actually covers the common understanding. Curiously Adobe claims that AIR is their RIA technology, not Flash. But me, Wikipedia, and general consensus agree that Flash indeed is a valid RIA technology.

By the way: Leaving HTML+AJAX out of this picture is by no means meant to be deprecatory, it just reflects common understanding. Wikipedia actually makes the distinction based on the (lack of) necessity to install an additional software framework.

And a final tidbit: Once upon a time Microsoft advertised Silverlight as Flash replacement, addressing video and graphics, just like in the typical Flash use cases. However, even with growing adoption of the Silverlight plugin, Silverlight never became a serious competitor for Flash in that area. (This may actually have played a role in Microsoft’s commitment to HTML5…) Still, Silverlight has long outgrown this narrow definition and later versions has put more emphasis on business features.

So, let’s have a look at where HTML5 reaches its limits and where RIA technologies might kick in. I’ll look at regular web applications before moving on to RIA applications.

Web Applications

HTML5 is going to address standard demands of web applications, including those addressed today by Flash. This will have a crowding-out effect on Flash and RIA technologies in general. But once the demands go beyond being “standard”, RIA technologies will find their niche even in web applications.

On example could be premium video delivery: Some vendors will probably be eager to offer unique selling propositions in the emerging markets of WebTV and high quality HD video content (probably involving DRM).

Since Flash can no longer play the trump of being the only or the broadest available platform in this area, this will also change the picture among the RIA technologies. Especially Silverlight has been very successful in this area recently. Take the Olympic Games or maxdome.

Other examples include complex user interactions that are not feasible with canvas and script, e.g. Mazda’s car configurator, and similarly dynamic data visualizations.

Finally there is the support of additional features. RIA technology vendors certainly have shorter innovation cycles than standards bodies. This especially includes hardware support (camera, game controller, hardware accelerated animations and 3D).

These scenarios all require the user to accept the plugin – which might become a more severe issue if this necessity is less ubiquitous. Thus for the web site provider this always incurs the question whether he can compel his users to use his offering despite that nuisance, or whether he may have to provide a (perhaps simplified and less capable) HTML based version.

RIA Applications

HTML5 won’t turn HTML into a RIA technology. It doesn’t come with a new programming model, doesn’t change server side processing, page model, and postbacks, doesn’t change that fact that the HTML ecosystem really is a conglomerate of diverse technologies.

Many applications – be it multimedia, some kind of hardware dependency, or line of business – simply require the potential of rich client applications. For these, HTML simply cannot deliver what is necessary. Typical demands include:

  • Data centric applications: Large amounts of data; data input with complex validations, lists with extended feature sets, …
  • Usability: Immediate feedback (not possible with postbacks), dynamic UIs with forms built dynamically or changing depending on user input, …
  • Business features: Printing, graphical presentation, Office integration, …
  • Offline capability…
  • Connectivity: Communication patterns such as peer-to-peer, server pushes, …
  • Multimedia and hardware support: Animations, camera, microphone, multitouch, …
  • Rich platform: Stateful programming model, component model, feature rich controls, rich databinding capabilities, …

While these are certainly not the demands for typical web applications. But intranet applications and applications addressing some distinct or closed user group on the web are very well within this category. Prominent example is SAP, one can also think of WebTV portals, home banking, or other.

In the past java applets were often used to cover these demands. Recently AJAX approach have spread, but while this worked to some degree, it often falls short of meeting the demands completely. From a technical perspective, RIA technologies are the adequate choice in these scenarios. And (in my opinion), Microsoft Silverlight is currently the best technology available in that area. Adobe AIR lacks availability and adoption, Flash alone is not sufficient, and JavaFx seems to die a slow death

Conclusion

HTML5 will push RIA technologies out of their makeshift role (video and canvas). However this doesn’t affect the feasibility of employing RIA technologies on their own turf, i.e. beyond-HTML-capability demands in web applications and fully fledged RIA applications.

However, since this “pushing out of RIA technologies” mainly affects Flash, HTML5 has an interesting effect on the RIA market: Broad availability is no longer a strong USP for Flash, which is to the benefit of Silverlight. Add the hazy prospect of JavaFx and the fact that Silverlight is not only a RIA platform, but also enters devices (WP7, WebTV), and HTML5 may actually further the adoption of Silverlight – not as cross-platform tool, as it was once intended, but in all areas not covered by HTML5.

The one argument in favor of HTML5 – which no RIA technology is likely to ever achieve – is its universal availability across all platforms, even if that comes at a cost.

Where are we?

The conclusion of this little series may be as follows: The conflict, or enmity, between HTML5 and RIA that some people see (or exaggerate) doesn’t really exist. There may be a competition between HTML5 and Flash, but even that may turn out differently form what people expect.

Actually HTML5 and RIA complement each other. There are areas in which one technology certainly make more sense than the other, other areas in which there is a choice, again other areas in which a combination of both may work best; even areas in which neither is an ideal choice. E.g.…

  • A web application addressing the broadest available audience? HTML5.
  • An LOB application with high usability demands? Silverlight.
  • A mobile application addressing a broad audience? HTML5. As long as not tighter device integration is necessary, in which case one has to address several mobile OSes…

And between these black-and-white examples there’s a lot gray areas, to be decided on a case-by-case basis. And usually the important thing is not exactly which technology you favor. The important thing is to make an informed decision, aware of the pros and cons, and not solely based on political opinions of certain apologists.

That’s all for now folks,
AJ.NET

kick it on DotNetKicks.com

March 10, 2011

HTML5 – Part II: New Standard for Web Applications

Filed under: HTML5, Software Architecture — ajdotnet @ 6:35 pm

As I laid out in the first post, a lot of people talk about HTML5, but there are also a lot of misconceptions – and misguided expectations – about HTML5. So, what is HTML5, anyway? And for whom?

HTML5 is a lot of things for a lot of people. For some it is a vehicle to rid the web of patent laden video formats. For Apple it is a means to keep Flash off iPhone and iPad. Microsoft uses it to push IE9. Some people are using it to – at least try to – bury RIA. Anything else…? Oh yes, some people actually look into HTML5 technologies.

In an attempt to join the last group, here is my opinion on what HTML5 is and what it will mean.

The Standard

Formally, HTML5 is just the next version of HTML. (Period!) In terms of scope however it covers some more ground than “HTML” did before. Included is not only the markup language we know as HTML 4.1, but also the formerly distinct standards XHTML and DOM.

Given that HTML 4.0 became a recommendation in 1997 one can only say (shout!) “It’s about time!”. The fact that HTML 4.x cannot be considered “state of the art” for quite some time now is exactly the reason why browser vendors chose to implement proprietary extensions and why technologies like Flash – even ActiveX – have to fill in the gaps.

HTML5 is available as working draft (latest version today from January 2011) and all major browser venders are more or less committed to implementing it:

Regarding general support for HTML5, the industry for once agrees on something. Surprising enough. Regarding the details however, one has to be careful, which part of HTML5 is supported by which browser to what degree. It may be going to take some time – and more than one version number – until we get broad HTML5 support on all browsers.

For some time the critics gloated at the fact that HTML5 has barely reached “working draft” status and that “recommendation” status is not expected before 2022. Even if that were the case, it would have been totally irrelevant, as the industry is implementing and therefore standardizing parts of HTML5 right now. Additionally the W3C group is just now reconsidering its approach and looking for a more timely “delivery”. TODO

So far for the term, now for the content…

The Details

In the details, HTML5 is a conglomerate of different – and not necessarily related – improvements and new features. Of course this includes the two features mentioned mostly: video and 2D graphics (a.k.a. “canvas”).

Video is nothing spectacular: It simply displays a video, albeit without depending on some 3rd party plugin (namely Flash). Benefit for web developers: a standardized API based on HTML and JavaScript (rather than having to learn another technology). Benefit for the user: He can watch the video, independently on the device and plugin availability.

Canvas allows 2D graphics, even (with JavaScript) animated. This again allows (in principle) to address use cases formerly the domain of Flash. Diagrams for usage statistics, stock exchange rates, and so on. Contrary to simple (server rendered) images this could be including user interaction. This even may include more complex things, like web games; the technology is up to it, as this classic proves.

Regarding multimedia, one probably hast to mention audio support for a complete picture.

Video and canvas are mentioned quite often, probably because they constitute the use cases today most often addressed using Flash. Still, it would be unfair to reduce HTML5 to these two.

If it comes to plain old markup code HTML5 offers some improvements regarding java script control, as well as semantic tags like “header” and “footer”.

Regarding user interaction HTML5 offers new types of input fields (e.g. date picker), complete with validations (e.g. textbox with email address). Also add APIs for drag-and-drop, browser history management, and some other.

You may find this in more detail at the W3C or on Wikipedia. A nicely illustrated introduction can be found here (German, but the pictures shouldn’t need translation ;-) ).

Yet this still doesn’t conclude the list. For a complete picture one has to name topics closely related to (even if not formally part of) HTML5: CSS3, Web Storage, and (especially for mobile applications) Geolocation.

It should be noted that the recent improvements in JavaScript execution in all major browsers (well… – IE starting with IE9) also contribute to HTML5: Many of the features unfold their full potential only with scripting. It’s a fair assumption that HTML5 will cause a further growth in scripting in general, and probably the adoption of respective AJAX frameworks.

The Impact

At a closer look HTML5 is a mixture of rather different and unrelated things – none of them especially outstanding. Basically HTML is only upgraded to accommodate current state-of-the-art technologies. All together a (long overdue and therefore a little extensive) evolution, but certainly no revolution or “groundbreaking upgrade”, as some like to think.

Therefor the relevance of HTML5 is not the functionality itself. It stems from two facts:

  1. The broad support from all major browser vendors. No matter why they do it, that fact that they agree on HTML5 in such an unequivocal and joined fashion is without precedence. This will likely ensure that all browsers level on comparable features and capabilities. Which is important to break todays disparities and incompatibilities. HTML5 shows all promises of becoming a platform for the web that is state-of-the-art as well as broadly available. Something HTML has increasingly failed at in recent years.
  2. The timely appearance together with the emerging mobile ecosystem (smart phones, pads). In this area we have a far more diverse and inhomogeneous platform landscape than on desktops (iOS, Android, WP7, other mobile OSes, desktop OS adaptions). No platform has a dominance similar to Windows, thus vendors need to address more than one platform. And web applications built for mobile devices are the only feasible cross platform approach available. Even if HTML5 lacks full device integration (e.g. phone integration or multitouch), it goes a long way with web storage, geolocation, and rudimentary offline capabilities.

To conclude: HTML5 is not going to be some academic standard, it will be a true and broadly supported industry standard. Together with browser improvements, especially regarding script engines, HTML will become an adequate development platform for state-of-the-art web applications and the emerging mobile area.

For web developers HTML5 is a good thing. At least as long as the agreement among the browser vendors holds – and as long as we don’t have to wait another 10 years for the next version.

That’s all for now folks,
AJ.NET

kick it on DotNetKicks.com

March 7, 2011

HTML5 – Part I: The Hype

Filed under: HTML5, Silverlight, Software Architecture — ajdotnet @ 5:17 pm

META: This blog got a little sleepy recently. But actually I’ve been spending quite some time writing blog posts, albeit for our company blog. And I’m planning to reuse some of that content here (this post is actually the first one). Also I’ve been busy in several new areas, including WP7, and I may have something to say about those, too. So, this blog is still alive and kicking.

There’s a small hype around HTML5 for some time now. Ironically the reason were more political than for technical ones, since browsers begin to support HTML5 only just now. Be it organizational hassles, discussions about a video format, or a certain company having issues with Flash on their iPlatform. And since Microsoft has announced its decision to make HTML5 their cross platform strategy, the last big browser vendor has joined the camp.

And this is a good thing! Not only homogenizes HTML5 the web platform again, it is also the only feasible platform for cross platform development in the mobile world, which is much more diverse than our desktop eco system.

On the other hand I am regularly irritated about what people think HTML5 will be able to accomplish. Especially in the relation to RIA applications that are all but dead, according to various sources:

“HTML5, a groundbreaking upgrade to the prominent Web presentation specification, could become a game-changer in Web application development, one that might even make obsolete such plug-in-based rich Internet application (RIA) technologies as Adobe Flash, Microsoft Silverlight, and Sun JavaFX.” (link)

“Will HTML 5 one day make Flash, Silverlight and other plug-in technologies obsolete? Most likely, but unfortunately that day is still quite a way off.” (link)

“Sure maybe today, we have to rely on these proprietary browser plugins to deliver content to users, but the real innovative developers and companies are going to standard on HTML 5 and in turn revolutionize how users interact with data.  We all want faster web applications and the only way to deliver this is to use HTML 5.” (link)

To put it bluntly: HTML is no RIA technology and HTML5 is not going to change that. Thus Silverlight is a valid choice for any RIA application today, and it will be one tomorrow.

On the other hand, HTML5 is certainly going to deliver features that today are the domain of RIA technologies, namely Flash. And this will affect RIA technologies in some way.

Then how will HTML5 affect RIA? Well, I’m afraid, it’s not that simple and there is no short and sufficient answer that I’m aware of. In order to decide – probably on a case by case basis – what HTML5 can do, in which use cases HTML5 is the right answer, and in which cases RIA technologies still are the better choices, we need to take a closer look at some details…

To keep it a little more concise, I’m going to break with my usual habit of very long posts. I’m splitting the remainder into two additional not-quite-so-long posts:

Stay tuned,
AJ.NET

January 12, 2011

2010 in review

Filed under: Miscellaneous — ajdotnet @ 9:45 pm

The following post is by courtesy of wordpress. The reported content is by courtesy of my readers — in other words: YOU!

Thank you. And a happy new year.

The stats helper monkeys at WordPress.com mulled over how this blog did in 2010, and here’s a high level summary of its overall blog health:

Healthy blog!

The Blog-Health-o-Meter™ reads Wow.

Crunchy numbers

Featured image

About 3 million people visit the Taj Mahal every year. This blog was viewed about 40,000 times in 2010. If it were the Taj Mahal, it would take about 5 days for that many people to see it.

In 2010, there were 21 new posts, growing the total archive of this blog to 130 posts. There were 81 pictures uploaded, taking up a total of 2mb. That’s about 2 pictures per week.

The busiest day of the year was May 21st with 453 views. The most popular post that day was Visual Studio 2010 Architecture Edition.

Where did they come from?

The top referring sites in 2010 were forums.silverlight.net, dotnetkicks.com, forums.asp.net, google.com, and google.co.in.

Some visitors came searching, mostly for silverlight 4 validation, visual studio 2010 class diagram, visual studio 2010 architecture, visual studio 2010 modeling project, and visual studio 2010 architecture explorer.

Attractions in 2010

These are the posts and pages that got the most views in 2010.

1

Visual Studio 2010 Architecture Edition March 2009
12 comments

2

Understanding Validation in Silverlight February 2010
4 comments

3

ASP.NET 2.0 DataBinding Examined July 2006
7 comments

4

Silverlight Bits&Pieces: The First Steps with Visual State Manager January 2010
3 comments and 1 Like on WordPress.com,

5

Command line tool vs. PowerShell Cmdlet January 2008
3 comments

December 23, 2010

Visual Studio Async CTP – An Analysis

Filed under: .NET, .NET Framework, C# — ajdotnet @ 12:21 pm

OK, buckle up. This is going to be a long one, even by my standards…

During the last PDC Microsoft announced a next innovation: Async C#, currently available as CTP. There is also a respective white paper; I recommend reading it, if you need an introduction.

Just for the record, here’s what we are talking about:

This roughly translates to:

As you can see, the compiler mainly translates an await into a new task and the remainder of the method into a continuation for that task.

To tell the truth, the actual generated code looks quite different; this is semantically equal, though.

Simple enough, but that’s only a simple case. Actually there’s more:

  • If we are talking about a UI thread, the runtime ensures that the continuation runs on the UI thread as well. The task version would need to marshal the call to the UI thread explicitly, e.g. by calling Dispatcher.BeginInvoke.
  • If the wait is contained within a loop of some kind, the compiler also handles that, cutting the loop into asynchronous bits and pieces. Similarly for conditional calls.

That’s a nice set of features and there is no doubt that this approach works (there is a CTP after all). And reception within the community so far has been very positive.

However!

If this is really such a compelling feature, it should be quite easy to present a bunch of examples in which it pays off. Instead, what I found was a bunch of examples that made me wonder. Therefore I decided to put it to some…

Litmus tests…

To test whether async/await actually merits the praise, I set out to recheck and question the examples provided by various Microsoft people:

  • Soma Segar’s introduction (actually taken from the white paper mentioned above)
  • Netflix (used by Anders Hejlsberg during his PDC talk and available as sample within the CTP)
  • Eric Lippert’s discussion

Note: Examples have a tendency to oversimplify. I chose this set to overcome that effect: Soma provides a simple introduction, Netflix is more “real world”, and Eric looks at it form a language designer point of view. Three different samples, three different people, three different perspectives.

Note 2: The code I present is from my test solution (download link at the end), thus it is not exactly a citation, rather it’s complemented with my bookkeeping code. I also didn’t address every question that may arise (such as exception handling) explicitly. This post got long enough as it is.

Soma Segar’s blog

Let’s begin with Soma’s introduction, as it is the most simple one:

He provides a „conventional“ asynchronous solution, that looks… quite convoluted, actually. Note that I prepended the necessary code to synchronize the call.

code_soma_taskasproposed_a

code_soma_taskasproposed_b

And his respective solution using the async/await looks quite nice in comparison:

code_soma_withasync

Easier to write, and easier to understand, no question about that.

However: Looking at the awfully convoluted task based version, I asked myself: „Who would write such code in the first place?“.

The use case is to load some web pages and sum up their size. And to do this asynchronously, probably to avoid freezing the main thread. And the solution – awful and async/await alike – insists on getting the value for one web page asynchronously, but coming back to the UI thread to update the sum. Then starting the next fetch asynchronously, and again come back to the UI thread to update the sum.

But then, why not put the whole loop in a separate thread? The only caveat would be the marshaling of UI calls (i.e. a call to Dispatcher.BeginInvoke, which I left out here in favor of simple tracing, but it’s addressed in the next example). Somewhat like this:

code_soma_mytask

This is very close to the await/async version, nearly equally easy to write, and certainly as easy to understand. And it did not need a language addition, merely a little thinking about what it is that shall actually be accomplished.

OK, one example that didn’t really convince me.

Netflix (sample in the CTP)

The Netflix sample is part of the CTP and was also used by Anders Hejlsberg during his PDC talk. The sample solution comes with synchronous version, conventional asynchronous version, and new async/await version.

The synchronous version looks straight forward, with 43 of relatively harmless LOC for the relevant two methods (LoadMovies and QueryMovies):

code_netflix_sync_a

code_netflix_sync_b

The conventional asynchronous version – do I even have to mention it? – is in comparison an ugly little piece of code. For the sake of completeness:

code_netflix_taskasproposed_a

code_netflix_taskasproposed_b

code_netflix_taskasproposed_c

Twice as much code (85 LOC), a mixture of event handler registrations with nested lambdas and invokes. It takes considerable time to fully understand it. No one in his right mind would want to have to write this.

The async/await version – again – turns the synchronous version into a similarly straight forward looking asynchronous version:

code_netflix_async_a

code_netflix_async_b

Again the initial verdict: The async/await version looks nice and clean compared to the ugly task based version, and very similar to the synchronous one. Hail to async/await.

But again, looking at the ugly asynchronous version, I asked myself, “Who would actually write such code? And why? Masochistic tendencies?”

Let’s take a step back and look at the use case: Call a web service asynchronously to avoid freezing the UI (as the synchronous version does), update the UI with the result, and call the web service again if there is more information available.

The task based version tries to manually dismantle this loop into a sequence of asynchronous call followed by callback on the main thread to update the UI, followed again by the next asynchronous call. Add cancelation and exception handling and it is surprising that it isn’t even more ugly than it already is.

But! Why even try to dismantle the loop? Why not put the whole loop in a separate thread? Yes, that would solve the use case, and yes, it would be just as clean as the synchronous version. The only caveat is that each interaction with the UI has to be marshaled into the main thread, but I can live with that. Here it is:

code_netflix_mytask_a

code_netflix_mytask_b

I left the QueryMovies Method out for brevity, as it is similar to the synchronous version above.

Again this is very close to the await/async version, again nearly equally easy to write, and – again – certainly as easy to understand. And – again (pardon the repetition) – it did not need a language addition. Merely – ag… ok, ok – a little thinking about what it is that shall actually be accomplished.

Another example that didn’t convince me. But two is still coincidence.

Eric Lippert‘s discussion

Eric has a slightly different use case: For a list of web addresses, fetch the web page and archive it. There should be only one fetch at a time, and only one archive operation, but fetch and archive may overlap (described here). This is more about overlapping different operations, rather than avoid freezing the UI, as in the previous examples.

The synchronous version is this simple:

code_lippert_synchronous

He constructed the asynchronous version (not even mentioning async/await) as state machine, described in the post I just mentioned. I’ll spare you the reiteration this time; follow the link if you have doubts that it is far more convoluted than the simple loop above. But of course, async/await comes to the rescue:

code_lippert_withasync

Nice and simple. But can you deduce the logic behind this? I have to admit it required some mind twists on my part. Now, to make it short, here is the task version:

code_lippert_mytasks1

Not quite as simple as the async/await version, but if you look closely, it’s actually a very close translation into continuations. And… equally inefficient. You may have noticed the comments I put in there, stating that there is some unnecessary synchronization between a fetch and an earlier archive operation.

So, this time I actually went a little bit further: This is why I complemented a little test data, bookkeeping, and a nice little printout to visualize the sequence. Here’s what the async/await version (and similarly the task version) produces:

app_lippert_async

“‘f” stands for fetch, “a” for archive. The lower part shows the operations according to their start and end time. You can depict nicely how tasks follow other tasks, and how fetch and archive run in parallel. No fetch overlaps another, no archive overlaps another archive operation. Well. Have a look at line 3. See how the fetch starts after the archive in line 1 was finished? It could have started earlier, couldn’t it? Same in line 6. That’s the unnecessary synchronization I mentioned above.

A little working on the task version solves that by chaining the fetches and archives onto their respective tasks:

code_lippert_mytasks2

However, now I becomes a little more complex and hard to understand.

Going back to the drawing-board. What again is the use case? It’s actually a pipeline, with multiple stages (two in this case), each stage throttled to process only a certain amount of input values (one in this case). The cookbook solution is to put a queue in front of each stage, and have separate workers (again, in our case just one) take input from this queue, process it, and place the result in the next stages queue. Like this:

code_lippert_myqueues

Two queues of lambdas, two tasks processing these queues, the first lambda placing new entries into the second queue upon completion. If you ask me, this is way closer to the proposed use case than either the task based versions or the async/await version. And the logic behind it – intention as well as control flow –, which in this case is a little more complicated than in the previous examples, is also far easier to comprehend. And the best part: Look at the output:

app_lippert_queues

Fetch and archive start independently of each other, making the solution more effective than the async/await version. Why? Because I actually thought about the problem and the solution, rather than simply throwing asynchronicity on the code.

If anything, this example raises even more concerns than the other ones.

Verdict

Three different samples. Three times presenting some conventional task based asynchronous code – code that is rather convoluted, ugly, and hard to understand. Three times a nice async/await version that clearly makes the code nicer.

But also three times it “only” took a little thinking to come up with a far nicer task based version than the proposed convolution. Two times very close to the async/await version. The third time actually more efficient than that.

One could actually get the impression that the convoluted task based code has been deliberately made ugly in order to provide a better motivation for the new features. I wouldn’t go that far, but still, it raises some questions, as to how these examples came into being. Perhaps a back-port of what the compiler produces for async/await?

Granted, each example I examined may have its own compromises which slightly invalidates it (as is often the case with examples); had I only found one, I wouldn’t have bothered writing this post. But: One is an incident, two is coincidence, three is a trend. And I did not stumble over one example yielding a different result.

So, to summarize my concerns:

  1. I showed that the value of async/await is less compelling than presented. This does raise the question, whether it is still compelling enough to merit a language extension.

    I judge that value by its ability to making code shorter, easier to write, easier to comprehend. Or to quote Eric Lippert:

    “Features have to be so compelling that they are worth the enormous dollar costs of designing, implementing, testing, documenting and shipping the feature. They have to be worth the cost of complicating the language and making it more difficult to design other features in the future.” http://blogs.msdn.com/b/ericlippert/archive/2008/10/08/the-future-of-c-part-one.aspx

  2. The way I verified my concerns was actually to take one step back and think about the demand. I hate to think that async/await actually encourages developers to think less and in turn write less than optimal code – especially the less experienced developers who’ll have a hard time understanding the implications of those keywords in the first place.

To make that clear: I did not show anything that suggests that the async/await language feature is per se wrong. Nor did I prove that there is no use case that does not suffer from my concerns (only that Microsoft failed to present them yet – or I failed to find them).

Conclusion

Here my conclusion: I could live with concern #1, but #2 is something that gives me the creeps. There’s two things I would like Microsoft to do to make the feature work (or drop it altogether):

  1. Make more obvious what the code actually does (e.g. see the comments here for some naming suggestions – although my concern goes beyond simple naming issues).
  2. Rethink the task based samples you are basing your reasoning on. We don’t need a feature that makes convoluted code simpler; we need features that make code simple, we would write in the first place.

BTW: Whether async/await is backed into the language or not, this endeavor showed one thing quite clearly: Asynchronicity is important, and becoming even more so. And Microsoft certainly did accomplish something great with the TPL, on which all these discussions built without even mentioning it anymore. And as Reed pointed out, Tasks play a major role in the CTP as well.

Finally: Here is the download link for those who’d like to recheck my findings.

Merry Christmas!

That’s all for now folks,
AJ.NET

kick it on DotNetKicks.com

November 7, 2010

Silverlight. What if?

Filed under: .NET, .NET Framework, Silverlight, Software Development — ajdotnet @ 6:39 pm

PDC happened and Microsoft fouled up the Silverlight message big time. The talk was that Silverlight is dead on the client, based on Steve Ballmer not mentioning Silverlight, and an interview with Bob Muglia published at Mary-Jo’s blog. Actually even we got irritated emails from our own customers, whom we had just convinced that Silverlight is the right choice for RIA applications.

It took some time for Microsoft to realize what fatal message they had sent, but eventually Muglia backpedaled, and from there one it seems that every other Microsoftie and close associate came out to deny the imminent death of Silverlight. So far I’ve stumbled over:

Among the non-Microsofties where

So, just for the record: I sincerely believe that Microsoft is still very much committed to Silverlight as RIA technology for regular (read non-WP7) clients.

 

Still, as relieved as I am that this mess unfolded that way, it kept me thinking. What if? I mean, what if Microsoft actually had dropped Silverlight on the client…?

What if?

Just imagine… What would happen if Microsoft actually had changed their strategy? What if Silverlight was really dead on the client, and “only” the development platform for WP7?

  • For the vast majority of regular web applications: Nothing much would have happened. Use cases here include mostly video and advertisement. And due to the availability of the plugin this is the domain of Adobe Flash. With the advent of HTML5, and it’s coverage of video and graphics (canvas) – and none the least the backing it gets from Apple – it should have been clear to everybody with open eyes that HTML5 will be the future in that area. But that will happen at the expense of Flash, not Silverlight!

But from there it would go downhill, and Microsoft would start losing…

  • Microsoft would lose a platform for non-typical demands on the web. Demands that go far beyond what HTML5 can deliver. Complex UIs such as car configurators (Mazda), HD video streaming (maxdome). And Silverlight it gaining momentum in the market, not Flash or some other technology.
     
  • Microsoft would lose their platform for RIA applications. In this area HTML5 is of no further relevance at all, rather Adobe AIR and JavaFx are the competition. And in this area Silverlight is way ahead of the completion, both technically in terms of business features, as well as by adoption (usually intranet applications, but also SAP).
     
  • Microsoft would lose the developer base it relies on for Windows Phone 7, and with it WP7 itself. One of the big selling points for WP7 is the fact that WP7 uses the very same platform as is used for RIA, thus every developer using Silverlight instantly becomes a WP7 developer. Ironically, focusing Silverlight on WP7 would take away that advantage. Silverlight would become a platform you have to learn before doing phone development. And since WP7 is just taking off, the future not yet certain, why take the risk? Why not learn Android instead? Who would then build the apps Microsoft needs?
     
  • It gets worse: Microsoft would lose credibility, and the trust of the developer community. This is not a technology at the end of its life cycle we’re talking about. It’s a technology just beginning to take off, and a technology that they told us were strategic! A technology more and more developers are just beginning to adopt, to invest in. If Microsoft dropped Silverlight – without any warning I might add –, how would those developers react? How could they trust Microsoft to be true to what they call “strategic” in the future? I know what I would think.
     
  • Needless to say that this would affect their partners and customers in the same way. Who would invest in any platform if he cannot be sure the platform is maintained for a reasonable time (rather than being dropped at the spur of a moment). And if the vendor cannot be trusted? The platform may be as good as it wants, the first thing to care about is to protect my investments.
     
  • In the end this would include every API, every platform, every offering they have. This specially includes Azure – the very platform Microsoft is betting the company on. Which developer would work against that API? Which ISV would build his software on Azure? Which partner would counsel his customers to use Azure? Which enterprise would rely on Azure with his applications and his data? It’s a strategic platform for Microsoft, sure. But with dropping Silverlight they would just have taught us what that means.

Ultimately Microsoft could lose… Microsoft. Because at the end of the day, credibility is the most important thing. That’s what made this whole thing a marketing fiasco. Not the fact that a bunch of developers and companies sat on the wrong bandwagon. Lose credibility and you lose the company.

Now, all this is hypothetical – I hope I made that clear with my statement above. And it is also just an opinion and certainly exaggerated in some points. But it may very well be the kind of trash and FUD that Microsoft will be experiencing for some time. Which is why I believe that Microsoft will continue to have to do damage control for quite some time to come.

Yours sincerely,
AJ.NET

kick it on DotNetKicks.com

September 4, 2010

The Cost of String.Split

Filed under: .NET, .NET Framework, C# — ajdotnet @ 8:13 pm

Some code I wrote a while ago came back to haunt me. You may know the feeling.

The use case was simple: A tool chain, processing some files and spitting out others (host service descriptions as input and configuration and proxy code as output – is doesn’t really matter though). At one stage I needed to process a file line by line. And, as usually, my code was nice, clean, tested, maintainable, performing quite well, robust, and unbreakable. In one word: Just perfect. Well, until someone broke it. All he did was feeding a “slightly” larger code fragment — about 5MB file size for a corresponding text file — and he encountered OutOfMemoryExceptions. Sik!

So, what on earth could have happened here? Well, one of the least things I would have expected: string.Split and StringBuilder – despite the fact that I of course had employed them correctly, concise with the general recommendations! 

The Cost of String.Split

It turned out that string.Split trades memory for performance…. Take a string of a certain length, say 100, and split into, say, 10 parts. The result you’ll get will consist of the array (4 bytes per entry, 10 entries in our example), and the content fragments. This is roughly the same memory consumption for the result as for the input string (see also on MSDN).

Note: I‘m leaving out the overhead for internal management of strings and memory allocation in general.

That’s the memory consumption that is obvious and cannot be avoided (OK, I’ll get back to that one!). But what does String.Split add to that cost, if only temporarily?

String.Split internally creates an array of integers, with the length of the string as size. In other words for an input string of 100 characters it creates an int[100], using up 400 bytes! This array is used to remember the index of the found separator, by writing the found index at the next free position. That implies that only the first slots are actually used, the same number as the number of parts the string is split into. In our example 90 slots are simply wasted. This is a usage ratio of 10%! It would only need this array completely in the extreme case of a string only consisting of separators.

In case of StringSplitOptions.RemoveEmptyEntries and at least one empty entry, another temporary array for the result is created, add another array the size of the number of parts. Seems things can only get worse.

Once more: For a any given string as input String.Split returns something more than that as result – and on top of that it needs twice as much memory temporarily!

OK, so 100 characters, 200 bytes, produce 240 bytes result (40 bytes for the array) and 400 bytes temporarily on top. Who cares? But wait, remember the 5MB text file? The resulting string needed 10MB and the result ~11MB. Additionally ~20MB temporarily, of which only 4% – less than 1MB – where actually used. And all this is subject to the Large Object Heap. Well? Who cares now?

Mending…

Granted, that’s an extreme case. But how often did I use String.Split in other cases? How often within loops? How big where the input strings? How much unnecessary overhead and memory pressure did that introduce?

What if I could get rid of the temporary overhead? Great. What if I could even get rid of the result? Wait… what?

Matter of fact, quite often the result from String.Split is processed once, entry per entry, in a loop. And that’s what enumerators are for. So, if I had a respective implementation, instead of writing

string[] lines = text.Split(Environment.NewLine[0]);
foreach(string line in lines)
    …

I could call a method that returns an enumerator:

var lines= text.SplitString(Environment.NewLine[0]);
foreach(string line in lines)
    …

And with the lazy evaluation of enumerators I would get one part at a time. And once I’m done processing it, I drop it before going on to the next part. Granted, I still need to touch every part, but no longer all at once. When memory get’s tight, chances are all those parts are in gen 0 when the GC hits.

Meaning I would do no longer consume more than three times the memory of the input string at once. A string of 100 characters/200 bytes as input would not acquire additional 600 bytes. A 10MB string would not need additional 31MB (and only using 12MB of that anyway, subject to the LOH).

Well, I had a minute to spare… . I wrote a helper class for this post, tested to behave exactly like String.Split, so it should be possible to just replace every call to Split with the SplitString extension method, like above. You can find the code for download here.

That’s all for now folks,
AJ.NET

kick it on DotNetKicks.com

August 29, 2010

CommunicationException: NotFound

Filed under: .NET, .NET Framework, ASP.NET, C#, Silverlight, Software Development, WCF — ajdotnet @ 3:44 pm

CommunicationException: NotFound – that is the one exception that bugs every Silverlight developer sooner or later. Take the image from an earlier post:

app_error

This error essentially tells you that a server call somehow messed up – which is obvious – and nothing beyond, much less anything useful to diagnose the issue.

This not exactly rocket science, but the question comes up regularly at the Silverlight forums, so I’m trying to convey the complete picture once and for all (and only point to it, once the question comes up again – and it will!).

I’m also violating my rule not to write about something that is readily available somewhere else. But I have the feeling that the available information is either limited to certain aspects, not conveying the complete picture, or hard to come by or to understand. Why else would the question come up that regularly?

 

The Root Cause

So, why the “NotFound”, anyway? Any HTTP response contains a numeric code. 200 (OK) if everything went well, others for errors, redirections, caching, etc.; a list can be found at wikipedia. Any error whatsoever results in a different result code, say 401 (Unauthorized), 404 (NotFound), or 503 (Service unavailable).

Any plugin using the browser network stack (as Silverlight does by default) however is also subject to some restrictions the browser imposes in the name of security: The browser will only pass 200 in good cases or 404 without any further information in any other case to the plugin. And the plugin can do exactly NIL about it, as it never gets around to see the original response.

Note: This is not Silverlight specific, but happens to every plugin that makes use of the browser network stack.

Generally speaking there are two different groups of issues that are reported as errors:

  1. Service errors: The services throws some kind of exception.
  2. Infrastructure issues: The service cannot be reached at all.

Since those two groups of issues have very different root causes, it makes sense to be able to at least tell them apart, if nothing else. This is already half of the diagnosis.

 

Handling Service Errors

Any exception thrown by a WCF service is by default returns as service error (i.e. SOAP fault) with HTTP response code 500 (Internal Server Errors). And as we have established above, the Silverlight plugin never get’s to see that error.

The recommended way to handle this situation is to tweak the HTTP response code to 200 (OK) and expect the Silverlight client code to be able to distinguish error from valid result. Actually this is already backed into WCF: A generated client proxy will deliver errors via the AsyncCompletedEventArgs.Error property – if we tweak the response code that is. Fortunately the extensible nature of WCF allows us to do just that using a behavior, which you can find readily available here.

Once we get errors through to Silverlight we can go ahead and make actual use of the error to further distinguish server errors:

  1. Business errors (e.g. server side validations) with additional information (like the property that was invalid).
  2. Generic business errors with no additional information.
  3. Technical errors on the server (database not available, NullReferenceException, …).

It’s the technical errors that will reveal more diagnostic information about the issue at hand, but let’ go through them one by one…

Business errors with additional information are actually part of the service’s contract, more to the point, the additional information constitutes the fault contract:

code_declared_fault1

code_declared_fault2

These faults are also called declared faults for the very reason that they are part of the contract and declared in advance. Declared faults are thrown and handled as FaultException<T> (available as full blown .NET version on the server, and as respective counterpart in Silverlight), with the additional information as generic type parameter:

code_throw_declared

Note: There’s no need to construct the FaultException from another exception. And of course this StandardFault class is rather simplistic, not covering more fine-grained information, e.g. invalid properties – which you may need in order to plug into the client side validation infrastructure. But that’s another post.

On the client side this information is available in a similar way, and can be used to give the user feedback:

code_handle_declared

Generic business errors are not part of the service contract, hence they are called undeclared faults, and they cannot contain additional information beyond what the already got. From a coding perspective they are represented by FaultExceptions (the non-generic version, .NET and Silverlight) and thrown and handled similarly to declared faults:

code_handle_undeclared

However, the documentation states…

“In a service, use the FaultException class to create an untyped fault to return to the client for debugging purposes. […]

In general, it is strongly recommended that you use the FaultContractAttribute to design your services to return strongly typed SOAP faults (and not managed exception objects) for all fault cases in which you decide the client requires fault information. […]”

MSDN

 

That leaves arbitrary exceptions thrown for whatever reason in your service. WCF also translates them to (undeclared) faults, yet it uses the generic version of FaultException, with the predefined type ExceptionDetails. This way, any exception in the service can (or rather could) be picked up on the client:

code_handle_exception

However, while ExceptionDetails contains information about exception type, stack trace, and so on, that fault contains by default only a generic text, stating “The server was unable to process the request due to an internal error.”. This is exactly as it should be in production, where any further information might give the wrong person too much information. During development however it may make sense to get more information, to be able to diagnose these issues more quickly. To do that, the configuration has to be changed:

config_exception_debug

And now the returned information contains various details about the original exception:

app_exception_info

BTW: To complete the error handling on the client, you need to to address the situation were the issue was on the client itself, in which case the exception would not be of some FaultException type:

code_handle_client_error

This covers any exception thrown from the WCF service, provided it could be reached at all.

Alternative routes…

As I said, tweaking the HTTP response code is the recommended way to handle these errors. This is still a compromise on the protocol level to work around the browser network stack limitation. However, there are other workarounds to do that, and for the sake of completeness:

  1. Compromise on the service’s contract: Rather than using the fault contract, one could include the error information in the regular data contract. This is typical for REST style services, e.g. Amazon works that way. For my application services I am generally reluctant to make that compromise. The down side is that is doesn’t cover technical errors, but that can be remedied with a global try/catch in your service method.
  2. Avoid the browser network stack. Silverlight offers its own network stack implementation (client HTTP handling), though it defaults to using the browser stack. Using client HTTP handling, one can handle any HTTP response code, as well as offering more freedom regarding HTTP headers and methods. The downside however is, that we lose some of the features the browser adds to its network stack. Cookie handling and browser cache come to mind.

 

Handling Infrastructure Issues

If some issue prevented the service to be called at all, there is obviously no way for it to tweak the response. And unless we revert to client HTTP handling (which would be a rather drastic means, given the implications), the Silverlight client gets no chance to look at it either. Hence, we cannot do anything about our CommunicationException: NotFound.

However, by tweaking the response code for service exceptions as proposed above, we at least make it immediately obvious (if only by indirect reasoning) that the remaining CommunicationException: NotFound is indeed an infrastructure issue.

The good news is that infrastructure issues usually carry enough information by themselves. Also they appear rarely, but if they do they usually are quite obvious (including obviously linked to some recent change), affect any call (not just some), and are easily reproducibly. Hence using Fiddler one can get information about the issue very easily (even in the localhost scenario).

The fact that the issue is pretty obvious pretty fast, in turn makes it usually quite easy to attribute it to the actual cause – it must have been a change made very recently. Typical candidates are easy to track down:

  • Switching between Cassini and IIS. I have written about that here.
  • Changing some application URLs, e.g. giving the web project a root folder for Cassini, without updating the service references.
  • Generating or updating service proxies, but forgetting to change the generated URLs to relative addresses.
  • Visual Studio sometimes assigns a new port to Cassini if the project settings say “auto-assign port”, and the last used port is somehow blocked. This may happen if another Cassini instance still lingers around from the last debugging session.
  • Any change recently made to the protocol or IIS configuration.

This only get’s dirty if the change was made by some team member and you have no way of knowing what he actually changed. But since this will likely affect the whole team, you will be in good company ;-)

 

Wrap up

There are two main issues with CommunicationException: NotFound:

  1. It doesn’t tell you anything and the slew of possible reasons makes it unnecessarily hard to diagnose the root cause.
  2. It prevents legitimate handling of business errors in a WCF/SOAP conformant way.

Both issues are addressed sufficiently by tweaking the HTTP response code of exceptions thrown within the service, which is simple enough. Hence the respective WCF endpoint behavior should be part of every Silverlight web project. And in case this is not possible for some reason, you can revert to client HTTP handling.

 

Much if not all of this information is available somewhere within the Silverlight documentation. However, each link I found only covered certain aspects or symptoms, and I hope I have provided a more complete picture on how to tackle (for the last time) CommunicationException: NotFound.

That’s all fro now folks,
AJ.NET

kick it on DotNetKicks.com

August 15, 2010

A Pesky Little Silverlight Problem: The Presumptuous Scrollbar

Filed under: Silverlight — ajdotnet @ 1:54 pm

Just a small issue, but it may drive you crazy if you have to hunt it down… (it did that with me.)

I have my Silverlight application sitting on an .aspx page, occupying all real estate. I work a while. And suddenly there is this scrollbar appearing on the right side:

app_with_scrollbar

To hunt it down, I create a new Silverlight project. No scrollbar. I compare the .aspx‘’. No difference to speak of. I deconstruct the Silverlight part of my application in hope the scrollbar will disappear. It won’t.

 

Finally I stumbled by accident over the reason (which is – in retrospect – quite obvious):

Here’s the .aspx fragment that creates the Silverlight plugin:

code_with_scrollbar

Created by VS, I changed some code above this frament, and reformatted it in VS for better readability. And you know what? It’s already broken!

And I broke it by… drum-roll please… reformatting it in VS! The issue is the (irrelevant, according to any standard I’m aware of) whitespaces between the tags. Manually changing the code back to the original (closing object tag and iframe element at the end)…

code_without_scrollbar

… will solve the problem and the scrollbar is gone:

app_without_scrollbar

Just one more reason to prefer Silverlight over HTML, if you ask me!

That’s all for now folks,
AJ.NET

kick it on DotNetKicks.com

Older Posts »

Theme: Shocking Blue Green. Blog at WordPress.com.