PageRenderTime 49ms CodeModel.GetById 21ms RepoModel.GetById 1ms app.codeStats 0ms

/BlogEngine/DotNetSlave.BusinessLogic/Providers/FileSystemProviders/UNCFileSystemProvider.cs

#
C# | 344 lines | 211 code | 32 blank | 101 comment | 17 complexity | b638946d6f20919cef1091cc7fe9e1fc MD5 | raw file
Possible License(s): LGPL-2.1, Apache-2.0, BSD-3-Clause
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Web.Hosting;
  6. using System.IO;
  7. namespace BlogEngine.Core.Providers
  8. {
  9. public partial class UNCFileSystemProvider : BlogFileSystemProvider
  10. {
  11. /// <summary>
  12. /// unc path to store files. This will be the base path for all blogs.
  13. /// Each blog will then seperate into seperate paths built upon the UNC path by the blog name.
  14. /// ie. [unc]/primary, [unc]/template
  15. /// </summary>
  16. private string uncPath;
  17. public override void Initialize(string name, System.Collections.Specialized.NameValueCollection config)
  18. {
  19. if (config == null)
  20. {
  21. throw new ArgumentNullException("config");
  22. }
  23. if (String.IsNullOrEmpty(name))
  24. {
  25. name = "UNCBlogProvider";
  26. }
  27. base.Initialize(name, config);
  28. if (String.IsNullOrEmpty(config["description"]))
  29. {
  30. config.Remove("description");
  31. config.Add("description", "Generic UNC File Path Blog Provider");
  32. }
  33. if (config["storageVariable"] == null)
  34. {
  35. // default to BlogEngine XML provider paths
  36. config["storageVariable"] = HostingEnvironment.MapPath(Blog.CurrentInstance.StorageLocation);
  37. }
  38. else
  39. {
  40. if(config["storageVariable"].EndsWith(@"\"))
  41. config["storageVariable"] = config["storageVariable"].Substring(0, config["storageVariable"].Length - 1);
  42. if(!System.IO.Directory.Exists(config["storageVariable"]))
  43. throw new ArgumentException("storageVariable (as unc path) does not exist. or does not have read\\write permissions");
  44. }
  45. this.uncPath = config["storageVariable"];
  46. config.Remove("storageVariable");
  47. }
  48. private string VirtualPathToUNCPath(string VirtualPath)
  49. {
  50. VirtualPath = CleanVirtualPath(VirtualPath);
  51. VirtualPath = VirtualPath.Replace("//","/").Replace("/",@"\").Trim();
  52. VirtualPath = VirtualPath.StartsWith(@"\") ? VirtualPath : string.Concat(@"\", VirtualPath);
  53. var storageContainerName = (string.IsNullOrWhiteSpace(Blog.CurrentInstance.StorageContainerName) ? Blog.CurrentInstance.Name : Blog.CurrentInstance.StorageContainerName).Replace(" ", "").Trim();
  54. var fileContainer = string.Concat(this.uncPath, @"\" ,storageContainerName).Trim();
  55. if(VirtualPath.ToLower().Contains(fileContainer.ToLower()))
  56. return VirtualPath;
  57. return string.Concat(fileContainer,VirtualPath);
  58. }
  59. private string CleanVirtualPath(string VirtualPath)
  60. {
  61. return VirtualPath.Replace(Blog.CurrentInstance.StorageLocation + "files", "").Trim();
  62. }
  63. /// <summary>
  64. /// Clears a file system. This will delete all files and folders recursivly.
  65. /// </summary>
  66. /// <remarks>
  67. /// Handle with care... Possibly an internal method?
  68. /// </remarks>
  69. public override void ClearFileSystem()
  70. {
  71. var root = GetDirectory("");
  72. foreach(var directory in root.Directories)
  73. directory.Delete();
  74. foreach(var file in root.Files)
  75. file.Delete();
  76. }
  77. /// <summary>
  78. /// Creates a directory at a specific path
  79. /// </summary>
  80. /// <param name="VirtualPath">The virtual path to be created</param>
  81. /// <returns>the new Directory object created</returns>
  82. /// <remarks>
  83. /// Virtual path is the path starting from the /files/ containers
  84. /// The entity is created against the current blog id
  85. /// </remarks>
  86. internal override FileSystem.Directory CreateDirectory(string VirtualPath)
  87. {
  88. VirtualPath = CleanVirtualPath(VirtualPath);
  89. var aPath = VirtualPathToUNCPath(VirtualPath);
  90. if(!System.IO.Directory.Exists(aPath))
  91. System.IO.Directory.CreateDirectory(aPath);
  92. return GetDirectory(VirtualPath);
  93. }
  94. /// <summary>
  95. /// Deletes a spefic directory from a virtual path
  96. /// </summary>
  97. /// <param name="VirtualPath">The path to delete</param>
  98. /// <remarks>
  99. /// Virtual path is the path starting from the /files/ containers
  100. /// The entity is queried against to current blog id
  101. /// </remarks>
  102. public override void DeleteDirectory(string VirtualPath)
  103. {
  104. VirtualPath = CleanVirtualPath(VirtualPath);
  105. if (!this.DirectoryExists(VirtualPath))
  106. return;
  107. var aPath = VirtualPathToUNCPath(VirtualPath);
  108. var sysDir = new System.IO.DirectoryInfo(aPath);
  109. sysDir.Delete(true);
  110. }
  111. /// <summary>
  112. /// Returns wether or not the specific directory by virtual path exists
  113. /// </summary>
  114. /// <param name="VirtualPath">The virtual path to query</param>
  115. /// <returns>boolean</returns>
  116. public override bool DirectoryExists(string VirtualPath)
  117. {
  118. VirtualPath = CleanVirtualPath(VirtualPath);
  119. var aPath = VirtualPathToUNCPath(VirtualPath);
  120. return System.IO.Directory.Exists(aPath);
  121. }
  122. /// <summary>
  123. /// gets a directory by the virtual path
  124. /// </summary>
  125. /// <param name="VirtualPath">the virtual path</param>
  126. /// <returns>the directory object or null for no directory found</returns>
  127. public override FileSystem.Directory GetDirectory(string VirtualPath)
  128. {
  129. return GetDirectory(VirtualPath, true);
  130. }
  131. public override FileSystem.Directory GetDirectory(string VirtualPath, bool CreateNew)
  132. {
  133. VirtualPath = CleanVirtualPath(VirtualPath);
  134. var aPath = VirtualPathToUNCPath(VirtualPath);
  135. var sysDir = new System.IO.DirectoryInfo(aPath);
  136. if (!sysDir.Exists)
  137. this.CreateDirectory(VirtualPath);
  138. var dir = new FileSystem.Directory();
  139. dir.FullPath = VirtualPath;
  140. dir.Name = sysDir.Name;
  141. dir.IsRoot = string.IsNullOrWhiteSpace(VirtualPath);
  142. dir.LastAccessTime = sysDir.LastAccessTime;
  143. dir.DateModified = sysDir.LastWriteTime;
  144. dir.DateCreated = sysDir.CreationTime;
  145. dir.Id = Guid.NewGuid();
  146. return dir;
  147. }
  148. /// <summary>
  149. /// gets a directory by a basedirectory and a string array of sub path tree
  150. /// </summary>
  151. /// <param name="BaseDirectory">the base directory object</param>
  152. /// <param name="SubPath">the params of sub path</param>
  153. /// <returns>the directory found, or null for no directory found</returns>
  154. public override FileSystem.Directory GetDirectory(FileSystem.Directory BaseDirectory, params string[] SubPath)
  155. {
  156. return GetDirectory(string.Join("/", BaseDirectory.FullPath, SubPath), true);
  157. }
  158. /// <summary>
  159. /// gets a directory by a basedirectory and a string array of sub path tree
  160. /// </summary>
  161. /// <param name="BaseDirectory">the base directory object</param>
  162. /// <param name="CreateNew">if set will create the directory structure</param>
  163. /// <param name="SubPath">the params of sub path</param>
  164. /// <returns>the directory found, or null for no directory found</returns>
  165. public override FileSystem.Directory GetDirectory(FileSystem.Directory BaseDirectory, bool CreateNew, params string[] SubPath)
  166. {
  167. return GetDirectory(string.Join("/", BaseDirectory.FullPath, SubPath), CreateNew);
  168. }
  169. /// <summary>
  170. /// gets all the directories underneath a base directory. Only searches one level.
  171. /// </summary>
  172. /// <param name="BaseDirectory">the base directory</param>
  173. /// <returns>collection of Directory objects</returns>
  174. public override IEnumerable<FileSystem.Directory> GetDirectories(FileSystem.Directory BaseDirectory)
  175. {
  176. var aPath = VirtualPathToUNCPath(BaseDirectory.FullPath);
  177. var sysDirectory = new System.IO.DirectoryInfo(aPath);
  178. return sysDirectory.GetDirectories().Select(x => GetDirectory(string.Format("{0}/{1}", BaseDirectory.FullPath, x.Name)));
  179. }
  180. /// <summary>
  181. /// gets all the files in a directory, only searches one level
  182. /// </summary>
  183. /// <param name="BaseDirectory">the base directory</param>
  184. /// <returns>collection of File objects</returns>
  185. public override IEnumerable<FileSystem.File> GetFiles(FileSystem.Directory BaseDirectory)
  186. {
  187. var aPath = VirtualPathToUNCPath(BaseDirectory.FullPath);
  188. var sysDirectory = new DirectoryInfo(aPath);
  189. return sysDirectory.GetFiles().Where(x => x.Name.ToLower() != "thumbs.db").Select(x => GetFile(string.Format("{0}/{1}", BaseDirectory.FullPath, x.Name)));
  190. }
  191. /// <summary>
  192. /// gets a specific file by virtual path
  193. /// </summary>
  194. /// <param name="VirtualPath">the virtual path of the file</param>
  195. /// <returns></returns>
  196. public override FileSystem.File GetFile(string VirtualPath)
  197. {
  198. VirtualPath = CleanVirtualPath(VirtualPath);
  199. var aPath = VirtualPathToUNCPath(VirtualPath);
  200. var sysFile = new FileInfo(aPath);
  201. if (!sysFile.Exists)
  202. throw new FileNotFoundException("The file at " + VirtualPath + " was not found.");
  203. var file = new FileSystem.File
  204. {
  205. FullPath = VirtualPath,
  206. Name = sysFile.Name,
  207. DateModified = sysFile.LastWriteTime,
  208. DateCreated = sysFile.CreationTime,
  209. Id = Guid.NewGuid().ToString(),
  210. LastAccessTime = sysFile.LastAccessTime,
  211. ParentDirectory = GetDirectory(VirtualPath.Substring(0, VirtualPath.LastIndexOf("/"))),
  212. FilePath = VirtualPath,
  213. FileSize = sysFile.Length,
  214. };
  215. return file;
  216. }
  217. /// <summary>
  218. /// boolean wether a file exists by its virtual path
  219. /// </summary>
  220. /// <param name="VirtualPath">the virtual path</param>
  221. /// <returns>boolean</returns>
  222. public override bool FileExists(string VirtualPath)
  223. {
  224. VirtualPath = CleanVirtualPath(VirtualPath);
  225. var aPath = VirtualPathToUNCPath(VirtualPath);
  226. return File.Exists(aPath);
  227. }
  228. /// <summary>
  229. /// deletes a file by virtual path
  230. /// </summary>
  231. /// <param name="VirtualPath">virtual path</param>
  232. public override void DeleteFile(string VirtualPath)
  233. {
  234. VirtualPath = CleanVirtualPath(VirtualPath);
  235. if (!this.DirectoryExists(VirtualPath))
  236. return;
  237. var aPath = VirtualPathToUNCPath(VirtualPath);
  238. var sysFile = new FileInfo(aPath);
  239. sysFile.Delete();
  240. }
  241. /// <summary>
  242. /// uploads a file to the provider container
  243. /// </summary>
  244. /// <param name="FileBinary">file contents as byte array</param>
  245. /// <param name="FileName">the file name</param>
  246. /// <param name="BaseDirectory">directory object that is the owner</param>
  247. /// <returns>the new file object</returns>
  248. public override FileSystem.File UploadFile(byte[] FileBinary, string FileName, FileSystem.Directory BaseDirectory)
  249. {
  250. return UploadFile(FileBinary, FileName, BaseDirectory, false);
  251. }
  252. /// <summary>
  253. /// uploads a file to the provider container
  254. /// </summary>
  255. /// <param name="FileBinary">the contents of the file as a byte array</param>
  256. /// <param name="FileName">the file name</param>
  257. /// <param name="BaseDirectory">the directory object that is the owner</param>
  258. /// <param name="Overwrite">boolean wether to overwrite the file if it exists.</param>
  259. /// <returns>the new file object</returns>
  260. public override FileSystem.File UploadFile(byte[] FileBinary, string FileName, FileSystem.Directory BaseDirectory, bool Overwrite)
  261. {
  262. var virtualPath = string.Format("{0}/{1}", BaseDirectory.FullPath, FileName);
  263. if (FileExists(virtualPath))
  264. if (Overwrite)
  265. DeleteFile(virtualPath);
  266. else
  267. throw new IOException("File " + virtualPath + " already exists. Unable to upload file.");
  268. var aPath = VirtualPathToUNCPath(virtualPath);
  269. File.WriteAllBytes(aPath, FileBinary);
  270. return GetFile(virtualPath);
  271. }
  272. /// <summary>
  273. /// gets the file contents via Lazy load, however in the DbProvider the Contents are loaded when the initial object is created to cut down on DbReads
  274. /// </summary>
  275. /// <param name="BaseFile">the baseFile object to fill</param>
  276. /// <returns>the original file object</returns>
  277. internal override FileSystem.File GetFileContents(FileSystem.File BaseFile)
  278. {
  279. var aPath = VirtualPathToUNCPath(BaseFile.FullPath);
  280. BaseFile.FileContents = FileToByteArray(aPath);
  281. return BaseFile;
  282. }
  283. /// <summary>
  284. /// Converts a file path to a byte array for handler processing
  285. /// </summary>
  286. /// <param name="FilePath">the file path to process</param>
  287. /// <returns>a new binary array</returns>
  288. private static byte[] FileToByteArray(string FilePath)
  289. {
  290. byte[] Buffer = null;
  291. try
  292. {
  293. System.IO.FileStream FileStream = new System.IO.FileStream(FilePath, System.IO.FileMode.Open, System.IO.FileAccess.Read);
  294. System.IO.BinaryReader BinaryReader = new System.IO.BinaryReader(FileStream);
  295. long TotalBytes = new System.IO.FileInfo(FilePath).Length;
  296. Buffer = BinaryReader.ReadBytes((Int32)TotalBytes);
  297. FileStream.Close();
  298. FileStream.Dispose();
  299. BinaryReader.Close();
  300. }
  301. catch (Exception ex)
  302. {
  303. Utils.Log("File Provider FileToByArray", ex);
  304. }
  305. return Buffer;
  306. }
  307. public override FileSystem.Image ImageThumbnail(string VirtualPath, int MaximumSize)
  308. {
  309. throw new NotImplementedException();
  310. }
  311. }
  312. }