Question

I am trying to create a unique activation code that doesn't already exist in the database. My question is how can I test this?

I tried using a breakpoint then changing the db table to the new result but it doesn't pick up

private string CreateActivationCode()
{
    string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    Random random = new Random();
    string result = new string(
        Enumerable.Repeat(chars, 4)
                  .Select(s => s[random.Next(s.Length)])
                  .ToArray());

    IEnumerable<string> existingActivationKeys = _mobileDeviceService.GetAll().Select(x => x.UsageKey).ToList();

    if (existingActivationKeys.Contains(result))
    {
        //USE GO TO????
        CreateUsageKey();
    }

    return result;
}
Was it helpful?

Solution

As Dean Ward suggested in his comment, you could instead use a GUID as your activation key.

An example of how this could be done is as follows:

private string CreateActivationKey()
{
    var activationKey = Guid.NewGuid().ToString();

    var activationKeyAlreadyExists = 
     mobileDeviceService.GetActivationKeys().Any(key => key == activationKey);

    if (activationKeyAlreadyExists)
    {
        activationKey = CreateActivationKey();
    }

    return activationKey;
}

I've used "GetActivationKeys" to keep my solution in-line with your "GetAll" method; However I'd probably implement a method to perform a database query to check for the existence of a key (bringing back all the activation keys to your service is not the most performant solution).

The likelihood of generating a duplicate GUID is very low. A nice article about GUIDs is here.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top