AzureStorageTableExtensions.cs 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517
  1. using Microsoft.Azure.Cosmos.Table;
  2. using Microsoft.Azure.Cosmos.Table.Queryable;
  3. using System;
  4. using System.Collections;
  5. using System.Collections.Generic;
  6. using System.Text;
  7. using System.Threading;
  8. using System.Threading.Tasks;
  9. using System.Linq;
  10. using TEAMModelOS.SDK;
  11. using System.Reflection;
  12. using HTEXLib.COMM.Helpers;
  13. namespace TEAMModelOS.SDK.DI
  14. {
  15. public static class AzureStorageTableExtensions
  16. {
  17. #region CloudTable 批次操作
  18. /// <summary>
  19. /// 批次新增資料至Table儲存區。
  20. /// </summary>
  21. /// <param name="entities">欲快取的集合</param>
  22. /// <returns></returns>
  23. public static async Task<TableBatchResult> BatchInsertAsync<T>(this CloudTable table, IEnumerable<T> entities) where T : ITableEntity, new()
  24. {
  25. TableBatchOperation batchOperation = new TableBatchOperation();
  26. foreach (var cache in entities)
  27. {
  28. batchOperation.Insert(cache);
  29. }
  30. return await table.ExecuteBatchAsync(batchOperation);
  31. }
  32. #endregion
  33. #region CloudTable Get
  34. /// <summary>
  35. /// (同步)取得 table 中指定 PartitionKey 的所有集合。
  36. /// </summary>
  37. /// <returns></returns>
  38. public static IEnumerable<T> Get<T>(this CloudTable table, string partitionKey) where T : ITableEntity, new()
  39. {
  40. TableQuery<T> query = new TableQuery<T>().Where(TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.Equal, partitionKey));
  41. return table.ExecuteQuery(query);
  42. }
  43. /// <summary>
  44. /// (同步)取得指定 PartitionKey與 RowKey 的數據,效能:點查詢,最佳。
  45. /// </summary>
  46. /// <typeparam name="T">T</typeparam>
  47. /// <param name="partitionKey">PartitionKey</param>
  48. /// <param name="rowKey">RowKey</param>
  49. /// <returns></returns>
  50. public static T Get<T>(this CloudTable table, string partitionKey, string rowKey) where T : ITableEntity, new()
  51. {
  52. TableOperation retrieveOperation = TableOperation.Retrieve<T>(partitionKey, rowKey);
  53. var retrieveResult = table.Execute(retrieveOperation);
  54. if (retrieveResult.Result != null)
  55. {
  56. //DynamicTableEntityJsonSeria1lizer
  57. return (T)retrieveResult.Result;
  58. }
  59. else
  60. {
  61. return default(T);
  62. }
  63. }
  64. public static DynamicTableEntity Get(this CloudTable table, string partitionKey, string rowKey)
  65. {
  66. TableOperation retrieveOperation = TableOperation.Retrieve(partitionKey, rowKey);
  67. var retrieveResult = table.Execute(retrieveOperation);
  68. if (retrieveResult.Result != null)
  69. {
  70. return retrieveResult.Result as DynamicTableEntity;
  71. }
  72. else
  73. {
  74. return null;
  75. }
  76. }
  77. /// <summary>
  78. /// 取得指定 PartitionKey 的所有集合(分頁),效能:範圍查詢,次佳。
  79. /// </summary>
  80. /// <typeparam name="T">T</typeparam>
  81. /// <param name="partitionKey">PartitionKey</param>
  82. /// <param name="takeCount">指定每次返回數量</param>
  83. /// <param name="specifyPropertys">指定只須返回的屬性,效能:伺服器端預測,降低延遲和成本</param>
  84. /// <param name="onProgress">要返回集合的委派</param>
  85. /// <param name="ct">CancellationToken</param>
  86. /// <returns></returns>
  87. public static async Task GetAsync<T>(this CloudTable table, string partitionKey, int? takeCount = null, List<string> specifyPropertys = null, Action<IList<T>> onProgress = null, CancellationToken ct = default(CancellationToken)) where T : ITableEntity, new()
  88. {
  89. TableQuery<T> tableQuery = null;
  90. TableContinuationToken token = null;
  91. var filter = TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.Equal, partitionKey);
  92. if (specifyPropertys != null)
  93. tableQuery = new TableQuery<T>().Where(filter).Select(specifyPropertys);
  94. else
  95. tableQuery = new TableQuery<T>().Where(filter);
  96. if (takeCount != null) tableQuery.TakeCount = takeCount;
  97. do
  98. {
  99. var queryResponse = await table.ExecuteQuerySegmentedAsync(tableQuery, token);
  100. token = queryResponse.ContinuationToken;
  101. onProgress?.Invoke(queryResponse.Results);
  102. } while (token != null && !ct.IsCancellationRequested);
  103. }
  104. /// <summary>
  105. /// 取得指定 PartitionKey 的所有集合,效能:範圍查詢,次佳。
  106. /// </summary>
  107. /// <typeparam name="T">T</typeparam>
  108. /// <param name="partitionKey">PartitionKey</param>
  109. /// <param name="takeCount">指定每次返回數量</param>
  110. /// <param name="specifyPropertys">指定只須返回的屬性,效能:伺服器端預測,降低延遲和成本</param>
  111. /// <param name="onProgress">要返回集合的委派</param>
  112. /// <param name="ct">CancellationToken</param>
  113. /// <returns></returns>
  114. public static async Task<IEnumerable<T>> GetAsync<T>(this CloudTable table, string partitionKey, int? takeCount = null, List<string> specifyPropertys = null, CancellationToken ct = default(CancellationToken)) where T : ITableEntity, new()
  115. {
  116. TableQuery<T> tableQuery = null;
  117. TableContinuationToken token = null;
  118. var filter = TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.Equal, partitionKey);
  119. if (specifyPropertys != null)
  120. tableQuery = new TableQuery<T>().Where(filter).Select(specifyPropertys);
  121. else
  122. tableQuery = new TableQuery<T>().Where(filter);
  123. if (takeCount != null) tableQuery.TakeCount = takeCount;
  124. var items = new List<T>();
  125. do
  126. {
  127. var queryResponse = await table.ExecuteQuerySegmentedAsync(tableQuery, token);
  128. token = queryResponse.ContinuationToken;
  129. items.AddRange(queryResponse.Results);
  130. } while (token != null && !ct.IsCancellationRequested);
  131. return items;
  132. }
  133. /// <summary>
  134. /// 傳回指定partitionKey的Count數量
  135. /// </summary>
  136. /// <param name="partitionKey"></param>
  137. /// <returns></returns>
  138. public static int GetCount(this CloudTable table, string partitionKey)
  139. {
  140. TableQuery query = new TableQuery().Where(TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.Equal, partitionKey)).Select(new List<string> { "PartitionKey" });
  141. var queryResponse = table.ExecuteQuery(query).ToList();
  142. return queryResponse.Count();
  143. }
  144. #endregion
  145. #region CloudTable Get All
  146. /// <summary>
  147. /// (同步)取得 table 的所有集合,效能:資料表掃描,不佳。
  148. /// </summary>
  149. /// <returns></returns>
  150. public static IEnumerable<T> GetAll<T>(this CloudTable table) where T : ITableEntity, new()
  151. {
  152. return table.ExecuteQuery(new TableQuery<T>());
  153. }
  154. /// <summary>
  155. /// 取得 table 的所有集合(分頁),效能:資料表掃描,不佳。
  156. /// </summary>
  157. /// <param name="takeCount">指定每次返回數量</param>
  158. /// <param name="specifyPropertys">指定只須返回的屬性,效能:伺服器端預測,降低延遲和成本</param>
  159. /// <param name="onProgress">要返回集合的委派</param>
  160. /// <returns></returns>
  161. public static async Task GetAllAsync<T>(this CloudTable table, int? takeCount = null, List<string> specifyPropertys = null, Action<IList<T>> onProgress = null, CancellationToken ct = default(CancellationToken)) where T : ITableEntity, new()
  162. {
  163. TableContinuationToken token = null;
  164. TableQuery<T> tableQuery = new TableQuery<T>();
  165. if (specifyPropertys != null)
  166. tableQuery = new TableQuery<T>().Select(specifyPropertys);
  167. else
  168. tableQuery = new TableQuery<T>();
  169. if (takeCount != null) tableQuery.TakeCount = takeCount;
  170. var items = new List<T>();
  171. do
  172. {
  173. var queryResponse = await table.ExecuteQuerySegmentedAsync(tableQuery, token);
  174. token = queryResponse.ContinuationToken;
  175. items.AddRange(queryResponse.Results);
  176. onProgress?.Invoke(queryResponse.Results);
  177. } while (token != null && !ct.IsCancellationRequested);
  178. }
  179. /// <summary>
  180. /// 取得 table 的所有集合,效能:資料表掃描,不佳。
  181. /// </summary>
  182. /// <param name="takeCount">指定每次返回數量</param>
  183. /// <param name="specifyPropertys">指定只須返回的屬性,效能:伺服器端預測,降低延遲和成本</param>
  184. /// <returns></returns>
  185. public static async Task<IEnumerable<T>> GetAllAsync<T>(this CloudTable table, int? takeCount = null, List<string> specifyPropertys = null, CancellationToken ct = default(CancellationToken)) where T : ITableEntity, new()
  186. {
  187. TableContinuationToken token = null;
  188. TableQuery<T> tableQuery = new TableQuery<T>();
  189. if (takeCount != null) tableQuery.TakeCount = takeCount;
  190. if (specifyPropertys != null)
  191. tableQuery = new TableQuery<T>().Select(specifyPropertys);
  192. else
  193. tableQuery = new TableQuery<T>();
  194. var items = new List<T>();
  195. do
  196. {
  197. var queryResponse = await table.ExecuteQuerySegmentedAsync(tableQuery, token);
  198. token = queryResponse.ContinuationToken;
  199. items.AddRange(queryResponse.Results);
  200. } while (token != null && !ct.IsCancellationRequested);
  201. return items;
  202. }
  203. #endregion
  204. public static async Task<T> Save<T>(this AzureStorageFactory azureStorage, TableEntity entity) where T : TableEntity, new()
  205. {
  206. CloudTable TableName = await azureStorage.InitializeTable<T>();
  207. TableOperation operation = TableOperation.Insert(entity);
  208. TableResult result = await TableName.ExecuteAsync(operation);
  209. return (T)result.Result;
  210. }
  211. public static async Task<T> SaveOrUpdate<T>(this AzureStorageFactory azureStorage, TableEntity entity) where T : TableEntity, new()
  212. {
  213. CloudTable TableName = await azureStorage.InitializeTable<T>();
  214. TableOperation operation = TableOperation.InsertOrReplace(entity);
  215. TableResult result = await TableName.ExecuteAsync(operation);
  216. return (T)result.Result;
  217. }
  218. public static async Task<T> Update<T>(this AzureStorageFactory azureStorage, TableEntity entity) where T : TableEntity, new()
  219. {
  220. CloudTable TableName = await azureStorage.InitializeTable<T>();
  221. TableOperation operation = TableOperation.Replace(entity);
  222. TableResult result = await TableName.ExecuteAsync(operation);
  223. return (T)result.Result;
  224. }
  225. public static async Task<T> Delete<T>(this AzureStorageFactory azureStorage, TableEntity entity) where T : TableEntity, new()
  226. {
  227. CloudTable TableName = await azureStorage.InitializeTable<T>();
  228. TableOperation operation = TableOperation.Delete(entity);
  229. TableResult result = await TableName.ExecuteAsync(operation);
  230. return (T)result.Result;
  231. }
  232. public static async Task<List<T>> DeleteAll<T>(this AzureStorageFactory azureStorage, List<T> entitys) where T : TableEntity, new()
  233. {
  234. if (!entitys.IsNotEmpty())
  235. {
  236. return null;
  237. }
  238. CloudTable TableName = await azureStorage.InitializeTable<T>();
  239. IList<Dictionary<string, List<T>>> listInfo = new List<Dictionary<string, List<T>>>();
  240. foreach (IGrouping<string, T> group in entitys.GroupBy(c => c.PartitionKey))
  241. {
  242. Dictionary<string, List<T>> dictInfo = new Dictionary<string, List<T>>
  243. {
  244. { group.Key, group.ToList() }
  245. };
  246. listInfo.Add(dictInfo);
  247. }
  248. foreach (Dictionary<string, List<T>> dict in listInfo)
  249. {
  250. IList<TableResult> result = null;
  251. foreach (string key in dict.Keys)
  252. {
  253. List<T> values = dict[key];
  254. int pageSize = 100;
  255. int pages = (int)Math.Ceiling((double)values.Count / pageSize);
  256. for (int i = 0; i < pages; i++)
  257. {
  258. List<T> lists = values.Skip((i) * pageSize).Take(pageSize).ToList();
  259. TableBatchOperation batchOperation = new TableBatchOperation();
  260. for (int j = 0; j < lists.Count; j++)
  261. {
  262. batchOperation.Delete(lists[j]);
  263. }
  264. result = await TableName.ExecuteBatchAsync(batchOperation);
  265. }
  266. }
  267. }
  268. return entitys;
  269. }
  270. public static async Task<List<T>> SaveOrUpdateAll<T>(this AzureStorageFactory azureStorage, List<T> entitys) where T : TableEntity, new()
  271. {
  272. if (!entitys.IsNotEmpty())
  273. {
  274. return null;
  275. }
  276. CloudTable TableName = await azureStorage.InitializeTable<T>();
  277. IList<Dictionary<string, List<T>>> listInfo = new List<Dictionary<string, List<T>>>();
  278. foreach (IGrouping<string, T> group in entitys.GroupBy(c => c.PartitionKey))
  279. {
  280. Dictionary<string, List<T>> dictInfo = new Dictionary<string, List<T>>
  281. {
  282. { group.Key, group.ToList() }
  283. };
  284. listInfo.Add(dictInfo);
  285. }
  286. foreach (Dictionary<string, List<T>> dict in listInfo)
  287. {
  288. IList<TableResult> result = null;
  289. foreach (string key in dict.Keys)
  290. {
  291. List<T> values = dict[key];
  292. int pageSize = 100;
  293. int pages = (int)Math.Ceiling((double)values.Count / pageSize);
  294. for (int i = 0; i < pages; i++)
  295. {
  296. List<T> lists = values.Skip((i) * pageSize).Take(pageSize).ToList();
  297. TableBatchOperation batchOperation = new TableBatchOperation();
  298. for (int j = 0; j < lists.Count; j++)
  299. {
  300. batchOperation.InsertOrReplace(lists[j]);
  301. }
  302. result = await TableName.ExecuteBatchAsync(batchOperation);
  303. }
  304. }
  305. }
  306. return entitys;
  307. }
  308. public static async Task<List<T>> UpdateAll<T>(this AzureStorageFactory azureStorageFactory, List<T> entitys) where T : TableEntity, new()
  309. {
  310. if (!entitys.IsNotEmpty())
  311. {
  312. return null;
  313. }
  314. CloudTable TableName = await azureStorageFactory.InitializeTable<T>();
  315. IList<Dictionary<string, List<T>>> listInfo = new List<Dictionary<string, List<T>>>();
  316. foreach (IGrouping<string, T> group in entitys.GroupBy(c => c.PartitionKey))
  317. {
  318. Dictionary<string, List<T>> dictInfo = new Dictionary<string, List<T>>
  319. {
  320. { group.Key, group.ToList() }
  321. };
  322. listInfo.Add(dictInfo);
  323. }
  324. foreach (Dictionary<string, List<T>> dict in listInfo)
  325. {
  326. IList<TableResult> result = null;
  327. foreach (string key in dict.Keys)
  328. {
  329. List<T> values = dict[key];
  330. int pageSize = 100;
  331. int pages = (int)Math.Ceiling((double)values.Count / pageSize);
  332. for (int i = 0; i < pages; i++)
  333. {
  334. List<T> lists = values.Skip((i) * pageSize).Take(pageSize).ToList();
  335. TableBatchOperation batchOperation = new TableBatchOperation();
  336. for (int j = 0; j < lists.Count; j++)
  337. {
  338. batchOperation.Replace(lists[j]);
  339. }
  340. result = await TableName.ExecuteBatchAsync(batchOperation);
  341. }
  342. }
  343. }
  344. return entitys;
  345. }
  346. public static async Task<List<T>> SaveAll<T>(this AzureStorageFactory azureStorage, List<T> entitys) where T : TableEntity, new()
  347. {
  348. if (!entitys.IsNotEmpty())
  349. {
  350. return null;
  351. }
  352. CloudTable TableName = await azureStorage.InitializeTable<T>();
  353. IList<Dictionary<string, List<T>>> listInfo = new List<Dictionary<string, List<T>>>();
  354. foreach (IGrouping<string, T> group in entitys.GroupBy(c => c.PartitionKey))
  355. {
  356. Dictionary<string, List<T>> dictInfo = new Dictionary<string, List<T>>
  357. {
  358. { group.Key, group.ToList() }
  359. };
  360. listInfo.Add(dictInfo);
  361. }
  362. foreach (Dictionary<string, List<T>> dict in listInfo)
  363. {
  364. IList<TableResult> result = null;
  365. foreach (string key in dict.Keys)
  366. {
  367. List<T> values = dict[key];
  368. int pageSize = 100;
  369. int pages = (int)Math.Ceiling((double)values.Count / pageSize);
  370. for (int i = 0; i < pages; i++)
  371. {
  372. List<T> lists = values.Skip((i) * pageSize).Take(pageSize).ToList();
  373. TableBatchOperation batchOperation = new TableBatchOperation();
  374. for (int j = 0; j < lists.Count; j++)
  375. {
  376. batchOperation.Insert(lists[j]);
  377. }
  378. result = await TableName.ExecuteBatchAsync(batchOperation);
  379. }
  380. }
  381. }
  382. return entitys;
  383. }
  384. public static async Task<List<T>> FindListByDict<T>(this AzureStorageFactory azureStorage, Dictionary<string, object> dict) where T : TableEntity, new()
  385. {
  386. CloudTable TableName = await azureStorage.InitializeTable<T>();
  387. var exQuery = new TableQuery<T>();
  388. StringBuilder builder = new StringBuilder();
  389. if (null != dict && dict.Count > 0)
  390. {
  391. var keys = dict.Keys;
  392. int index = 1;
  393. foreach (string key in keys)
  394. {
  395. if (dict[key] != null && !string.IsNullOrEmpty(dict[key].ToString()))
  396. {
  397. string typeStr = SwitchType<T>(dict[key], key);
  398. if (string.IsNullOrEmpty(typeStr))
  399. {
  400. continue;
  401. }
  402. if (index == 1)
  403. {
  404. //builder.Append(TableQuery.GenerateFilterCondition(key, QueryComparisons.Equal, dict[key].ToString()));
  405. builder.Append(typeStr);
  406. }
  407. else
  408. {
  409. //builder.Append(" " + TableOperators.And + " " + TableQuery.GenerateFilterCondition(key, QueryComparisons.Equal, dict[key].ToString()));
  410. builder.Append(" " + TableOperators.And + " " + typeStr);
  411. }
  412. index++;
  413. }
  414. else
  415. {
  416. throw new Exception("The parameter must have value!");
  417. }
  418. }
  419. exQuery.Where(builder.ToString());
  420. return await QueryList<T>(exQuery, TableName);
  421. }
  422. else
  423. {
  424. return null;
  425. }
  426. }
  427. private static async Task<List<T>> QueryList<T>(TableQuery<T> exQuery, CloudTable TableName ) where T : TableEntity, new()
  428. {
  429. TableContinuationToken continuationToken = null;
  430. List<T> entitys = new List<T>();
  431. do
  432. {
  433. var result = await TableName.ExecuteQuerySegmentedAsync(exQuery, continuationToken);
  434. if (result.Results.Count > 0)
  435. {
  436. entitys.AddRange(result.ToList());
  437. }
  438. continuationToken = result.ContinuationToken;
  439. } while (continuationToken != null);
  440. return entitys;
  441. }
  442. private static string SwitchType<T>(object obj, string key)
  443. {
  444. Type objType = typeof(T);
  445. PropertyInfo property = objType.GetProperty(key);
  446. //Type s = obj.GetType();
  447. //TypeCode typeCode = Type.GetTypeCode(s);
  448. if (property == null)
  449. {
  450. //return null;
  451. throw new Exception(objType.FullName + " PropertyInfo doesn't include this parameter :" + key);
  452. }
  453. TypeCode typeCode = Type.GetTypeCode(property.PropertyType);
  454. switch (typeCode)
  455. {
  456. case TypeCode.String: return TableQuery.GenerateFilterCondition(key, QueryComparisons.Equal, obj.ToString());
  457. case TypeCode.Int32: return TableQuery.GenerateFilterConditionForInt(key, QueryComparisons.Equal, int.Parse(obj.ToString()));
  458. case TypeCode.Double: return TableQuery.GenerateFilterConditionForDouble(key, QueryComparisons.Equal, (double)obj);
  459. case TypeCode.Byte: return TableQuery.GenerateFilterConditionForBinary(key, QueryComparisons.Equal, (byte[])obj);
  460. case TypeCode.Boolean: return TableQuery.GenerateFilterConditionForBool(key, QueryComparisons.Equal, (bool)obj);
  461. case TypeCode.DateTime: return TableQuery.GenerateFilterConditionForDate(key, QueryComparisons.Equal, (DateTimeOffset)obj);
  462. case TypeCode.Int64: return TableQuery.GenerateFilterConditionForLong(key, QueryComparisons.Equal, long.Parse(obj.ToString()));
  463. default: return null;
  464. }
  465. }
  466. }
  467. }