AzureStorageFactory.cs 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244
  1. using Microsoft.Azure.Cosmos.Table;
  2. using Microsoft.Extensions.Options;
  3. using Microsoft.Extensions.Logging;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.Text;
  7. using Microsoft.Extensions.DependencyInjection;
  8. using Azure.Storage.Blobs;
  9. using Azure.Storage.Blobs.Models;
  10. using Azure.Storage.Blobs.Specialized;
  11. using Azure.Storage.Sas;
  12. using Azure.Storage;
  13. using TEAMModelOS.SDK.Extension;
  14. using Azure.Storage.Queues;
  15. using TEAMModelOS.SDK.Context.Attributes.Azure;
  16. using System.Threading.Tasks;
  17. namespace TEAMModelOS.SDK.DI
  18. {
  19. public class AzureStorageFactory
  20. {
  21. private readonly IServiceProvider _services;
  22. private readonly IOptionsMonitor<AzureStorageFactoryOptions> _optionsMonitor;
  23. private readonly ILogger _logger;
  24. public AzureStorageFactory(IServiceProvider services, IOptionsMonitor<AzureStorageFactoryOptions> optionsMonitor, ILogger<AzureStorageFactory> logger)
  25. {
  26. if (services == null) throw new ArgumentNullException(nameof(services));
  27. if (optionsMonitor == null) throw new ArgumentNullException(nameof(optionsMonitor));
  28. _services = services;
  29. _optionsMonitor = optionsMonitor;
  30. _logger = logger;
  31. }
  32. public BlobServiceClient GetBlobServiceClient(string name = "Default")
  33. {
  34. try
  35. {
  36. var options = _optionsMonitor.Get(name);
  37. return new BlobServiceClient(options.StorageAccountConnectionString);
  38. }
  39. catch (OptionsValidationException e)
  40. {
  41. _logger?.LogWarning(e, e.Message);
  42. return null;
  43. }
  44. }
  45. public BlobContainerClient GetBlobContainerClient(string containerName, string name = "Default")
  46. {
  47. try
  48. {
  49. var options = _optionsMonitor.Get(name);
  50. return new BlobContainerClient(options.StorageAccountConnectionString, containerName);
  51. }
  52. catch (OptionsValidationException e)
  53. {
  54. _logger?.LogWarning(e, e.Message);
  55. return null;
  56. }
  57. }
  58. public BlobBatchClient GetBlobBatchClient(string name = "Default")
  59. {
  60. try
  61. {
  62. var options = _optionsMonitor.Get(name);
  63. BlobServiceClient blobServiceClient = new BlobServiceClient(options.StorageAccountConnectionString);
  64. return blobServiceClient.GetBlobBatchClient();
  65. }
  66. catch (OptionsValidationException e)
  67. {
  68. _logger?.LogWarning(e, e.Message);
  69. return null;
  70. }
  71. }
  72. /// <summary>
  73. /// 取得Blob Container SAS (有效期預設一天)
  74. /// </summary>
  75. /// <param name="containerName">容器名稱</param>
  76. /// <param name="blobContainerSasPermissions">權限(可多選)Flags</param>
  77. /// <param name="name"></param>
  78. /// <returns></returns>
  79. public (string uri ,string sas) GetBlobContainerSAS(string containerName, BlobContainerSasPermissions blobContainerSasPermissions, string name = "Default")
  80. {
  81. try
  82. {
  83. var keys = Utils.ParseConnectionString(_optionsMonitor.Get(name).StorageAccountConnectionString);
  84. var accountname = keys["AccountName"];
  85. var accountkey = keys["AccountKey"];
  86. var endpoint = keys["EndpointSuffix"];
  87. var blobSasBuilder = new BlobSasBuilder
  88. {
  89. StartsOn = DateTimeOffset.UtcNow.Subtract(new TimeSpan(0, 15, 0)),
  90. ExpiresOn = DateTimeOffset.UtcNow.Add(new TimeSpan(1, 0, 15, 0)),
  91. BlobContainerName = containerName
  92. };
  93. blobSasBuilder.SetPermissions(blobContainerSasPermissions);
  94. var sskc = new StorageSharedKeyCredential(accountname, accountkey);
  95. BlobSasQueryParameters sasQueryParameters = blobSasBuilder.ToSasQueryParameters(sskc);
  96. UriBuilder fullUri = new UriBuilder()
  97. {
  98. Scheme = "https",
  99. Host = $"{accountname}.blob.{endpoint}",
  100. Path = containerName
  101. //Query = sasQueryParameters.ToString()
  102. };
  103. return (fullUri.Uri.ToString(), sasQueryParameters.ToString());
  104. }
  105. catch
  106. {
  107. return (null, null);
  108. }
  109. }
  110. /// <summary>
  111. /// 取得Blob SAS (有效期預設一天)
  112. /// </summary>
  113. /// <param name="containerName">容器名稱</param>
  114. /// <param name="blobName"></param>
  115. /// <param name="blobSasPermissions">權限(可多選)Flags</param>
  116. /// <param name="name"></param>
  117. /// <returns></returns>
  118. public string GetBlobSAS(string containerName, string blobName, BlobSasPermissions blobSasPermissions, string name = "Default")
  119. {
  120. try
  121. {
  122. var keys = Utils.ParseConnectionString(_optionsMonitor.Get(name).StorageAccountConnectionString);
  123. var accountname = keys["AccountName"];
  124. var accountkey = keys["AccountKey"];
  125. var endpoint = keys["EndpointSuffix"];
  126. var blobSasBuilder = new BlobSasBuilder
  127. {
  128. StartsOn = DateTimeOffset.UtcNow.Subtract(new TimeSpan(0, 15, 0)),
  129. ExpiresOn = DateTimeOffset.UtcNow.Add(new TimeSpan(1, 0, 15, 0)),
  130. BlobContainerName = containerName,
  131. BlobName = blobName
  132. };
  133. blobSasBuilder.SetPermissions(blobSasPermissions);
  134. var sskc = new StorageSharedKeyCredential(accountname, accountkey);
  135. BlobSasQueryParameters sasQueryParameters = blobSasBuilder.ToSasQueryParameters(sskc);
  136. UriBuilder fullUri = new UriBuilder()
  137. {
  138. Scheme = "https",
  139. Host = $"{accountname}.blob.{endpoint}",
  140. Path = $"{containerName}/{blobName}",
  141. Query = sasQueryParameters.ToString()
  142. };
  143. return fullUri.Uri.ToString();
  144. }
  145. catch
  146. {
  147. return null;
  148. }
  149. }
  150. public CloudTableClient GetCloudTableClient(string name = "Default")
  151. {
  152. try
  153. {
  154. var options = _optionsMonitor.Get(name);
  155. CloudStorageAccount storageAccount = CloudStorageAccount.Parse(options.StorageAccountConnectionString);
  156. return storageAccount.CreateCloudTableClient();
  157. }
  158. catch (OptionsValidationException e)
  159. {
  160. _logger?.LogWarning(e, e.Message);
  161. return null;
  162. }
  163. }
  164. /// <summary>
  165. /// 可讓您管理儲存體帳戶中的所有佇列
  166. /// </summary>
  167. /// <param name="name"></param>
  168. /// <returns></returns>
  169. public QueueServiceClient GetQueueServiceClient(string name = "Default")
  170. {
  171. try
  172. {
  173. var options = _optionsMonitor.Get(name);
  174. return new QueueServiceClient(options.StorageAccountConnectionString);
  175. }
  176. catch (OptionsValidationException e)
  177. {
  178. _logger?.LogWarning(e, e.Message);
  179. return null;
  180. }
  181. }
  182. /// <summary>
  183. /// 可讓您管理和操作個別佇列及其訊息
  184. /// </summary>
  185. /// <param name="name"></param>
  186. /// <param name="queueName"></param>
  187. /// <returns></returns>
  188. public QueueClient GetQueueClient(string queueName, string name = "Default")
  189. {
  190. if (name == null) throw new ArgumentNullException(nameof(name));
  191. try
  192. {
  193. var options = _optionsMonitor.Get(name);
  194. return new QueueClient(options.StorageAccountConnectionString, queueName);
  195. }
  196. catch (OptionsValidationException e)
  197. {
  198. _logger?.LogWarning(e, e.Message);
  199. return null;
  200. }
  201. }
  202. public async Task<CloudTable> InitializeTable<T>()
  203. {
  204. string TableName = GetTableSpace<T>();
  205. CloudTable cloudTable = GetCloudTableClient().GetTableReference(TableName);
  206. await cloudTable.CreateIfNotExistsAsync();
  207. return cloudTable;
  208. }
  209. private string GetTableSpace<T>()
  210. {
  211. Type type = typeof(T);
  212. string Name = type.Name;
  213. object[] attributes = type.GetCustomAttributes(true);
  214. foreach (object attribute in attributes) //2.通过映射,找到成员属性上关联的特性类实例,
  215. {
  216. if (attribute is TableNameAttribute tableSpace)
  217. {
  218. Name = tableSpace.Name;
  219. }
  220. }
  221. return Name;
  222. }
  223. }
  224. }