如何创建唯一的激活码?

时间:2021-08-23 20:14:02

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

我尝试使用断点然后将db表更改为新结果但它没有接收

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;
}

1 个解决方案

#1


6  

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

正如Dean Ward在评论中建议的那样,您可以使用GUID作为激活密钥。

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).

我使用“GetActivationKeys”让我的解决方案与你的“GetAll”方法保持一致;但是,我可能会实现一种方法来执行数据库查询以检查密钥的存在(将所有激活密钥恢复到您的服务并不是最高性能的解决方案)。

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

生成重复GUID的可能性非常低。关于GUID的一篇很好的文章就在这里。

#1


6  

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

正如Dean Ward在评论中建议的那样,您可以使用GUID作为激活密钥。

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).

我使用“GetActivationKeys”让我的解决方案与你的“GetAll”方法保持一致;但是,我可能会实现一种方法来执行数据库查询以检查密钥的存在(将所有激活密钥恢复到您的服务并不是最高性能的解决方案)。

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

生成重复GUID的可能性非常低。关于GUID的一篇很好的文章就在这里。