The inline if statement in C# : Surprise !

NET%20LogoHi, I got a strange issue today I posted on stackoverflow.

The Issue

Here’s the situation, I’ve abstracted the name and logic to focus on the issue. Got 3 types, A, B and C. B & C have implicit operators defined to convert to A object.

public class A
{
    public static implicit operator A(B input){ /* Convert B to A */ }
    public static implicit operator A(C input) { /* Convert C to A*/ }
}

public class B { }
public class C { }

Then, when I do this, the code compile and work fine :

A myObject = null;
if (condition)
    myObject = new B();
else
    myObject = new C();

But when I write the same logic with an inline if, I got an error :

A myObject = condition ? new B() : new C();
Type of conditional expression cannot be determined because there is no implicit conversion between 'B' and 'C'

WHY ? Why does it work in classical if statement and not in inline if statement ?

The Answer

1775769

Here’s his answer :

Absolutely. The type of a conditional operator expression must either be the type of the second operand or the type of the third operand. (And if those two types aren’t the same, exactly one of the types has to be implicitly convertible to the other.) The compiler doesn’t try to find a “lower common denominator” type, and the use of the result isn’t important either (the compiler doesn’t “notice” that you’re assigning the result to a variable of type A).

You can fix this yourself by just explicitly casting either operand:

A myObject = condition ? (A) new B() : new C();

or

A myObject = condition ? new B() : (A) new C();

Note that this isn’t limited to user-defined conversion operators; the same is true for simple reference conversions based on derived classes:

Button x = new Button();
String y = "foo";
object z = condition ? x : y; // Compile-time error

See section 7.14 of the C# specification for more details.

Behind the scene

But the answer wasn’t totally complete for me. So I took my lovely decompiler and anaylyze what’s generated in the case of an inline and classical if. The code is “self explanatory” and I’ve commented each MSIL instruction to make it readable.

static void ClassicalIf(bool condition)
{
    int i = 0;
    if (condition)
        i = 1;
    else
        i = 2;
}

static void InlineIf(bool condition)
{
    int i = condition ? 1 : 2;
}

For the inline if :

.method private hidebysig static void InlineIf(bool condition) cil managed
{
    .maxstack 1
    .locals init (
        [0] int32 i)
    L_0000: nop 
    L_0001: ldarg.0         -- Load argument '0' onto the stack
    L_0002: brtrue.s L_0007 -- Branch to L_0007 if value is non-zero
    L_0004: ldc.i4.2        -- Push 2 onto the stack
    L_0005: br.s L_0008     -- Branch to L_0008
    L_0007: ldc.i4.1        -- Push 1 onto the stack
    L_0008: nop 
    L_0009: stloc.0         -- Pop from stack into local variable 0
    L_000a: ret 
}

And here’s the one for the “normal” if :

.method private hidebysig static void ClassicalIf(bool condition) cil managed
{
    .maxstack 2
    .locals init (
        [0] int32 i,
        [1] bool CS$4$0000) -- Additional bool for if
    L_0000: nop 
    L_0001: ldc.i4.0        -- Push 0 onto the stack
    L_0002: stloc.0         -- Pop from stack into local variable '0'
    L_0003: ldarg.0         -- Load argument '0' onto the stack
    L_0004: ldc.i4.0        -- Push 0 onto the stack 
    L_0005: ceq             -- Push 1 if value1 equals value2 (on stack), else push 0.
    L_0007: stloc.1         -- Pop from stack into local variable '1'
    L_0008: ldloc.1         -- Load local variable '1' onto stack.
    L_0009: brtrue.s L_000f -- Branch to L_000f if value is non-zero
    L_000b: ldc.i4.1        -- Push 1 onto the stack 
    L_000c: stloc.0         -- Pop from stack into local variable '0'
    L_000d: br.s L_0011     -- Branch to L_0011
    L_000f: ldc.i4.2        -- Push 2 onto the stack 
    L_0010: stloc.0         -- Pop from stack into local variable '0'
    L_0011: ret 
}

Now same thing with an additional cast :

static void ClassicalIf(bool condition)
{
    object i = 0;
    if (condition)
        i = new object();
    else
        i = 2;
}
    
static void InlineIf(bool condition)
{
    object i = condition ? new object() : 2;
}

For the inline if :

.method private hidebysig static void InlineIf(bool condition) cil managed
{
    .maxstack 1
    .locals init (
        [0] object i)
    L_0000: nop 				
    L_0001: ldarg.0 			-- Load argument '0' onto the stack
    L_0002: brtrue.s L_000c     -- Branch to L_000c if value is non-zero (true)
    L_0004: ldc.i4.2            -- Push 2 onto the stack
    L_0005: box int32           -- Boxing
    L_000a: br.s L_0011         -- Branch to L_0008
    L_000c: newobj instance void-- Create new object  
    L_0011: nop                                                     
    L_0012: stloc.0 			-- Pop from stack into local variable 0
    L_0013: ret 
}

And here’s the one for the “normal” if :

.method private hidebysig static void ClassicalIf(bool condition) cil managed
{
    .maxstack 2
    .locals init (
        [0] object i,
        [1] bool CS$4$0000)
    L_0000: nop 					-- Push 0 onto the stack
    L_0001: ldc.i4.0                -- Pop from stack into local variable '0'
    L_0002: box int32               -- Boxing
    L_0007: stloc.0                 -- Pop from stack into local variable 0
    L_0008: ldarg.0                 -- Load argument '0' onto the stack
    L_0009: ldc.i4.0                -- Push 0 onto the stack 
    L_000a: ceq                     -- Push 1 if value1 equals value2 (on stack), else push 0.
    L_000c: stloc.1                 -- Pop from stack into local variable '1'
    L_000d: ldloc.1                 -- Load local variable '1' onto stack.
    L_000e: brtrue.s L_0018         -- Branch to L_0018 if value is non-zero (true)
    L_0010: newobj instance void [ms-- Create new object
    L_0015: stloc.0                 -- Pop from stack into local variable '0'
    L_0016: br.s L_001f             -- Branch to L_001f
    L_0018: ldc.i4.2                -- Push 2 onto the stack 
    L_0019: box int32               -- Boxing
    L_001e: stloc.0 				-- Pop from stack into local variable '0'
    L_001f: ret 
}

Conclusion

1) So I will also try to use inline if as possible. Less instructions (so CPU) and less memory usage.
2) Also it’s now crystal clear when we see how an inline if is converted to MSIL 🙂

Catch you next time and keep it bug free !

Automatic Recovery & Restart in .Net application

NET%20LogoThe goal here is to improve the reliability of a .net client application by managing cases where things goes wrong and the universe of your product fall on himself, for example due to memory corruption, unhandled exception, Stack/Memory/<place your stuff-Overflow and so on.

The Issue

In the current situation, when you want to know if things goes wrong there’s natively nothing really in place. You can register for unhandled exception, but if for some reason your application hangs more than 60 seconds and come in the famous “Not Responding” state… well there’s not a lot of things to do. When it occurs, we could want to be able to backup some data’s, cleanly closed some connections, alert the backend, etc

The Answer

The answer is provided by the Windows API Codepack. This codepack available through NuGet package work on windows vista and higher (tested on Vista, 7 and 8, haven’t test on 8.1, ut it should too) and expose some P/Invoke calls to kernel32.dll functions (so be carefull too, when used, it’s out of the “nice pink unicorn .net land”). Once you’ve added the NuGet package reference you gain access to two “events”, Recovery and Restart. Here’s a method to register to theses.

protected override void OnStartup(StartupEventArgs e)
{
    RegisterARR();
    base.OnStartup(e);
}

private void RegisterARR()
{
    if (CoreHelpers.RunningOnVista)
    {
        // register for Application Restart
        ApplicationRestartRecoveryManager.RegisterForApplicationRestart(new RestartSettings(string.Empty, RestartRestrictions.None));

        // register for Application Recovery
        ApplicationRestartRecoveryManager.RegisterForApplicationRecovery(new RecoverySettings(new RecoveryData(PerformRecovery, null), 5000));
    }
}

For my part I put the code in the App.cs and call the register method within the OnStartup. If it’s “running on vista” which means “running on higher version than vista”, we first register to the restart event. When registering for restart we provide an instance of RestartSettings. The first parameter it gets is the command line arguments that will be used for the restart, in case we want to define some special parameters. The second parameters is an enum that allows us to restrict the restart in some cases with 5 defined states.

  • None: No restart restrictions
    NotOnCrash: Do not restart the process if it terminates due to an unhandled exception.
  • NotOnHang: Do not restart the process if it terminates due to the application not responding.
  • NotOnPatch: Do not restart the process if it terminates due to the installation of an update.
  • NotOnReboot: Do not restart the process if the computer is restarted as the result of an update.

The second thing we do is register for recovery. This means that if the application will need a restart (from the same reasons as before), what function do we want to run to allow later recovery.

When registering for recovery we supply an instance of RecoverySettings. The first parameter it gets is the RecoveryData object, which wraps a delegate to be called and some state parameter that will be passed (in this example, null). The second parameter is the keep alive interval, which will be explained shortly. The recovery function should obey some rules in order to avoid the application getting stuck (again) in the recovery function. You must call ApplicationRecoveryInProgress every few miliseconds (in the example, KeepAliveInterval = 5000). This tells the ARR mechanism, “I know it takes some time, but don’t worry, I’m still alive and working on the recovery stuff”.

private int PerformRecovery(object parameter)
{
    try
    {
        ApplicationRestartRecoveryManager.ApplicationRecoveryInProgress();
        // Perform recovery here
        ApplicationRestartRecoveryManager.ApplicationRecoveryFinished(true);
    }
    catch
    {
        ApplicationRestartRecoveryManager.ApplicationRecoveryFinished(false);
    }
    return 0;
}

And finally we just need to define an unregister method, called after the Recovery & Restart to end the process and called from the OnExit event handler of the application. (Yeah, sometimes things goes well… sometimes…)

private void UnregisterApplicationRecoveryAndRestart()
{
    if (CoreHelpers.RunningOnVista)
    {
        ApplicationRestartRecoveryManager.UnregisterApplicationRestart();
        ApplicationRestartRecoveryManager.UnregisterApplicationRecovery();
    }
}

Conclusion

That’s it, now you can face the death and tackle the hell of that kind of situation. But I want to precise some things to conclude. This mechanism doesn’t prevent your application to fall in an inconsistent state. So it means, if this mechanism is called, something really bad happened and you can’t guarantee the consistency of the memory, you should always rely on other mechanism to manage the persistence scenario when things goes wrong, work with little transaction, cache datas, provide validity flags on the database records etc. Most of the time I use it to :

1. Send a memory dump to an ftp server for further debugging
2. Report the issue in a tracking system
3. Dump the memory, check the file on reboot and try to recover the lost documents/datas and always ask the user to check the validity if he want to re-inject them in the system or avoid him to re-inject them based on automatic validation.
3. Clean connections, context, etc… We all knows server with badly managed sessions, not responding due to a massive client crash with persistent connection for whatever reason or a faulty batch/transaction process hanging due to the same reasons…

Catch you next time and keep it bug free !

Kent Beck : “I get paid for code that works, not for tests”

Ohhh...Alright...That’s perhaps the most surprising, powerful and reassuring sentence I’ve read on stackoverflow since I write code ! Kent Beck, respected authority, creator of Extreme Programming, TDD and writter of several great reference books, mainly at the great Addison-Wesley edition, have answered the following text to someone asking “how deep do you unit test”. Myself I usually break on this question as I tend to be JEST (Just Enough System Testing) in the JESA spirit (Just Enough System Analysis, great book)  from Jesa Yourden. And as I’ve started to go deep in BDD, the question was even more important as I can really quickly test stuffs but also forget to test specific dark cases that I would probably test in a more classical TDD way. So here’s the inspiring Beck’s answer :

I get paid for code that works, not for tests, so my philosophy is to test as little as possible to reach a given level of confidence (I suspect this level of confidence is high compared to industry standards, but that could just be hubris). If I don’t typically make a kind of mistake (like setting the wrong variables in a constructor), I don’t test for it. I do tend to make sense of test errors, so I’m extra careful when I have logic with complicated conditionals. When coding on a team, I modify my strategy to carefully test code that we, collectively, tend to get wrong.

Different people will have different testing strategies based on this philosophy, but that seems reasonable to me given the immature state of understanding of how tests can best fit into the inner loop of coding. Ten or twenty years from now we’ll likely have a more universal theory of which tests to write, which tests not to write, and how to tell the difference. In the meantime, experimentation seems in order.

So when that kind of ground breaking answers are made by that kind of guy… it’s always good to meditate a bit on it !

Indeed, since this answer, 5years ago, some big improvements have been made, but it’s still a great view from a inspiring person.

The original StackOverflow topic : http://stackoverflow.com/questions/153234/how-deep-are-your-unit-tests/153565#153565

Catch you next time and keep it bug free !

Noninvasive global software mocking with registry

RegEditI recently had to do something unusual for me.

The issue

In production-like environment, I had to “mock” a third party application called by mine. My application call the third party app just like as we do when we run something from command prompt with some arguments. The problem was a little bug in theses arguments, but I can’t update directly my application and had to find a workaround until I can. Also I would like at the same time to debug a bit what’s done by logging the passed arguments. So here’s the initial situation :

exereplace1

The solution

Here’s what I want to do to solve the problem :

exereplace2

Adding an intermediate application that my application will call and then forward the call to the third party app. A kind of software man-in-the-middle. But as I can’t modify my app I just can’t ask her to point to another place and the call target is not soft coded. I finally, after a day of search, found a solution, this good ol’ registry !

If you go to :

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options

You can create a registry key with the name of your app, in my case it’s ThirdPartyApplication.exe and then create a string value called Debugger with the name of the application to run instead. Each time we’ll call ThirdPartyApplication.exe, the mentioned application will be executed with the normal target as arguments. I can then call my third party app and patch the transmitted values until I can patch my application and remove the registry key.

Also it can be a good joke to do to some colleague you (don’t) like… Let’s say, replacing explorer.exe by mspaint… or making iexplore to call iexplore, resulting in a beautiful call loop… I’m sure you have enough imagination to do something a bit fun for 2 minutes the monday morning with that 😉 But never forget, the shorter jokes are the better…

Catch you next time and keep it bug free !

5 things learned in 5 years of blogging : The personas

eLogoAs said in my previous article, I would like to share some master tips I learned during these 5 years without falling in the most obvious tips like “Quality first article”. It’s not a recipe for a successful blog but I’m sure they could help you and improve your blog overall quality. This series will be composed by 5 article, here’s the first one.

Identify what’s your profile and the profiles of your readers.

That’s perhaps the most important things to do if you want to have a relatively consistent blog and that’s perhaps the most undone thing by bloggers. I’m not saying your have to be a marketing guru or act as a Mad Men actor trying to sell anything to anyone ! The goal here is to identify clearly your target, what are your goals and how to stay consistent.

Bloggers Personas

If I take a look at the well known “10 Blogging Personas to Help You Target and Focus Your Content” from John Saddington I can define my blog writer persona as a “How to” or Educational blogger. What’s the point of knowing that ? Well, once again : consistency. That mean if for example I want to start to talk about music or photography, with other blog writer persona on theses, I’ll create dedicated blogs. This blog as a purpose and clearly identifying it allow me to keep it clean. At the beginning I’ve done this error with some article about music or politic and guess what ? They are the less consulted one, not because they’re not great, just because they’re not on their right location. On my other music related blog, the exact same article bought me many viewers and comments. What if I start to explain my last travel on this blog ? Well I’m pretty sure you don’t care, and you’re right to don’t care about, you’re not here for that. That allow me to talk about the second point, your reader personas.

Readers Personas

Readers personas will allow you to improve quality of your articles. You can easily found articles about how to create persona like this one or this one.  I’ll not give you the full list of persona’s I’ve identify on this blog but one of the most important one is ‘John the .Net Developer coming from Google’. This one is +/- 80% of my total traffic. (I know it with the analytics reports, 80% of the incomes have google as referrer). He’s mainly between 20 and 30, male sex (assume that based on the Forbes article “Women in Tech: Female Developers By the Numbers”) and looking for a quick solution to a technical problem. That means I can improve my article structure and choice to match their need. The benefit for me are multiple, but the one I prefer is feeling more useful and helpful for the others !

Usage of Personas

That said I also want to precise something really important. IF YOU WANT, DO IT ! By this I mean, if I want to write an article without meeting one or more of my readers personas and outside of my writer persona, well, I’ll do it, but I’ll not except a lot from it. Also, even if you start to work in a more structured and analysed way, always make things fun ! There’s, for me, no interest in writing about something I hate just because I feel like it will give me a lot of readers or anything. Just before concluding here’s how I mentally include the usage of personas in my blog writings :

1. I want to talk about something, it’s übber cool, I feel like god and got rays of light at the end of my fingers !
2. Brainstorm or find documentation/experiment
3. Step into my article writing process (1 to 3 iterations of write -> stylize -> review -> ask external review -> patch/correct/adapt -> wait 24 min/hours/days -> review)
4. Analyse the article and verify it fit my writer persona, if not, adapt it or put it on another blog/medium, back to step 3.
5. Analyse the article to find out what could be the personas in my readers personas that could be interested in. If none, is the article relevant for my blog ? If the article is relevant and no personas, perhaps I’m talking to a new reader persona, in that case I start to create his persona sheet and add it to the others. (but it’s relatively rare 5 years). If it’s not relevant, then, I perhaps need to post it on another blog or another medium. (sometimes something is not done for blogging 😉 )
6. Polish, tag, categorize
7. Post.

For the point 4 and 5 related to personas, the check take about 10 minutes, it’s not a hard task and it’s a good security !

Conclusion

I thing I’ve give you a good overview and starting point to use personas in your daily blogging. Persona’s are at the same time easy to use and really complex as they need a lot of practice. By this I mean, unless you’re a marketing-related person, the way I and many others use personas is like the way my grandma is driving a F1, she’s driving but not at the full potential of the tool and that’s not, and for me never should be, the goal ! We’re blogging for many reason, in mine, for fun and sharing, so it’s just one of the tool I have and I consider it as that, I prefer to spend time on writing than on marketing and this activity is perhaps 10% of the time compared to the writing activity. Keep that in mind 😉

Hope you’ve enjoyed it !

See you next time for the rest of the series and keep it bug free !

Is Apple mimicking Metro UI with the new iPhone 5C and iPhone 5S ?

Apple-LogoToday, Apple show to the world their two new devices, the iPhone 5C and the iPhone 5S. There’s a lot of new technical stuff’s, sometimes interresting (64bits, fingerprint, …) sometimes not… The price cuts are also a good thing and from what I’ve understand they tend to have a kind of 3 segment strategy to cover a larger market with low cost/normal cost/high cost devices. Anyway, I’m pretty sure a lot of bloggers will share the infos, the point here is not on that. If you agree, take a look at the following pictures coming from the conference found on Wired.com article :

tumblr_msx934wSNA1si636ro1_500

tumblr_msx6i2tRfD1si636ro1_500

tumblr_msx72t6zsR1si636ro1_500

For me, Apple is now following Microsoft and NokiaLumia-like devices (property of Microsoft too since they acquire Nokia few days ago). The interface of the iOS6 start to looks like totally cleaned, the colors also remind me the Windows Phone devices… Tim Cook said : “Apple wants to make things easier and better for users. They don’t want to just pack in feature after feature.” I wanted to point that out as the situation is usually the opposite. Are the Apple’s engineers missing creativity since the death of Steve Jobs ?

Last remarks, something that totally surprise me, the Apple stock value of the day. I was expecting increases but… nop… https://www.google.com/finance?cid=22144

See you next time and keep it bug free !

New look for the 5th blog anniversary

eLogo 5 years ! I’m writting articles since 5 years at the end of this month ! Approximatively a fifth of my life. Started on blogger and 6 month later migrating to wordpress after a friend showed me this plateform. For the nonce, the blog have a totally new look I judge easier to read and a new logo (on the left). In 5 years 123 articles written, 24 categories, 363 tags, 314 different commentators, 233 images uploaded, 60 documents uploaded and a lot of fun ! During this half decade, this blog allowed me to gain a lot of experience in knowledge sharing , articles writting  and teaching. So I will certainly in the next few days or week write an article about the lessons learned about blogging during these 5 years of sharing. Also I would start to write about more “career” or “industry” stuff’s, perhaps with another media like the Medium plateform so stay tuned ! I’ve also written some articles about other languages than the classical .Net related like Prolog or Eiffel and how to use them from a .Net application, they’re just waiting for some pairs reviews and formating and will certainly be published during the next weeks 🙂 This experience was a real pleasure with a lot of evolution, fun and passion !

And the most important, thanks to you too, you’re the biggest motivation for me to continue writting and always trying to increase blog and content quality. Thanks !

See you next time and keep it bug free 😉