PageRenderTime 106ms CodeModel.GetById 92ms app.highlight 11ms RepoModel.GetById 1ms app.codeStats 0ms

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

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