Created
January 19, 2012 17:39
-
-
Save nberardi/1641384 to your computer and use it in GitHub Desktop.
Sequential Number Generator for RavenDB
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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"); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment