Random Generation of Various Types

Sorry for the lack of updates last week. I went on vacation to a spot where I was told there would be internet access... That was not the case. Anyway, I've already shown in the past how to do random string generation and even lorem ipsum generation. Today I'm building on that and showing easy ways to generate random values for various other data types including bool, enum, TimeSpan, and Color:

public class Random:System.Random
{
        /// <summary>
        /// Returns a random boolean value
        /// </summary>
        /// <returns>returns a boolean</returns>
        public bool NextBool()
        {
            if (Next(0, 2) == 1)
                return true;
            return false;
        }

        /// <summary>
        /// Gets a random enum value
        /// </summary>
        /// <typeparam name="T">The enum type</typeparam>
        /// <returns>A random value from an enum</returns>
        public T NextEnum<T>()
        {
            Array Values = Enum.GetValues(typeof(T));
            int Index = Next(0, Values.Length);
            return (T)Values.GetValue(Index);
        }

        /// <summary>
        /// Randomly generates a new time span
        /// </summary>
        /// <param name="Start">Start time span</param>
        /// <param name="End">End time span</param>
        /// <returns>A time span between the start and end</returns>
        public TimeSpan NextTimeSpan(TimeSpan Start, TimeSpan End)
        {
            if (Start > End)
            {
                throw new ArgumentException("The start value must be earlier than the end value");
            }
            return Start + new TimeSpan((long)(new TimeSpan(End.Ticks - Start.Ticks).Ticks * NextDouble()));
        }

        /// <summary>
        /// Returns a random color
        /// </summary>
        /// <returns>A random color between black and white</returns>
        public Color NextColor()
        {
            return NextColor(Color.Black, Color.White);
        }

        /// <summary>
        /// Returns a random color within a range
        /// </summary>
        /// <param name="MinColor">The inclusive minimum color (minimum for A, R, G, and B values)</param>
        /// <param name="MaxColor">The inclusive maximum color (max for A, R, G, and B values)</param>
        /// <returns>A random color between the min and max values</returns>
        public Color NextColor(Color MinColor, Color MaxColor)
        {
            return Color.FromArgb(Next(MinColor.A, MaxColor.A + 1),
                Next(MinColor.R, MaxColor.R + 1),
                Next(MinColor.G, MaxColor.G + 1),
                Next(MinColor.B, MaxColor.B + 1));
        }
}

They're all fairly simply and work well enough. The only one that may cause confusion would be the NextColor function. When you define the min/max value for the function, you're really defining the min/max for the A, R, G, and B values. So if you use black as the min and blue as the max, it will give you shades of blue only. If you use black and red, it gives you shades of red. Anyway, hopefully this will help you out a bit. So give it a try, leave feedback, and happy coding.

kick it on DotNetKicks.com   Shout it
Digg It!DZone It!StumbleUponTechnoratiRedditDel.icio.usNewsVineFurlBlinkListEmail

Posted by: James Craig
Posted on: 8/18/2009 at 1:59 PM
Tags: ,
Categories: C#
Post Information: Permalink | Comments (0) | Post RSSRSS comment feed

Lorem Ipsum Generator in C#

Every time I've created a web page design, I've used Lorem Ipsum as text placeholders. For those of you curious as to what Lorem Ipsum is, it's dummy text. If that's not enough of a description, the link earlier in the post has a better explination... Anyway, in order to use it I've generally gone online, found a generator, and used that to generate paragraphs of various lengths. To be honest, it's just too annoying (I hate to copy and paste unless I have to). To mitigate this, I created my own:

    public class Random:System.Random
    {
        /// <summary>
        /// Creates a Lorem Ipsum sentence.
        /// </summary>
        /// <param name="NumberOfWords">Number of words for the sentence</param>
        /// <returns>A string containing Lorem Ipsum text</returns>
        public string NextLoremIpsum(int NumberOfWords)
        {
            StringBuilder Builder = new StringBuilder();
            Builder.Append(StringHelper.ToFirstCharacterUpperCase(Words[Next(Words.Length)]));
            for (int x = 1; x < NumberOfWords; ++x)
            {
                Builder.Append(" " + Words[Next(Words.Length)]);
            }
            Builder.Append(".");
            return Builder.ToString();
        }

        /// <summary>
        /// Creates a Lorem Ipsum paragraph.
        /// </summary>
        /// <param name="NumberOfParagraphs">Number of paragraphs</param>
        /// <param name="MaxSentenceLength">Maximum sentence length</param>
        /// <param name="MinSentenceLength">Minimum sentence length</param>
        /// <param name="NumberOfSentences">Number of sentences per paragraph</param>
        /// <returns>A string containing Lorem Ipsum text</returns>
        public string NextLoremIpsum(int NumberOfParagraphs, int NumberOfSentences, int MinSentenceLength, int MaxSentenceLength, bool HTMLFormatting)
        {
            StringBuilder Builder = new StringBuilder();
            if (HTMLFormatting)
                Builder.Append("<p>");
            Builder.Append("Lorem ipsum dolor sit amet. ");
            for (int y = 0; y < NumberOfSentences; ++y)
            {
                Builder.Append(NextLoremIpsum(Next(MinSentenceLength, MaxSentenceLength)) + " ");
            }
            if (HTMLFormatting)
                Builder.Append("</p>");
            for (int x = 1; x < NumberOfParagraphs; ++x)
            {
                if (HTMLFormatting)
                    Builder.Append("<p>");
                for (int y = 0; y < NumberOfSentences; ++y)
                {
                    Builder.Append(NextLoremIpsum(Next(MinSentenceLength, MaxSentenceLength)) + " ");
                }
                if (HTMLFormatting)
                    Builder.Append("</p>");
                else
                    Builder.Append(System.Environment.NewLine + System.Environment.NewLine);
            }
            return Builder.ToString();
        }

        private string[] Words = new string[] { "consetetur", "sadipscing", "elitr", "sed", "diam", "nonumy", "eirmod",
        "tempor", "invidunt", "ut", "labore", "et", "dolore", "magna", "aliquyam", "erat", "sed", "diam", "voluptua",
        "at", "vero", "eos", "et", "accusam", "et", "justo", "duo", "dolores", "et", "ea", "rebum", "stet", "clita",
        "kasd", "gubergren", "no", "sea", "takimata", "sanctus", "est", "lorem", "ipsum", "dolor", "sit", "amet",
        "lorem", "ipsum", "dolor", "sit", "amet", "consetetur", "sadipscing", "elitr", "sed", "diam", "nonumy", "eirmod",
        "tempor", "invidunt", "ut", "labore", "et", "dolore", "magna", "aliquyam", "erat", "sed", "diam", "voluptua",
        "at", "vero", "eos", "et", "accusam", "et", "justo", "duo", "dolores", "et", "ea", "rebum", "stet", "clita",
        "kasd", "gubergren", "no", "sea", "takimata", "sanctus", "est", "lorem", "ipsum", "dolor", "sit", "amet",
        "lorem", "ipsum", "dolor", "sit", "amet", "consetetur", "sadipscing", "elitr", "sed", "diam", "nonumy", "eirmod",
        "tempor", "invidunt", "ut", "labore", "et", "dolore", "magna", "aliquyam", "erat", "sed", "diam", "voluptua",
        "at", "vero", "eos", "et", "accusam", "et", "justo", "duo", "dolores", "et", "ea", "rebum", "stet", "clita",
        "kasd", "gubergren", "no", "sea", "takimata", "sanctus", "est", "lorem", "ipsum", "dolor", "sit", "amet", "duis",
        "autem", "vel", "eum", "iriure", "dolor", "in", "hendrerit", "in", "vulputate", "velit", "esse", "molestie",
        "consequat", "vel", "illum", "dolore", "eu", "feugiat", "nulla", "facilisis", "at", "vero", "eros", "et",
        "accumsan", "et", "iusto", "odio", "dignissim", "qui", "blandit", "praesent", "luptatum", "zzril", "delenit",
        "augue", "duis", "dolore", "te", "feugait", "nulla", "facilisi", "lorem", "ipsum", "dolor", "sit", "amet",
        "consectetuer", "adipiscing", "elit", "sed", "diam", "nonummy", "nibh", "euismod", "tincidunt", "ut", "laoreet",
        "dolore", "magna", "aliquam", "erat", "volutpat", "ut", "wisi", "enim", "ad", "minim", "veniam", "quis",
        "nostrud", "exerci", "tation", "ullamcorper", "suscipit", "lobortis", "nisl", "ut", "aliquip", "ex", "ea",
        "commodo", "consequat", "duis", "autem", "vel", "eum", "iriure", "dolor", "in", "hendrerit", "in", "vulputate",
        "velit", "esse", "molestie", "consequat", "vel", "illum", "dolore", "eu", "feugiat", "nulla", "facilisis", "at",
        "vero", "eros", "et", "accumsan", "et", "iusto", "odio", "dignissim", "qui", "blandit", "praesent", "luptatum",
        "zzril", "delenit", "augue", "duis", "dolore", "te", "feugait", "nulla", "facilisi", "nam", "liber", "tempor",
        "cum", "soluta", "nobis", "eleifend", "option", "congue", "nihil", "imperdiet", "doming", "id", "quod", "mazim",
        "placerat", "facer", "possim", "assum", "lorem", "ipsum", "dolor", "sit", "amet", "consectetuer", "adipiscing",
        "elit", "sed", "diam", "nonummy", "nibh", "euismod", "tincidunt", "ut", "laoreet", "dolore", "magna", "aliquam",
        "erat", "volutpat", "ut", "wisi", "enim", "ad", "minim", "veniam", "quis", "nostrud", "exerci", "tation",
        "ullamcorper", "suscipit", "lobortis", "nisl", "ut", "aliquip", "ex", "ea", "commodo", "consequat", "duis",
        "autem", "vel", "eum", "iriure", "dolor", "in", "hendrerit", "in", "vulputate", "velit", "esse", "molestie",
        "consequat", "vel", "illum", "dolore", "eu", "feugiat", "nulla", "facilisis", "at", "vero", "eos", "et", "accusam",
        "et", "justo", "duo", "dolores", "et", "ea", "rebum", "stet", "clita", "kasd", "gubergren", "no", "sea",
        "takimata", "sanctus", "est", "lorem", "ipsum", "dolor", "sit", "amet", "lorem", "ipsum", "dolor", "sit",
        "amet", "consetetur", "sadipscing", "elitr", "sed", "diam", "nonumy", "eirmod", "tempor", "invidunt", "ut",
        "labore", "et", "dolore", "magna", "aliquyam", "erat", "sed", "diam", "voluptua", "at", "vero", "eos", "et",
        "accusam", "et", "justo", "duo", "dolores", "et", "ea", "rebum", "stet", "clita", "kasd", "gubergren", "no",
        "sea", "takimata", "sanctus", "est", "lorem", "ipsum", "dolor", "sit", "amet", "lorem", "ipsum", "dolor", "sit",
        "amet", "consetetur", "sadipscing", "elitr", "at", "accusam", "aliquyam", "diam", "diam", "dolore", "dolores",
        "duo", "eirmod", "eos", "erat", "et", "nonumy", "sed", "tempor", "et", "et", "invidunt", "justo", "labore",
        "stet", "clita", "ea", "et", "gubergren", "kasd", "magna", "no", "rebum", "sanctus", "sea", "sed", "takimata",
        "ut", "vero", "voluptua", "est", "lorem", "ipsum", "dolor", "sit", "amet", "lorem", "ipsum", "dolor", "sit",
        "amet", "consetetur", "sadipscing", "elitr", "sed", "diam", "nonumy", "eirmod", "tempor", "invidunt", "ut",
        "labore", "et", "dolore", "magna", "aliquyam", "erat", "consetetur", "sadipscing", "elitr", "sed", "diam",
        "nonumy", "eirmod", "tempor", "invidunt", "ut", "labore", "et", "dolore", "magna", "aliquyam", "erat", "sed",
        "diam", "voluptua", "at", "vero", "eos", "et", "accusam", "et", "justo", "duo", "dolores", "et", "ea",
        "rebum", "stet", "clita", "kasd", "gubergren", "no", "sea", "takimata", "sanctus", "est", "lorem", "ipsum" };
    }

 

 

    public static class StringHelper
    {
        /// <summary>
        /// Takes the first character of an input string and makes it uppercase
        /// </summary>
        /// <param name="Input">Input string</param>
        /// <returns>String with the first character capitalized</returns>
        public static string ToFirstCharacterUpperCase(string Input)
        {
            if (string.IsNullOrEmpty(Input))
                return null;
            char[] InputChars = Input.ToCharArray();
            InputChars[0] = char.ToUpper(InputChars[0]);
            return new string(InputChars);
        }
    }

The first class is the actual random Lorem Ipsum generator and there are two options. The first simply generates a sentence. The second actually generates a number of paragraphs. It uses, for the most part, proper capitalization but punctuation is hit or miss (let alone the fact that each word is random so if you know Latin, the sentences will definately be nonsensical). Also, the word list I was lucky enough to find here. I would have used his code as well but it didn't offer the flexibility that I wanted (nor the html markup). The second class is simply a string helper function. It takes the first letter in the input string and capitalizes it. That's all the function is there for. Anyway, I hope this helps out someone. So try it out, leave feedback, and happy coding.

kick it on DotNetKicks.com   Shout it
Digg It!DZone It!StumbleUponTechnoratiRedditDel.icio.usNewsVineFurlBlinkListEmail

Posted by: James Craig
Posted on: 2/2/2009 at 3:16 PM
Tags: , ,
Categories: C# | Web Design
Post Information: Permalink | Comments (1) | Post RSSRSS comment feed

Random String/Password Generation in C#

I'm guessing that someone out there has been in my position at some point in time... Basically I needed a password generator for a web site that I'm working on. I've seen a number of password generators out there and to be honest, I'm not a big fan of most of them. At the same time I couldn't use the default membership providers (long story as to why not). So basically I was stuck finding a way to generate my own random passwords (not to mention my own membership provider).

It's not a difficult task mind you, just annoying. That being said, I came up with the following class:

    public class Random:System.Random
    {
        public Random()
            : base()
        {
        }

        public Random(int Seed)
            : base(Seed)
        {
        }

        public string NextString(int Length)
        {
            if(Length<1)
                return "";
            StringBuilder TempBuilder=new StringBuilder();
            while(TempBuilder.Length<Length)
            {
                TempBuilder.Append(Convert.ToChar(Convert.ToInt32(Math.Floor(94*NextDouble()+32))));
            }
            return TempBuilder.ToString();
        }

        public string NextString(int Length,string AllowedCharacters)
        {
            if (Length < 1)
                return "";
            StringBuilder TempBuilder = new StringBuilder();
            Regex Comparer=new Regex(AllowedCharacters);
            while (TempBuilder.Length < Length)
            {
                string TempValue = new string(Convert.ToChar(Convert.ToInt32(Math.Floor(94 * NextDouble() + 32))), 1);
                if(Comparer.IsMatch(TempValue))
                    TempBuilder.Append(TempValue);
            }
            return TempBuilder.ToString();
        }

        public string NextString(int Length, string AllowedCharacters,int NumberOfNonAlphaNumericsAllowed)
        {
            if (Length < 1)
                return "";
            StringBuilder TempBuilder = new StringBuilder();
            Regex Comparer = new Regex(AllowedCharacters);
            Regex AlphaNumbericComparer=new Regex("[0-9a-zA-z]");
            int Counter = 0;
            while (TempBuilder.Length < Length)
            {
                string TempValue = new string(Convert.ToChar(Convert.ToInt32(Math.Floor(94 * NextDouble() + 32))), 1);
                if (Comparer.IsMatch(TempValue))
                {
                    if (!AlphaNumbericComparer.IsMatch(TempValue) && NumberOfNonAlphaNumericsAllowed > Counter)
                    {
                        TempBuilder.Append(TempValue);
                        ++Counter;
                    }
                    else if (AlphaNumbericComparer.IsMatch(TempValue))
                    {
                        TempBuilder.Append(TempValue);
                    }
                }
            }
            return TempBuilder.ToString();
        }
    }

This class has three functions that it adds to the Random classes normal ones (NextDouble, etc.). The one that is probably of most interest is going to be the last one. That function takes in the length of the string that you want, a regular expression stating what characters are allowed, and the number of non alpha numeric characters. So for instance calling the function with this:

NextString(10,"[0-9a-zA-Z_]",1);

That would create a random string of 10 characters that contained letters, numbers, and up to one underscore. The other functions are similar but with less control. For instance the one that just takes the length will use all characters on the ASCII table from 32 (space) up to 126 (~). But you can use this for quite a few items, passwords, testing, blog post generation when you're extremely bored and lazy... The list is rather endless... Anyway, I hope this helps someone out, so try out the code, leave feedback, and happy coding.

kick it on DotNetKicks.com   Shout it
Digg It!DZone It!StumbleUponTechnoratiRedditDel.icio.usNewsVineFurlBlinkListEmail

Posted by: James Craig
Posted on: 11/24/2008 at 11:27 AM
Tags: , , ,
Categories: ASP.Net | C#
Post Information: Permalink | Comments (0) | Post RSSRSS comment feed