Create a gist now

Instantly share code, notes, and snippets.

@abock /guid.cs
Created Apr 13, 2017

What would you like to do?
A GUID generator written in C# using the scripting mode of `csharp`
#!/usr/bin/env csharp -s
string error = null;
var showHelp = false;
var count = 1u;
var format = "D";
var upper = false;
var bojangles = false;
for (int i = 0; i < Args.Length && error == null; i++) {
switch (Args [i]) {
case "-h":
case "/h":
case "-?":
case "/?":
case "-help":
case "--help":
case "/help":
showHelp = true;
break;
case "-n":
case "/n":
if (i < Args.Length - 1) {
if (!uint.TryParse (Args [++i], out count))
error = "-n requires a positive integer";
} else
error = "number not provided";
break;
case "-u":
case "/u":
case "-upper":
case "--upper":
case "/upper":
upper = true;
break;
case "-f":
case "/f":
case "-format":
case "--format":
case "/format":
if (i < Args.Length - 1) {
format = Args [++i].ToUpperInvariant ();
switch (format) {
case "N":
case "D":
case "B":
case "P":
case "X":
break;
default:
error = $"invalid format specifier '{Args[i]}'";
break;
}
} else
error = "format not provided";
break;
case "-b":
case "/b":
case "-bojangles":
case "--bojangles":
case "/bojangles":
bojangles = true;
break;
default:
error = $"invalid argument `{Args [i]}`";
break;
}
}
if (error != null) {
Console.Error.WriteLine ("error: {0}", error);
Console.Error.WriteLine ();
showHelp = true;
}
if (showHelp) {
Console.WriteLine (@"usage: guid [OPTIONS]
OPTIONS:
-help, -h show this help
-format, -f FORMAT ToString format to use (see FORMATS)
-upper, -u uppercase GUID
-n NUMBER produce NUMBER GUIDs
-bojangles, -b produces GUIDs with all 'AA' strings
replaced with 'BB' strings
FORMATS:
N 32 digits:
00000000000000000000000000000000
D 32 digits separated by hyphens:
00000000-0000-0000-0000-000000000000
B 32 digits separated by hyphens, enclosed in braces:
{{00000000-0000-0000-0000-000000000000}}
P 32 digits separated by hyphens, enclosed in parentheses:
(00000000-0000-0000-0000-000000000000)
X Four hexadecimal values enclosed in braces, where the
fourth value is a subset of eight hexadecimal values
that is also enclosed in braces:
{0x00000000,0x0000,0x0000,{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00}}
");
Environment.Exit (1);
}
for (uint i = 0; i < count; i++) {
var guid = Guid.NewGuid ().ToString (format);
if (upper) {
guid = guid.ToUpperInvariant ();
if (bojangles)
guid = guid.Replace ("AA", "BB");
} else if (bojangles)
guid = guid.Replace ("aa", "bb");
Console.WriteLine (guid);
}

grawity commented Nov 11, 2017

Unfortunately Linux doesn't split the argument in #!. So if you use /usr/bin/env, then it tries to use csharp -s as the literal executable name... (Which could be symlinked actually, but it'd be weird.)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment