-
Notifications
You must be signed in to change notification settings - Fork 165
Expand file tree
/
Copy pathCosmosDBEntityBase.cs
More file actions
55 lines (48 loc) · 2.07 KB
/
Copy pathCosmosDBEntityBase.cs
File metadata and controls
55 lines (48 loc) · 2.07 KB
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
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Security.Cryptography;
namespace Microsoft.GS.DPS.Storage.Components
{
public class CosmosDBEntityBase : IEntityModel<Guid>
{
public CosmosDBEntityBase()
{
this.id = Guid.NewGuid();
this.__partitionkey = CosmosDBEntityBase.GetKey(id, 9999);
}
/// <summary>
/// id will be generated automatically. you don't need to manage it by yourself
/// </summary>
public Guid id { get; set; }
/// <summary>
/// the partitionkey will be used for storage partitioning. you don't need to manage it by yourself
/// </summary>
public string __partitionkey { get; set; }
/// <summary>
/// Generate partitionkey for CosmosDB
/// using SHA256 hash with id, convert it to uint and divide with number of partitions
/// assigned default value as 9999 (9999 partition at this moment)
/// </summary>
/// <param name="id"></param>
/// <param name="numberofPartitions"></param>
/// <returns></returns>
public static string GetKey(Guid id, int numberofPartitions)
{
// Use SHA256 instead of SHA1 (SHA1 flagged as broken/weak by SDL).
// This is a *non-cryptographic* use: only the first 4 bytes are consumed to derive a numeric
// partition key. Existing rows already in CosmosDB persist their original __partitionkey field,
// so changing the algorithm only affects partition assignment for newly-created entities.
var hashedVal = SHA256.HashData(id.ToByteArray());
var intHashedVal = BitConverter.ToUInt32(hashedVal, 0);
var range = numberofPartitions - 1;
var length = range.ToString().Length;
var key = (intHashedVal % numberofPartitions).ToString();
return key.PadLeft(length, '0');
}
}
}