Creating Random Names and Dates
Often, website demos are more compelling when using a copy of production data. However, my current client has no production data. Nonetheless, I want to give them a realistic view of my work. So I needed to create a great deal of realistic looking data.
I began by creating random Customer objects. For the first and last names I could have created random strings. But this particular client would be distracted by the random character names. Silly I know, but that’s my reality sometimes. First names are often either female or male, so the firstnames collection is an IDictionary
using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using JCS.Model; namespace LoadTestData { internal class Program { private static readonly string connection = ConfigurationManager.ConnectionStrings["XXXAAA"].ConnectionString; // class variables so they can be used for other names, e.g. parent names private static readonly Dictionary<string, char> firstnames = new Dictionary<string, char> {{"Troy", 'M'},{"Jamal", 'M'},{"Alicia", 'F'},{"Gabriel", 'M'},{"Christian", 'M'}, {"Benjamin", 'M'},{"Gavin", 'M'},{"Jose", 'M'},{"Brandon", 'M'},{"Dylan", 'M'}, {"Victoria", 'F'},{"Savannah", 'F'},{"Riley", 'F'},{"Hailey", 'F'},{"Nevaeh", 'F'}, {"Lily", 'F'},{"Kandis", 'F'},{"Dominique", 'F'}}; // class variables so they can be used for other names, e.g. parent names private static readonly List<string> lastnames = new List<string> {"Scott","Stewart","Sanchez","Morris","Rogers","Reed","Cook", "Morgan","Bell","Murphy","Rivera","Ward","Peterson", "Watson","Brooks","Bennett","Wood","Henderson","Jenkins","Sanders","Cox"}; static void Main() { Random random = new Random(DateTime.Now.Millisecond); DateTime minCustomerDOB = new DateTime(1940, 1, 1); DateTime maxCustomerDOB = new DateTime(1989, 1, 1); string firstname = firstnames.RandomKey(random); var customer = new Customer { FirstName = firstname, LastName = lastnames.RandomElement(random), Gender = firstnames[firstname], DOB = minCustomerDOB.RandomDate(maxCustomerDOB, random) }; using (var context = new JCSDBDataContext(connection)) { context.Customers.InsertOnSubmit(customer); context.SubmitChanges(); } } } public static class Extensions { static public TKey RandomKey<TKey, TValue>(this Dictionary<TKey, TValue> dictionary, Random random) { int i = random.Next(0, dictionary.Count - 1); return dictionary.ElementAt(i).Key; } static public T RandomElement<T>(this List<T> list, Random random) { int i = random.Next(0, list.Count - 1); return list.ElementAt(i); } static public DateTime RandomDate(this DateTime min, DateTime max, Random random) { int days = (max - min).Days; // use absolute value in case max is lesser than min int i = random.Next(Math.Abs(days)); DateTime ranDate = min.AddDays(i); //maybe the max date is actually lesser than the min date. if (max < min) ranDate = max.AddDays(i); return ranDate; } } }