public
Created

Sequential Number Generator for RavenDB

  • Download Gist
SequentialNumberGenerator.cs
C#
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
private static readonly object GeneratorLock = new object();
 
///<summary>
/// Create the next id (numeric)
///</summary>
private int NextAccountNumber()
{
lock (GeneratorLock)
{
using (new TransactionScope(TransactionScopeOption.Suppress))
{
while (true)
{
try
{
var document = GetDocument();
if (document == null)
{
PutDocument(new JsonDocument {
Etag = Guid.Empty, // sending empty guid means - ensure the that the document does NOT exists
Metadata = new RavenJObject(),
DataAsJson = RavenJObject.FromObject(new { Current = 1000 }),
Key = "Raven/InvoiceNumber"
});
return 1000;
}
 
int current;
current = document.DataAsJson.Value<int>("Current");
current++;
 
document.DataAsJson["Current"] = current;
PutDocument(document);
 
return current;
}
catch (ConcurrencyException)
{
// expected, we need to retry
}
}
}
}
}
 
private void PutDocument(JsonDocument document)
{
DocumentStore.DatabaseCommands.Put(
"Raven/InvoiceNumber",
document.Etag,
document.DataAsJson,
document.Metadata);
}
 
private JsonDocument GetDocument()
{
return DocumentStore.DatabaseCommands.Get("Raven/InvoiceNumber");
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.