PageRenderTime 47ms CodeModel.GetById 19ms RepoModel.GetById 1ms app.codeStats 0ms

/aspclassiccompiler/AzureStoreAsp/Assets/AspProviders/BlobProvider.cs

#
C# | 277 lines | 230 code | 24 blank | 23 comment | 17 complexity | 9a5bcea520a308b97324a006957ce4ba MD5 | raw file
Possible License(s): Apache-2.0, AGPL-3.0
  1. // ----------------------------------------------------------------------------------
  2. // Microsoft Developer & Platform Evangelism
  3. //
  4. // Copyright (c) Microsoft Corporation. All rights reserved.
  5. //
  6. // THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND,
  7. // EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES
  8. // OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
  9. // ----------------------------------------------------------------------------------
  10. // The example companies, organizations, products, domain names,
  11. // e-mail addresses, logos, people, places, and events depicted
  12. // herein are fictitious. No association with any real company,
  13. // organization, product, domain name, email address, logo, person,
  14. // places, or events is intended or should be inferred.
  15. // ----------------------------------------------------------------------------------
  16. //
  17. // <copyright file="BlobProvider.cs" company="Microsoft">
  18. // Copyright (c) Microsoft Corporation. All rights reserved.
  19. // </copyright>
  20. //
  21. using System;
  22. using System.Collections.Generic;
  23. using System.IO;
  24. using System.Configuration;
  25. using Microsoft.ServiceHosting.ServiceRuntime;
  26. using System.Diagnostics;
  27. using System.Linq;
  28. using System.Text;
  29. using System.Globalization;
  30. using Microsoft.Samples.ServiceHosting.StorageClient;
  31. namespace Microsoft.Samples.ServiceHosting.AspProviders
  32. {
  33. public enum EventKind
  34. {
  35. Critical,
  36. Error,
  37. Warning,
  38. Information,
  39. Verbose
  40. };
  41. static class Log
  42. {
  43. internal static void WriteToLog(string logName, string fmt, params object[] args)
  44. {
  45. RoleManager.WriteToLog(logName, String.Format(CultureInfo.InvariantCulture, fmt, args));
  46. }
  47. internal static void Write(EventKind eventKind, string message, params object[] args)
  48. {
  49. if (RoleManager.IsRoleManagerRunning)
  50. {
  51. switch(eventKind)
  52. {
  53. case EventKind.Error:
  54. WriteToLog("Error", message, args);
  55. break;
  56. case EventKind.Critical:
  57. WriteToLog("Critical", message, args);
  58. break;
  59. case EventKind.Warning:
  60. WriteToLog("Warning", message, args);
  61. break;
  62. case EventKind.Information:
  63. WriteToLog("Information", message, args);
  64. break;
  65. case EventKind.Verbose:
  66. WriteToLog("Verbose", message, args);
  67. break;
  68. }
  69. }
  70. else
  71. {
  72. switch (eventKind)
  73. {
  74. case EventKind.Error:
  75. case EventKind.Critical:
  76. Trace.TraceError(message, args);
  77. break;
  78. case EventKind.Warning:
  79. Trace.TraceWarning(message, args);
  80. break;
  81. case EventKind.Information:
  82. case EventKind.Verbose:
  83. Trace.TraceInformation(message, args);
  84. break;
  85. }
  86. }
  87. }
  88. }
  89. internal class BlobProvider
  90. {
  91. private StorageAccountInfo _info;
  92. private BlobContainer _container;
  93. private string _containerName;
  94. private object _lock = new object();
  95. private static readonly TimeSpan _Timeout = TimeSpan.FromSeconds(30);
  96. private static readonly RetryPolicy _RetryPolicy = RetryPolicies.RetryN(3, TimeSpan.FromSeconds(1));
  97. private const string _PathSeparator = "/";
  98. internal BlobProvider(StorageAccountInfo info, string containerName)
  99. {
  100. this._info = info;
  101. this._containerName = containerName;
  102. }
  103. internal string ContainerUrl
  104. {
  105. get
  106. {
  107. return string.Join(_PathSeparator, new string[] { _info.BaseUri.AbsolutePath, _containerName });
  108. }
  109. }
  110. internal bool GetBlobContentsWithoutInitialization(string blobName, Stream outputStream, out BlobProperties properties)
  111. {
  112. Debug.Assert(outputStream != null);
  113. BlobContainer container = GetContainer();
  114. try
  115. {
  116. properties = container.GetBlob(blobName, new BlobContents(outputStream), false);
  117. Log.Write(EventKind.Information, "Getting contents of blob {0}", _info.BaseUri + _PathSeparator + _containerName + _PathSeparator + blobName);
  118. return true;
  119. }
  120. catch (StorageClientException sc)
  121. {
  122. if (sc.ErrorCode == StorageErrorCode.ResourceNotFound || sc.ErrorCode == StorageErrorCode.BlobNotFound)
  123. {
  124. properties = null;
  125. return false;
  126. }
  127. else
  128. throw;
  129. }
  130. }
  131. internal MemoryStream GetBlobContent(string blobName, out BlobProperties properties)
  132. {
  133. MemoryStream blobContent = new MemoryStream();
  134. properties = GetBlobContent(blobName, blobContent);
  135. blobContent.Seek(0, SeekOrigin.Begin);
  136. return blobContent;
  137. }
  138. internal BlobProperties GetBlobContent(string blobName, Stream outputStream)
  139. {
  140. BlobProperties properties;
  141. BlobContainer container = GetContainer();
  142. try
  143. {
  144. properties = container.GetBlob(blobName, new BlobContents(outputStream), false);
  145. Log.Write(EventKind.Information, "Getting contents of blob {0}", ContainerUrl + _PathSeparator + blobName);
  146. return properties;
  147. }
  148. catch (StorageClientException sc)
  149. {
  150. Log.Write(EventKind.Error, "Error getting contents of blob {0}: {1}", ContainerUrl + _PathSeparator + blobName, sc.Message);
  151. throw;
  152. }
  153. }
  154. internal void UploadStream(string blobName, Stream output)
  155. {
  156. UploadStream(blobName, output, true);
  157. }
  158. internal bool UploadStream(string blobName, Stream output, bool overwrite)
  159. {
  160. BlobContainer container = GetContainer();
  161. try
  162. {
  163. output.Position = 0; //Rewind to start
  164. Log.Write(EventKind.Information, "Uploading contents of blob {0}", ContainerUrl + _PathSeparator + blobName);
  165. BlobProperties properties = new BlobProperties(blobName);
  166. return container.CreateBlob(properties, new BlobContents(output), overwrite);
  167. }
  168. catch (StorageException se)
  169. {
  170. Log.Write(EventKind.Error, "Error uploading blob {0}: {1}", ContainerUrl + _PathSeparator + blobName, se.Message);
  171. throw;
  172. }
  173. }
  174. internal bool DeleteBlob(string blobName)
  175. {
  176. BlobContainer container = GetContainer();
  177. try
  178. {
  179. return container.DeleteBlob(blobName);
  180. }
  181. catch (StorageException se)
  182. {
  183. Log.Write(EventKind.Error, "Error deleting blob {0}: {1}", ContainerUrl + _PathSeparator + blobName, se.Message);
  184. throw;
  185. }
  186. }
  187. internal bool DeleteBlobsWithPrefix(string prefix)
  188. {
  189. bool ret = true;
  190. IEnumerable<BlobProperties> e = ListBlobs(prefix);
  191. if (e == null)
  192. {
  193. return true;
  194. }
  195. IEnumerator<BlobProperties> props = e.GetEnumerator();
  196. if (props == null)
  197. {
  198. return true;
  199. }
  200. while (props.MoveNext())
  201. {
  202. if (props.Current != null)
  203. {
  204. if (!DeleteBlob(props.Current.Name))
  205. {
  206. // ignore this; it is possible that another thread could try to delete the blob
  207. // at the same time
  208. ret = false;
  209. }
  210. }
  211. }
  212. return ret;
  213. }
  214. public IEnumerable<BlobProperties> ListBlobs(string folder)
  215. {
  216. BlobContainer container = GetContainer();
  217. try
  218. {
  219. return container.ListBlobs(folder, false).OfType<BlobProperties>();
  220. }
  221. catch (StorageException se)
  222. {
  223. Log.Write(EventKind.Error, "Error enumerating contents of folder {0} exists: {1}", ContainerUrl + _PathSeparator + folder, se.Message);
  224. throw;
  225. }
  226. }
  227. private BlobContainer GetContainer()
  228. {
  229. // we have to make sure that only one thread tries to create the container
  230. lock (_lock)
  231. {
  232. if (_container != null)
  233. {
  234. return _container;
  235. }
  236. try
  237. {
  238. BlobContainer container = BlobStorage.Create(_info).GetBlobContainer(_containerName);
  239. container.Timeout = _Timeout;
  240. container.RetryPolicy = _RetryPolicy;
  241. container.CreateContainer();
  242. _container = container;
  243. return _container;
  244. }
  245. catch (StorageException se)
  246. {
  247. Log.Write(EventKind.Error, "Error creating container {0}: {1}", ContainerUrl, se.Message);
  248. throw;
  249. }
  250. }
  251. }
  252. }
  253. }