C # arbitrary code field generator for an object

I have an object with the following properties


GID
ID
code
Name

Some of the clients do not want to enter the code, so the initial plan was to put the identifier in the code, but the base object for orm is different from me, so I'm like screwed ...

my plan was to put #### - #### completely random values ​​in the code, how can I generate something like this, such as a serial window generator 7, but that would not have overhead, what would you do in this case.

+3
source share
3 answers

?

random!= unique.

, . - . ?

Guid [. ]. , , .


[.. ],

OrmObject ormObject= new OrmObject ();
string code = string.
    Format ("{0} [{1}]", ormObject.Name, Guid.NewGuid ()).
    Trim ();
// generates something like
// "My Product [DA9190E1-7FC6-49d6-9EA5-589BBE6E005E]"

ormObject.Name . typeof (objectInstance.GetType ()).Name, , OrmObject , , , . , - , , @Yuriy Faktorovich, wtf article - .


- . , , .

, ,

public static class IRandomExtensions
{
    public static CodeType GetCode (this IRandom random)
    {
        // 1. get as many random bytes as required
        // 2. transform bytes into a 'Code'
        // 3. bob your uncle
        ...
    }
}

    // elsewhere in code
    ...
    OrmObject ormObject = new OrmObject ();
    ormObject.Code = random.GetCode ();
    ...

, IRandom System.Security.Cryptography.RNGCryptoServiceProvider. X , , .

- , , , ! - CodeType - , "" Base64

public static class IRandomExtensions
{
    // assuming 'CodeType' is in fact a string
    public static string GetCode (this IRandom random)
    {
        // 1. get as many random bytes as required
        byte[] randomBytes; // fill from random
        // 2. transform bytes into a 'Code'
        string randomBase64String = 
            System.Convert.ToBase64String (randomBytes).Trim ("=");
        // 3. bob your uncle
        ...
    }
}

random!= unique.

. .


, .

  • Code ? [ , ]
  • Code? [ , Guid]
  • ? [ , DB, @LBushkin ]
  • , ? [ , , Guids - ]

, , , , , . . .

, :)

Btw, , [.. ] . , Code, ? ? ?

, , . Guids, "" , base64 - base64 .

public static class GuidExtensions
{
    public static string ToBase64String (this Guid id)
    {
        return System.Convert.
            ToBase64String (id.ToByteArray ()).
            Trim ("=");
    }
}

, base64 . , base64, = , , , Guid. base64, base64, 4 - , base64, :)

+3

Guid, :

Guid.NewGuid().ToString();

- :

788E94A0-C492-11DE-BFD4-FCE355D89593

+1

Autonumber Sequencer . . , .

Autonumber / Sequencer values ​​from the database are guaranteed to be unique and relatively inexpensive to purchase. If you want to avoid the completely sequential numbers assigned to codes, you can combine and combine several sequencer values ​​together.

0
source

Source: https://habr.com/ru/post/1721398/


All Articles