AzureStorageTableExtensions.cs 23 KB

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