AzureCosmosDBRepository.cs 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Threading.Tasks;
  4. using System.Linq;
  5. using TEAMModelOS.SDK.Module.AzureCosmosDB.Configuration;
  6. using TEAMModelOS.SDK.Module.AzureCosmosDB.Interfaces;
  7. using Microsoft.Azure.Documents.Client;
  8. using Microsoft.Azure.Documents;
  9. using TEAMModelOS.SDK.Helper.Security.AESCrypt;
  10. using TEAMModelOS.SDK.Context.Exception;
  11. using Microsoft.Azure.Documents.Linq;
  12. using TEAMModelOS.SDK.Helper.Query.LinqHelper;
  13. using System.Reflection;
  14. using Microsoft.Azure.CosmosDB.BulkExecutor;
  15. using Microsoft.Azure.CosmosDB.BulkExecutor.BulkImport;
  16. using System.Threading;
  17. using TEAMModelOS.SDK.Helper.Common.JsonHelper;
  18. using Microsoft.Azure.CosmosDB.BulkExecutor.BulkUpdate;
  19. using TEAMModelOS.SDK.Helper.Common.CollectionHelper;
  20. using Microsoft.Azure.CosmosDB.BulkExecutor.BulkDelete;
  21. using TEAMModelOS.SDK.Context.Attributes.Azure;
  22. namespace TEAMModelOS.SDK.Module.AzureCosmosDB.Implements
  23. { /// <summary>
  24. /// sdk 文档https://github.com/Azure/azure-cosmos-dotnet-v2/tree/master/samples
  25. /// https://github.com/Azure/azure-cosmos-dotnet-v2/blob/530c8d9cf7c99df7300246da05206c57ce654233/samples/code-samples/DatabaseManagement/Program.cs#L72-L121
  26. /// </summary>
  27. public class AzureCosmosDBRepository : IAzureCosmosDBRepository
  28. {
  29. /// <summary>
  30. /// sdk 文档https://github.com/Azure/azure-cosmos-dotnet-v2/tree/master/samples
  31. /// https://github.com/Azure/azure-cosmos-dotnet-v2/blob/530c8d9cf7c99df7300246da05206c57ce654233/samples/code-samples/DatabaseManagement/Program.cs#L72-L121
  32. /// </summary>
  33. private readonly string china_con = "417A7572654368696E6120202020202020202020202020202020202020202020D63873D37F845F9DC7607B4DF4787EE26598454CE32FB5F2EE778A34A5015736196DF7940C67A034CDD4C4B44CD37C20";
  34. private readonly string china_key = "417A7572654368696E61202020202020202020202020202020202020202020203CAA1DF7E3203F0ABCB2D60C1F3DCB6D90676C4D5467167F6E6A2CB3DDE975EA37B06BBAE6E012936BEDB6D5D60B28B13642F755CB25D1958BE5366EA20FA7C47E04A67B6A96111C61C3270CD0E5539CA45E3A77A6B483F47419BBAEDE75C0F6";
  35. private readonly string global_con = "417A757265476C6F62616C2020202020202020202020202020202020202020200E357979CB69243DBF4E41BF5526830F89AB746007AC68A3DD3F9CFDA781509F1C48B2359120A5E58B8C7B1EDAA99DEA";
  36. private readonly string global_key = "417A757265476C6F62616C2020202020202020202020202020202020202020209FF199D61813D1F4857D55CFB0A7D6A797FECF39A7F47553E9C1AF23674CB04BA95748A4A3C07B90F32E5EF26E0982DBF90001E066432075C434351D73FB387D27A50716D90F414F34A4579D846C27804F658705C05A7224EC4D695FD7A5EE23";
  37. private DocumentClient CosmosClient { get; set; }
  38. private DocumentCollection CosmosCollection { get; set; }
  39. private string Database { get; set; }
  40. private int CollectionThroughput { get; set; }
  41. public AzureCosmosDBRepository(AzureCosmosDBOptions options)
  42. {
  43. try
  44. {
  45. if (!string.IsNullOrEmpty(options.ConnectionString))
  46. {
  47. CosmosClient = CosmosDBClientSingleton.getInstance(options.ConnectionString, options.ConnectionKey).GetCosmosDBClient();
  48. }
  49. else if (AzureCosmosDBConfig.AZURE_CHINA.Equals(options.AzureTableDialect))
  50. {
  51. AESCrypt crypt = new AESCrypt();
  52. CosmosClient = CosmosDBClientSingleton.getInstance(crypt.Decrypt(china_con, options.AzureTableDialect), crypt.Decrypt(china_key, options.AzureTableDialect)).GetCosmosDBClient();
  53. }
  54. else if (AzureCosmosDBConfig.AZURE_GLOBAL.Equals(options.AzureTableDialect))
  55. {
  56. AESCrypt crypt = new AESCrypt();
  57. CosmosClient = CosmosDBClientSingleton.getInstance(crypt.Decrypt(global_con, options.AzureTableDialect), crypt.Decrypt(global_key, options.AzureTableDialect)).GetCosmosDBClient();
  58. }
  59. else
  60. {
  61. throw new BizException("请设置正确的AzureCosmosDB数据库配置信息!");
  62. }
  63. Database = options.Database;
  64. CollectionThroughput = options.CollectionThroughput;
  65. CosmosClient.CreateDatabaseIfNotExistsAsync(new Database { Id = Database });
  66. // _connectionString = options.ConnectionString;
  67. }
  68. catch (DocumentClientException de)
  69. {
  70. Exception baseException = de.GetBaseException();
  71. Console.WriteLine("{0} error occurred: {1}, Message: {2}", de.StatusCode, de.Message, baseException.Message);
  72. }
  73. catch (Exception e)
  74. {
  75. Exception baseException = e.GetBaseException();
  76. Console.WriteLine("Error: {0}, Message: {1}", e.Message, baseException.Message);
  77. }
  78. finally
  79. {
  80. Console.WriteLine("End of demo, press any key to exit.");
  81. // Console.ReadKey();
  82. }
  83. }
  84. private async Task<DocumentCollection> InitializeCollection<T>()
  85. {
  86. Type t = typeof(T);
  87. if (CosmosCollection == null || !CosmosCollection.Id.Equals(t.Name))
  88. {
  89. DocumentCollection collectionDefinition = new DocumentCollection { Id = t.Name };
  90. collectionDefinition.IndexingPolicy = new IndexingPolicy(new RangeIndex(DataType.String) { Precision = -1 });
  91. string partitionKey = GetPartitionKey<T>();
  92. // collectionDefinition.PartitionKey = new PartitionKeyDefinition { Paths = new System.Collections.ObjectModel.Collection<string>() };
  93. if (!string.IsNullOrEmpty(partitionKey))
  94. {
  95. collectionDefinition.PartitionKey.Paths.Add("/" + partitionKey);
  96. }
  97. // CosmosCollection = await this.CosmosClient.CreateDocumentCollectionIfNotExistsAsync(UriFactory.CreateDatabaseUri(Database), collectionDefinition);
  98. CosmosCollection = await this.CosmosClient.CreateDocumentCollectionIfNotExistsAsync(
  99. UriFactory.CreateDatabaseUri(Database), collectionDefinition, new RequestOptions { OfferThroughput = CollectionThroughput }
  100. );
  101. }
  102. return CosmosCollection;
  103. }
  104. private string GetPartitionKey<T>()
  105. {
  106. Type type = typeof(T);
  107. PropertyInfo[] properties = type.GetProperties();
  108. List<PropertyInfo> attrProperties = new List<PropertyInfo>();
  109. foreach (PropertyInfo property in properties)
  110. {
  111. if (property.Name.Equals("PartitionKey"))
  112. {
  113. attrProperties.Add(property);
  114. break;
  115. }
  116. object[] attributes = property.GetCustomAttributes(true);
  117. foreach (object attribute in attributes) //2.通过映射,找到成员属性上关联的特性类实例,
  118. {
  119. if (attribute is PartitionKeyAttribute)
  120. {
  121. attrProperties.Add(property);
  122. }
  123. }
  124. }
  125. if (attrProperties.Count <= 0)
  126. {
  127. return null;
  128. }
  129. else
  130. {
  131. if (attrProperties.Count == 1)
  132. {
  133. return attrProperties[0].Name;
  134. }
  135. else { throw new BizException("PartitionKey can only be single!"); }
  136. }
  137. }
  138. public async Task<T> Save<T>(T entity) //where T : object, new()
  139. {
  140. Type t = typeof(T);
  141. DocumentCollection documentCollection = await InitializeCollection<T>();
  142. ResourceResponse<Document> doc =
  143. await CosmosClient.CreateDocumentAsync(UriFactory.CreateDocumentCollectionUri(Database, t.Name), entity);
  144. //Console.WriteLine(doc.ActivityId);
  145. return entity;
  146. }
  147. public async Task<T> Update<T>(T entity)
  148. {
  149. Type t = typeof(T);
  150. await InitializeCollection<T>();
  151. ResourceResponse<Document> doc =
  152. await CosmosClient.UpsertDocumentAsync(UriFactory.CreateDocumentCollectionUri(Database, t.Name), entity);
  153. return entity;
  154. }
  155. public async Task<string> ReplaceObject<T>(T entity, string key)
  156. {
  157. Type t = typeof(T);
  158. await InitializeCollection<T>();
  159. try
  160. {
  161. ResourceResponse<Document> doc =
  162. await CosmosClient.ReplaceDocumentAsync(UriFactory.CreateDocumentUri(Database, t.Name, key), entity);
  163. return key;
  164. }
  165. catch (Exception e)
  166. {
  167. Console.WriteLine("{0} Exception caught.", e);
  168. //return false;
  169. }
  170. return null;
  171. }
  172. public async Task<string> ReplaceObject<T>(T entity, string key, string partitionKey)
  173. {
  174. Type t = typeof(T);
  175. await InitializeCollection<T>();
  176. try
  177. {
  178. ResourceResponse<Document> doc =
  179. await CosmosClient.ReplaceDocumentAsync(UriFactory.CreateDocumentUri(Database, t.Name, key),
  180. entity,
  181. new RequestOptions { PartitionKey = new PartitionKey(partitionKey) });
  182. return key;
  183. }
  184. catch (Exception e)
  185. {
  186. Console.WriteLine("{0} Exception caught.", e);
  187. //return false;
  188. }
  189. return null;
  190. }
  191. public async Task<List<T>> FindAll<T>()
  192. {
  193. Type t = typeof(T);
  194. Boolean open = true;
  195. List<T> objs = new List<T>();
  196. //await InitializeCollection<T>();
  197. //查询条数 -1是全部
  198. FeedOptions queryOptions = new FeedOptions { MaxItemCount = -1, EnableCrossPartitionQuery = open };
  199. var query = CosmosClient.CreateDocumentQuery<T>(UriFactory.CreateDocumentCollectionUri(Database, t.Name), queryOptions).AsDocumentQuery();
  200. while (query.HasMoreResults)
  201. {
  202. foreach (T obj in await query.ExecuteNextAsync())
  203. {
  204. objs.Add(obj);
  205. }
  206. }
  207. return objs;
  208. //return CosmosClient.CreateDocumentQuery<T>(UriFactory.CreateDocumentCollectionUri(Database, t.Name),sql);
  209. }
  210. public async Task<List<T>> FindLinq<T>(Func<IQueryable<object>, object> singleOrDefault)
  211. {
  212. Type t = typeof(T);
  213. List<T> objs = new List<T>();
  214. await InitializeCollection<T>();
  215. //查询条数 -1是全部
  216. FeedOptions queryOptions = new FeedOptions { MaxItemCount = -1 };
  217. var query = CosmosClient.CreateDocumentQuery<T>(UriFactory.CreateDocumentCollectionUri(Database, t.Name), queryOptions);
  218. // query.Where();
  219. return objs;
  220. //return CosmosClient.CreateDocumentQuery<T>(UriFactory.CreateDocumentCollectionUri(Database, t.Name),sql);
  221. }
  222. public async Task<List<T>> FindSQL<T>(string sql)
  223. {
  224. Type t = typeof(T);
  225. List<T> objs = new List<T>();
  226. await InitializeCollection<T>();
  227. var query = CosmosClient.CreateDocumentQuery<T>(UriFactory.CreateDocumentCollectionUri(Database, t.Name), sql);
  228. foreach (var item in query)
  229. {
  230. objs.Add(item);
  231. }
  232. return objs;
  233. }
  234. public async Task<List<T>> FindSQL<T>(string sql, bool IsPk)
  235. {
  236. Type t = typeof(T);
  237. List<T> objs = new List<T>();
  238. Boolean open = IsPk;
  239. await InitializeCollection<T>();
  240. //查询条数 -1是全部
  241. FeedOptions queryOptions = new FeedOptions { MaxItemCount = -1, EnableCrossPartitionQuery = open };
  242. var query = CosmosClient.CreateDocumentQuery<T>(UriFactory.CreateDocumentCollectionUri(Database, t.Name), sql, queryOptions);
  243. foreach (var item in query)
  244. {
  245. objs.Add(item);
  246. }
  247. return objs;
  248. }
  249. public async Task<List<T>> FindByparams<T>(Dictionary<string, object> dict)
  250. {
  251. //await InitializeCollection<T>();
  252. Type t = typeof(T);
  253. Boolean open = true;
  254. List<Filter> filters = new List<Filter>();
  255. string PKname = "";
  256. PropertyInfo[] properties = t.GetProperties();
  257. foreach (PropertyInfo property in properties)
  258. {
  259. object[] attributes = property.GetCustomAttributes(true);
  260. foreach (object attribute in attributes) //2.通过映射,找到成员属性上关联的特性类实例,
  261. {
  262. if (attribute is PartitionKeyAttribute)
  263. {
  264. PKname = property.Name;
  265. break;
  266. }
  267. }
  268. }
  269. foreach (string key in dict.Keys)
  270. {
  271. //if (t.Name.Equals(key)) {
  272. // open = false;
  273. //}
  274. if (PKname.Equals(key))
  275. {
  276. open = false;
  277. }
  278. filters.Add(new Filter { Key = key, Value = dict[key] != null ? dict[key].ToString() : throw new Exception("参数值不能为null") });
  279. }
  280. //List<T> objs = new List<T>();
  281. await InitializeCollection<T>();
  282. //查询条数 -1是全部
  283. FeedOptions queryOptions = new FeedOptions { MaxItemCount = -1, EnableCrossPartitionQuery = open };
  284. var query = CosmosClient.CreateDocumentQuery<T>(UriFactory.CreateDocumentCollectionUri(Database, t.Name), queryOptions);
  285. List<T> list = DynamicLinq.GenerateFilter<T>(query, filters).ToList();
  286. return list;
  287. //return CosmosClient.CreateDocumentQuery<T>(UriFactory.CreateDocumentCollectionUri(Database, t.Name),sql);
  288. }
  289. public async Task<string> DeleteAsync<T>(string id)
  290. {
  291. Type t = typeof(T);
  292. await InitializeCollection<T>();
  293. ResourceResponse<Document> doc =
  294. await CosmosClient.DeleteDocumentAsync(UriFactory.CreateDocumentUri(Database, t.Name, id));
  295. //Console.WriteLine(doc.ActivityId);
  296. return id;
  297. }
  298. public async Task<T> DeleteAsync<T>(T entity)
  299. {
  300. await InitializeCollection<T>();
  301. Type t = typeof(T);
  302. string PartitionKey = GetPartitionKey<T>();
  303. if (!string.IsNullOrEmpty(PartitionKey))
  304. {
  305. string pkValue = entity.GetType().GetProperty(PartitionKey).GetValue(entity).ToString();
  306. string idValue = entity.GetType().GetProperty("id").GetValue(entity).ToString();
  307. ResourceResponse<Document> doc =
  308. await CosmosClient.DeleteDocumentAsync(UriFactory.CreateDocumentUri(Database, t.Name, idValue), new RequestOptions { PartitionKey = new PartitionKey(pkValue) });
  309. }
  310. else
  311. {
  312. string idValue = entity.GetType().GetProperty("id").GetValue(entity).ToString();
  313. ResourceResponse<Document> doc =
  314. await CosmosClient.DeleteDocumentAsync(UriFactory.CreateDocumentUri(Database, t.Name, idValue));
  315. }
  316. //Console.WriteLine(doc.ActivityId);
  317. return entity;
  318. }
  319. public async Task<string> DeleteAsync<T>(string id, string partitionKey)
  320. {
  321. Type t = typeof(T);
  322. await InitializeCollection<T>();
  323. ResourceResponse<Document> doc =
  324. await CosmosClient.DeleteDocumentAsync(UriFactory.CreateDocumentUri(Database, t.Name, id), new RequestOptions { PartitionKey = new PartitionKey(partitionKey) });
  325. //Console.WriteLine(doc.ActivityId);
  326. return id;
  327. }
  328. public async Task<List<T>> SaveAll<T>(List<T> enyites)
  329. {
  330. DocumentCollection dataCollection = await InitializeCollection<T>();
  331. // Set retry options high for initialization (default values).
  332. CosmosClient.ConnectionPolicy.RetryOptions.MaxRetryWaitTimeInSeconds = 30;
  333. CosmosClient.ConnectionPolicy.RetryOptions.MaxRetryAttemptsOnThrottledRequests = 9;
  334. IBulkExecutor bulkExecutor = new BulkExecutor(CosmosClient, dataCollection);
  335. await bulkExecutor.InitializeAsync();
  336. // Set retries to 0 to pass control to bulk executor.
  337. CosmosClient.ConnectionPolicy.RetryOptions.MaxRetryWaitTimeInSeconds = 0;
  338. CosmosClient.ConnectionPolicy.RetryOptions.MaxRetryAttemptsOnThrottledRequests = 0;
  339. BulkImportResponse bulkImportResponse = null;
  340. long totalNumberOfDocumentsInserted = 0;
  341. double totalRequestUnitsConsumed = 0;
  342. double totalTimeTakenSec = 0;
  343. var tokenSource = new CancellationTokenSource();
  344. var token = tokenSource.Token;
  345. int pageSize = 100;
  346. int pages = (int)Math.Ceiling((double)enyites.Count / pageSize);
  347. for (int i = 0; i < pages; i++)
  348. {
  349. List<string> documentsToImportInBatch = new List<string>();
  350. List<T> lists = enyites.Skip((i) * pageSize).Take(pageSize).ToList();
  351. for (int j = 0; j < lists.Count; j++)
  352. {
  353. documentsToImportInBatch.Add(lists[j].ToJson());
  354. }
  355. var tasks = new List<Task>
  356. { Task.Run(async () =>
  357. {
  358. do
  359. {
  360. //try
  361. //{
  362. bulkImportResponse = await bulkExecutor.BulkImportAsync(
  363. documents: documentsToImportInBatch,
  364. enableUpsert: true,
  365. disableAutomaticIdGeneration: true,
  366. maxConcurrencyPerPartitionKeyRange: null,
  367. maxInMemorySortingBatchSize: null,
  368. cancellationToken: token);
  369. //}
  370. //catch (DocumentClientException de)
  371. //{
  372. // break;
  373. //}
  374. //catch (Exception e)
  375. //{
  376. // break;
  377. //}
  378. } while (bulkImportResponse.NumberOfDocumentsImported < documentsToImportInBatch.Count);
  379. totalNumberOfDocumentsInserted += bulkImportResponse.NumberOfDocumentsImported;
  380. totalRequestUnitsConsumed += bulkImportResponse.TotalRequestUnitsConsumed;
  381. totalTimeTakenSec += bulkImportResponse.TotalTimeTaken.TotalSeconds;
  382. },
  383. token)
  384. };
  385. await Task.WhenAll(tasks);
  386. }
  387. return enyites;
  388. }
  389. public async Task<List<T>> UpdateAll<T>(Dictionary<string, object> dict, Dictionary<string, object> updateFilters, List<string> deleteKeys = null)
  390. {
  391. DocumentCollection dataCollection = await InitializeCollection<T>();
  392. IBulkExecutor bulkExecutor = new BulkExecutor(CosmosClient, dataCollection);
  393. await bulkExecutor.InitializeAsync();
  394. BulkUpdateResponse bulkUpdateResponse = null;
  395. long totalNumberOfDocumentsUpdated = 0;
  396. double totalRequestUnitsConsumed = 0;
  397. double totalTimeTakenSec = 0;
  398. var tokenSource = new CancellationTokenSource();
  399. var token = tokenSource.Token;
  400. // Generate update operations.
  401. List<UpdateOperation> updateOperations = new List<UpdateOperation>();
  402. // Unset the description field.
  403. if (null != updateFilters && updateFilters.Count > 0)
  404. {
  405. var keys = updateFilters.Keys;
  406. foreach (string key in keys)
  407. {
  408. // updateOperations.Add(new SetUpdateOperation<string>())
  409. if (updateFilters[key] != null && !string.IsNullOrEmpty(updateFilters[key].ToString()))
  410. {
  411. updateOperations.Add(SwitchType(key, updateFilters[key]));
  412. }
  413. }
  414. }
  415. if (deleteKeys.IsNotEmpty())
  416. {
  417. foreach (string key in deleteKeys)
  418. {
  419. updateOperations.Add(new UnsetUpdateOperation(key));
  420. }
  421. }
  422. List<T> list = await FindByparams<T>(dict);
  423. int pageSize = 100;
  424. int pages = (int)Math.Ceiling((double)list.Count / pageSize);
  425. string partitionKey = "/" + GetPartitionKey<T>();
  426. Type type = typeof(T);
  427. for (int i = 0; i < pages; i++)
  428. {
  429. List<UpdateItem> updateItemsInBatch = new List<UpdateItem>();
  430. List<T> lists = list.Skip((i) * pageSize).Take(pageSize).ToList();
  431. for (int j = 0; j < lists.Count; j++)
  432. {
  433. string partitionKeyValue = lists[j].GetType().GetProperty(partitionKey).GetValue(lists[j]) + "";
  434. string id = lists[j].GetType().GetProperty("id").GetValue(lists[j]) + "";
  435. updateItemsInBatch.Add(new UpdateItem(id, partitionKeyValue, updateOperations));
  436. }
  437. var tasks = new List<Task>
  438. { Task.Run(async () =>
  439. {
  440. do
  441. {
  442. //try
  443. //{
  444. bulkUpdateResponse = await bulkExecutor.BulkUpdateAsync(
  445. updateItems: updateItemsInBatch,
  446. maxConcurrencyPerPartitionKeyRange: null,
  447. cancellationToken: token);
  448. //}
  449. //catch (DocumentClientException de)
  450. //{
  451. // break;
  452. //}
  453. //catch (Exception e)
  454. //{
  455. // break;
  456. //}
  457. } while (bulkUpdateResponse.NumberOfDocumentsUpdated < updateItemsInBatch.Count);
  458. totalNumberOfDocumentsUpdated += bulkUpdateResponse.NumberOfDocumentsUpdated;
  459. totalRequestUnitsConsumed += bulkUpdateResponse.TotalRequestUnitsConsumed;
  460. totalTimeTakenSec += bulkUpdateResponse.TotalTimeTaken.TotalSeconds;
  461. },
  462. token)
  463. };
  464. await Task.WhenAll(tasks);
  465. }
  466. return list;
  467. }
  468. public async Task<List<T>> DeleteALl<T>(Dictionary<string, object> dict)
  469. {
  470. DocumentCollection dataCollection = await InitializeCollection<T>();
  471. List<T> list = await FindByparams<T>(dict);
  472. List<Tuple<string, string>> pkIdTuplesToDelete = new List<Tuple<string, string>>();
  473. if (list.IsNotEmpty())
  474. {
  475. foreach (T t in list)
  476. {
  477. string id = t.GetType().GetProperty("id").GetValue(t) + "";
  478. pkIdTuplesToDelete.Add(new Tuple<string, string>(id, id));
  479. }
  480. }
  481. else
  482. {
  483. return null;
  484. }
  485. long totalNumberOfDocumentsDeleted = 0;
  486. double totalRequestUnitsConsumed = 0;
  487. double totalTimeTakenSec = 0;
  488. BulkDeleteResponse bulkDeleteResponse = null;
  489. BulkExecutor bulkExecutor = new BulkExecutor(CosmosClient, dataCollection);
  490. await bulkExecutor.InitializeAsync();
  491. bulkDeleteResponse = await bulkExecutor.BulkDeleteAsync(pkIdTuplesToDelete);
  492. totalNumberOfDocumentsDeleted = bulkDeleteResponse.NumberOfDocumentsDeleted;
  493. totalRequestUnitsConsumed = bulkDeleteResponse.TotalRequestUnitsConsumed;
  494. totalTimeTakenSec = bulkDeleteResponse.TotalTimeTaken.TotalSeconds;
  495. return list;
  496. }
  497. private static UpdateOperation SwitchType(string key, object obj)
  498. {
  499. Type s = obj.GetType();
  500. TypeCode typeCode = Type.GetTypeCode(s);
  501. return typeCode switch
  502. {
  503. TypeCode.String => new SetUpdateOperation<string>(key, obj.ToString()),
  504. TypeCode.Int32 => new SetUpdateOperation<Int32>(key, (Int32)obj),
  505. TypeCode.Double => new SetUpdateOperation<Double>(key, (Double)obj),
  506. TypeCode.Byte => new SetUpdateOperation<Byte>(key, (Byte)obj),
  507. TypeCode.Boolean => new SetUpdateOperation<Boolean>(key, (Boolean)obj),
  508. TypeCode.DateTime => new SetUpdateOperation<DateTime>(key, (DateTime)obj),
  509. TypeCode.Int64 => new SetUpdateOperation<Int64>(key, (Int64)obj),
  510. _ => null,
  511. };
  512. }
  513. }
  514. }