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