AzureCosmosDBRepository.cs 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557
  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. object[] attributes = property.GetCustomAttributes(true);
  112. foreach (object attribute in attributes) //2.通过映射,找到成员属性上关联的特性类实例,
  113. {
  114. if (attribute is PartitionKeyAttribute)
  115. {
  116. attrProperties.Add(property);
  117. }
  118. }
  119. }
  120. if (attrProperties.Count <= 0)
  121. {
  122. return null;
  123. }
  124. else
  125. {
  126. if (attrProperties.Count == 1)
  127. {
  128. return attrProperties[0].Name;
  129. }
  130. else { throw new BizException("PartitionKey can only be single!"); }
  131. }
  132. }
  133. public async Task<T> Save<T>(T entity) //where T : object, new()
  134. {
  135. Type t = typeof(T);
  136. DocumentCollection documentCollection = await InitializeCollection<T>();
  137. ResourceResponse<Document> doc =
  138. await CosmosClient.CreateDocumentAsync(UriFactory.CreateDocumentCollectionUri(_Database, t.Name), entity);
  139. //Console.WriteLine(doc.ActivityId);
  140. return entity;
  141. }
  142. public async Task<T> Update<T>(T entity)
  143. {
  144. Type t = typeof(T);
  145. await InitializeCollection<T>();
  146. ResourceResponse<Document> doc =
  147. await CosmosClient.UpsertDocumentAsync(UriFactory.CreateDocumentCollectionUri(_Database, t.Name), entity);
  148. return entity;
  149. }
  150. public async Task<string> ReplaceObject<T>(T entity, string key)
  151. {
  152. Type t = typeof(T);
  153. await InitializeCollection<T>();
  154. try
  155. {
  156. ResourceResponse<Document> doc =
  157. await CosmosClient.ReplaceDocumentAsync(UriFactory.CreateDocumentUri(_Database, t.Name, key), entity);
  158. return key;
  159. }
  160. catch (Exception e)
  161. {
  162. Console.WriteLine("{0} Exception caught.", e);
  163. //return false;
  164. }
  165. return null;
  166. }
  167. public async Task<string> ReplaceObject<T>(T entity, string key, string partitionKey)
  168. {
  169. Type t = typeof(T);
  170. await InitializeCollection<T>();
  171. try
  172. {
  173. ResourceResponse<Document> doc =
  174. await CosmosClient.ReplaceDocumentAsync(UriFactory.CreateDocumentUri(_Database, t.Name, key),
  175. entity,
  176. new RequestOptions { PartitionKey = new PartitionKey(partitionKey) });
  177. return key;
  178. }
  179. catch (Exception e)
  180. {
  181. Console.WriteLine("{0} Exception caught.", e);
  182. //return false;
  183. }
  184. return null;
  185. }
  186. public async Task<List<T>> FindAll<T>()
  187. {
  188. Type t = typeof(T);
  189. Boolean open = true;
  190. List<T> objs = new List<T>();
  191. //await InitializeCollection<T>();
  192. //查询条数 -1是全部
  193. FeedOptions queryOptions = new FeedOptions { MaxItemCount = -1, EnableCrossPartitionQuery = open };
  194. var query = CosmosClient.CreateDocumentQuery<T>(UriFactory.CreateDocumentCollectionUri(_Database, t.Name), queryOptions).AsDocumentQuery();
  195. while (query.HasMoreResults)
  196. {
  197. foreach (T obj in await query.ExecuteNextAsync())
  198. {
  199. objs.Add(obj);
  200. }
  201. }
  202. return objs;
  203. //return CosmosClient.CreateDocumentQuery<T>(UriFactory.CreateDocumentCollectionUri(_Database, t.Name),sql);
  204. }
  205. public async Task<List<T>> FindLinq<T>(Func<IQueryable<object>, object> singleOrDefault)
  206. {
  207. Type t = typeof(T);
  208. List<T> objs = new List<T>();
  209. await InitializeCollection<T>();
  210. //查询条数 -1是全部
  211. FeedOptions queryOptions = new FeedOptions { MaxItemCount = -1 };
  212. var query = CosmosClient.CreateDocumentQuery<T>(UriFactory.CreateDocumentCollectionUri(_Database, t.Name), queryOptions);
  213. // query.Where();
  214. return objs;
  215. //return CosmosClient.CreateDocumentQuery<T>(UriFactory.CreateDocumentCollectionUri(_Database, t.Name),sql);
  216. }
  217. public async Task<List<T>> FindSQL<T>(string sql)
  218. {
  219. Type t = typeof(T);
  220. List<T> objs = new List<T>();
  221. await InitializeCollection<T>();
  222. var query = CosmosClient.CreateDocumentQuery<T>(UriFactory.CreateDocumentCollectionUri(_Database, t.Name), sql);
  223. foreach (var item in query)
  224. {
  225. objs.Add(item);
  226. }
  227. return objs;
  228. }
  229. public async Task<List<T>> FindSQL<T>(string sql, bool IsPk)
  230. {
  231. Type t = typeof(T);
  232. List<T> objs = new List<T>();
  233. Boolean open = IsPk;
  234. await InitializeCollection<T>();
  235. //查询条数 -1是全部
  236. FeedOptions queryOptions = new FeedOptions { MaxItemCount = -1, EnableCrossPartitionQuery = open };
  237. var query = CosmosClient.CreateDocumentQuery<T>(UriFactory.CreateDocumentCollectionUri(_Database, t.Name), sql, queryOptions);
  238. foreach (var item in query)
  239. {
  240. objs.Add(item);
  241. }
  242. return objs;
  243. }
  244. public async Task<List<T>> FindByparams<T>(Dictionary<string, object> dict)
  245. {
  246. //await InitializeCollection<T>();
  247. Type t = typeof(T);
  248. Boolean open = true;
  249. List<Filter> filters = new List<Filter>();
  250. string PKname = "";
  251. PropertyInfo[] properties = t.GetProperties();
  252. List<PropertyInfo> attrProperties = new List<PropertyInfo>();
  253. foreach (PropertyInfo property in properties)
  254. {
  255. object[] attributes = property.GetCustomAttributes(true);
  256. foreach (object attribute in attributes) //2.通过映射,找到成员属性上关联的特性类实例,
  257. {
  258. if (attribute is PartitionKeyAttribute)
  259. {
  260. PKname = property.Name;
  261. break;
  262. }
  263. }
  264. }
  265. foreach (string key in dict.Keys)
  266. {
  267. //if (t.Name.Equals(key)) {
  268. // open = false;
  269. //}
  270. if (PKname.Equals(key))
  271. {
  272. open = false;
  273. }
  274. filters.Add(new Filter { Key = key, Value = dict[key] != null ? dict[key].ToString() : throw new Exception("参数值不能为null") });
  275. }
  276. //List<T> objs = new List<T>();
  277. await InitializeCollection<T>();
  278. //查询条数 -1是全部
  279. FeedOptions queryOptions = new FeedOptions { MaxItemCount = -1, EnableCrossPartitionQuery = open };
  280. var query = CosmosClient.CreateDocumentQuery<T>(UriFactory.CreateDocumentCollectionUri(_Database, t.Name), queryOptions);
  281. List<T> list = DynamicLinq.GenerateFilter<T>(query, filters).ToList();
  282. return list;
  283. //return CosmosClient.CreateDocumentQuery<T>(UriFactory.CreateDocumentCollectionUri(_Database, t.Name),sql);
  284. }
  285. public async Task<string> DeleteAsync<T>(string id)
  286. {
  287. Type t = typeof(T);
  288. await InitializeCollection<T>();
  289. ResourceResponse<Document> doc =
  290. await CosmosClient.DeleteDocumentAsync(UriFactory.CreateDocumentUri(_Database, t.Name, id));
  291. //Console.WriteLine(doc.ActivityId);
  292. return id;
  293. }
  294. public async Task<T> DeleteAsync<T>(T entity)
  295. {
  296. await InitializeCollection<T>();
  297. Type t = typeof(T);
  298. string PartitionKey = GetPartitionKey<T>();
  299. if (!string.IsNullOrEmpty(PartitionKey))
  300. {
  301. string pkValue = entity.GetType().GetProperty(PartitionKey).GetValue(entity).ToString();
  302. string idValue = entity.GetType().GetProperty("id").GetValue(entity).ToString();
  303. ResourceResponse<Document> doc =
  304. await CosmosClient.DeleteDocumentAsync(UriFactory.CreateDocumentUri(_Database, t.Name, idValue), new RequestOptions { PartitionKey = new PartitionKey(pkValue) });
  305. }
  306. else
  307. {
  308. string idValue = entity.GetType().GetProperty("id").GetValue(entity).ToString();
  309. ResourceResponse<Document> doc =
  310. await CosmosClient.DeleteDocumentAsync(UriFactory.CreateDocumentUri(_Database, t.Name, idValue));
  311. }
  312. //Console.WriteLine(doc.ActivityId);
  313. return entity;
  314. }
  315. public async Task<string> DeleteAsync<T>(string id, string partitionKey)
  316. {
  317. Type t = typeof(T);
  318. await InitializeCollection<T>();
  319. ResourceResponse<Document> doc =
  320. await CosmosClient.DeleteDocumentAsync(UriFactory.CreateDocumentUri(_Database, t.Name, id), new RequestOptions { PartitionKey = new PartitionKey(partitionKey) });
  321. //Console.WriteLine(doc.ActivityId);
  322. return id;
  323. }
  324. public async Task<List<T>> SaveAll<T>(List<T> enyites)
  325. {
  326. DocumentCollection dataCollection = await InitializeCollection<T>();
  327. // Set retry options high for initialization (default values).
  328. CosmosClient.ConnectionPolicy.RetryOptions.MaxRetryWaitTimeInSeconds = 30;
  329. CosmosClient.ConnectionPolicy.RetryOptions.MaxRetryAttemptsOnThrottledRequests = 9;
  330. IBulkExecutor bulkExecutor = new BulkExecutor(CosmosClient, dataCollection);
  331. await bulkExecutor.InitializeAsync();
  332. // Set retries to 0 to pass control to bulk executor.
  333. CosmosClient.ConnectionPolicy.RetryOptions.MaxRetryWaitTimeInSeconds = 0;
  334. CosmosClient.ConnectionPolicy.RetryOptions.MaxRetryAttemptsOnThrottledRequests = 0;
  335. BulkImportResponse bulkImportResponse = null;
  336. long totalNumberOfDocumentsInserted = 0;
  337. double totalRequestUnitsConsumed = 0;
  338. double totalTimeTakenSec = 0;
  339. var tokenSource = new CancellationTokenSource();
  340. var token = tokenSource.Token;
  341. int pageSize = 100;
  342. int pages = (int)Math.Ceiling((double)enyites.Count / pageSize);
  343. for (int i = 0; i < pages; i++)
  344. {
  345. List<string> documentsToImportInBatch = new List<string>();
  346. List<T> lists = enyites.Skip((i) * pageSize).Take(pageSize).ToList();
  347. for (int j = 0; j < lists.Count; j++)
  348. {
  349. documentsToImportInBatch.Add(lists[j].ToJson());
  350. }
  351. var tasks = new List<Task>();
  352. tasks.Add(Task.Run(async () =>
  353. {
  354. do
  355. {
  356. //try
  357. //{
  358. bulkImportResponse = await bulkExecutor.BulkImportAsync(
  359. documents: documentsToImportInBatch,
  360. enableUpsert: true,
  361. disableAutomaticIdGeneration: true,
  362. maxConcurrencyPerPartitionKeyRange: null,
  363. maxInMemorySortingBatchSize: null,
  364. cancellationToken: token);
  365. //}
  366. //catch (DocumentClientException de)
  367. //{
  368. // break;
  369. //}
  370. //catch (Exception e)
  371. //{
  372. // break;
  373. //}
  374. } while (bulkImportResponse.NumberOfDocumentsImported < documentsToImportInBatch.Count);
  375. totalNumberOfDocumentsInserted += bulkImportResponse.NumberOfDocumentsImported;
  376. totalRequestUnitsConsumed += bulkImportResponse.TotalRequestUnitsConsumed;
  377. totalTimeTakenSec += bulkImportResponse.TotalTimeTaken.TotalSeconds;
  378. },
  379. token));
  380. await Task.WhenAll(tasks);
  381. }
  382. return enyites;
  383. }
  384. public async Task<List<T>> UpdateAll<T>(Dictionary<string, object> dict, Dictionary<string, object> updateFilters, List<string> deleteKeys = null)
  385. {
  386. DocumentCollection dataCollection = await InitializeCollection<T>();
  387. IBulkExecutor bulkExecutor = new BulkExecutor(CosmosClient, dataCollection);
  388. await bulkExecutor.InitializeAsync();
  389. BulkUpdateResponse bulkUpdateResponse = null;
  390. long totalNumberOfDocumentsUpdated = 0;
  391. double totalRequestUnitsConsumed = 0;
  392. double totalTimeTakenSec = 0;
  393. var tokenSource = new CancellationTokenSource();
  394. var token = tokenSource.Token;
  395. // Generate update operations.
  396. List<UpdateOperation> updateOperations = new List<UpdateOperation>();
  397. // Unset the description field.
  398. if (null != updateFilters && updateFilters.Count > 0)
  399. {
  400. var keys = updateFilters.Keys;
  401. foreach (string key in keys)
  402. {
  403. // updateOperations.Add(new SetUpdateOperation<string>())
  404. if (updateFilters[key] != null && !string.IsNullOrEmpty(updateFilters[key].ToString()))
  405. {
  406. updateOperations.Add(SwitchType(key, updateFilters[key]));
  407. }
  408. }
  409. }
  410. if (deleteKeys.IsNotEmpty())
  411. {
  412. foreach (string key in deleteKeys)
  413. {
  414. updateOperations.Add(new UnsetUpdateOperation(key));
  415. }
  416. }
  417. List<T> list = await FindByparams<T>(dict);
  418. int pageSize = 100;
  419. int pages = (int)Math.Ceiling((double)list.Count / pageSize);
  420. string partitionKey = "/" + GetPartitionKey<T>();
  421. Type type = typeof(T);
  422. for (int i = 0; i < pages; i++)
  423. {
  424. List<UpdateItem> updateItemsInBatch = new List<UpdateItem>();
  425. List<T> lists = list.Skip((i) * pageSize).Take(pageSize).ToList();
  426. for (int j = 0; j < lists.Count; j++)
  427. {
  428. string partitionKeyValue = lists[j].GetType().GetProperty(partitionKey).GetValue(lists[j]) + "";
  429. string id = lists[j].GetType().GetProperty("id").GetValue(lists[j]) + "";
  430. updateItemsInBatch.Add(new UpdateItem(id, partitionKeyValue, updateOperations));
  431. }
  432. var tasks = new List<Task>();
  433. tasks.Add(Task.Run(async () =>
  434. {
  435. do
  436. {
  437. //try
  438. //{
  439. bulkUpdateResponse = await bulkExecutor.BulkUpdateAsync(
  440. updateItems: updateItemsInBatch,
  441. maxConcurrencyPerPartitionKeyRange: null,
  442. cancellationToken: token);
  443. //}
  444. //catch (DocumentClientException de)
  445. //{
  446. // break;
  447. //}
  448. //catch (Exception e)
  449. //{
  450. // break;
  451. //}
  452. } while (bulkUpdateResponse.NumberOfDocumentsUpdated < updateItemsInBatch.Count);
  453. totalNumberOfDocumentsUpdated += bulkUpdateResponse.NumberOfDocumentsUpdated;
  454. totalRequestUnitsConsumed += bulkUpdateResponse.TotalRequestUnitsConsumed;
  455. totalTimeTakenSec += bulkUpdateResponse.TotalTimeTaken.TotalSeconds;
  456. },
  457. token));
  458. await Task.WhenAll(tasks);
  459. }
  460. return list;
  461. }
  462. public async Task<List<T>> DeleteALl<T>(Dictionary<string, object> dict)
  463. {
  464. DocumentCollection dataCollection = await InitializeCollection<T>();
  465. List<T> list = await FindByparams<T>(dict);
  466. List<Tuple<string, string>> pkIdTuplesToDelete = new List<Tuple<string, string>>();
  467. if (list.IsNotEmpty())
  468. {
  469. foreach (T t in list)
  470. {
  471. string id = t.GetType().GetProperty("id").GetValue(t) + "";
  472. pkIdTuplesToDelete.Add(new Tuple<string, string>(id, id));
  473. }
  474. }
  475. else
  476. {
  477. return null;
  478. }
  479. long totalNumberOfDocumentsDeleted = 0;
  480. double totalRequestUnitsConsumed = 0;
  481. double totalTimeTakenSec = 0;
  482. BulkDeleteResponse bulkDeleteResponse = null;
  483. BulkExecutor bulkExecutor = new BulkExecutor(CosmosClient, dataCollection);
  484. await bulkExecutor.InitializeAsync();
  485. bulkDeleteResponse = await bulkExecutor.BulkDeleteAsync(pkIdTuplesToDelete);
  486. totalNumberOfDocumentsDeleted = bulkDeleteResponse.NumberOfDocumentsDeleted;
  487. totalRequestUnitsConsumed = bulkDeleteResponse.TotalRequestUnitsConsumed;
  488. totalTimeTakenSec = bulkDeleteResponse.TotalTimeTaken.TotalSeconds;
  489. return list;
  490. }
  491. private static UpdateOperation SwitchType(string key, object obj)
  492. {
  493. Type s = obj.GetType();
  494. TypeCode typeCode = Type.GetTypeCode(s);
  495. switch (typeCode)
  496. {
  497. case TypeCode.String: return new SetUpdateOperation<string>(key, obj.ToString());
  498. case TypeCode.Int32: return new SetUpdateOperation<Int32>(key, (Int32)obj);
  499. case TypeCode.Double: return new SetUpdateOperation<Double>(key, (Double)obj);
  500. case TypeCode.Byte: return new SetUpdateOperation<Byte>(key, (Byte)obj);
  501. case TypeCode.Boolean: return new SetUpdateOperation<Boolean>(key, (Boolean)obj);
  502. case TypeCode.DateTime: return new SetUpdateOperation<DateTime>(key, (DateTime)obj);
  503. case TypeCode.Int64: return new SetUpdateOperation<Int64>(key, (Int64)obj);
  504. default: return null;
  505. }
  506. }
  507. }
  508. }