Auto Increment / Identity Custom Field Type

2019-05-30 17:35发布

问题:

I am currently implementing a system where there are user generated items, we can call them Orders. I would like to have a field (non-GUID) that is easy for customers to say over the phone or to write down that represents their order. The field should be simple and unique which made me think of an identity field. Can a portion of the item's GUID, say 10 characters, be unique enough? How can a unique field like this be implemented in Sitecore?

GUIDs are alpha-numeric which is fine for my situation, but are too long. Currently I am doing so an example could be 103143317 (Store 103, at 2:33.17pm)

Version: Sitecore 6.6

回答1:

You can use the following code:

static string uniqueCode()
{
    string characters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#";
    string ticks = DateTime.UtcNow.Ticks.ToString();
    var code = "";
    for (var i = 0; i < characters.Length; i += 2)
    {
        if ((i + 2) <= ticks.Length)
        {
            var number = int.Parse(ticks.Substring(i, 2));
            if (number > characters.Length - 1)
            {
                var one = double.Parse(number.ToString().Substring(0, 1));
                var two = double.Parse(number.ToString().Substring(1, 1));
                code += characters[Convert.ToInt32(one)];
                code += characters[Convert.ToInt32(two)];
            }
            else
                code += characters[number];
        }
    }
    return code;
}

This code will generate a unique code / key based on universal time stamp ticks.

More details in this link



回答2:

You can achieve this via custom token instead of a custom field. I already answered a similar question here: Sitecore - Custom field, add unique value on create

Basically you will create a custom token and add your generation algorithm inside. You can use Guid.NewGuid() apply some kind of hash over it and pick as many characters as you want.