Mike Barnes
Mike Barnes

Reputation: 4305

Create my own Unique ID

I am trying to create a my own unique ID in C# for each document in my NoSQL database but I am not too sure how I would do that?

My example UID would look something like this ######.entityType@######.contextName.worldName

The hashes are alphanumeric characters.

Upvotes: 0

Views: 5129

Answers (4)

Tatham Oddie
Tatham Oddie

Reputation: 4290

The SnowMaker library is good at giving you unique identifiers within a particular uniqueness scope.

Upvotes: 2

Anthony Queen
Anthony Queen

Reputation: 2358

Making some assumptions here, but you could just generate a GUID, split the guid on the hyphen, use the parts of the guid in your user name.

Use a string builder to concatenate it all.

Here's a bit of sample code to give the idea (untested):

    Guid g = Guid.NewGuid();
    String[] parts = g.ToString().Split('-');

    StringBuilder sb = new StringBuilder();
    sb.Append(parts[0]);
    sb.Append("entityType@");
    sb.Append(parts[1]);
    sb.Append(".contextName.worldName");

    string ID = sb.ToString();

This won't be GLOBALLY unique, but should give you fairly good range of uniqueness for your scenario.

To match your hash lengths above you could do this:

        String gString = Guid.NewGuid().ToString().Replace("-","");

        StringBuilder sb = new StringBuilder();
        sb.Append(gString.Substring(0,6));
        sb.Append("entityType@");
        sb.Append(gString.Substring(6,6));
        sb.Append(".contextName.worldName");

        string ID = sb.ToString();
        MessageBox.Show(ID);

Upvotes: 1

Rob
Rob

Reputation: 10258

Do something like this to create it:

string characters = "abcdefghi123456";

string result = "";

Random random = new Random();

for(int i = 0; i < 10; i++)
{
     result += characters[random.Next(0, characters.Length - 1)];
}

There's no assurance that it's going to be unique so you would have to check against your stored records in the DB before attempting to insert it, if that's what you're planning to do and be careful using upper and lower case as these may seen as the same in the database e.g. Abc may be the same as aBC

Upvotes: -2

Habib
Habib

Reputation: 223402

Use Guid.NewGuid method.

Guid guid = Guid.NewGuid();
string uniqueID = guid.ToString();

Globally unique identifier - WIKI

A Globally Unique Identifier is a unique reference number used as an identifier in computer software. The term GUID typically refers to various implementations of the universally unique identifier (UUID) standard.

Upvotes: 13

Related Questions