Skip to content

Commit

Permalink
Merge pull request #20 from bolorundurowb/feature/#6/fix-random-usages
Browse files Browse the repository at this point in the history
feature/fix random usages
  • Loading branch information
Bolorunduro Winner-Timothy committed Aug 26, 2020
2 parents 4aabda0 + 6d206a4 commit c3c8717
Show file tree
Hide file tree
Showing 5 changed files with 60 additions and 41 deletions.
60 changes: 39 additions & 21 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,20 +4,35 @@

## About ShortId

A CSharp library to generate completely random short id's. They can be used as primary keys or unique identifiers. This library is different in that you can specify the length of the id's generated. I have tested the application generating 180000 id's without duplicates.
A CSharp library to generate completely random short id's. They can be used as primary keys or unique identifiers. This library is different in that you can specify the length of the ids to be generated. This library is thread-safe and can generate millions of unique ids across multiple threads.

## How to use
## Getting Started

To make use of the `shortid`, add it to your project via the Nuget package manager UI or console via this command:

#### Package Manager

```
Install-Package shortid
```

#### .NET CLI
```
> dotnet add package shortid
```

#### PackageReference
```csharp
<PackageReference Include="shortid" />
```

## Usage

Add the following using command to the top of your csharp code file:

```csharp
using shortid;
using shortid.Configuration;
```

This gives your code access the classes and methods of the `shortid` namespace.
Expand All @@ -29,36 +44,39 @@ string id = ShortId.Generate();
// id = KXTR_VzGVUoOY
```

If you want to include numbers in the generated id, then you call the `Generate` method with a boolean indicating your preference.
If you want to include numbers in the generated id, then you call the `Generate` method with options indicating your preference.

```csharp
string id = ShortId.Generate(true);
var options = new GenerationOptions
{
UseNumbers = true
};
string id = ShortId.Generate(options);
// id = O_bBY-YUkJg
```

If you do not want special characters *i.e _ and -* in your generated id, then call the `Generate` method with two boolean parameters, the first indicating whether or not you want numbers and the second indicating whether or not you want special characeters.
If you do not want special characters *i.e _ and -* in your generated id, then call the `Generate` method with options indicating your preferences.

```csharp
string id = ShortId.Generate(true, false);
var options = new GenerationOptions
{
UseSpecialCharacters = false
};
string id = ShortId.Generate(options);
// id = waBfk3z
```

If you want to specify the length of the generated id, call the `Generate` method with an integer parameter which is the desired length.
If you want to specify the length of the generated id, call the `Generate` method with options indicating your preferences.

```csharp
string id = ShortId.Generate(8);
// id = M-snXzBk
var options = new GenerationOptions
{
Length = 9
};
string id = ShortId.Generate(options);
// id = M-snXzBkj
```

If you want to control the type of id generated by specifying whether you want numbers, special characters and the length, call the `Generate` method and pass three parameters, the first a boolean stating whether you want numbers, the second a boolean stating whether you want special characters, the last a number indicating your length preference.

```csharp
string id = ShortId.Generate(true, false, 12);
// id = VvoCDPazES_w
```

**NOTE: v2.0.0 introduced a change that prevents lengths of less than 7**


## Customize ShortId

Expand All @@ -67,11 +85,11 @@ string id = ShortId.Generate(true, false, 12);
To change the character set in use, run the following:

```csharp
string characters = //whatever you want;
string characters = "ⒶⒷⒸⒹⒺⒻⒼⒽⒾⒿⓀⓁⓂⓃⓄⓅⓆⓇⓈⓉⓊⓋⓌⓍⓎⓏⓐⓑⓒⓓⓔⓕⓖⓗⓘⓙⓚⓛⓜⓝⓞⓟⓠⓡⓢⓣⓤⓥⓦⓧⓨⓩ①②③④⑤⑥⑦⑧⑨⑩⑪⑫"; //whatever you want;
ShortId.SetCharacters(characters);
```

**NOTE: the new character set must not be `null`, an empty string or whitespace. Also, all whitespace characters would be removed, finally the character set cannot be less than 20 characters.**
**NOTE: the new character set must not be `null`, an empty string or whitespace. Also, all whitespace and duplicate characters would be removed, finally the character set cannot be less than 20 characters.**

`ShortId` also allows the seed for the random number generator to be set.

Expand All @@ -86,4 +104,4 @@ Finally, `ShortId` allows for all customizations to be reset using the following

```csharp
ShortId.Reset();
```
```
2 changes: 1 addition & 1 deletion shortid.Test/Configuration/GenerationOptions.Tests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ public void ShouldAssignRandomLengthOnInstantiation()
options
.Length
.Should()
.BeGreaterThan(7);
.BeGreaterThan(6);
options
.Length
.Should()
Expand Down
30 changes: 13 additions & 17 deletions shortid/ShortId.cs
Original file line number Diff line number Diff line change
@@ -1,17 +1,18 @@
using System;
using System.Text;
using shortid.Configuration;
using shortid.Utils;

namespace shortid
{
public static class ShortId
{
// app variables
private static Random _random = new Random();
private const string Bigs = "ABCDEFGHIJKLMNOPQRSTUVWXY";
private const string Smalls = "abcdefghjlkmnopqrstuvwxyz";
private const string Bigs = "ABCDEFGHIJKLMNPQRSTUVWXY";
private const string Smalls = "abcdefghjklmnopqrstuvwxyz";
private const string Numbers = "0123456789";
private const string Specials = "-_";
private const string Specials = "_-";
private static string _pool = $"{Smalls}{Bigs}";

// thread management variables
Expand Down Expand Up @@ -85,21 +86,13 @@ public static string Generate(GenerationOptions options)
throw new ArgumentNullException(nameof(options));
}

if (options.Length < 7)
if (options.Length < Constants.MinimumAutoLength)
{
throw new ArgumentException(
$"The specified length of {options.Length} is less than the lower limit of 7.");
}

string characterPool;
Random rand;

lock (ThreadLock)
{
characterPool = _pool;
rand = _random;
$"The specified length of {options.Length} is less than the lower limit of {Constants.MinimumAutoLength}.");
}

var characterPool = _pool;
var poolBuilder = new StringBuilder(characterPool);
if (options.UseNumbers)
{
Expand All @@ -116,8 +109,11 @@ public static string Generate(GenerationOptions options)
var output = new char[options.Length];
for (var i = 0; i < options.Length; i++)
{
var charIndex = rand.Next(0, pool.Length);
output[i] = pool[charIndex];
lock (ThreadLock)
{
var charIndex = _random.Next(0, pool.Length);
output[i] = pool[charIndex];
}
}

return new string(output);
Expand Down Expand Up @@ -145,7 +141,7 @@ public static void SetCharacters(string characters)
}
}

if (stringBuilder.Length < 20)
if (stringBuilder.Length < Constants.MinimumCharacterSetLength)
{
throw new InvalidOperationException(
"The replacement characters must be at least 20 letters in length and without whitespace.");
Expand Down
2 changes: 2 additions & 0 deletions shortid/Utils/Constants.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,5 +5,7 @@ internal static class Constants
public const int MinimumAutoLength = 7;

public const int MaximumAutoLength = 15;

public const int MinimumCharacterSetLength = 20;
}
}
7 changes: 5 additions & 2 deletions shortid/shortid.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,16 @@
<PackageIconUrl>https://members.orcid.org/sites/default/files/vector_iD_icon.svg</PackageIconUrl>
<RepositoryUrl>https://github.com/bolorundurowb/shortid/</RepositoryUrl>
<PackageTags>shortid short id databse identifier key primarykey mongodb sql</PackageTags>
<PackageReleaseNotes>- add in options validation</PackageReleaseNotes>
<PackageReleaseNotes>- fix- random usages</PackageReleaseNotes>
<Authors>Bolorunduro Winner-Timothy</Authors>
<Description>A library that generates random identifiers from 7 to 14 characters. Identifiers generated can be used as primary keys for databases or unique identifiers.</Description>
<PackageRequireLicenseAcceptance>true</PackageRequireLicenseAcceptance>
<GeneratePackageOnBuild>true</GeneratePackageOnBuild>
<Title>shortid</Title>
<RepositoryType>git</RepositoryType>
<PackageVersion>2.0.3</PackageVersion>
<PackageVersion>2.0.4</PackageVersion>
<AssemblyVersion>2.0.4.0</AssemblyVersion>
<FileVersion>2.0.4.0</FileVersion>
<NeutralLanguage>en-NG</NeutralLanguage>
</PropertyGroup>
</Project>

0 comments on commit c3c8717

Please sign in to comment.