PageRenderTime 29ms CodeModel.GetById 10ms app.highlight 14ms RepoModel.GetById 1ms app.codeStats 0ms

/projects/PigeonCms.Core/BaseClasses/FilesGallery.cs

http://pigeoncms.googlecode.com/
C# | 627 lines | 516 code | 56 blank | 55 comment | 43 complexity | bfda0d8323e0b798362fd6af9342b52d MD5 | raw file
  1using System;
  2using System.Data;
  3using System.Configuration;
  4using System.Web;
  5using System.Web.Security;
  6using System.Web.UI;
  7using System.Web.UI.WebControls;
  8using System.Web.UI.WebControls.WebParts;
  9using System.Web.UI.HtmlControls;
 10using System.IO;
 11using System.Drawing;
 12using System.Diagnostics;
 13using System.Collections.Generic;
 14using System.ComponentModel;
 15using System.Threading;
 16using System.Xml;
 17
 18namespace PigeonCms
 19{
 20    /// <summary>
 21    /// meta info about generic uploaded file
 22    /// </summary>
 23    public class FileMetaInfo
 24    {
 25        private bool dataLoaded = false;
 26        private Dictionary<string, string> titleTranslations = new Dictionary<string, string>();
 27        private Dictionary<string, string> descriptionTranslations = new Dictionary<string, string>();
 28
 29
 30        public FileMetaInfo(){}
 31
 32        public FileMetaInfo(string fileUrl): this(fileUrl, false){}
 33
 34        public FileMetaInfo(string fileUrl, bool isFolder)
 35        {
 36            this.FileUrl = fileUrl;
 37            this.isFolder = isFolder;
 38            if (!string.IsNullOrEmpty(this.FileUrl))
 39                GetData();
 40        }
 41
 42        private bool isFolder = false;
 43        public bool IsFolder
 44        {
 45            [DebuggerStepThrough()]
 46            get { return isFolder; }
 47        }
 48
 49        public string FileName
 50        {
 51            [DebuggerStepThrough()]
 52            get 
 53            {
 54                string res = "";
 55                if (!string.IsNullOrEmpty(fileUrl))
 56                    res = VirtualPathUtility.GetFileName(fileUrl);
 57                return res;
 58            }
 59        }
 60
 61        public string FileNameNoExtension
 62        {
 63            [DebuggerStepThrough()]
 64            get 
 65            { 
 66                int dot = this.FileName.LastIndexOf(".");
 67                return this.FileName.Substring(0, dot); 
 68            }
 69        }
 70
 71        private string fileUrl = "";
 72        //absolute path in local website eg:/public/filename.ext
 73        public string FileUrl
 74        {
 75            [DebuggerStepThrough()]
 76            get { return fileUrl; }
 77            [DebuggerStepThrough()]
 78            set { fileUrl = value; }
 79        }
 80
 81        private string fileFullUrl = null;
 82        //absolute path eg:http://www.yoursite.com/public/filename.ext
 83        public string FileFullUrl
 84        {
 85            [DebuggerStepThrough()]
 86            get 
 87            {
 88                if (fileFullUrl == null)
 89                {
 90                    fileFullUrl = "";
 91                    if (!string.IsNullOrEmpty(this.FileUrl))
 92                        fileFullUrl = HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority) + this.FileUrl;
 93                }
 94                return fileFullUrl; 
 95            }
 96        }
 97
 98        private long fileLength = 0;
 99        public long FileLength
100        {
101            [DebuggerStepThrough()]
102            get { return fileLength; }
103            [DebuggerStepThrough()]
104            set { fileLength = value; }
105        }
106
107        /// <summary>
108        /// file length in B, KB, MB, GB
109        /// </summary>
110        public string HumanLength
111        {
112            [DebuggerStepThrough()]
113            get 
114            {
115                return Utility.GetFileHumanLength(this.FileLength);
116            }
117        }
118
119        public string FileExtension
120        {
121            [DebuggerStepThrough()]
122            get { return new FileInfo(this.FileName).Extension; }
123        }
124
125        /// <summary>
126        /// Title in current culture
127        /// </summary>
128        public string Title
129        {
130            get
131            {
132                if (!dataLoaded) GetData();
133                string res = "";
134                titleTranslations.TryGetValue(Thread.CurrentThread.CurrentCulture.Name, out res);
135                if (string.IsNullOrEmpty(res))
136                    titleTranslations.TryGetValue(Config.CultureDefault, out res);
137                return res;
138            }
139        }
140
141        /// <summary>
142        /// Title in different cultures
143        /// </summary>
144        public Dictionary<string, string> TitleTranslations
145        {
146            [DebuggerStepThrough()]
147            get { return titleTranslations; }
148            [DebuggerStepThrough()]
149            set { titleTranslations = value; }
150        }
151
152        /// <summary>
153        /// Description in current cultures
154        /// </summary>
155        public string Description
156        {
157            get
158            {
159                if (!dataLoaded) GetData();
160                string res = "";
161                descriptionTranslations.TryGetValue(Thread.CurrentThread.CurrentCulture.Name, out res);
162                if (string.IsNullOrEmpty(res))
163                    descriptionTranslations.TryGetValue(Config.CultureDefault, out res);
164                return res;
165            }
166        }
167
168        /// <summary>
169        /// Description in different cultures
170        /// </summary>
171        public Dictionary<string, string> DescriptionTranslations
172        {
173            [DebuggerStepThrough()]
174            get { return descriptionTranslations; }
175            [DebuggerStepThrough()]
176            set { descriptionTranslations = value; }
177        }
178
179        /// <summary>
180        /// save file meta data (title, description, etc.)
181        /// </summary>
182        /// <returns></returns>
183        public bool SaveData()
184        {
185            bool res = true;
186            string filename = HttpContext.Current.Request.MapPath(this.FileUrl);
187            FileStream fs = new FileStream(filename + ".xml", FileMode.Create);
188            XmlWriter w = XmlWriter.Create(fs);
189
190            w.WriteStartDocument();
191            w.WriteStartElement("FileInfo");
192
193            w.WriteStartElement("TitleTranslations");
194            foreach (KeyValuePair<string, string> item in Config.CultureList)
195            {
196                string currVal = "";
197                titleTranslations.TryGetValue(item.Key, out currVal);
198                w.WriteStartElement("item");
199                w.WriteAttributeString("len", item.Key);
200                w.WriteCData(currVal);
201                //w.WriteString(currTitle);
202                //w.WriteElementString("title", currTitle);
203                w.WriteEndElement();
204            }
205            w.WriteEndElement();
206
207            w.WriteStartElement("DescriptionTranslations");
208            foreach (KeyValuePair<string, string> item in Config.CultureList)
209            {
210                string currVal = "";
211                descriptionTranslations.TryGetValue(item.Key, out currVal);
212                w.WriteStartElement("item");
213                w.WriteAttributeString("len", item.Key);
214                w.WriteCData(currVal);
215                w.WriteEndElement();
216            }
217            w.WriteEndElement();
218            
219            w.WriteEndElement();
220            w.WriteEndDocument();
221            w.Flush();
222            fs.Close();
223
224            return res;
225        }
226
227        /// <summary>
228        /// get file data (Title, Description, etc.)
229        /// </summary>
230        /// <returns></returns>
231        public bool GetData()
232        {
233            bool res = true;
234            string filename = HttpContext.Current.Request.MapPath(this.FileUrl) + ".xml";
235            XmlDocument doc = new XmlDocument();
236            try
237            {
238                if (System.IO.File.Exists(filename))
239                {
240                    doc.Load(filename);
241
242                    XmlNode rootNode;
243                    rootNode = doc.SelectSingleNode("FileInfo");
244                    if (rootNode == null)
245                    {
246                        //backward compatibility
247                        rootNode = doc.SelectSingleNode("EmbeddedImage");
248                    }
249
250                    //titles
251                    this.TitleTranslations.Clear();
252                    XmlNodeList titleNodes = rootNode.SelectNodes("TitleTranslations/item");
253                    foreach (XmlNode item in titleNodes)
254                    {
255                        string lenAttr = "";
256                        string currValue = "";
257                        if (item.Attributes["len"] != null)
258                        {
259                            lenAttr = item.Attributes["len"].Value;
260                        }
261                        currValue = item.InnerText;
262                        this.TitleTranslations.Add(lenAttr, currValue);
263                    }
264
265                    //descriptions
266                    this.DescriptionTranslations.Clear();
267                    XmlNodeList descNodes = rootNode.SelectNodes("DescriptionTranslations/item");
268                    foreach (XmlNode item in descNodes)
269                    {
270                        string lenAttr = "";
271                        string currValue = "";
272                        if (item.Attributes["len"] != null)
273                        {
274                            lenAttr = item.Attributes["len"].Value;
275                        }
276                        currValue = item.InnerText;
277                        this.DescriptionTranslations.Add(lenAttr, currValue);
278                    }
279                }
280            }
281            catch
282            {
283                res = false;
284            }
285            finally
286            {
287            }
288            this.dataLoaded = res;
289            return res;
290        }
291
292    }
293
294    /// <summary>
295    /// generic file gallery
296    /// </summary>
297    [DataObject()]
298    public class FilesGallery
299    {
300        #region fields
301
302        public string TempPath
303        {
304            get
305            {
306                const string tempPath = "~/public/files/temp/";
307                string res = "";
308                if (!string.IsNullOrEmpty(Utility._SessionID()))
309                {
310                    res = VirtualPathUtility.ToAbsolute(tempPath + Utility._SessionID());
311                }
312                return res;
313            }
314        }
315
316        public string TempPhisicalPath
317        {
318            get
319            {
320                string res = this.TempPath;
321                res = HttpContext.Current.Request.MapPath(res);
322                return res;
323            }
324        }
325
326        private string searchPattern = "*.*";
327        /// <summary>
328        /// search pattern string used by GetAll() method
329        /// </summary>
330        public string SearchPattern
331        {
332            [DebuggerStepThrough()]
333            get { return searchPattern; }
334            [DebuggerStepThrough()]
335            set
336            {
337                if (!string.IsNullOrEmpty(value))
338                {
339                    searchPattern = value;
340                }
341            }
342        }
343
344        private string folderName = "";
345        public string FolderName
346        {
347            [DebuggerStepThrough()]
348            get { return this.folderName; }
349            [DebuggerStepThrough()]
350            set
351            {
352                if (!string.IsNullOrEmpty(value))
353                {
354                    if (!value.EndsWith("/")) value += "/";
355                    this.folderName = value;
356                }
357            }
358        }
359
360        private string virtualPath = "~/Public/files/";
361        /// <summary>
362        /// virtual base path for files gallery 
363        /// example: "~/Public/files/"
364        /// </summary>
365        public string VirtualPath
366        {
367            [DebuggerStepThrough()]
368            get { return this.virtualPath; }
369            [DebuggerStepThrough()]
370            set
371            {
372                if (!string.IsNullOrEmpty(value))
373                {
374                    if (!value.EndsWith("/")) value += "/";
375                    this.virtualPath = value;
376                }
377            }
378        }
379
380        /// <summary>
381        /// absolute path
382        /// </summary>
383        public string AbsolutePath
384        {
385            [DebuggerStepThrough()]
386            get
387            {
388                string res = this.virtualPath;
389                if (!string.IsNullOrEmpty(this.folderName))
390                    res += this.folderName;
391                res = VirtualPathUtility.ToAbsolute(res);
392                return res;
393            }
394        }
395
396        /// <summary>
397        /// phisical path of foldername
398        /// </summary>
399        protected string PhisicalPath
400        {
401            [DebuggerStepThrough()]
402            get
403            {
404                string res = this.virtualPath;
405                if (!string.IsNullOrEmpty(this.folderName))
406                    res += this.folderName;
407                res = HttpContext.Current.Request.MapPath(res);
408                return res;
409            }
410        }
411
412        #endregion
413
414
415        [DebuggerStepThrough()]
416        public FilesGallery(){ }
417
418        [DebuggerStepThrough()]
419        public FilesGallery(string virtualPath, string folderName)
420        {
421            this.VirtualPath = virtualPath;
422            this.FolderName = folderName;
423        }
424
425        [DebuggerStepThrough()]
426        public FilesGallery(string virtualPath, string folderName, string searchPattern)
427        {
428            this.VirtualPath = virtualPath;
429            this.FolderName = folderName;
430            this.SearchPattern = searchPattern;
431        }
432
433        /// <summary>
434        /// get list of files filtered by searchPattern
435        /// </summary>
436        /// <returns></returns>
437        [DataObjectMethod(DataObjectMethodType.Select, true)]
438        public List<FileMetaInfo> GetAll()
439        {
440            List<FileMetaInfo> result = new List<FileMetaInfo>();
441            try
442            {
443                DirectoryInfo dir = new DirectoryInfo(this.PhisicalPath);
444                if (dir.Exists)
445                {
446                    var folders = dir.GetDirectories(this.SearchPattern);
447                    foreach (DirectoryInfo folder in folders)
448                    {
449
450                        if (folder.Name.ToLower() != ".svn" && folder.Name.ToLower() != "_vti_cnf")
451                        {
452                            var item = new FileMetaInfo("", true);
453                            fillObject(item, folder);
454                            result.Add(item);
455                        } 
456                    }
457
458                    var files = dir.GetFiles(this.SearchPattern);
459                    foreach (FileInfo file in files)
460                    {
461                        if (file.Extension.ToLower() != ".xml")
462                        {
463                            var item = new FileMetaInfo();
464                            fillObject(item, file);
465                            result.Add(item);
466                        }
467                    }
468                }
469            }
470            finally
471            {
472            }
473            return result;
474        }
475
476        [DataObjectMethod(DataObjectMethodType.Select, false)]
477        public FileMetaInfo GetByFileName(string fileName)
478        {
479            var result = new FileMetaInfo();
480            try
481            {
482                var file = new FileInfo(this.AbsolutePath + fileName);
483                if (file.Exists)
484                    fillObject(result, file);
485            }
486            finally
487            {
488            }
489            return result;
490        }
491
492        public void RenameFile(string sourceFileName, string destFileName)
493        {
494            if (sourceFileName == destFileName)
495                return;
496            File.Move(Path.Combine(this.PhisicalPath, sourceFileName), Path.Combine(this.PhisicalPath, destFileName));
497            File.Move(Path.Combine(this.PhisicalPath, sourceFileName + ".xml"), Path.Combine(this.PhisicalPath, destFileName + ".xml"));
498        }
499
500        public bool CreateFolder(string folderName)
501        {
502            bool res = false;
503            try
504            {
505                var dir = new DirectoryInfo(this.PhisicalPath);
506                if (dir.Exists)
507                {
508                    Directory.CreateDirectory(this.PhisicalPath + folderName);
509                    res = true;
510                }
511            }
512            finally
513            {
514            }
515            return res;
516        }
517
518        [DataObjectMethod(DataObjectMethodType.Delete, true)]
519        public bool DeleteByFileName(string fileName)
520        {
521            return DeleteByFileName(fileName, false);
522        }
523
524        [DataObjectMethod(DataObjectMethodType.Delete, false)]
525        public bool DeleteByFileName(string fileName, bool isFolder)
526        {
527            bool res = false;
528            try
529            {
530                if (isFolder)
531                {
532                    var dir = new DirectoryInfo(this.PhisicalPath + fileName);
533                    if (dir.Exists)
534                    {
535                        dir.Delete();
536                        res = true;
537                    }
538                }
539                else
540                {
541                    var file = new FileInfo(this.PhisicalPath + fileName);
542                    if (file.Exists)
543                    {
544                        file.Delete();
545                        res = true;
546                    }
547                }
548                //delete file with meta info
549                var metafile = new FileInfo(this.PhisicalPath + fileName + ".xml");
550                if (metafile.Exists)
551                    metafile.Delete();
552            }
553            finally
554            {
555            }
556            return res;
557        }
558
559        [DataObjectMethod(DataObjectMethodType.Delete, true)]
560        public bool DeleteFolderContent()
561        {
562            bool res = false;
563            try
564            {
565                Utility.DeleteFolderContent(this.PhisicalPath);
566                res = true;
567            }
568            finally
569            {
570            }
571            return res;
572        }
573
574        [DataObjectMethod(DataObjectMethodType.Delete, true)]
575        public bool RemoveSessionTempFolder()
576        {
577            bool res = false;
578            try
579            {
580                if (string.IsNullOrEmpty(this.TempPhisicalPath))
581                    return true;
582                DirectoryInfo dir = new DirectoryInfo(this.TempPhisicalPath);
583                if (dir.Exists)
584                    dir.Delete(true);
585                res = true;
586            }
587            catch { }
588            return res;
589        }
590
591        public bool MoveTempFiles()
592        {
593            bool res = false;
594            try
595            {
596                if (string.IsNullOrEmpty(this.TempPhisicalPath))
597                    return true;
598                DirectoryInfo dir = new DirectoryInfo(this.TempPhisicalPath);
599                if (!dir.Exists)
600                    return true;
601
602                Utility.CopyFolder(this.TempPhisicalPath, this.PhisicalPath);
603                dir.Delete(true);
604                res = true;
605            }
606            catch { }
607            return res;
608        }
609
610        private void fillObject(FileMetaInfo result, FileInfo item)
611        {
612            fillObject(result, item.Name, item.Length);
613        }
614
615        private void fillObject(FileMetaInfo result, DirectoryInfo item)
616        {
617            fillObject(result, item.Name, 0);
618        }
619
620        private void fillObject(FileMetaInfo result, string name, long fileLength)
621        {
622            //result.FileFullUrl = this.
623            result.FileUrl = this.AbsolutePath + name;
624            result.FileLength = fileLength;
625        }
626    }
627}