Read serial input in C#

NET%20LogoHere’s a simple code snippet to read the serial inputs in C#. I had to use this code several times when working with arduino like devices.

Hope you’ll enjoy it.
Catch you next time and keep it bug free !

    using System;
    using System.IO.Ports;

    class Program
    {
        [STAThread]
        static void Main(string[] args)
        {
            new Program();
        }

        // Create the serial port with basic settings
        // port name, bauds, parity, packet size and stop bits.
        private SerialPort port = new SerialPort("COM3", 115200, Parity.None, 8, StopBits.Two);

        private Program()
        {
            // Called when data received through serial
            port.DataReceived += new SerialDataReceivedEventHandler(port_DataReceived);

            // Can crash if the port is already used, haven't found a way to detect it...
            try
            {
                // Start to listen
                port.Open();
            }
            catch(Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

            // Just avoid console to return
            Console.ReadKey();
        }

        private void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            // Write the incoming data
            Console.Write(port.ReadExisting());
        }
    }

Browser compatibility: Look at your market!

8Today I want to talk about a topic a bit touchy, the web browser backward compatibility. And in particular a strange behaviour: “The worldwide market share analysis followers”.

This is for me the biggest mistake in the web development when trying to figure out what to do and setup a backward compatibility plan. For the purpose of this article, I’ll take a case I personally had to face today. I’ve quickly developed with Bootstrap.js and JQuery a beautiful and reactive CV web site. It took me about 5 hours max, deployment to the Microsoft Azure cloud included. But before going live I would like to test it against different browsers to be sure about the displays. It’s okay for the Chromes, Firefox’s too, on my android tablet with integrated browser and chrome browser too, on my android samsung mobile too and then, the horror ! It totally sucks with IE 8 and lower… well… Let’s take a look at the famous “worldwide browser market shares” to figure out the impact of that. I use one of the reference analytics website, allowing me to export datas as csv and play a bit with Excel. The complete spreadsheet book is available for download at the end of this article. Here’s the world wide top 20 browsers in terms of market shares:

WWShares

Okay but who’s compatible? I’ve aggregated these market shares based on the compatibility and assuming that the ‘other’ part wasn’t compatible to face the worst case:

WWCompatible

Damn, 20%… I’ll need to take that in account… that’s pretty huge… So I’ll need to dev… STOP ! Who am I really targeting with my CV website? Well, future client and recruiters, mainly in Belgium… So let’s refine the results and take a look at the Belgian situation instead, perhaps it’s better:

BEShares BECompatible

Only 10% remaining… And now let’s refine again the analysis by testing the “others” in terms of compatibility :

BECompatibleOthers

Only 6% of possible incompatibility in the worst case… Well… That’s acceptable for me. The site will work fine in terms of content, just some features will be a bit ugly and the user experience will perhaps suck a bit, but anyway, most of the viewers will have great experience on it.

So will I spent the same amount of development time to the backward compatibility feature? Well, perhaps in the future, but it’s really not a priority.  If my target was the entire world, then yes I should, but let’s be honest, I don’t really care about Chinese or Russian recruiters. So what’s the point of these graphs excepted playing with Excel ?With this I really want to demonstrate you two things:

First, when you have to be backward compatible, don’t do it because you have to and everyone say it’s great to be, but because you have to. This point lead me to the second, always define and keep in mind your audience and don’t work based on “global datas” or techies chatting. That’s true for web development but also desktop applications, trainings, writing, everything! It sound obvious, but once again let’s be honest, who had never spend too much time on features or improvements who appears to be useless or minor once in production?

To conclude, keep that in mind: Know your target and it’s always better to develop for the future than develop for the past !

Catch you next time and keep it bug free !

You can download the Excel doc here

Truly random algorithm in C# – The chaotic user

NET%20LogoIf you’ve already use System.Random in a fine tuned app you’ve probably notice something strange. You get the same random values across sessions. Why ?
If you take a look at the code behind System.Random you’ll notice that it’s mainly based on CPU thick. If the same number of thick elapse each time you do the new/next you potentially get the same random number.
How can we put a kind of truly random, non predictable and chaotic randomness in the algo ? User mouse !
Indeed that’s perhaps the only chaotic stuff in a computer.
Some cryptographic algos use this and it’s not so hard to implement. Indeed it will work only on client app with access to the mouse object and require the user to move the mouse (or the algo will hang).

Here’s the pseudo-code algo I’ll implement :

define RealRandom := Limit += number
	sampleRate = 10 < Random < 20
	numberOfSample = 1 < Random < 10

	for(i < numberOfSample)
		// HERE COMES THE CHAOS !
		samples[i] = MousePositionY * MousePositionX;
		Wait MousePosition != datas[numberOfSample]
		Add 1 to i
		Wait sampleRate
	end

	foreach sample in samples
		returnValue += sample % limit
	end

	return returnValue % limit
end

And here’s the C# implementation.

public static class TrueRandom
{
    public static int NextRandom(int limit)
    {
        int SampleRate = (new Random()).Next(10, 20);
        int NumberOfSample = (new Random()).Next(1, 10);
        long result = 0;

        for(int i = 0; i < NumberOfSample; i++)
        {
            long sample = 0;
            do
            {
                sample = Cursor.Position.X * Cursor.Position.Y;
                Thread.Sleep(10);
            }
            while (sample == Cursor.Position.X * Cursor.Position.Y);
            result += sample % limit;
            Thread.Sleep(SampleRate);
        }

        return (int)result % limit; // Can't cause issue as limit is an integer so the modulo result will always be lower than Int32.MaxValue
    }
}

Catch you next time and keep it bug free !

Generate IIS application with Powershell based on a list

powershellHere’s another simple code snippet to create an IIS application, set the name, physical path, protocol and set the version of the runtime for the AppPool. In that case we use a list of objects representing the applications we have to create.

# First load the mgmt module
import-module webadministration 
foreach($Application in $Applications)
{
	# Check if the app is not already existing. If yes, delete it.
	if(Test-Path 'iis:\Sites\Default Web Site\'$Application.Name)
	{
		# Delete the existing application
		Remove-Item 'iis:\Sites\Default Web Site\'$Application.Name
	}
	# Create the new one
	New-Item 'iis:\Sites\Default Web Site\'$Application.Name -physicalPath $Application.Path -type Application
	# Set the protocol
	Set-ItemProperty 'iis:\Sites\Default Web Site\'$Application.Name  -Name "enabledProtocols" -Value "http,net.tcp"
}
# Set the runtime version
Set-ItemProperty 'iis:\AppPools\DefaultAppPool' -name managedRuntimeVersion -Value 'v4.0'

Catch you next time and keep it bug free !

3 ways to list installed software with Powershell

powershell Here’s 3 little code snippet to get the software installed on the local machine using powershell. Usefull when scripting setups and deployment !

Slow but really complete.

Get-WmiObject -Class Win32_Product

Based on the software in Add/Remove Programs. Fast but may miss some software.

Get-WmiObject -Class Win32Reg_AddRemovePrograms

Based on the software registering in the registry for uninstall. Fast but may miss some software.

Get-ChildItem HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall |
% {Get-ItemProperty $_.PsPath} |
where {$_.Displayname -and ($_.Displayname -match ".*")} |
sort Displayname | select DisplayName, Publisher

Catch you next time and keep it bug free !

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 !

Why is honesty and integrity a key factor ?

honesty-is-the-best-policy_o_1816195

After writting this article, I really hesitate to publish it as it sound a bit utopia, naive and strict. Myself I sometimes messed-up, but I’ve seen the clear difference once I’ve changed my behaviour. Also I’m still a bit angry about the example company as they reach an incredible level in the discipline, but well, I think it as to be written and posted.

This title can sound a bit obvious, but really, the more I go the more I realize people aren’t in business. But as they are smart, it’s evident that they’ll not tell you, on the contrary. (Did you really want to shoot you a bullet in your foot and put some citrus and salt on the plague? No, I don’t think so). But these last weeks I really started to get bored with that kind of behaviors. Let’s be clear, we can all make mistakes, I’m the first to. But when it’s a systemic and automatic behavior, it’s a real pain in the arse. Also for this article I’ll take one example without mentioning the company, but be sure, I experience tons of similar situations with others company. This article is also dedicated to the guys a bit “new to the business” as there’s not a lot of blog article on the web relating that kind of situations even if it’s very common. (and I’m not old in too, anyway)

Our great error is that we suppose mankind more honest than they are. – Alexander Hamilton

Approximately one week ago I started to get in touch with a Belgian resourcing company. I already was aware of that company and not only for good reasons. But well, sometimes the peoples tends to exaggerate a bit the situation and the job was really looking great. Firstly in contact with them for a freelance position, I explained them my will to move to an employee position for the next few months/years. They seems really comprehensive and they found me this consultant position. Screening pass alright and I immediately got an interview at the client office, first “strange” thing. I asked them to have an interview with them before, but the commercial guy, a bit harsher than the HR guy explains me that he will have a week of holiday, so he’ll ask a colleague to call me the day before. Well, I can’t ask him to cancel his holidays for me and I can understand the situation. I asked for the client job description but the answer was short: “we have privileged relationship with them, so I don’t have a clear job desc, they just sent us some keyword/requirements and trust us for the rest”. Well … I started to feel a bit uncomfortable with that, but anyway, nothing to lose and the position was really great. Week pass, I wait the day before for the phone call, nothing… To be honest, I hesitate a moment to cancel it, but the appointment was ready since a week and I don’t want to get a bad image from the client point-of-view, even if it doesn’t work now, who knows in some months/years.

At the end, this was the WORST and most EMBARRASSING moment in my short career! I arrive approximately 15minutes before the time and I learn that the person I’ll met is not the one they told me. The interview start and I present my path, after some checks the HR asked me the classical “why I think I match their needs”. Based on the few keywords they gave me one week ago I try to make an answer relying on my previous experience and then a totally unexpected question is asked: “But you’ve only worked as freelance and in Consultancy Company? You’re not interested by internal position…  Why are you here?’ And there, it really started to be strange… But I made the right choice which “saved me” in terms of image, I explained the complete situation. She goes out of the office and comes back with a beautiful well written and complete job description… I started to read it and I discover that the job they explained to me and the actual job were totally different. And that the client have sent that too to the resourcing company! But compared to what was explained by phone, not the same goals and not the same technology. The second page contained a section “why you can get from us”, from a client it’s not a usual section… I get it, it’s not as consultant but as internal employee! What’s the point of that? I understand it when I came back home, they just gave me what I want to hear to go to the client interview… But at that level it’s a kind of EPIC LIE FAIL, when you lie, try at least to make it a bit hard to verify, not like “- I can fly. – Ok so jumps from the 4th stage.” As I start feeling less and less comfortable I try to find some interest in the position, a clear “no, thanks’” is a bit hard to pronounce from my mouth and I’m still a bit stunt by this incredibly surrealistic situation. Discovering the job after having discussed the package, validated the HR, etc… After some discussions, we agree that the position really doesn’t interest me, I excuse myself for the loss of time and more important, we agree on the professionalism of the resourcing company… We exchange our visit cards, as I know someone interested for the position, and we quit on this.

” In failing circumstances no one can be relied on to keep their integrity.” –Ralph Waldo Emerson

That’s for me a typical example of “how being or not being honest can totally create or destroy your business relationship”. It was, for me, even worse than some bad experience like falsified resume based interviews (for example, people added some skills to my resume to match the needs, I let you imagine the situation when I’ve discovered that at the same time than the client). The client will never work again with the resourcing company, I will never work with too and more than that, I’ll discourage every people trying to work with them. But if they were a bit more honest from the beginning, perhaps the situation could have been slightly different. Even some well-known body shoppers/headhunters are smarter than that in their approach and I don’t have any problem with that if it’s clearly established and pro from the beginning. If they were honest, they could have won 1hours of phone call, a better image from my point of view (and I will really hunts them when I’ll hear friends of mine wanting to collaborate with) and kept a big insurance industry client and perhaps a new contract with me. And the other problem in this case is that the company start to have a really bad global image in the industry.

”The glue that holds all relationships together — including the relationship between the leader and the led — is trust, and trust is based on integrity.” –Brian Tracy

stupidationally-honest_c_186761So for me the conclusion is the following, you can have the process you want, the goals and objectives you want, the structure you want, the culture you want, anything you want, if you’re honest in your relationship, it will always be alright in the long term, just be careful to don’t mix honesty and stupidity. For example, from the employee side in negotiation process you have to know what you want and stay focused on it. And in your day-to-day relationship, there’s, for me, nothing better than a trust based relationship. You can argue that it’s not ok for every jobs and companies but you know why? I don’t want to work with company who’s looking for the professional liars, so problem solved. It’s not a magical recipe, this can’t avoid you to work with dumb ass or slavers, it’s just a tips from my point of view. I really know a lot of people lying in business relationship, but I’m pretty sure in the long term, to be crystal clear is far away better than trying to get the result whatever the way. With this attitude I’ve created a lot of great and sane relations with people, and one day or another they will be helpful, just by, even when it’s not on my direct benefit, be honest.

I believe fundamental honesty is the keystone of business. – Harvey S. Firestone

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 !

Follow

Get every new post delivered to your Inbox.

Join 228 other followers

%d bloggers like this: