Toying around with F# Queries, Rx, Portables Libraries, Windows [Phone] 8 and the Zip operator

By jay at January 02, 2013 22:42 Tags: , , ,

Agreed, that’s a lot of keywords. Yet, they fit one another in a very interesting way.

I find more and more that F#, particularly regarding the way my development trends are going, is getting more and more of a fit regarding the immutability and flexibility needs.

Given that, I thought I’d give a try at running some F# Query Expressions using custom Rx operators, on Windows Phone 8, using Portable Libraries.

More...

DataBinding performance in WinRT and the Bindable attribute

By jay at November 26, 2012 20:51 Tags: , , , ,

tl;dr: The Bindable attribute can be placed on standard C# classes in Metro Apps to make them appear in the generated IXamlMetadataProvider class, to create static metadata. This technique allows for a 10% increase in data-binding performance over reflection based binding, but also adds a temporary cost in JITting, until Windows generates native images 24 hours later.

Databinding in WPF/WinRT is very easy to use. Just put the name of the field you want to bind, set the DataContext, and voila, it is displayed on screen. Yet, this is a tricky feature under the hood. It relies on the presence of an arbitrary string that may exist in the current DataContext to get the data to be displayed.

In WPF and Silverlight, this is fairly easy to do because everything is in managed code. Resolving that data member was performed using a bit of type Reflection, where the string "{Binding SomeValue}" would result in a sequence of Type.GetProperty to get a PropertyInfo instance, then call GetValue to get the actual value.

But in WinRT, all this is a lot different, mainly because WinRT is purely native and there is no reflection or metadata there.

More...

Reducing apps startup time with Pre-JITing and NGEN on a Surface RT

By jay at November 24, 2012 21:13 Tags: , , , , ,

TL;DR: The JIT can take over a third of the startup time of a managed Metro App, and using Native Image Generation (NGEN) can greatly improve the startup time of these apps. There is also a way to check for these native images to act accordingly.

 

A while back, I’ve had the chance to work with the guys that are behind the Pre-JIT feature of the CLR 4.5 for Metro Apps. Back then, I was only able to work on x86/x64 architectures, as ARM/Windows RT devices were not available.

Now that the Surface RT devices are available, we’re facing quite a few challenges in terms of code execution performance, and I’m going to discuss a few tips and tricks about the Managed Code JIT on Windows RT.

 

Profiling a slow starting app on a Surface RT

Running apps on the Surface can be troubling. Having an app that is useable after 16 to 18 seconds is definitely not acceptable, let alone the fact that the Splash Screen can disappear after 6 to 8 seconds.

Profiling such an app that starts slowly is very interesting, when looking a the Visual Studio profiler, where during these 17 seconds, about a third is spent in a “clr.dll” module in exclusive time (time spent only in this module and not its descendants). This is a very big number.

This time is actually spent in the JIT, where big methods tend to take more time to be JITed, sometimes on the UI thread, making the app sluggish.

More...

Of Static Code Analysis, CA0001, WinMD files and C# Dynamic in Metro Style apps

By jay at October 27, 2012 12:42 Tags: , , , ,

tl;dr: This article is about working around an FxCop internal bug using the C# dynamic keyword, not exactly the way is was supposed to be used.

 

With the release of Windows 8 and WinRT, developing in .NET requires adding references to the new WinMD file format.

This format is a .NET assembly look-alike, so look-alike that old ILDASM builds can open them.

These files are only containing stubs, the definition of types that come from WinRT, which is developed using native C++ code.

 

WinMD files and Static Code Analysis

FxCop is working rather fine with WinMD files in Metro style apps, except for one interest case, when compiling the following code :

private static void SomeMethod()
{
   var b = new Button();
   b.Command = null;
}

Which fails with the following exception when analyzed by FxCop, using the “Microsoft Managed Recommended Rules”:

CA0001 : Rule=Microsoft.Reliability#CA2002, Target=App.MainPage.#SomeMethod() : The following error was encountered while reading module 'App3': Could not resolve member reference: [Windows, Version=255.255.255.255, Culture=neutral, PublicKeyToken=null] Windows.UI.Xaml.Controls.Primitives.ButtonBase::put_Command.

The reason for this is rather obscure though. It seems that FxCop is trying to analyse the declarative security attributes of WinMD exposed methods, but fails to do so… Which is ironic since these attributes cannot be used in Metro style apps :) But still, this is a multi-framework analysis engine.

Unfortunately, there seem to be no way to put an ignore directive, or supression attribute for this kind of internal error so fixing this, until this gets resolved by Microsoft, requires a bit of a hack.

 

A CA0001 workaround and the Dynamic keyword

The problem here is that FxCop tries to analyze the code, and finds the put_Command() method and tries to analyse it. The goal here is to get the code compiled and executable, while having FxCop ignore it.

Here’s how to do it :

private static void SomeMethod()
{
   #if DEBUG
   var b = new Button();
   #else
   dynamic b = new Button();
   #endif

   b.Command = null;
}

I do agree with you, really. This is not a particularly pretty code, and may not be that fast to execute, but it does the trick to still have Static Code Analysis running to catch all other possible code issues.

Having a dynamic variable in Release configuration, where FxCop is executed, allows to hide the call to put_Command() as a string generated by the C# compiler, while maintaining it original meaning.

Here's what actually generated by the compiler, to evade FxCop scrutiny :

object b = new Button();
if (MainPage.o__SiteContainer0.<>p__Site1 == null)
{
   MainPage.o__SiteContainer0.<>p__Site1 = CallSite>.Create(Binder.SetMember(CSharpBinderFlags.None, "Command", typeof(MainPage), new CSharpArgumentInfo[]
   {
      CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null), 
      CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.Constant, null)
   }));
}
MainPage.o__SiteContainer0.<>p__Site1.Target(MainPage.o__SiteContainer0.<>p__Site1, b, null);

Having the code compiling using an actual static typing in Debug configuration leaves a bit of compile-time type checking, nonetheless.

There should be a connect entry for this soon, if you'd like to follow-up.

Happing dynamic hacking ! :)

C# Async Tips and Tricks, Part 3: Tasks and the Synchronization Context

By jay at September 29, 2012 21:12 Tags: , , , , , , , ,

TL;DR: It is possible to mix C# async and basic TPL style programming, but when doing so, the synchronization context capture feature of C# async is not forwarded to TPL continuations automatically, making UI dependent (and others) code fail and raise exceptions. This can lead to the termination of the process when exceptions are not handled properly, particularly in WinRT/C# apps.

 

I’ve discussed in a previous article of this series, the relation between async Task/Void methods and the ambient SynchronizationContext.

Just as a simple reminder, when executing a async method, whether it is Task, Task<T> or Void returning, the caller’s SynchronizationContext is captured to ensure that all the code in an async method is executed in the same context. The main scenario for this is to easily execute UI bound code in an async method.

It is important to remember that async methods are based on the TPL framework, and that async methods (except in infamous async void) return System.Threading.Tasks.Task instances.

More...

An update to @matthieumezil, Rx and the FileSystemWatcher

By jay at August 26, 2012 20:52 Tags: , , , , , , ,

@MatthieuMEZIL is a fellow MVP and friend of mine, and back in february at the MVP summit we shared our mutual interests with Rx on my side, and Roslyn on his side.

I’ve yet to blog about Roslyn, (even though a blog post is in preparation) but he started using Rx and is a bit blogging about it.

Now, Rx is a tricky beast and there are many ways to do the same thing. I’ve promised Matthieu I’d give him a few tricks on how to improve his code. Now that I do have a bit of time, here it is.

More...

C# Async Tips and Tricks Part 2 : Async Void

By jay at July 08, 2012 17:05 Tags: , , , , , , ,

TL;DR: This article discusses the differences between async Task and async void, and how async void methods and async void lambdas, used outside the DispatcherSynchronizationContext, can crash the process if exceptions are not handled.

You can also read the part 3, Tasks and the Synchronization Context.

In the first part of the series, we discussed the behavior of async methods. The second part discusses how async Task and async void methods can differ in behavior, while seemingly being similar.

 

Authoring Async Methods

Async methods can be authored in three different ways:

async Task MyMethod() { }

which creates a method that can be awaited, but does not return any value,

async Task<T> MyReturningMethod { return default(T); }

which creates a method that can be awaited, and returns a value of the type T,

async void MyFireAndForgetMethod() { }

which is allows for fire and forget methods, and cannot be awaited.

You may be wondering why there are two ways to declare a void returning method. Read on.

More...

C# 5.0 Async Tips and Tricks, Part 1

By jay at June 18, 2012 21:22 Tags: , , ,

Cet article est aussi disponible en francais.

TL;DR: This article is a discussion about how C#5.0 async captures the executing context when running an async method, which allows to easily stay on the UI Thread to access UI elements, but can be problematic when running CPU-bound work. Off of the UI thread, an async method may jump from thread to thread, breaking thread context dependent code along with it.

You can also read : Part 2, Async void 

C# 5.0 has introduced, language-wise, just two of new features (async and caller information) and a gotcha fix (a lambda lifted foreach loop variable scope change).

The biggest addition though, in terms of compiler magic, is the addition async. It’s been covered all over the place, and I will just comment the addition feature by itself, and the impacts it has when using it.

This article is the first of a small series about some C# async tricks and gotchas that I will try to cover to give a bit of insight, and hopefully help developers avoid them.

More...

No Threads for you ! (in metro style apps)

By jay at March 17, 2012 13:06 Tags: , , , , , , ,

Cet article est disponible en francais.

As would say this guy, since you’ve most probably been using threads the wrong way (as Microsoft seems to think), you won’t be able to use the Thread class anymore in Metro Style applications. The class is simply not available anymore, and neither are Timer or ThreadPool.

That may come a shock to you, but this actually makes a lot of sense. But don’t worry, the concept of parallel execution is still there, but it takes the form of Tasks.

 

Why using Threads is not good for you

Threads are very powerful but there are a lot of terrible gotchas that come with it :

  • Unhandled exceptions in threads handlers, either raised from a Timer, a Thread or ThreadPool thread, lead to the termination of the process
  • Using Abort is quite bad for the process, and should be avoided
  • People tend to use Thread.Sleep to arbitrarily wait for some constant time that will most probably be incorrect, and that will waste CPU resources to manage a thread that does not do anything while it waits,
  • People tend to come up with complex designs to chain operations on threads, which most of the time fail miserably.

There are some more, but these a main scenarios where using Threads fall short.

More...

Windows 8 Event Viewer’s Immersive-Shell and Metro Style apps

By jay at March 16, 2012 20:41 Tags: , , , , , , , ,

TL;DR: This article talks about an app startup error that can happen with Metro Style apps in Windows 8, how the presence of an app.config file can prevent the app from starting and how the Windows event log viewer’s new Immersive-Shell section can help.

 

The Windows 8 Metro style Xaml/C# application development is an interesting experience.

Since .NET is merely on top of a WinRT and its native structure, you’re left in a bit of a darkness sometimes, when it comes to debugging problems that come from WinRT.

Silverlight and Windows Phone also have their fair share of blind issues of this kind, either by having the application that exits with no apparent reason (when it is in fact a StackOverflow) or because you’ve set two namespaces names with the same content.

You’ve basically left at guessing, particularly on Windows Phone and Silverlight for the desktop, and if you’re lucky enough you’re having a error code that specific enough so that you can narrow your solution to a dozen google can find for you. If you’re not, well you’ve got a E_ERROR. Fail, as they say.

Windows 8 is actually a bit better at that, because of the Event Viewer. There’s a lot of details that appear there, and it’s very informative.

More...

About me

My name is Jerome Laban, I am a Software Architect, C# MVP and .NET enthustiast from Montréal, QC. You will find my blog on this site, where I'm adding my thoughts on current events, or the things I'm working on, such as the Remote Control for Windows Phone.