public void ExtractFolder(string extractionPath, IVirtualFolder folder)
        {
            var saveService = new VirtualFileSaveService();
            var extractor   = new VirtualFileExtractionService();

            var thisFolderPath = saveService.SaveFolder(extractionPath, folder.Name);

            foreach (var file in folder.Files)
            {
                WriteToConsole(Color.LightBlue, "Extracting " + file.Name);
                var fileData     = extractor.GetDataForVirtualFile(file);
                var savefileType = file.FileData.Type;

                if (file.FileData.Type == FileType.Zap)
                {
                    fileData     = ConversionService.ConvertFromZapToJpg(fileData);
                    savefileType = FileType.Jpg;
                }
                saveService.SaveFile(thisFolderPath, file.Name, savefileType, fileData);
            }
            foreach (var subFolder in folder.SubFolders)
            {
                ExtractFolder(thisFolderPath, subFolder);
            }
        }
 public static FileSystemItem FromFullName(string fullName, VirtualItemType type, IVirtualFolder parent)
 {
     if (fullName == null)
     {
         throw new ArgumentNullException("fullName");
     }
     if (type == VirtualItemType.Unknown)
     {
         if (!Directory.Exists(fullName))
         {
             if (!File.Exists(fullName))
             {
                 throw new FileNotFoundException(string.Format("Cannot discover '{0}' item type because no such file or folder found.", fullName), fullName);
             }
             type = VirtualItemType.File;
         }
         else
         {
             type = VirtualItemType.Folder;
         }
     }
     fullName = fullName.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar);
     if (type == VirtualItemType.Folder)
     {
         return new FileSystemFolder(fullName, parent);
     }
     if (VirtualItem.IsLink(fullName))
     {
         return new FileSystemShellLink(fullName, parent);
     }
     return new FileSystemFile(fullName, parent);
 }
Example #3
0
        public IVirtualFile MoveFile(IVirtualFile file, IVirtualFolder newParentFolder)
        {
            if (file != null && newParentFolder != null)
            {
                string sourcePath = file.AbsolutePath;
                string destinationParentPath = newParentFolder.AbsolutePath;


                if (File.Exists(sourcePath) && Directory.Exists(destinationParentPath))
                {
                    string relativePath = Path.Combine(newParentFolder.RelativePath, file.Name);
                    string destinationPath = newParentFolder.FileSystem.GetAbsolutePath(relativePath);

                    if (File.Exists(destinationPath))
                    {
                        File.Delete(destinationPath);
                    }

                    File.Move(sourcePath, destinationPath);
                    return new DiskVirtualFile(newParentFolder.FileSystem, relativePath, file.Name);
                }
            }

            return null;
        }
Example #4
0
        public IVirtualFile CreateFile(IVirtualFolder folder, string fileName, Stream content = null)
        {
            if (folder != null)
            {
                if (folder.FileSystem != this)
                {
                    return folder.FileSystem.CreateFile(folder, fileName, content);
                }

                if (this.FolderExists(folder) && !string.IsNullOrWhiteSpace(fileName))
                {
                    string relativePath = Path.Combine(folder.RelativePath, fileName);
                    string path = this.GetAbsolutePath(relativePath);


                    using (Stream writeStream = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None))
                    {
                        if (content != null)
                        {
                            content.CopyTo(writeStream);
                        }
                    }

                    return new DiskVirtualFile(this, relativePath, fileName);
                }
            }

            return null;
        }
Example #5
0
        public XmlSitemapGenerator(
            ICategoryService categoryService,
            IProductService productService,
            IManufacturerService manufacturerService,
            ITopicService topicService,
            ILanguageService languageService,
            ICustomerService customerService,
            ICatalogSearchService catalogSearchService,
            IUrlRecordService urlRecordService,
            ICommonServices services,
            ILockFileManager lockFileManager,
            UrlHelper urlHelper)
        {
            _categoryService      = categoryService;
            _productService       = productService;
            _manufacturerService  = manufacturerService;
            _topicService         = topicService;
            _languageService      = languageService;
            _customerService      = customerService;
            _catalogSearchService = catalogSearchService;
            _urlRecordService     = urlRecordService;
            _services             = services;
            _lockFileManager      = lockFileManager;
            _urlHelper            = urlHelper;

            _tenantFolder = _services.ApplicationEnvironment.TenantFolder;
            _baseDir      = _tenantFolder.Combine("Sitemaps");

            Logger = NullLogger.Instance;
        }
Example #6
0
        private void ListFolders(IVirtualFolder nodeFolderInfo)
        {
            foreach (IVirtualFolder folder in nodeFolderInfo.SubFolders)
            {
                ListViewItem item = null;
                ListViewItem.ListViewSubItem[] subItems;
                if (folder == null)
                {
                    continue;
                }

                item     = new ListViewItem(folder.Name, 0);
                item.Tag = folder;
                if (folder.Name.CaseInsensitiveContains(app.M4B_FileExtension))
                {
                    item.ImageIndex = (int)FileType.M4B;
                }
                else if (folder.Name.Contains(app.M3A_FileExtension))
                {
                    item.ImageIndex = (int)FileType.M3A;
                }
                subItems = new ListViewItem.ListViewSubItem[]
                {
                    new ListViewItem.ListViewSubItem(item, ""),
                };

                item.SubItems.AddRange(subItems);
                fileExplorer.Items.Add(item);
            }
        }
 public static void CopyResursiveFolderTo(this IVirtualFolder folder, IVirtualFolder dstfolder, CopyFileMode mode)
 {
     if (!dstfolder.Exists())
     {
         dstfolder.Create();
     }
     folder.CopyFolderContent(dstfolder, mode);
 }
Example #8
0
 public SqlScripts_TreeNode(IDatabaseSource conn, IVirtualFolder folder, ITreeNode parent, string titlePostfix, string namePostfix)
     : base(parent, folder, "sqlscripts" + namePostfix)
 {
     m_conn         = conn;
     m_titlePostfix = titlePostfix;
     //DXDriver driver = conn.Connection.GetDXDriver();
     //if (driver != null) m_virtualFolders.Add(driver.GetFolder("sqlscripts", conn.DatabaseName));
 }
Example #9
0
 public VirtualFolderTreeNode(string protocol, IVirtualFolder folder)
     : base(protocol)
 {
     m_folder        = folder;
     m_DoGetChildren = DoGetChildren;
     SetAppObject(new FolderAppObject {
         Folder = folder
     });
 }
Example #10
0
 public VirtualFolderTreeNode(ITreeNode parent, IVirtualFolder folder, string name)
     : base(parent, name)
 {
     m_folder        = folder;
     m_DoGetChildren = DoGetChildren;
     SetAppObject(new FolderAppObject {
         Folder = folder
     });
 }
Example #11
0
        public LockFile(IVirtualFolder folder, string path, string content, ReaderWriterLockSlim rwLock)
        {
            _folder  = folder;
            _content = content;
            _rwLock  = rwLock;
            _path    = path;

            // create the physical lock file
            _folder.CreateTextFile(_path, content);
        }
Example #12
0
        private void ListFiles(IVirtualFolder nodeFolderInfo)
        {
            ListViewItem.ListViewSubItem[] subItems;
            ListViewItem item         = null;
            bool         isSmallImage = true;

            foreach (var file in nodeFolderInfo.Files)
            {
                isSmallImage = true;
                item         = new ListViewItem(file.Name, (int)file.FileData.Type);
                item.Tag     = file;

                if (file.FileData is VirtualFileDataInArchive)
                {
                    var archiveIndex    = file.FileData as VirtualFileDataInArchive;
                    var fileSizeInBytes = archiveIndex.End - archiveIndex.Start;
                    subItems = new ListViewItem.ListViewSubItem[]
                    {
                        new ListViewItem.ListViewSubItem(item, FormatUtils.GetBytesReadable(fileSizeInBytes)),
                        new ListViewItem.ListViewSubItem(item, "(" + archiveIndex.Start + ", " + archiveIndex.End + ")")
                    };

                    // using a size cutoff for now, not reliable, but useful
                    // anything below 20KB is filtered out
                    // (I've never seen a cube face size fall below 30KB+)
                    isSmallImage = fileSizeInBytes < 20000;
                }
                else if (file.FileData is VirtualFileTiledImage)
                {
                    isSmallImage    = false;
                    item.ImageIndex = 9;
                    var tiledImage = file.FileData as VirtualFileTiledImage;
                    subItems = new ListViewItem.ListViewSubItem[]
                    {
                        new ListViewItem.ListViewSubItem(item, ""),
                        new ListViewItem.ListViewSubItem(item, tiledImage.Tiles.Count().ToString() + " images")
                    };
                }
                else
                {
                    subItems = new ListViewItem.ListViewSubItem[0];
                }

                if (filterSmallImages)
                {
                    if (isSmallImage)
                    {
                        continue;
                    }
                }

                item.SubItems.AddRange(subItems);
                fileExplorer.Items.Add(item);
            }
        }
Example #13
0
        private static void LoadItems(IVirtualFolder folder, ConfigNode parentnode)
        {
            var loaded = new Dictionary <string, ConfigFileNode>();
            List <ConfigNode> result = new List <ConfigNode>();

            var files = folder.LoadFiles();

            files.Sort((a, b) => a.Name.Length - b.Name.Length);

            foreach (IVirtualFile file in files)
            {
                if (PrefixTest(loaded, file))
                {
                    continue;
                }
                var childnode = ConfigNodeHandlerAddonType.Instance.LoadFile(parentnode, file);
                if (childnode == null)
                {
                    continue;
                }
                parentnode.Children.Add(childnode);
                loaded[file.Name] = childnode;
            }

            foreach (IVirtualFolder cf in folder.LoadFolders())
            {
                var master = PrefixTest(loaded, cf);
                if (master != null)
                {
                    var childnode = ConfigNodeHandlerAddonType.Instance.LoadSubFolder(master, cf);
                    if (childnode == null)
                    {
                        childnode = new ConfigFolderNode(master, cf)
                        {
                            _Title = cf.Name.Substring(master.Name.Length),
                            _Image = CoreIcons.img_folder,
                        }
                    }
                    ;
                    childnode._AutoSelect = false;
                    LoadItems(cf, childnode);
                    master.Children.Add(childnode);
                }
                else
                {
                    var childnode = ConfigNodeHandlerAddonType.Instance.LoadFolder(parentnode, cf);
                    if (childnode == null)
                    {
                        continue;
                    }
                    LoadItems(cf, childnode);
                    parentnode.Children.Add(childnode);
                }
            }
        }
Example #14
0
 public static void CopyFolderContent(this IVirtualFolder folder, IVirtualFolder dstfolder, CopyFileMode mode)
 {
     foreach (var file in folder.LoadFiles())
     {
         file.CopyFileTo(dstfolder.GetFile(file.Name), mode);
     }
     foreach (var fld in folder.LoadFolders())
     {
         fld.CopyResursiveFolderTo(dstfolder.GetFolder(fld.Name), mode);
     }
 }
Example #15
0
 public static bool TryDeleteDirectory(this IVirtualFolder folder, string relativePath)
 {
     try
     {
         folder.DeleteDirectory(relativePath);
         return(true);
     }
     catch
     {
         return(false);
     }
 }
 public ConfigFolderNode LoadFolder(ITreeNode parent, IVirtualFolder folder)
 {
     foreach (var holder in CommonSpace.GetAllAddons())
     {
         var hnd  = (IConfigNodeHandler)holder.InstanceModel;
         var node = hnd.LoadFolder(parent, folder);
         if (node != null)
         {
             return(node);
         }
     }
     return(null);
 }
Example #17
0
        private void nodeExplorer_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            TreeNode newSelected = e.Node;

            fileExplorer.Items.Clear();
            IVirtualFolder nodeFolderInfo = (IVirtualFolder)newSelected.Tag;

            SetLocation(newSelected);

            ListFolders(nodeFolderInfo);
            ListFiles(nodeFolderInfo);
            //fileExplorer.AutoResizeColumns(ColumnHeaderAutoResizeStyle.HeaderSize);
        }
 public SizePropertyBag(IVirtualFolder owner, AsyncCompletedEventHandler completed)
 {
     if (owner is ICloneable)
     {
         this.FOwner = (IVirtualFolder) ((ICloneable) owner).Clone();
     }
     else
     {
         this.FOwner = owner;
     }
     this.FOwnerParent = owner.Parent as IVirtualCachedFolder;
     this.FCompleted = completed;
 }
 public SetAttributesWorker(IEnumerable<IVirtualItem> items, bool includeSubfolders, FileAttributes setAttributes, FileAttributes resetAttributes, DateTime? creationTime, DateTime? lastAccessTime, DateTime? lastWriteTime)
 {
     if (!((((setAttributes != 0) || (resetAttributes != 0)) || (creationTime.HasValue || lastAccessTime.HasValue)) || lastWriteTime.HasValue))
     {
         throw new ArgumentException();
     }
     this.FContent = new AggregatedVirtualFolder(items);
     this.FSearchOptions = includeSubfolders ? SearchFolderOptions.ProcessSubfolders : ((SearchFolderOptions) 0);
     this.FSetAttributes = setAttributes;
     this.FResetAttributes = resetAttributes;
     this.FCreationTime = creationTime;
     this.FLastAccessTime = lastAccessTime;
     this.FLastWriteTime = lastWriteTime;
 }
 private static string GetFolderLocalPath(IVirtualFolder folder)
 {
   if (folder != null)
   {
     IGetFileSystemInfoService GetFileSystemInfo = folder.GetService<IGetFileSystemInfoService>();
     if (GetFileSystemInfo != null)
     {
       DirectoryInfo CurrentDirectory = GetFileSystemInfo.Info as DirectoryInfo;
       if (CurrentDirectory != null)
         return CurrentDirectory.FullName;
     }
   }
   return null;
 }
Example #21
0
        public bool FolderExists(IVirtualFolder folder)
        {
            if (folder != null)
            {
                if (folder.FileSystem != this)
                {
                    return folder.FileSystem.FolderExists(folder);
                }

                return this.FolderExists(folder.RelativePath);
            }

            return false;
        }
Example #22
0
 private static void EstablishPaths(BuildContext context, IVirtualFolder webRootFolder, string extensionName, string extensionType = "Plugin")
 {
     context.SourceFolder = webRootFolder;
     if (extensionType.IsCaseInsensitiveEqual("theme"))
     {
         context.SourcePath = "Themes/" + extensionName + "/";
         context.TargetPath = "\\Content\\Themes\\" + extensionName + "\\";
     }
     else
     {
         context.SourcePath = "Plugins/" + extensionName + "/";
         context.TargetPath = "\\Content\\Plugins\\" + extensionName + "\\";
     }
 }
 public virtual ConfigFolderNode LoadSubFolder(ConfigFileNode parent, IVirtualFolder folder)
 {
     foreach (var fld in m_subFolders)
     {
         if (folder.PathStarts(fld.Folder + "/") && folder.NameEnds("." + fld.SubFolderName))
         {
             return(new ConfigFolderNode(parent, folder)
             {
                 _Title = fld.Title ?? folder.Name,
                 _Image = fld.Image,
             });
         }
     }
     return(null);
 }
 private static string GetFolderLocalPath(IVirtualFolder folder)
 {
     if (folder != null)
     {
         IGetFileSystemInfoService GetFileSystemInfo = folder.GetService <IGetFileSystemInfoService>();
         if (GetFileSystemInfo != null)
         {
             DirectoryInfo CurrentDirectory = GetFileSystemInfo.Info as DirectoryInfo;
             if (CurrentDirectory != null)
             {
                 return(CurrentDirectory.FullName);
             }
         }
     }
     return(null);
 }
 public bool Execute(IWin32Window owner, IVirtualFolder currentFolder)
 {
     this.tsCurrentFolder.Add(currentFolder);
     HistorySettings.PopulateComboBox(this.cmbNewFolder, HistorySettings.Default.NewFolderName);
     CustomFileSystemFolder folder = currentFolder as CustomFileSystemFolder;
     if (folder != null)
     {
         this.AutoComplete.CurrentDirectory = folder.FullName;
     }
     if (base.ShowDialog(owner) == DialogResult.OK)
     {
         HistorySettings.Default.AddStringToNewFolderName(this.NewFolderName);
         return true;
     }
     return false;
 }
Example #26
0
        public void DeleteFolder(IVirtualFolder folder)
        {
            if (folder != null)
            {
                if (folder.FileSystem != this)
                {
                    folder.FileSystem.DeleteFolder(folder);
                }

                string path = this.GetAbsolutePath(folder.RelativePath);

                if (Directory.Exists(path))
                {
                    DeleteDirectory(path);
                }
            }
        }
 public CopyWorker(IEnumerable<IVirtualItem> items, IVirtualFolder dest, CopySettings settings, CopyWorkerOptions copyOptions, IVirtualItemFilter filter, IRenameFilter renameFilter)
 {
     this.FSnapshotLock = new object();
     this.FTotalProcessed = new ProcessedSize();
     this.FStoredProgress = -1;
     this.FCopyBufferSize = 0x40000;
     if (items == null)
     {
         throw new ArgumentNullException("items");
     }
     if (dest == null)
     {
         throw new ArgumentNullException("dest");
     }
     if (!VirtualItemHelper.CanCreateInFolder(dest))
     {
         throw new ArgumentException(string.Format(Resources.sCannotCopyToBasicFolder, dest.FullName));
     }
     this.FContent = new AggregatedVirtualFolder(items);
     ICloneable cloneable = dest as ICloneable;
     if (cloneable != null)
     {
         this.FDest = (IVirtualFolder) cloneable.Clone();
     }
     else
     {
         this.FDest = dest;
     }
     this.FCopyOptions = copyOptions;
     if (settings != null)
     {
         this.FCopyOptions |= settings.DefaultCopyOptions & (CopyWorkerOptions.CopyFolderTime | CopyWorkerOptions.ClearROFromCD);
         this.FCopyBufferSize = settings.CopyBufferSize;
     }
     this.FFilter = filter;
     this.FRenameFilter = renameFilter;
     if (this.FRenameFilter != null)
     {
         this.FRenameContent = new Dictionary<IVirtualItem, int>();
         foreach (IVirtualItem item in items)
         {
             this.FRenameContent.Add(item, 0);
         }
     }
     this.Buffer1 = new byte[this.FCopyBufferSize];
 }
Example #28
0
 public void CopyFileTo(IVirtualFile target, CopyFileMode mode)
 {
     GetFile().CopyFileTo(target, mode);
     foreach (IVirtualFile subfile in GetSubFiles())
     {
         string       postfix = subfile.Name.Substring(GetFile().Name.Length);
         IVirtualFile newsub  = target.Parent.GetFile(target.Name + postfix);
         subfile.CopyFileTo(newsub, mode);
     }
     foreach (IVirtualFolder subfolder in GetSubFolders())
     {
         string         postfix = subfolder.Name.Substring(GetFile().Name.Length);
         IVirtualFolder newsub  = target.Parent.GetFolder(target.Name + postfix);
         subfolder.CopyResursiveFolderTo(newsub, mode);
         //subfile.CopyFileTo(newsub, mode);
     }
 }
 public static FileSystemItem FromFileSystemInfo(FileSystemInfo info, IVirtualFolder parent)
 {
     if (info == null)
     {
         throw new ArgumentNullException("info");
     }
     DirectoryInfo info2 = info as DirectoryInfo;
     if (info2 != null)
     {
         return new FileSystemFolder(info2, parent);
     }
     FileInfo info3 = (FileInfo) info;
     if (VirtualItem.IsLink(info3.FullName))
     {
         return new FileSystemShellLink(info3, parent);
     }
     return new FileSystemFile(info3, parent);
 }
        public static IVirtualFolder FromFullName(string fullName, IVirtualFolder parent)
        {
            if (fullName == null)
            {
                throw new ArgumentNullException("fullName");
            }
            if (fullName.StartsWith(PathHelper.UncPrefix))
            {
                return new NetworkFolder(fullName, parent);
            }
            Uri uri = new Uri(fullName);
            if (uri.Scheme != UriScheme)
            {
                throw new ArgumentException(string.Format(Resources.sErrorAnotherSchemeExpected, UriScheme, uri.Scheme));
            }
            if (uri.Host != ".")
            {
                throw new ArgumentException(string.Format(Resources.sErrorOnlyDotHostAccepted, uri.Host));
            }
            string[] strArray = uri.LocalPath.Split(new char[] { Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar }, StringSplitOptions.RemoveEmptyEntries);
            NETRESOURCE resource = new NETRESOURCE {
                dwType = RESOURCETYPE.RESOURCETYPE_ANY,
                dwUsage = RESOURCEUSAGE.RESOURCEUSAGE_CONTAINER
            };
            switch (strArray.Length)
            {
                case 0:
                    return NetworkRoot;

                case 1:
                    resource.lpProvider = strArray[0];
                    resource.lpRemoteName = strArray[0];
                    resource.dwUsage |= (RESOURCEUSAGE) (-2147483648);
                    resource.dwDisplayType = RESOURCEDISPLAYTYPE.RESOURCEDISPLAYTYPE_NETWORK;
                    return new NetworkFolder(resource, parent ?? NetworkRoot);

                case 2:
                    resource.lpProvider = strArray[0];
                    resource.lpRemoteName = strArray[1];
                    resource.dwDisplayType = RESOURCEDISPLAYTYPE.RESOURCEDISPLAYTYPE_DOMAIN;
                    return new NetworkFolder(resource, parent);
            }
            throw new ArgumentException(string.Format("'{0}' is not valid network folder name", fullName));
        }
        public virtual ConfigFolderNode LoadFolder(ITreeNode parent, IVirtualFolder folder)
        {
            foreach (var fld in m_folders)
            {
                if (fld.TestFunc(folder, fld.TestData))
                {
                    return new ConfigFolderNode(parent, folder)
                           {
                               _Title = fld.Title ?? folder.Name,
                               _Image = fld.Image,
                           }
                }
                ;
            }
            return(null);
        }

        #endregion
    }
Example #32
0
        public IVirtualFolder RenameFolder(IVirtualFolder folder, string name)
        {
            if (folder != null && !string.IsNullOrWhiteSpace(name))
            {
                string sourcePath = folder.AbsolutePath;


                if (Directory.Exists(sourcePath))
                {
                    string relativePath = Path.Combine(folder.RelativePath.ReplaceLast(folder.Name, string.Empty), name);
                    string destinationPath = folder.FileSystem.GetAbsolutePath(relativePath);

                    Directory.Move(sourcePath, destinationPath);
                    return new DiskVirtualFolder(folder.FileSystem, relativePath, name);
                }
            }

            return null;
        }
Example #33
0
        public IVirtualFolder MoveFolder(IVirtualFolder folder, IVirtualFolder newParentFolder)
        {
            if (folder != null && newParentFolder != null)
            {
                string sourcePath = folder.AbsolutePath;
                string destinationParentPath = newParentFolder.AbsolutePath;


                if (Directory.Exists(sourcePath) && Directory.Exists(destinationParentPath))
                {
                    string relativePath = Path.Combine(newParentFolder.RelativePath, folder.Name);
                    string destinationPath = newParentFolder.FileSystem.GetAbsolutePath(relativePath);

                    Directory.Move(sourcePath, destinationPath);
                    return new DiskVirtualFolder(newParentFolder.FileSystem, relativePath, folder.Name);
                }
            }

            return null;
        }
Example #34
0
        public XmlSitemapGenerator(
            IEnumerable <Lazy <IXmlSitemapPublisher> > publishers,
            ILanguageService languageService,
            ICustomerService customerService,
            IUrlRecordService urlRecordService,
            ICommonServices services,
            ILockFileManager lockFileManager,
            UrlHelper urlHelper)
        {
            _publishers       = publishers;
            _languageService  = languageService;
            _customerService  = customerService;
            _urlRecordService = urlRecordService;
            _services         = services;
            _lockFileManager  = lockFileManager;
            _urlHelper        = urlHelper;

            _tenantFolder = _services.ApplicationEnvironment.TenantFolder;
            _baseDir      = _tenantFolder.Combine("Sitemaps");

            Logger = NullLogger.Instance;
        }
Example #35
0
        public IVirtualFolder CreateFolder(IVirtualFolder parent, string folderName)
        {
            if (parent != null && !string.IsNullOrWhiteSpace(folderName))
            {
                if (parent.FileSystem != this)
                {
                    parent.FileSystem.CreateFolder(parent, folderName);
                }

                string relativePath = Path.Combine(parent.RelativePath, folderName);
                string path = this.GetAbsolutePath(relativePath);

                DirectoryInfo directory = new DirectoryInfo(path);
                if (!directory.Exists)
                {
                    directory.Create();
                }

                return new DiskVirtualFolder(this, relativePath, folderName);
            }
            return null;
        }
Example #36
0
        public IVirtualFile CreateFile(IVirtualFolder folder, string fileName, string content = null)
        {
            if (folder != null)
            {
                if (folder.FileSystem != this)
                {
                    return folder.FileSystem.CreateFile(folder, fileName, content);
                }

                if (this.FolderExists(folder) && !string.IsNullOrWhiteSpace(fileName))
                {
                    string relativePath = Path.Combine(folder.RelativePath, fileName);
                    string path = this.GetAbsolutePath(relativePath);


                    File.WriteAllText(path, content);

                    return new DiskVirtualFile(this, relativePath, fileName);
                }
            }

            return null;
        }
 internal FtpItemInfo(FtpContext context, Uri absoluteUri, IVirtualFolder parent)
 {
     if (absoluteUri == null)
     {
         throw new ArgumentNullException("absoluteUri");
     }
     if (absoluteUri.Scheme != Uri.UriSchemeFtp)
     {
         throw new ArgumentException("Ftp uri scheme expected");
     }
     if (!absoluteUri.IsAbsoluteUri)
     {
         throw new ArgumentException("Relative uri is not supported");
     }
     this.Context = context;
     this.AbsoluteUri = absoluteUri;
     string[] segments = this.AbsoluteUri.Segments;
     if (segments.Length > 1)
     {
         this.FName = context.DecodeString(PathHelper.ExcludeTrailingDirectorySeparator(Uri.UnescapeDataString(segments[segments.Length - 1])));
     }
     else
     {
         UriBuilder builder = new UriBuilder(this.AbsoluteUri) {
             UserName = string.Empty,
             Password = string.Empty
         };
         if (this.AbsoluteUri.IsDefaultPort)
         {
             builder.Port = -1;
         }
         this.FName = PathHelper.ExcludeTrailingDirectorySeparator(builder.ToString());
     }
     this.FParent = parent;
     this.SetCapability(FtpItemCapability.HasParent, (this.FParent != null) || (segments.Length < 2));
     this.Initialize();
 }
        private void btnOk_Click(object sender, EventArgs e)
        {
            if (this.DestinationItem == CopyDestinationItem.Ask)
            {
                this.DestFolderNeeded();
                int num = this.Selection.Count<IVirtualItem>();
                if (((num > 1) && (this.RenameFilter != null)) && (Path.GetFileName(this.CopyTo).IndexOfAny(FileMaskChars) < 0))
                {
                    bool checkBoxChecked = false;
                    switch (MessageDialog.Show(this, PluralInfo.Format(Resources.sAskCopyToSingleFile, new object[] { num }), Resources.sConfirmCopyToFile, Resources.sRememberQuestionAnswer, ref checkBoxChecked, MessageDialog.ButtonsYesNoCancel, MessageBoxIcon.Question))
                    {
                        case MessageDialogResult.Yes:
                            this.DestinationItem = CopyDestinationItem.Folder;
                            this.FDestFolder = null;
                            break;

                        case MessageDialogResult.No:
                            break;

                        default:
                            return;
                    }
                    if (checkBoxChecked)
                    {
                        ConfirmationSettings.Default.CopyDestinationItem = this.DestinationItem;
                    }
                }
            }
            if (this.Validator.Validate(true))
            {
                base.DialogResult = DialogResult.OK;
            }
            else if (!this.Validator.GetIsValid(this.cmbCopyTo))
            {
                this.cmbCopyTo.Select();
            }
        }
Example #39
0
        public IReadOnlyList<IVirtualFolder> GetFolders(IVirtualFolder folder)
        {
            List<IVirtualFolder> folders = new List<IVirtualFolder>();
            if (folder != null)
            {
                if (folder.FileSystem != this)
                {
                    return folder.FileSystem.GetFolders(folder);
                }

                string path = this.GetAbsolutePath(folder);
                DirectoryInfo directory = new DirectoryInfo(path);
                if (directory.Exists)
                {
                    folders.AddRange(
                        directory.GetDirectories()
                                     .Where(info => ((info.Attributes & FileAttributes.Hidden) == 0) || (info.Attributes & FileAttributes.System) == 0)
                                     .Select(fileInfo => new DiskVirtualFolder(this, Path.Combine(folder.RelativePath, fileInfo.Name), fileInfo.Name)));
                }

            }

            return folders;
        }
 public IChangeVirtualFile CreateShortCut(IVirtualFolder destFolder, string name)
 {
     if (destFolder == null)
     {
         throw new ArgumentNullException("destFolder");
     }
     ICreateVirtualFile file = destFolder as ICreateVirtualFile;
     if (file == null)
     {
         throw new ArgumentException("destFolder does not implements ICreateVirtualFile");
     }
     IChangeVirtualFile file2 = file.CreateFile(name);
     using (Stream stream = file2.Open(FileMode.Create, FileAccess.Write, FileShare.Read, FileOptions.None, 0L))
     {
         using (IniWriter writer = new IniWriter(new StreamWriter(stream, Encoding.ASCII)))
         {
             writer.WriteSection("InternetShortcut");
             writer.WriteValue("URL", this.AbsoluteUri.AbsoluteUri);
             writer.WriteLine();
             writer.WriteSection("FTP");
             writer.WriteValue("UsePassive", this.Context.UsePassive.ToString());
             writer.WriteValue("UseCache", this.Context.UseCache.ToString());
             writer.WriteValue("UsePrefetch", this.Context.UsePrefetch.ToString());
             writer.WriteValue("StoreCredential", this.Context.StoreCredential.ToString());
             writer.WriteValue("UploadFileNameCasing", this.Context.UploadFileNameCasing.ToString());
             writer.WriteValue("Encoding", this.Context.ListEncoding.WebName);
             if (this.Context.StoreCredential && (this.Context.Credentials != null))
             {
                 NetworkCredential credential = this.Context.Credentials.GetCredential(null, string.Empty);
                 writer.WriteLine();
                 writer.WriteSection("Credential");
                 writer.WriteValue("UserName", credential.UserName);
                 writer.WriteValue("Password", ByteArrayHelper.ToString(SimpleEncrypt.EncryptString(credential.Password, DES.Create())));
             }
         }
     }
     return (IChangeVirtualFile) VirtualItem.FromFullName(file2.FullName, VirtualItemType.File);
 }
 public static IVirtualItem FromUri(Uri absoluteUri, VirtualItemType type, IVirtualFolder parent)
 {
     return FtpItem.FromUri(new FtpContext(), absoluteUri, type, parent);
 }
 protected void SetCapability(FtpItemCapability capability, bool value)
 {
     if (value)
     {
         this.HasCapabilities |= capability;
     }
     else
     {
         this.HasCapabilities &= ~capability;
     }
     if (!(value || ((capability & FtpItemCapability.HasParent) <= 0)))
     {
         this.FParent = null;
     }
 }
        private IVirtualFolder CreateNewFolder(IVirtualFolder destFolder, IVirtualFolder sourceFolder)
        {
            ChangeItemAction action;
            ICreateVirtualFolder folder = destFolder as ICreateVirtualFolder;
            if (folder == null)
            {
                throw new WarningException(string.Format(Resources.sCannotCopyToBasicFolder, destFolder.FullName));
            }
            AvailableItemActions canRetryOrElevate = AvailableItemActions.CanRetryOrElevate;
        Label_002D:;
            try
            {
                IVirtualFolder dest = folder.CreateFolder(this.CreateNewName(sourceFolder));
                if (this.CopyAlternateStreams(sourceFolder, dest, false) != CopyItemAction.Next)
                {
                    return null;
                }
                IChangeVirtualItem destItem = dest as IChangeVirtualItem;
                if ((destItem != null) && (this.SetOutFileAttributes(sourceFolder, destItem, true, false) != CopyItemAction.Next))
                {
                    return null;
                }
                return dest;
            }
            catch (UnauthorizedAccessException exception)
            {
                action = this.CreateFolderError(destFolder, canRetryOrElevate, exception);
                canRetryOrElevate &= ~AvailableItemActions.CanElevate;
            }
            catch (Exception exception2)
            {
                action = this.CreateFolderError(destFolder, canRetryOrElevate, exception2);
            }
            switch (action)
            {
                case ChangeItemAction.Retry:
                    goto Label_002D;

                case ChangeItemAction.Skip:
                    return null;

                case ChangeItemAction.Cancel:
                    base.CancelAsync();
                    return null;
            }
            throw new InvalidEnumArgumentException();
        }
 private ChangeItemAction CreateFolderError(IVirtualFolder folder, AvailableItemActions availableActions, Exception error)
 {
     return this.ItemError(this.OnCreateFolderError, folder, availableActions, error);
 }
 private void btnOk_Click(object sender, EventArgs e)
 {
     try
     {
         this.FFolder = (IVirtualFolder) VirtualItem.FromFullName(this.FolderPath, VirtualItemType.Folder, this.CurrentFolder);
         Task.Create<IVirtualFolder>(delegate (IVirtualFolder x) {
             HistorySettings.Default.AddStringToChangeFolder(x.FullName);
         }, this.FFolder).Start();
         base.DialogResult = DialogResult.OK;
     }
     catch (SystemException exception)
     {
         MessageDialog.ShowException(this, exception);
     }
 }
 private void DestFolderNeeded()
 {
     if (this.FDestFolder == null)
     {
         this.FRenameFilter = null;
         string copyTo = this.CopyTo;
         if (string.IsNullOrEmpty(copyTo))
         {
             this.FDestFolder = this.CurrentFolder;
         }
         else
         {
             PathType pathType = PathHelper.GetPathType(copyTo);
             if ((pathType & PathType.Folder) > PathType.Unknown)
             {
                 this.FDestFolder = (IVirtualFolder) VirtualItem.FromFullName(copyTo, VirtualItemType.Folder, this.CurrentFolder);
             }
             else
             {
                 if ((pathType & PathType.File) > PathType.Unknown)
                 {
                     string fileName = Path.GetFileName(copyTo);
                     if (fileName.IndexOfAny(FileMaskChars) < 0)
                     {
                         if (this.SelectionHasFolders || (this.DestinationItem == CopyDestinationItem.Folder))
                         {
                             this.FDestFolder = (IVirtualFolder) VirtualItem.FromFullName(copyTo, VirtualItemType.Folder, this.CurrentFolder);
                         }
                         else
                         {
                             try
                             {
                                 IVirtualItem item = VirtualItem.FromFullName(copyTo, VirtualItemType.Unknown, this.CurrentFolder);
                                 this.FDestFolder = item as IVirtualFolder;
                                 if (this.FDestFolder == null)
                                 {
                                     this.FDestFolder = item.Parent;
                                     this.FRenameFilter = new RegexRenameFilter(fileName);
                                 }
                             }
                             catch (FileNotFoundException)
                             {
                             }
                         }
                         return;
                     }
                     copyTo = Path.GetDirectoryName(copyTo);
                     this.FRenameFilter = new RegexRenameFilter(fileName);
                 }
                 if (string.IsNullOrEmpty(copyTo))
                 {
                     this.FDestFolder = this.CurrentFolder;
                 }
                 else
                 {
                     this.FDestFolder = (IVirtualFolder) VirtualItem.FromFullName(copyTo, VirtualItemType.Folder, this.CurrentFolder);
                 }
             }
         }
     }
 }
        private void CopyItem(IVirtualItem sourceItem, IVirtualFolder destFolder, IGetStream getSourceStream, List<IVirtualItem> skippedItems)
        {
            Exception exception;
            object obj2;
            CopyItemAction next = CopyItemAction.Next;
            IChangeVirtualFile DestFile = null;
            try
            {
                if (!(sourceItem is IChangeVirtualFile))
                {
                    throw new ItemChangeNotSupportedException();
                }
                ICreateVirtualFile file = destFolder as ICreateVirtualFile;
                if (file == null)
                {
                    throw new WarningException(string.Format(Resources.sCannotCopyToBasicFolder, destFolder.FullName));
                }
                DestFile = file.CreateFile(this.CreateNewName(sourceItem));
                OverwriteDialogResult Overwrite = OverwriteDialogResult.Overwrite;
                do
                {
                    string str;
                    Overwrite = this.BeforeCopy((IVirtualFile) sourceItem, DestFile, out str);
                    switch (Overwrite)
                    {
                        case OverwriteDialogResult.Rename:
                            DestFile = file.CreateFile(str);
                            break;

                        case OverwriteDialogResult.Skip:
                            skippedItems.Add(sourceItem);
                            lock ((obj2 = this.FSnapshotLock))
                            {
                                this.FSkippedCount++;
                                if (sourceItem.IsPropertyAvailable(3))
                                {
                                    this.FTotalProcessed.AddProcessedSize(Convert.ToInt64(sourceItem[3]));
                                }
                            }
                            return;

                        case OverwriteDialogResult.Abort:
                            base.CancelAsync();
                            return;
                    }
                }
                while (((Overwrite != OverwriteDialogResult.Append) && (Overwrite != OverwriteDialogResult.Resume)) && (Overwrite != OverwriteDialogResult.Overwrite));
                if (sourceItem.Equals(DestFile))
                {
                    throw new WarningException(string.Format(Resources.sCannotCopyFileToItself, sourceItem.FullName));
                }
                IChangeVirtualFile CurrentFile = (IChangeVirtualFile) sourceItem;
                IChangeVirtualItem item = sourceItem as IChangeVirtualItem;
                IChangeVirtualItem destItem = DestFile as IChangeVirtualItem;
                if ((this.CheckOption(CopyWorkerOptions.DeleteSource) && (item != null)) && item.CanMoveTo(destFolder))
                {
                    if (this.MoveItem(item, destFolder) == null)
                    {
                        next = CopyItemAction.Skip;
                    }
                    lock ((obj2 = this.FSnapshotLock))
                    {
                        this.FTotalProcessed.AddProcessedSize(Convert.ToInt64(CurrentFile[3]));
                    }
                }
                else
                {
                    if (!(!this.CheckOption(CopyWorkerOptions.CheckFreeSpace) || this.CheckDestFreeSpace(Overwrite, CurrentFile, DestFile, destFolder)))
                    {
                        next = CopyItemAction.Skip;
                    }
                    if (next == CopyItemAction.Next)
                    {
                        long num = 0L;
                        FileAttributes attributes = 0;
                        bool flag = false;
                        long position = 0L;
                        ISetOwnerWindow window = CurrentFile as ISetOwnerWindow;
                        if (window != null)
                        {
                            window.Owner = this.Owner;
                        }
                        try
                        {
                            if ((destItem != null) && destItem.Exists)
                            {
                                num = Convert.ToInt64(DestFile[3]);
                                attributes = DestFile.Attributes;
                                VirtualItemHelper.ResetSystemAttributes(DestFile);
                            }
                            else
                            {
                                Overwrite = OverwriteDialogResult.Overwrite;
                            }
                            bool flag2 = (((this.CheckOption(CopyWorkerOptions.UseSystemCopy) && OS.IsWinNT) && ((Overwrite == OverwriteDialogResult.Overwrite) && (getSourceStream == null))) && (CurrentFile is CustomFileSystemFile)) && (DestFile is CustomFileSystemFile);
                            if (flag2)
                            {
                                try
                                {
                                    if (this.CopySystem(CurrentFile, DestFile))
                                    {
                                        VirtualItemHelper.ResetSystemAttributes(DestFile);
                                    }
                                    else
                                    {
                                        next = CopyItemAction.Skip;
                                    }
                                }
                                catch (UnauthorizedAccessException)
                                {
                                    IElevatable elevatable = CurrentFile as IElevatable;
                                    bool flag3 = (elevatable != null) && elevatable.CanElevate;
                                    if (!flag3)
                                    {
                                        elevatable = DestFile as IElevatable;
                                        flag3 = (elevatable != null) && elevatable.CanElevate;
                                    }
                                    if (!flag3)
                                    {
                                        throw;
                                    }
                                    flag2 = false;
                                }
                            }
                            if (!flag2)
                            {
                                bool asyncCopy = this.CheckOption(CopyWorkerOptions.AsyncCopy);
                                if (this.CheckOption(CopyWorkerOptions.AutoAsyncCopy))
                                {
                                    IGetVirtualVolume parent = CurrentFile.Parent as IGetVirtualVolume;
                                    IGetVirtualVolume volume2 = destFolder as IGetVirtualVolume;
                                    asyncCopy = ((volume2 != null) && (parent != null)) && ((volume2.Location != parent.Location) || (volume2.VolumeType != parent.VolumeType));
                                }
                                Stream InStream = null;
                                bool DoAsyncCopy = asyncCopy;
                                long StartOffset = 0L;
                                if (Overwrite == OverwriteDialogResult.Resume)
                                {
                                    StartOffset = num;
                                }
                                next = this.OpenItemStream(sourceItem, sourceItem, DestFile, delegate {
                                    if (getSourceStream != null)
                                    {
                                        InStream = getSourceStream.GetStream();
                                        if (StartOffset > 0L)
                                        {
                                            InStream.Seek(StartOffset, SeekOrigin.Begin);
                                        }
                                    }
                                    else
                                    {
                                        InStream = CurrentFile.Open(FileMode.Open, FileAccess.Read, FileShare.Read, FileOptions.SequentialScan | (DoAsyncCopy ? FileOptions.Asynchronous : FileOptions.None), StartOffset);
                                    }
                                });
                                using (InStream)
                                {
                                    if ((InStream != null) && (next == CopyItemAction.Next))
                                    {
                                        DoAsyncCopy = DoAsyncCopy && (!InStream.CanSeek || (InStream.Length > this.Buffer1.Length));
                                        Stream OutStream = null;
                                        next = this.OpenItemStream(DestFile, sourceItem, DestFile, delegate {
                                            OutStream = DestFile.Open((Overwrite == OverwriteDialogResult.Overwrite) ? FileMode.Create : FileMode.Append, FileAccess.Write, FileShare.None, FileOptions.SequentialScan | (DoAsyncCopy ? FileOptions.Asynchronous : FileOptions.None), 0L);
                                        });
                                        using (OutStream)
                                        {
                                            if ((OutStream != null) && (next == CopyItemAction.Next))
                                            {
                                                flag = true;
                                                FileStream stream = InStream as FileStream;
                                                DoAsyncCopy &= ((stream == null) || stream.IsAsync) && (InStream != Stream.Null);
                                                FileStream stream2 = OutStream as FileStream;
                                                DoAsyncCopy &= ((stream2 == null) || stream2.IsAsync) && (OutStream != Stream.Null);
                                                if (DoAsyncCopy)
                                                {
                                                    next = this.CopyStreamAsync(InStream, OutStream, CurrentFile, DestFile);
                                                }
                                                else
                                                {
                                                    next = this.CopyStream(InStream, OutStream, CurrentFile, DestFile);
                                                }
                                                if (OutStream.CanSeek)
                                                {
                                                    if (Overwrite == OverwriteDialogResult.Append)
                                                    {
                                                        position = OutStream.Position - num;
                                                    }
                                                    else
                                                    {
                                                        position = OutStream.Position;
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                                if (!((next != CopyItemAction.Next) || base.CancellationPending))
                                {
                                    this.CopyAlternateStreams(CurrentFile, DestFile, asyncCopy);
                                }
                            }
                            if ((next == CopyItemAction.Next) && !base.CancellationPending)
                            {
                                if (destItem != null)
                                {
                                    next = this.SetOutFileAttributes(sourceItem, destItem, true, this.CheckOption(CopyWorkerOptions.CopyItemTime));
                                }
                                if (((this.CheckOption(CopyWorkerOptions.DeleteSource) && (next == CopyItemAction.Next)) && (item != null)) && !this.DeleteItem(CurrentFile))
                                {
                                    next = CopyItemAction.Skip;
                                }
                                this.RaiseAfterCopy(sourceItem, DestFile);
                            }
                        }
                        catch (AbortException)
                        {
                            next = CopyItemAction.SkipUndoDest;
                            base.CancelAsync();
                        }
                        catch (Exception exception3)
                        {
                            exception = exception3;
                            next = this.CopyItemError(null, sourceItem, DestFile, flag ? AvailableItemActions.CanUndoDestination : AvailableItemActions.None, exception);
                        }
                        if ((next != CopyItemAction.Next) && CurrentFile.IsPropertyAvailable(3))
                        {
                            lock ((obj2 = this.FSnapshotLock))
                            {
                                this.FTotalProcessed.AddProcessedSize(Convert.ToInt64(CurrentFile[3]) - position);
                            }
                        }
                        if (flag && (next == CopyItemAction.SkipUndoDest))
                        {
                            if (Overwrite != OverwriteDialogResult.Overwrite)
                            {
                                using (Stream stream3 = DestFile.Open(FileMode.Open, FileAccess.Write, FileShare.None, FileOptions.None, 0L))
                                {
                                    if (stream3.CanSeek && stream3.CanWrite)
                                    {
                                        stream3.SetLength(num);
                                    }
                                }
                                if ((destItem != null) && destItem.CanSetProperty(6))
                                {
                                    destItem[6] = attributes;
                                }
                            }
                            else if (destItem != null)
                            {
                                destItem.Delete(false);
                            }
                        }
                    }
                }
            }
            catch (Exception exception4)
            {
                exception = exception4;
                next = this.CopyItemError(null, sourceItem, DestFile, AvailableItemActions.None, exception);
            }
            if (next != CopyItemAction.Next)
            {
                skippedItems.Add(sourceItem);
                lock ((obj2 = this.FSnapshotLock))
                {
                    this.FSkippedCount++;
                }
            }
            else
            {
                lock ((obj2 = this.FSnapshotLock))
                {
                    this.FProcessedCount++;
                }
            }
        }
        private bool CheckDestFreeSpace(OverwriteDialogResult overwrite, IVirtualFile source, IVirtualFile dest, IVirtualFolder destFolder)
        {
            bool flag;
            long num = -1L;
            IVirtualFolder folderRoot = VirtualItemHelper.GetFolderRoot(destFolder);
            if ((folderRoot != null) && folderRoot.IsPropertyAvailable(0x1b))
            {
                object obj2 = folderRoot[0x1b];
                if (obj2 != null)
                {
                    num = Convert.ToInt64(obj2);
                }
            }
            if (num < 0L)
            {
                return true;
            }
            object obj3 = source[3];
            if (obj3 == null)
            {
                return true;
            }
            uint clusterSize = 0;
            IGetVirtualVolume volume = destFolder as IGetVirtualVolume;
            if (volume != null)
            {
                clusterSize = volume.ClusterSize;
                if (string.Equals(volume.FileSystem, "FAT32", StringComparison.OrdinalIgnoreCase))
                {
                    num = Math.Min(num, 0x100000000L);
                }
            }
            long num3 = Convert.ToInt64(obj3);
            if (clusterSize > 0)
            {
                num3 = (long) (((num3 / ((ulong) clusterSize)) + Math.Sign((long) (num3 % ((ulong) clusterSize)))) * clusterSize);
            }
        Label_00E7:
            flag = num3 <= num;
            if ((!flag && (dest is IPersistVirtualItem)) && ((IPersistVirtualItem) dest).Exists)
            {
                long num4 = Convert.ToInt64(dest[3]);
                if (clusterSize > 0)
                {
                    num4 = (long) (((num4 / ((ulong) clusterSize)) + Math.Sign((long) (num4 % ((ulong) clusterSize)))) * clusterSize);
                }
                switch (overwrite)
                {
                    case OverwriteDialogResult.Overwrite:
                        flag = num3 < (num + num4);
                        break;

                    case OverwriteDialogResult.Resume:
                        flag = (num3 - num4) < num;
                        break;
                }
            }
            if (flag)
            {
                return true;
            }
            Exception error = new WarningException(string.Format(Resources.sNotEnoughSpaceInDest, destFolder.FullName, source.FullName));
            switch (this.ChangeItemError(null, source, dest, AvailableItemActions.CanRetryOrIgnore, error))
            {
                case ChangeItemAction.Retry:
                    goto Label_00E7;

                case ChangeItemAction.Ignore:
                    return true;

                case ChangeItemAction.Skip:
                    return false;

                case ChangeItemAction.Cancel:
                    base.CancelAsync();
                    return false;
            }
            throw error;
        }
        private IVirtualItem MoveItem(IChangeVirtualItem item, IVirtualFolder dest)
        {
            ChangeItemAction action;
            AvailableItemActions canRetryOrElevate = AvailableItemActions.CanRetryOrElevate;
        Label_0003:;
            try
            {
                return item.MoveTo(dest);
            }
            catch (UnauthorizedAccessException exception)
            {
                action = this.MoveItemError(item, canRetryOrElevate, exception);
                canRetryOrElevate &= ~AvailableItemActions.CanElevate;
            }
            catch (Exception exception2)
            {
                action = this.MoveItemError(item, canRetryOrElevate, exception2);
            }
            switch (action)
            {
                case ChangeItemAction.Retry:
                    goto Label_0003;

                case ChangeItemAction.Skip:
                    return null;

                case ChangeItemAction.Cancel:
                    base.CancelAsync();
                    return null;
            }
            throw new InvalidEnumArgumentException();
        }
 private IVirtualFolder GetDestFolder(IVirtualFolder sourceFolder, Dictionary<IVirtualFolder, IVirtualFolder> folderMap, Stack<Tuple<IVirtualFolder, IChangeVirtualItem>> setTimeFolders)
 {
     IVirtualFolder destFolder = folderMap[sourceFolder];
     if (destFolder == null)
     {
         Stack<IVirtualFolder> stack = new Stack<IVirtualFolder>();
         while (destFolder == null)
         {
             stack.Push(sourceFolder);
             sourceFolder = sourceFolder.Parent;
             if (folderMap.ContainsKey(sourceFolder))
             {
                 destFolder = folderMap[sourceFolder];
             }
             else
             {
                 destFolder = this.FDest;
             }
         }
         while (stack.Count > 0)
         {
             sourceFolder = stack.Pop();
             destFolder = this.CreateNewFolder(destFolder, sourceFolder);
             if (destFolder == null)
             {
                 return null;
             }
             IChangeVirtualItem item = destFolder as IChangeVirtualItem;
             if ((item != null) && (setTimeFolders != null))
             {
                 setTimeFolders.Push(Tuple.Create<IVirtualFolder, IChangeVirtualItem>(sourceFolder, item));
             }
             folderMap[sourceFolder] = destFolder;
         }
     }
     return destFolder;
 }
 public bool Execute(IVirtualFolder folder)
 {
     this.tsCurrentFolder.Add(folder);
     HistorySettings.PopulateComboBox(this.cmbNewName, HistorySettings.Default.NewFile);
     if (this.cmbNewType.SelectedIndex < 0)
     {
         this.cmbNewType.SelectedIndex = 0;
         for (int i = 0; i < this.cmbNewType.Items.Count; i++)
         {
             if (string.Equals(((ShellNew) this.cmbNewType.Items[i]).Extension, Settings.Default.NewFileLastExt, StringComparison.OrdinalIgnoreCase))
             {
                 this.cmbNewType.SelectedIndex = i;
                 break;
             }
         }
     }
     bool flag = base.ShowDialog() == DialogResult.OK;
     if (flag)
     {
         HistorySettings.Default.AddStringToNewFile(this.cmbNewName.Text);
         Settings.Default.NewFileLastExt = this.Command.Extension;
     }
     return flag;
 }
 public VirtualFolderChangedEventArgs(IVirtualFolder oldFolder, IVirtualFolder newFolder)
 {
     this.PreviousFolder = oldFolder;
     this.CurrentFolder = newFolder;
 }
 private void UpdateTree(string folderName)
 {
     bool flag = !string.IsNullOrEmpty(folderName);
     bool flag2 = false;
     if (flag && this.chkUpdateTree.Checked)
     {
         try
         {
             this.FFolder = null;
             IVirtualFolder fFolder = null;
             PathType pathType = PathHelper.GetPathType(folderName);
             if ((pathType & PathType.Uri) > PathType.Unknown)
             {
                 Uri uri = new Uri(folderName);
                 if (uri.Scheme == Uri.UriSchemeFile)
                 {
                     folderName = uri.LocalPath;
                     pathType &= ~PathType.Uri;
                 }
                 else if (((uri.Scheme != Uri.UriSchemeFtp) && (uri.Scheme != NetworkFileSystemCreator.UriScheme)) && (uri.Scheme != ShellFileSystemCreator.UriScheme))
                 {
                     throw new WarningException(Resources.sErrorUnsupportedUriScheme);
                 }
             }
             if (pathType == PathType.NetworkServer)
             {
                 if (folderName.EndsWith(new string(Path.DirectorySeparatorChar, 1)))
                 {
                     this.FFolder = (IVirtualFolder) VirtualItem.FromFullName(folderName, VirtualItemType.Folder, this.CurrentFolder);
                     fFolder = this.FFolder;
                 }
             }
             else if (pathType == PathType.NetworkShare)
             {
                 int length = folderName.LastIndexOf(Path.DirectorySeparatorChar);
                 if (length == (folderName.Length - 1))
                 {
                     this.FFolder = (IVirtualFolder) VirtualItem.FromFullName(folderName, VirtualItemType.Folder, this.CurrentFolder);
                     fFolder = this.FFolder;
                 }
                 else
                 {
                     fFolder = (IVirtualFolder) VirtualItem.FromFullName(folderName.Substring(0, length), VirtualItemType.Folder, this.CurrentFolder);
                     this.FFolder = null;
                 }
             }
             else if ((pathType & PathType.Uri) == PathType.Unknown)
             {
                 this.FFolder = (IVirtualFolder) VirtualItem.FromFullName(folderName, VirtualItemType.Folder, this.CurrentFolder);
                 IPersistVirtualItem parent = this.FFolder as IPersistVirtualItem;
                 while ((parent != null) && !parent.Exists)
                 {
                     parent = parent.Parent as IPersistVirtualItem;
                 }
                 fFolder = parent as IVirtualFolder;
             }
             if ((this.FFolder == null) || (fFolder == null))
             {
                 this.tvFolders.SelectedNode = null;
             }
             else
             {
                 this.tvFolders.ShowVirtualFolder(fFolder, true);
             }
             flag2 = ((this.FFolder != null) && !this.FFolder.Equals(fFolder)) && (fFolder is ICreateVirtualFolder);
         }
         catch (Exception exception)
         {
             this.cmbFolder.BackColor = Settings.TextBoxError;
             this.cmbFolder.ForeColor = SystemColors.HighlightText;
             this.toolTipError.Show(exception.Message, this.cmbFolder, 0, this.cmbFolder.Height + this.cmbFolder.Margin.Bottom);
             flag = false;
             flag2 = false;
         }
     }
     if (flag)
     {
         this.cmbFolder.ResetForeColor();
         this.cmbFolder.ResetBackColor();
         this.toolTipError.Hide(this.cmbFolder);
     }
     this.btnOk.Enabled = flag;
     this.btnMakeFolder.Enabled = flag2;
 }
 private void DestFolderNeeded()
 {
     this.FLinkName = null;
     string destFolderText = this.DestFolderText;
     if (string.IsNullOrEmpty(destFolderText))
     {
         this.FDestFolder = this.CurrentFolder;
     }
     else
     {
         PathType pathType = PathHelper.GetPathType(destFolderText);
         if ((pathType & PathType.Folder) > PathType.Unknown)
         {
             this.FDestFolder = (IVirtualFolder) VirtualItem.FromFullName(destFolderText, VirtualItemType.Folder, this.CurrentFolder);
         }
         else
         {
             if ((pathType & PathType.File) > PathType.Unknown)
             {
                 this.FLinkName = Path.GetFileName(destFolderText);
                 destFolderText = Path.GetDirectoryName(destFolderText);
             }
             if (string.IsNullOrEmpty(destFolderText))
             {
                 this.FDestFolder = this.CurrentFolder;
             }
             else
             {
                 this.FDestFolder = (IVirtualFolder) VirtualItem.FromFullName(destFolderText, VirtualItemType.Folder, this.CurrentFolder);
             }
         }
     }
 }
 private void cmbCopyTo_TextUpdate(object sender, EventArgs e)
 {
     this.FDestFolder = null;
 }
 public CopyWorker(IEnumerable<IVirtualItem> items, IVirtualFolder dest) : this(items, dest, null, 0, null, null)
 {
 }
 internal FtpItemInfo(FtpContext context, Uri baseUri, string name, DateTime lastWriteTime, IVirtualFolder parent)
 {
     if (baseUri == null)
     {
         throw new ArgumentNullException("baseUri");
     }
     if (baseUri.Scheme != Uri.UriSchemeFtp)
     {
         throw new ArgumentException("Ftp uri scheme expected");
     }
     if (name == null)
     {
         throw new ArgumentNullException("name");
     }
     this.Context = context;
     this.FLastWriteTime = new DateTime?(lastWriteTime);
     this.FName = name;
     this.AbsoluteUri = new Uri(baseUri, Path.Combine(baseUri.AbsolutePath, context.EncodeString(this.FName)));
     this.FParent = parent;
     this.SetCapability(FtpItemCapability.HasParent, this.FParent != null);
     this.Initialize();
 }
 public TempFileSystemFolder(DirectoryInfo info, string name, IVirtualFolder parent) : base(info, parent)
 {
     this._Name = name;
 }
        /// <summary>
        /// Recursively synchronizes all files and folders from server to client.
        /// Synchronizes only folders already loaded into the user file system.
        /// </summary>
        /// <param name="userFileSystemFolderPath">Folder path in user file system.</param>
        internal async Task SyncronizeFolderAsync(string userFileSystemFolderPath)
        {
            // In case of on-demand loading the user file system contains only a subset of the server files and folders.
            // Here we sync folder only if its content already loaded into user file system (folder is not offline).
            // The folder content is loaded inside IFolder.GetChildrenAsync() method.
            if (new DirectoryInfo(userFileSystemFolderPath).Attributes.HasFlag(System.IO.FileAttributes.Offline))
            {
                // LogMessage("Folder offline, skipping:", userFileSystemFolderPath);
                return;
            }

            IEnumerable <string> userFileSystemChildren = Directory.EnumerateFileSystemEntries(userFileSystemFolderPath, "*");
            //LogMessage("Synchronizing:", userFileSystemFolderPath);

            IVirtualFolder userFolder = await virtualDrive.GetItemAsync <IVirtualFolder>(userFileSystemFolderPath, this);

            IEnumerable <FileSystemItemMetadataExt> remoteStorageChildrenItems = await userFolder.EnumerateChildrenAsync("*");

            // Create new files/folders in the user file system.
            foreach (FileSystemItemMetadataExt remoteStorageItem in remoteStorageChildrenItems)
            {
                string userFileSystemPath = Path.Combine(userFileSystemFolderPath, remoteStorageItem.Name);
                try
                {
                    // We do not want to sync MS Office temp files, etc. from remote storage.
                    // We also do not want to create MS Office files during transactional save in user file system.
                    if (!FsPath.AvoidSync(remoteStorageItem.Name) && !FsPath.AvoidSync(userFileSystemPath))
                    {
                        if (!FsPath.Exists(userFileSystemPath))
                        {
                            LogMessage($"Creating", userFileSystemPath);

                            await virtualDrive.GetUserFileSystemRawItem(userFileSystemFolderPath, this).CreateAsync(new[] { remoteStorageItem });

                            LogMessage($"Created succesefully", userFileSystemPath);
                        }
                    }
                }
                catch (Exception ex)
                {
                    LogError("Creation failed", userFileSystemPath, null, ex);
                }
            }

            // Update files/folders in user file system and sync subfolders.
            userFileSystemChildren = Directory.EnumerateFileSystemEntries(userFileSystemFolderPath, "*");
            foreach (string userFileSystemPath in userFileSystemChildren)
            {
                try
                {
                    string itemName = Path.GetFileName(userFileSystemPath);
                    FileSystemItemMetadataExt remoteStorageItem = remoteStorageChildrenItems.FirstOrDefault(x => x.Name.Equals(itemName, StringComparison.InvariantCultureIgnoreCase));


                    if (!FsPath.AvoidSync(userFileSystemPath))
                    {
                        UserFileSystemRawItem userFileSystemRawItem = virtualDrive.GetUserFileSystemRawItem(userFileSystemPath, this);
                        if (remoteStorageItem == null)
                        {
                            if (PlaceholderItem.GetItem(userFileSystemPath).GetInSync()
                                //&& !PlaceholderItem.GetItem(userFileSystemPath).IsNew(virtualDrive) // Extra check to protect from deletion files that were deleted becuse of incorrect folder merging operation.
                                )
                            {
                                // Delete the file/folder in user file system.
                                LogMessage("Deleting item", userFileSystemPath);
                                await userFileSystemRawItem.DeleteAsync();

                                LogMessage("Deleted succesefully", userFileSystemPath);
                            }
                        }
                        else
                        {
                            if (PlaceholderItem.GetItem(userFileSystemPath).GetInSync() &&
                                !await virtualDrive.GetETagManager(userFileSystemPath).ETagEqualsAsync(remoteStorageItem))
                            {
                                // User file system <- remote storage update.
                                LogMessage("Remote item modified", userFileSystemPath);
                                await userFileSystemRawItem.UpdateAsync(remoteStorageItem);

                                LogMessage("Updated succesefully", userFileSystemPath);
                            }

                            // Set the read-only attribute and all custom columns data.
                            if (PlaceholderItem.GetItem(userFileSystemPath).GetInSync())
                            {
                                await userFileSystemRawItem.SetLockedByAnotherUserAsync(remoteStorageItem.LockedByAnotherUser);

                                await userFileSystemRawItem.SetCustomColumnsDataAsync(remoteStorageItem.CustomProperties);
                            }

                            // Hydrate / dehydrate the file.
                            if (userFileSystemRawItem.HydrationRequired())
                            {
                                LogMessage("Hydrating", userFileSystemPath);
                                try
                                {
                                    new PlaceholderFile(userFileSystemPath).Hydrate(0, -1);
                                    LogMessage("Hydrated succesefully", userFileSystemPath);
                                }
                                catch (FileLoadException)
                                {
                                    // Typically this happens if another thread already hydrating the file.
                                    LogMessage("Failed to hydrate. The file is blocked.", userFileSystemPath);
                                }
                            }
                            else if (userFileSystemRawItem.DehydrationRequired())
                            {
                                LogMessage("Dehydrating", userFileSystemPath);
                                new PlaceholderFile(userFileSystemPath).Dehydrate(0, -1);
                                LogMessage("Dehydrated succesefully", userFileSystemPath);
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    LogError("Update failed", userFileSystemPath, null, ex);
                }

                // Synchronize subfolders.
                try
                {
                    if (Directory.Exists(userFileSystemPath))
                    {
                        await SyncronizeFolderAsync(userFileSystemPath);
                    }
                }
                catch (Exception ex)
                {
                    LogError("Folder sync failed:", userFileSystemPath, null, ex);
                }
            }
        }
 private void treeView_AfterSelect(object sender, TreeViewEventArgs e)
 {
     if (this.tvFolders.Focused)
     {
         this.FFolder = (IVirtualFolder) e.Node.Tag;
         this.cmbFolder.Text = this.FFolder.FullName;
         this.btnOk.Enabled = true;
         this.btnMakeFolder.Enabled = false;
     }
 }