Exemplo n.º 1
0
        public virtual async Task <IActionResult> Index(string folder, string subFolder)
        {
            var driver = new FileSystemDriver();

            string absoluteUrl = UriHelper.BuildAbsolute(Request.Scheme, Request.Host);
            var    uri         = new Uri(absoluteUrl);

            var root = new Root(
                new DirectoryInfo(Startup.MapPath("~/Files/" + folder)),
                "http://" + uri.Authority + "/Files/" + folder)
            {
                // Sample using ASP.NET built in Membership functionality...
                // Only the super user can READ (download files) & WRITE (create folders/files/upload files).
                // Other users can only READ (download files)
                // IsReadOnly = !User.IsInRole(AccountController.SuperUser)

                IsReadOnly        = false,   // Can be readonly according to user's membership permission
                Alias             = "Files", // Beautiful name given to the root/home folder
                MaxUploadSizeInKb = 500,     // Limit imposed to user uploaded file <= 500 KB
                LockedFolders     = new List <string>(new string[] { "Folder1" })
            };

            // Was a subfolder selected in Home Index page?
            if (!string.IsNullOrEmpty(subFolder))
            {
                root.StartPath = new DirectoryInfo(Startup.MapPath("~/Files/" + folder + "/" + subFolder));
            }

            driver.AddRoot(root);

            var connector = new Connector(driver);

            return(await connector.Process(this.HttpContext.Request));
        }
Exemplo n.º 2
0
        public virtual ActionResult Index(string folder, string subFolder)
        {
            folder = "release";
            var driver = new FileSystemDriver();

            var root = new Root(new DirectoryInfo(FileController.Gpath + folder),
                                "http://" + Request.Url.Authority + "/" + folder + "/")
            {
                IsReadOnly        = false,
                Alias             = "Root",
                MaxUploadSizeInMb = 500,
                LockedFolders     = new List <string>()
            };

            if (!string.IsNullOrEmpty(subFolder))
            {
                root.StartPath = new DirectoryInfo(FileController.Gpath + folder + "/" + subFolder);
            }

            driver.AddRoot(root);
            var connector = new Connector(driver);

            NameValueCollection parameters = HttpContext.Request.QueryString.Count > 0 ? HttpContext.Request.QueryString : HttpContext.Request.Form;
            string cmdName = parameters["cmd"];

            if (cmdName != "file")
            {
                return(connector.Process(HttpContext.Request));
            }
            {
                return(null);
            }
        }
Exemplo n.º 3
0
        public virtual ActionResult Index(string folder, string subFolder)
        {
            FileSystemDriver driver = new FileSystemDriver();

            var root = new Root(
                new DirectoryInfo(Server.MapPath("~/Files/" + folder)),
                "http://" + Request.Url.Authority + "/Files/" + folder)
            {
                // Sample using ASP.NET built in Membership functionality...
                // Only the super user can READ (download files) & WRITE (create folders/files/upload files).
                // Other users can only READ (download files)
                // IsReadOnly = !User.IsInRole(AccountController.SuperUser)

                IsReadOnly        = false,   // Can be readonly according to user's membership permission
                Alias             = "Files", // Beautiful name given to the root/home folder
                MaxUploadSizeInKb = 500      // Limit imposed to user uploaded file <= 500 KB
            };

            // Was a subfolder selected in Home Index page?
            if (!string.IsNullOrEmpty(subFolder))
            {
                root.StartPath = new DirectoryInfo(Server.MapPath("~/Files/" + folder + "/" + subFolder));
            }

            driver.AddRoot(root);

            var connector = new Connector(driver);

            return(connector.Process(this.HttpContext.Request));
        }
        private Connector GetConnector()
        {
            var driver = new FileSystemDriver();

            string absoluteUrl = UriHelper.BuildAbsolute(Request.Scheme, Request.Host);
            var    uri         = new Uri(absoluteUrl);

            var root = new RootVolume(
                Startup.MapPath("~/Files"),
                $"{uri.Scheme}://{uri.Authority}/Files/",
                $"{uri.Scheme}://{uri.Authority}/el-finder/file-system/thumb/")
            {
                //IsReadOnly = !User.IsInRole("Administrators")
                IsReadOnly = false,   // Can be readonly according to user's membership permission
                IsLocked   = false,   // If locked, files and directories cannot be deleted, renamed or moved
                Alias      = "Files", // Beautiful name given to the root/home folder
                //MaxUploadSizeInKb = 2048, // Limit imposed to user uploaded file <= 2048 KB
                //LockedFolders = new List<string>(new string[] { "Folder1" })
            };

            driver.AddRoot(root);

            return(new Connector(driver)
            {
                // This allows support for the "onlyMimes" option on the client.
                MimeDetect = MimeDetectOption.Internal
            });
        }
Exemplo n.º 5
0
        public FileSystemDriver GetFileSystemDriver(RootVolume rootVolume)
        {
            var driver = new FileSystemDriver();

            driver.AddRoot(rootVolume);
            return(driver);
        }
Exemplo n.º 6
0
        public virtual ActionResult SelectFile(string target)
        {
            System.Web.HttpContext currentContext = System.Web.HttpContext.Current;
            bool login = currentContext.User.Identity.IsAuthenticated;

            if (login)
            {
                string           userid = currentContext.User.Identity.GetUserId().ToString();
                FileSystemDriver driver = new FileSystemDriver();

                driver.AddRoot(
                    new Root(
                        new DirectoryInfo(Path.Combine(GlobalVariables.MyAppPath, "UsersData", userid, "Files")),
                        "http://" + Request.Url.Authority + "/" + "UsersData" + "/" + userid + "/" + "Files")
                {
                    IsReadOnly = false
                });

                var connector = new Connector(driver);

                return(Json(connector.GetFileByHash(target).FullName));
            }
            //TODO :RETURN REDIRECT LOGIN
            return(null);
        }
Exemplo n.º 7
0
        public virtual ActionResult Index(string folder, string subFolder)
        {
            var driver = new FileSystemDriver();

            var root = new Root(new DirectoryInfo(Server.MapPath("~/Content/" + folder)),
                                "http://" + Request.Url.Authority + "/Content/" + folder + "/")
            {
                IsReadOnly        = false,
                Alias             = "Root",
                MaxUploadSizeInMb = 500,
                LockedFolders     = new List <string>()
            };

            //var root = new Root(new DirectoryInfo("D:\\blog"))
            //{
            //    IsReadOnly = false,
            //    Alias = "Root",
            //    MaxUploadSizeInMb = 500,
            //    LockedFolders = new List<string>(),
            //    UploadOverwrite = true
            //};

            if (!string.IsNullOrEmpty(subFolder))
            {
                root.StartPath = new DirectoryInfo(Server.MapPath("~/Content/" + folder + "/" + subFolder));
            }

            driver.AddRoot(root);
            var connector = new Connector(driver);

            return(connector.Process(HttpContext.Request));
        }
Exemplo n.º 8
0
 public ActionResult Index(string folder, string subFolder, string content)
 {
     try
     {
         //不存在,则直接创建目录
         string meeting_folder = Server.MapPath(pathfolder + folder);
         if (!Directory.Exists(meeting_folder))
         {
             Common.DirHelper.CheckFolder(meeting_folder);
             //Common.DirHelper.CopyDirectory(Server.MapPath(pathContent), meeting_folder);
         }
         FileSystemDriver driver = new FileSystemDriver();
         var root = new Root(
             new DirectoryInfo(meeting_folder),
             "http://" + Request.Url.Authority + urlfolder + folder)
         {
             IsReadOnly        = false,                           // Can be readonly according to user's membership permission
             Alias             = urlfolder.Substring(1) + folder, // Beautiful name given to the root/home folder
             MaxUploadSizeInKb = 500000                           // Limit imposed to user uploaded file <= 500 KB
         };
         if (!string.IsNullOrEmpty(subFolder))
         {
             root.StartPath = new DirectoryInfo(meeting_folder + "/" + subFolder);
         }
         driver.AddRoot(root);
         var connector = new Connector(driver);
         return(connector.Process(this.HttpContext.Request, content));
     }
     catch
     {
     }
     return(Content(string.Empty));
 }
Exemplo n.º 9
0
        /// <summary> </summary>
        public void get_index()
        {
            CancelLayout();
            CancelView();

            HttpRequest      httpRequest = HttpContext.Current.Request;
            site             site        = siteService.getCurrentSite();
            FileSystemDriver driver      = new FileSystemDriver();

            driver.AddRoot(new Root(new DirectoryInfo(HttpContext.Current.Server.MapPath("~/" + file_info.relative_site_uploads_path().Trim('/'))), "http://" + httpRequest.Url.Authority + "/" + file_info.relative_site_cache_path().Trim('/') + "/uploads/")
            {
                IsReadOnly = false, Alias = site.name
            });
            //driver.AddRoot(new Root(new DirectoryInfo(@"C:\Program Files"), "http://" + httpRequest.Url.Authority + "/") { IsReadOnly = true });
            var connector = new Connector(driver);


            var jsonResult = connector.Process(new HttpRequestWrapper(httpRequest));

            var data = jsonResult.Data;

            string json = new JavaScriptSerializer().Serialize(data);

            RenderText(json);
        }
Exemplo n.º 10
0
        public virtual ActionResult Index(string folder, string subFolder)
        {
            System.Web.HttpContext currentContext = System.Web.HttpContext.Current;
            bool login = currentContext.User.Identity.IsAuthenticated;

            if (login)
            {
                string userid = currentContext.User.Identity.GetUserId().ToString();

                string RootPath = Path.Combine("UsersData", userid, "Files", "Root");

                string UserRootFullPath = Path.Combine(GlobalVariables.MyAppPath, RootPath);
                bool   exists           = System.IO.Directory.Exists(UserRootFullPath);

                if (!exists)
                {
                    System.IO.Directory.CreateDirectory(Path.Combine(UserRootFullPath));
                }
                FileSystemDriver driver = new FileSystemDriver();

                var root = new Root(
                    new DirectoryInfo(Path.Combine(GlobalVariables.MyAppPath, "UsersData", userid, "Files", folder)),    //File Browserın gördüğü kullanıcı klasörü yolu
                    "http://" + Request.Url.Authority + "/" + "UsersData" + "/" + userid + "/" + "Files" + "/" + folder) // Önizleme yapmak için dosyanın url i
                {
                    // Sample using ASP.NET built in Membership functionality...
                    // Only the super user can READ (download files) & WRITE (create folders/files/upload files).
                    // Other users can only READ (download files)
                    // IsReadOnly = !User.IsInRole(AccountController.SuperUser)

                    IsReadOnly        = false,   // Can be readonly according to user's membership permission
                    Alias             = "Root",  // Beautiful name given to the root/home folder
                    UploadOverwrite   = false,
                    MaxUploadSizeInKb = 2000000, // Limit imposed to user uploaded file <= 500 KB
                    LockedFolders     = new List <string>(new string[] { "Folder1" })
                };

                // Was a subfolder selected in Home Index page?
                if (!string.IsNullOrEmpty(subFolder))
                {
                    root.StartPath = new DirectoryInfo(Path.Combine(GlobalVariables.MyAppPath, "UsersData", userid, "Files", folder, subFolder)); //arama sonucundan dosyanın klasörüne yönlendirme yapmak için başlangıç klasörü
                }

                driver.AddRoot(root);

                var connector = new Connector(driver);

                return(connector.Process(this.HttpContext.Request));
            }

            //TODO :RETURN REDIRECT LOGIN
            return(null);
        }
Exemplo n.º 11
0
        private Connector GetConnector()
        {
            var driver = new FileSystemDriver();

            string absoluteUrl = UriHelper.BuildAbsolute(Request.Scheme, Request.Host);
            var    uri         = new Uri(absoluteUrl);

            var root = new RootVolume(
                PathHelper.MapPath("~/Uploads"),
                $"{uri.Scheme}://{uri.Authority}/Uploads/",
                $"{uri.Scheme}://{uri.Authority}/el-finder/file-system/thumb/")
            {
                //IsReadOnly = !User.IsInRole("Administrators")
                IsReadOnly = false,   // Can be readonly according to user's membership permission
                IsLocked   = false,   // If locked, files and directories cannot be deleted, renamed or moved
                Alias      = "Files", // Beautiful name given to the root/home folder
                //MaxUploadSizeInKb = 2048, // Limit imposed to user uploaded file <= 2048 KB

                AccessControlAttributes = new HashSet <NamedAccessControlAttributeSet>()
                {
                    new NamedAccessControlAttributeSet(PathHelper.MapPath("~/Uploads/readonly.txt"))
                    {
                        Write  = false,
                        Locked = true
                    },
                    new NamedAccessControlAttributeSet(PathHelper.MapPath("~/Uploads/Prohibited"))
                    {
                        Read   = false,
                        Write  = false,
                        Locked = true
                    },
                    new NamedAccessControlAttributeSet(PathHelper.MapPath("~/Uploads/Parent/Children"))
                    {
                        Read   = true,
                        Write  = false,
                        Locked = true
                    }
                }
            };

            driver.AddRoot(root);

            return(new Connector(driver)
            {
                // This allows support for the "onlyMimes" option on the client.
                MimeDetect = MimeDetectOption.Internal
            });
        }
Exemplo n.º 12
0
        public virtual ActionResult SelectFile(string target)
        {
            var driver = new FileSystemDriver();

            driver.AddRoot(
                new Root(
                    new DirectoryInfo(Server.MapPath("~/Content")),
                    "http://" + Request.Url.Authority + "/Content")
            {
                IsReadOnly = false
            });

            var connector = new Connector(driver);

            return(Json(connector.GetFileByHash(target).FullName));
        }
Exemplo n.º 13
0
        /// <summary>
        ///
        /// </summary>
        public ElFinderController()
        {
            ViewBag.RootUrl = "/";
            FileSystemDriver driver        = new FileSystemDriver();
            string           scriptsPath   = @"C:\Users\Administrator";
            string           thumbsPath    = @"C:\Users\Administrator";
            DirectoryInfo    thumbsStorage = new DirectoryInfo(thumbsPath);

            driver.AddRoot(new Root(new DirectoryInfo(scriptsPath), "/Documents/")
            {
                IsLocked          = false,
                IsReadOnly        = false,
                IsShowOnly        = false,
                ThumbnailsStorage = thumbsStorage,
                ThumbnailsUrl     = "Thumbnails/"
            });
            InitDriver(driver);
        }
Exemplo n.º 14
0
        private Connector GetConnector()
        {
            var driver = new FileSystemDriver();

            var root = new elFinder.NetCore.RootVolume(
                DirectoryRoot,
                $"{HttpContext.Request.Scheme}://{HttpContext.Request.Host.Value}/file-manager/target/",
                $"{HttpContext.Request.Scheme}://{HttpContext.Request.Host.Value}/file-manager/thumb/")
            {
                IsReadOnly        = Platform.IsDemo,
                Alias             = "elFinder", // Beautiful name given to the root/home folder
                MaxUploadSizeInKb = 200000,     // Limit imposed to user uploaded file <= 200000 KB / 2GB
                //LockedFolders = new List<string>(new string[] { "Folder1" })
            };

            driver.AddRoot(root);

            return(new Connector(driver));
        }
Exemplo n.º 15
0
        public virtual IActionResult SelectFile(string target)
        {
            var driver = new FileSystemDriver();

            string absoluteUrl = UriHelper.BuildAbsolute(Request.Scheme, Request.Host);
            var    uri         = new Uri(absoluteUrl);

            driver.AddRoot(
                new Root(
                    new DirectoryInfo(Startup.MapPath("~/Files")),
                    "http://" + uri.Authority + "/Files")
            {
                IsReadOnly = false
            });

            var connector = new Connector(driver);

            return(Json(connector.GetFileByHash(target).FullName));
        }
        /// <summary>
        ///
        /// </summary>
        public ElFinderController()
        {
            ViewBag.RootUrl = "/";
            FileSystemDriver driver     = new FileSystemDriver();
            var           app_data      = HostingEnvironment.MapPath("~/Uploads");
            string        scriptsPath   = app_data;//@"C:\Users\Administrator";
            string        thumbsPath    = HostingEnvironment.MapPath("~/App_Data");
            DirectoryInfo thumbsStorage = new DirectoryInfo(thumbsPath);

            driver.AddRoot(new Root(new DirectoryInfo(scriptsPath), "/Documents/")
            {
                IsLocked          = false,
                IsReadOnly        = false,
                IsShowOnly        = false,
                ThumbnailsStorage = thumbsStorage,
                ThumbnailsUrl     = "/Tools/ElFinder/Thumbs?tmb=",
                ThumbnailsSize    = 100,
            });
            InitDriver(driver);
        }
Exemplo n.º 17
0
        public ActionResult SelectFile(string target)
        {
            try
            {
                FileSystemDriver driver = new FileSystemDriver();

                driver.AddRoot(
                    new Root(
                        new DirectoryInfo(pathfolder),
                        "http://" + Request.Url.Authority + urlfolder)
                {
                    IsReadOnly = false
                });

                var connector = new Connector(driver);

                return(Json(connector.GetFileByHash(target).FullName));
            }
            catch { }
            return(Content(string.Empty));
        }
Exemplo n.º 18
0
        public virtual ActionResult Index(string folder, string subFolder)
        {
            var driver = new FileSystemDriver();

            var root = new Root(new DirectoryInfo(Server.MapPath("~/Upload/" + folder)),
                                "http://" + Request.Url.Authority + "/Upload/" + folder + "/")
            {
                IsReadOnly        = false,
                Alias             = "Root",
                MaxUploadSizeInMb = 100
            };

            if (!string.IsNullOrEmpty(subFolder))
            {
                root.StartPath = new DirectoryInfo(Server.MapPath("~/Upload/" + folder + "/" + subFolder));
            }

            driver.AddRoot(root);
            var connector = new Connector(driver);

            return(connector.Process(HttpContext.Request));
        }
Exemplo n.º 19
0
        public virtual ActionResult Index(string folder, string subFolder)
        {
            string getpath = WebConfigurationManager.AppSettings["DirectoryElFinder"];
            var    driver  = new FileSystemDriver();

            var root = new Root(new DirectoryInfo(Server.MapPath("~/Themes/" + folder)),
                                "http://" + Request.Url.Authority + "/Themes/" + folder + "/")
            {
                IsReadOnly        = false,
                Alias             = "Root",
                MaxUploadSizeInMb = 500,
                LockedFolders     = new List <string>()
            };

            if (!string.IsNullOrEmpty(subFolder))
            {
                root.StartPath = new DirectoryInfo(Server.MapPath("~/Themes/" + folder + "/" + subFolder));
            }

            driver.AddRoot(root);
            var connector = new Connector(driver);

            return(connector.Process(HttpContext.Request));
        }
        private Connector GetConnector(string folderPath = "", string folderName = "Files")
        {
            var driver = new FileSystemDriver();

            string absoluteUrl = UriHelper.BuildAbsolute(Request.Scheme, Request.Host);
            var    uri         = new Uri(absoluteUrl);

            folderPath = folderPath != "" ? ("/" + folderPath) : "";
            var root = new RootVolume(
                Startup.MapPath($"~/Files{folderPath}"),
                $"http://{uri.Authority}/Files/{folderPath}",
                $"http://{uri.Authority}/el-finder/file-system/thumb/")
            {
                //IsReadOnly = !User.IsInRole("Administrators")
                IsReadOnly        = false,      // Can be readonly according to user's membership permission
                Alias             = folderName, // Beautiful name given to the root/home folder
                MaxUploadSizeInKb = 500,        // Limit imposed to user uploaded file <= 500 KB
                //LockedFolders = new List<string>(new string[] { "Folder1" })
            };

            driver.AddRoot(root);

            return(new Connector(driver));
        }
Exemplo n.º 21
0
        private Connector GetConnector()
        {
            // Thư mục gốc lưu trữ là wwwwroot/files (đảm bảo có tạo thư mục này)
            string pathroot = "files";

            var driver = new FileSystemDriver();

            string absoluteUrl = UriHelper.BuildAbsolute(Request.Scheme, Request.Host);
            var    uri         = new Uri(absoluteUrl);

            // .. ... wwww/files
            string rootDirectory = Path.Combine(environment.WebRootPath, pathroot);

            // https://localhost:5001/files/
            string url      = $"{uri.Scheme}://{uri.Authority}/{pathroot}/";
            string urlthumb = $"{uri.Scheme}://{uri.Authority}/file-system/thumb/";


            var root = new RootVolume(rootDirectory, url, urlthumb)
            {
                IsReadOnly = false,   // Can be readonly according to user's membership permission
                IsLocked   = false,   // If locked, files and directories cannot be deleted, renamed or moved
                Alias      = "Files", // Beautiful name given to the root/home folder
                //MaxUploadSizeInKb = 2048, // Limit imposed to user uploaded file <= 2048 KB
                //LockedFolders = new List<string>(new string[] { "Folder1" }
                ThumbnailSize = 100,
            };


            driver.AddRoot(root);

            return(new Connector(driver)
            {
                MimeDetect = MimeDetectOption.Internal
            });
        }
 protected void InitDriver(FileSystemDriver driver)
 {
     _driver = driver;
 }
Exemplo n.º 23
0
        public HttpResponseMessage Update(string explorerInfo)
        {
            ExplorerInfoViewModel einfo = JsonConvert.DeserializeObject <ExplorerInfoViewModel>(explorerInfo);
            Guid   projectId;
            string folder;

            if (Guid.TryParse(einfo.ProjectId, out projectId) == true)
            {
                folder = ShqConstants.ProjectRootFolder + "\\" + einfo.ParentPath;
            }
            else
            {
                folder = ShqConstants.TemplateRootFolder + "\\" + einfo.ParentPath;
            }
            folder = new DirectoryInfo(Path.Combine(folder, "1b2cd8ab-6d6c-4a05-931b-e40607bd8b19")).Parent.FullName;//to workaround a issue the if path end with \ will fail

            string name    = einfo.Name + "." + einfo.Id.ToString();
            string oldName = einfo.OldName + "." + einfo.Id.ToString();

            switch (einfo.cmd)
            {
            case "createFolder":
            {
                var     fileSystemDriver = new FileSystemDriver();
                IDriver driver           = fileSystemDriver;
                var     root             = new Root(new DirectoryInfo(folder))
                {
                    IsReadOnly        = false,
                    Alias             = "Root",
                    MaxUploadSizeInMb = 500,
                    LockedFolders     = new List <string>()
                };
                fileSystemDriver.AddRoot(root);
                string target = root.VolumeId + Helper.EncodePath(new DirectoryInfo(folder).Name);

                try
                {
                    driver.MakeDir(target, name);
                }
                finally
                {
                    if (Directory.Exists(Path.Combine(folder, name)))
                    {
                        db.ProjectFiles.Add(new ProjectFile
                            {
                                Id               = einfo.Id,
                                Name             = einfo.Name,
                                Level            = einfo.Level,
                                IsFolder         = true,
                                Path             = Path.Combine(folder, name),
                                CreatedById      = db.ShqUsers.Where(u => u.IdentityUser.UserName == HttpContext.Current.User.Identity.Name).FirstOrDefault().IdentityUserId,
                                LastModifiedById = db.ShqUsers.Where(u => u.IdentityUser.UserName == HttpContext.Current.User.Identity.Name).FirstOrDefault().IdentityUserId
                            });
                    }
                }

                break;
            }

            case "delete":
            {
                var     fileSystemDriver = new FileSystemDriver();
                IDriver driver           = fileSystemDriver;
                folder = Path.Combine(folder, name);
                var root = new Root(new DirectoryInfo(folder))
                {
                    IsReadOnly        = false,
                    Alias             = "Root",
                    MaxUploadSizeInMb = 500,
                    LockedFolders     = new List <string>()
                };
                fileSystemDriver.AddRoot(root);
                string target = root.VolumeId + Helper.EncodePath(new DirectoryInfo(folder).Name);

                driver.Remove(new string[] { target });
                var f = db.ProjectFiles.FirstOrDefault(item => item.Id == einfo.Id);
                if (f != null)
                {
                    f.Status           = 1;
                    f.LastModifiedById = db.ShqUsers.Where(u => u.IdentityUser.UserName == HttpContext.Current.User.Identity.Name).FirstOrDefault().IdentityUserId;
                    f.LastModfiedTime  = DateTime.Now;
                }
                break;
            }

            case "rename":
            {
                var     fileSystemDriver = new FileSystemDriver();
                IDriver driver           = fileSystemDriver;
                var     root             = new Root(new DirectoryInfo(folder))
                {
                    IsReadOnly        = false,
                    Alias             = "Root",
                    MaxUploadSizeInMb = 500,
                    LockedFolders     = new List <string>()
                };
                fileSystemDriver.AddRoot(root);
                string target = root.VolumeId + Helper.EncodePath(@"\" + oldName);

                driver.Rename(target, name);
                var f = db.ProjectFiles.FirstOrDefault(item => item.Id == einfo.Id);
                if (f != null)
                {
                    f.Name             = einfo.Name;
                    f.Path             = Path.Combine(Directory.GetParent(folder).FullName, name);
                    f.LastModifiedById = db.ShqUsers.Where(u => u.IdentityUser.UserName == HttpContext.Current.User.Identity.Name).FirstOrDefault().IdentityUserId;
                    f.LastModfiedTime  = DateTime.Now;
                }
                break;
            }

            case "uploadFile":    //https://forums.asp.net/t/2104884.aspx?Uploading+a+file+using+webapi+C+
            {
                var fileSystemDriver = new FileSystemDriver();
                var root             = new Root(new DirectoryInfo(folder))
                {
                    IsReadOnly        = false,
                    Alias             = "Root",
                    MaxUploadSizeInMb = 500,
                    LockedFolders     = new List <string>()
                };
                fileSystemDriver.AddRoot(root);
                string target = root.VolumeId + Helper.EncodePath(new DirectoryInfo(folder).Name);

                var    wrapper  = new HttpRequestWrapper(HttpContext.Current.Request);
                string fileName = wrapper.Files[0].FileName + "." + einfo.Id;
                try
                {
                    fileSystemDriver.Upload(target, wrapper.Files[0], fileName);
                }
                finally
                {
                    if (File.Exists(Path.Combine(folder, fileName)))
                    {
                        db.ProjectFiles.Add(new ProjectFile
                            {
                                Id               = einfo.Id,
                                Name             = wrapper.Files[0].FileName,
                                Level            = einfo.Level,
                                IsFolder         = false,
                                Path             = Path.Combine(folder, fileName),
                                CreatedById      = db.ShqUsers.Where(u => u.IdentityUser.UserName == HttpContext.Current.User.Identity.Name).FirstOrDefault().IdentityUserId,
                                LastModifiedById = db.ShqUsers.Where(u => u.IdentityUser.UserName == HttpContext.Current.User.Identity.Name).FirstOrDefault().IdentityUserId
                            });
                    }
                }

                break;
            }

            case "dowloadFile":
            {
                folder = Path.Combine(folder, einfo.Name);
                if (File.Exists(folder) == false)
                {
                    return(new HttpResponseMessage(HttpStatusCode.NotFound));
                }

                //converting Pdf file into bytes array
                var dataBytes = System.IO.File.ReadAllBytes(folder);
                //adding bytes to memory stream
                var stream = new MemoryStream(dataBytes);

                var result = new HttpResponseMessage(HttpStatusCode.OK)
                {
                    Content = new ByteArrayContent(stream.ToArray())
                };
                result.Content.Headers.ContentDisposition =
                    new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment")
                {
                    FileName = einfo.Name
                };
                result.Content.Headers.ContentType =
                    new MediaTypeHeaderValue("application/octet-stream");

                return(result);
            }
            }

            db.SaveChanges();

            return(new HttpResponseMessage(HttpStatusCode.OK));
        }
Exemplo n.º 24
0
        public HttpResponseMessage Update(ExplorerInfoViewModel einfo)
        {
            WorkProject wp = null;
            string      folder;
            var         pro = db.Projects.FirstOrDefault(item => item.Id == einfo.ProjectId);
            Guid?       workProjectId;
            Guid        worktemplateid = Guid.Empty;

            if (pro != null)
            {
                if (ProjectHelper.HasReadAccess(pro) == false)
                {
                    throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.Forbidden, "No Access"));
                }

                if (einfo.cmd != "dowloadFile" && ProjectHelper.HasUpdateAccess(pro) == false)
                {
                    throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.Forbidden, "No Access"));
                }

                folder          = ShqConstants.ProjectRootFolder + "\\" + einfo.ProjectId + "\\" + einfo.TartgetPath;
                wp              = db.WorkProjects.FirstOrDefault(item => item.ProjectId == einfo.ProjectId);
                workProjectId   = wp.Id;
                worktemplateid  = wp.WorkProjectTemplateId;
                einfo.Privilege = 1;
            }
            else if (db.WorkProjectTemplates.FirstOrDefault(item => item.Id == einfo.ProjectId) != null)
            {
                if (HttpContext.Current.User.IsInRole(ShqConstants.AdministratorRole) == false)
                {
                    throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.Forbidden, "No Access"));
                }

                workProjectId   = null;
                worktemplateid  = einfo.ProjectId;
                einfo.Privilege = 0;
                folder          = ShqConstants.TemplateRootFolder + "\\" + worktemplateid + "\\" + einfo.TartgetPath;
            }
            else
            {
                throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.Forbidden, "projectId is not found"));
            }

            folder = new DirectoryInfo(Path.Combine(folder, "1b2cd8ab-6d6c-4a05-931b-e40607bd8b19")).Parent.FullName;//to workaround a issue the if path end with \ will fail

            if (CheckIfParentExistInDb(folder) == false)
            {
                throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.Forbidden, "The parent folder is not found in the db"));
            }

            string name    = einfo.Name + "." + einfo.Id.ToString();
            string oldName = einfo.OldName + "." + einfo.Id.ToString();

            switch (einfo.cmd)
            {
            case "createFolder":
            {
                if (string.IsNullOrEmpty(einfo.Name) == true)
                {
                    break;
                }

                var     fileSystemDriver = new FileSystemDriver();
                IDriver driver           = fileSystemDriver;
                var     root             = new Root(new DirectoryInfo(folder))
                {
                    IsReadOnly        = false,
                    Alias             = "Root",
                    MaxUploadSizeInMb = 500,
                    LockedFolders     = new List <string>()
                };
                fileSystemDriver.AddRoot(root);

                var dbFile = db.ProjectFiles.FirstOrDefault(item => item.WorkProjectId == workProjectId &&
                                                            item.WorkProjectTemplateId == worktemplateid &&
                                                            item.Name == einfo.Name &&
                                                            item.Path == folder + "\\" + einfo.Name + "." + item.Id);

                if (dbFile != null)
                {
                    dbFile.Status           = (int)ShqConstants.FileStatus.Ready;
                    dbFile.LastModifiedById = db.ShqUsers.Where(u => u.IdentityUser.UserName == HttpContext.Current.User.Identity.Name).FirstOrDefault().IdentityUserId;
                    dbFile.LastModfiedTime  = DateTime.Now;
                }
                else
                {
                    dbFile = db.ProjectFiles.Add(new ProjectFile
                        {
                            FileId                = Guid.NewGuid(),
                            Name                  = einfo.Name,
                            Level                 = 0,
                            IsFolder              = true,
                            Path                  = Path.Combine(folder, einfo.Name),
                            WorkProjectId         = workProjectId,
                            WorkProjectTemplateId = worktemplateid,
                            Privilege             = einfo.Privilege,
                            CreatedById           = db.ShqUsers.Where(u => u.IdentityUser.UserName == HttpContext.Current.User.Identity.Name).FirstOrDefault().IdentityUserId,
                            LastModifiedById      = db.ShqUsers.Where(u => u.IdentityUser.UserName == HttpContext.Current.User.Identity.Name).FirstOrDefault().IdentityUserId
                        });

                    if (wp != null)
                    {
                        wp.ProjectFiles.Add(dbFile);
                    }

                    db.SaveChanges();
                }

                name = einfo.Name + "." + dbFile.Id.ToString();
                string target = root.VolumeId + Helper.EncodePath(new DirectoryInfo(folder).Name);

                try
                {
                    driver.MakeDir(target, name);
                }
                finally
                {
                    if (Directory.Exists(Path.Combine(folder, name)))
                    {
                        dbFile.Status = (int)ShqConstants.FileStatus.Ready;
                        dbFile.Path   = Path.Combine(folder, name);
                    }
                    else
                    {
                        dbFile.Status           = (int)ShqConstants.FileStatus.Deleted;
                        dbFile.LastModifiedById = db.ShqUsers.Where(u => u.IdentityUser.UserName == HttpContext.Current.User.Identity.Name).FirstOrDefault().IdentityUserId;
                        dbFile.LastModfiedTime  = DateTime.Now;
                    }
                }
            }

            break;

            case "delete":
            {
                var     fileSystemDriver = new FileSystemDriver();
                IDriver driver           = fileSystemDriver;
                //folder = Path.Combine(folder, name);
                var root = new Root(new DirectoryInfo(folder).Parent)
                {
                    IsReadOnly        = false,
                    Alias             = "Root",
                    MaxUploadSizeInMb = 500,
                    LockedFolders     = new List <string>()
                };
                fileSystemDriver.AddRoot(root);
                string target = root.VolumeId + Helper.EncodePath(@"\" + new DirectoryInfo(folder).Name);

                driver.Remove(new string[] { target });
                if (Directory.Exists(folder) == false && File.Exists(folder) == false)
                {
                    //var f = db.ProjectFiles.FirstOrDefault(item => item.Id == einfo.Id
                    //&& item.WorkProjectId == projectId
                    //&& item.WorkProjectTemplateId == worktemplateid);
                    //if (f != null)
                    //{
                    //    f.Status = 1;
                    //    f.LastModifiedById = db.ShqUsers.Where(u => u.IdentityUser.UserName == HttpContext.Current.User.Identity.Name).FirstOrDefault().IdentityUserId;
                    //    f.LastModfiedTime = DateTime.Now;
                    //}

                    string userId = db.ShqUsers.Where(u => u.IdentityUser.UserName == HttpContext.Current.User.Identity.Name).FirstOrDefault().IdentityUserId;
                    var    fs     = db.ProjectFiles.Where(item => item.Path.Contains(folder) == true &&
                                                          item.WorkProjectId == workProjectId &&
                                                          item.WorkProjectTemplateId == worktemplateid);
                    foreach (var f in fs)
                    {
                        f.Status           = 1;
                        f.LastModifiedById = userId;
                        f.LastModfiedTime  = DateTime.Now;
                    }
                }

                break;
            }

            case "rename":
            {
                var           fileSystemDriver = new FileSystemDriver();
                IDriver       driver           = fileSystemDriver;
                DirectoryInfo rootPath         = new DirectoryInfo(folder).Parent;
                var           root             = new Root(rootPath)
                {
                    IsReadOnly        = false,
                    Alias             = "Root",
                    MaxUploadSizeInMb = 500,
                    LockedFolders     = new List <string>()
                };
                fileSystemDriver.AddRoot(root);
                string target = root.VolumeId + Helper.EncodePath(@"\" + oldName);

                var dbFile = db.ProjectFiles.FirstOrDefault(item => item.WorkProjectId == workProjectId &&
                                                            item.WorkProjectTemplateId == worktemplateid &&
                                                            item.Name == einfo.Name &&
                                                            item.Path == rootPath.FullName + "\\" + einfo.Name + "." + item.Id &&
                                                            item.Status != (int)ShqConstants.FileStatus.Deleted);
                if (dbFile != null && (File.Exists(dbFile.Path) || Directory.Exists(dbFile.Path)))
                {
                    return(new HttpResponseMessage(HttpStatusCode.Conflict));
                }

                driver.Rename(target, name);
                string oldPath = Path.Combine(Directory.GetParent(folder).FullName, oldName);
                string newPath = Path.Combine(Directory.GetParent(folder).FullName, name);

                var userId  = db.ShqUsers.Where(u => u.IdentityUser.UserName == HttpContext.Current.User.Identity.Name).FirstOrDefault().IdentityUserId;
                var wpFiles = db.ProjectFiles.Where(item => item.WorkProjectId == workProjectId &&
                                                    item.WorkProjectTemplateId == worktemplateid &&
                                                    item.Path.Contains(oldPath) == true);
                if (wpFiles != null)
                {
                    foreach (var f in wpFiles)
                    {
                        if (f.Id == einfo.Id)
                        {
                            f.Name = einfo.Name;
                        }
                        f.Path             = f.Path.Replace(oldPath, newPath);
                        f.LastModifiedById = userId;
                        f.LastModfiedTime  = DateTime.Now;
                    }
                }
                break;
            }

            case "uploadFile":    //https://forums.asp.net/t/2104884.aspx?Uploading+a+file+using+webapi+C+
                //https://shazwazza.com/post/uploading-files-and-json-data-in-the-same-request-with-angular-js/
            {
                var fileSystemDriver = new FileSystemDriver();
                var root             = new Root(new DirectoryInfo(folder))
                {
                    IsReadOnly        = false,
                    Alias             = "Root",
                    MaxUploadSizeInMb = 500,
                    LockedFolders     = new List <string>()
                };
                fileSystemDriver.AddRoot(root);

                var dbFile = db.ProjectFiles.FirstOrDefault(item => item.WorkProjectId == workProjectId &&
                                                            item.WorkProjectTemplateId == worktemplateid &&
                                                            item.Name == einfo.Name &&
                                                            item.Path == folder + "\\" + einfo.Name + "." + item.Id);

                if (dbFile == null)
                {
                    dbFile = db.ProjectFiles.Add(new ProjectFile
                        {
                            FileId                = Guid.NewGuid(),
                            Name                  = einfo.Name,
                            Level                 = einfo.Level,
                            IsFolder              = false,
                            Path                  = Path.Combine(folder, name),
                            WorkProjectId         = workProjectId,
                            WorkProjectTemplateId = worktemplateid,
                            Privilege             = einfo.Privilege,
                            CreatedById           = db.ShqUsers.Where(u => u.IdentityUser.UserName == HttpContext.Current.User.Identity.Name).FirstOrDefault().IdentityUserId,
                            LastModifiedById      = db.ShqUsers.Where(u => u.IdentityUser.UserName == HttpContext.Current.User.Identity.Name).FirstOrDefault().IdentityUserId
                        });

                    if (wp != null)
                    {
                        wp.ProjectFiles.Add(dbFile);
                    }

                    db.SaveChanges();
                }
                else
                {
                    dbFile.Status           = (int)ShqConstants.FileStatus.Ready;
                    dbFile.LastModifiedById = db.ShqUsers.Where(u => u.IdentityUser.UserName == HttpContext.Current.User.Identity.Name).FirstOrDefault().IdentityUserId;
                    dbFile.LastModfiedTime  = DateTime.Now;
                }

                name = einfo.Name + "." + dbFile.Id.ToString();
                string target = root.VolumeId + Helper.EncodePath(new DirectoryInfo(folder).Name);

                try
                {
                    byte[] bytes = Convert.FromBase64String(einfo.FileContent);
                    fileSystemDriver.Upload(target, name, bytes);
                }
                finally
                {
                    if (File.Exists(Path.Combine(folder, name)))
                    {
                        if (File.Exists(Path.Combine(folder, name)))
                        {
                            dbFile.Path = Path.Combine(folder, name);
                        }
                        else
                        {
                            db.ProjectFiles.Remove(dbFile);
                        }
                    }
                }

                break;
            }

            case "dowloadFile":
            {
                if (File.Exists(folder) == false)
                {
                    return(new HttpResponseMessage(HttpStatusCode.NotFound));
                }

                //converting Pdf file into bytes array
                var dataBytes = System.IO.File.ReadAllBytes(folder);
                //adding bytes to memory stream
                var stream = new MemoryStream(dataBytes);

                var result = new HttpResponseMessage(HttpStatusCode.OK)
                {
                    Content = new ByteArrayContent(stream.ToArray())
                };
                result.Content.Headers.ContentDisposition =
                    new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment")
                {
                    FileName = einfo.Name
                };
                result.Content.Headers.ContentType =
                    new MediaTypeHeaderValue("application/octet-stream");

                return(result);
            }

            case "newLevel":
            {
                var f = db.ProjectFiles.FirstOrDefault(item => item.Id == einfo.Id && item.WorkProjectId == workProjectId && item.WorkProjectTemplateId == worktemplateid);
                if (f != null)
                {
                    f.Level            = einfo.Level;
                    f.LastModifiedById = db.ShqUsers.Where(u => u.IdentityUser.UserName == HttpContext.Current.User.Identity.Name).FirstOrDefault().IdentityUserId;
                    f.LastModfiedTime  = DateTime.Now;
                }

                break;
            }
            }

            db.SaveChanges();

            return(new HttpResponseMessage(HttpStatusCode.OK));
        }