Develop your own random number generator module

  • Homepage
  • Software
  • Thoughts and Ideas
  • Photos and Art
  • Contact

The development of a random number generator module is even more simpler than the development of a password generator module. You only need to create a class that inhertis from the base class RandomNumberGenerator and implements the method GetRandomNumber. This method is responsible for returning a random number between 0 and the passed number. Please note that the random number needs to be equal or greater than 0 and less than the passed number. The random number must not be equal or greater than the passed number.

Please note that the following example isn't a random number generator. It always returns the numbers one after the other from 0 to the passed number. If it reaches the passed number it starts again at 0.

The method GetRandomNumber expects a number as parameter, that defines the upper bound of the random number.

using System;
using CAM.PasswordGeneratorLibrary;

namespace CustomRandomNumberGeneratorSample
{
 public class CustomRandomNumberGenerator : RandomNumberGenerator
 {
  private int number = 0;

  public override int GetRandomNumber(int maxValue)
  {
   if(number >= maxValue)
    number = 0;

   int numberTemp = number;

   number++;

   return numberTemp;
  }
 }
}

The random number generator module needs to be registered in the *.config file. This is done in the "RandomNumberGenerators" element. Here you need to add an element with the name "add". With the attribute "key" you give the random number generator module a name and with the attribute "value" you need to specify the name of the class and the assembly in which the class is contained.

<CAM.PasswordGeneratorLibrary>
 <RandomNumberGenerators>
  ...
  <add key="CustomRandomNumberGenerator" 
       value="CustomRandomNumberGeneratorSample.CustomRandomNumberGenerator, 
        CustomRandomNumberGeneratorSample" />
 </RandomNumberGenerators>
</CAM.PasswordGeneratorLibrary>

Now you can activate the new random number generator with the name "CustomRandomNumberGenerator" either with the "RandomNumberGenerator" attribute of the "PasswordGeneratorDefaults" element in the *.config file, or by changing the property RandomNumberGeneratorFactory.Instance.RandomNumberGenerator.

© Christoph A. Müller - Contact/Imprint - Privacy