Tag Archives: random

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)
		samples[i] = MousePositionY * MousePositionX;
		Wait MousePosition != datas[numberOfSample]
		Add 1 to i
		Wait sampleRate

	foreach sample in samples
		returnValue += sample % limit

	return returnValue % limit

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;
                sample = Cursor.Position.X * Cursor.Position.Y;
            while (sample == Cursor.Position.X * Cursor.Position.Y);
            result += sample % limit;

        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 !

Events fantôme et interop office

Je développe actuellement une application ou j’ai besoin d’intégrer l’éditeur de dessin Visio et, entre autre, m’abonner a certains événements. Seul soucis, l’évènement survient de manière aléatoire. Après quelques heures de recherche et l’écriture d’un wrapper de COM event qui a donné le même résultat, j’ai trouvé ceci sur un forum concernant un problème d’event dans outlook.

The reason is: “GC collect the .NET object, whichc wrapps COM object from Outlook )”. The solution is hold reference to this .NET object.

La solution, simplement garder une référence sur l’objet. Dans mon cas, ma page Visio dans un attribut privé 😀