示例#1
0
        public override IAsyncOperation <BaseStorageFolder> CreateFolderAsync(string desiredName, CreationCollisionOption options)
        {
            return(AsyncInfo.Run <BaseStorageFolder>(async(cancellationToken) =>
            {
                using var ftpClient = new FtpClient();
                ftpClient.Host = FtpHelpers.GetFtpHost(Path);
                ftpClient.Port = FtpHelpers.GetFtpPort(Path);
                ftpClient.Credentials = FtpManager.Credentials.Get(ftpClient.Host, FtpManager.Anonymous);

                if (!await ftpClient.EnsureConnectedAsync())
                {
                    throw new IOException($"Failed to connect to FTP server.");
                }

                if (ftpClient.DirectoryExists($"{FtpPath}/{desiredName}"))
                {
                    return new FtpStorageFolder(new StorageFileWithPath(null, $"{Path}/{desiredName}"));
                }

                if (!await ftpClient.CreateDirectoryAsync($"{FtpPath}/{desiredName}",
                                                          options == CreationCollisionOption.ReplaceExisting,
                                                          cancellationToken))
                {
                    throw new IOException($"Failed to create folder {desiredName}.");
                }

                return new FtpStorageFolder(new StorageFileWithPath(null, $"{Path}/{desiredName}"));
            }));
        }
    protected void OnExport(object sender, EventArgs e)
    {
        try
        {
            string fileName = TBFileName.Text;
            fileName = Path.ChangeExtension(fileName, "csv");

            byte[] fileBytes = null;
            PalletStacking.Export(
                DimCase, WeightCase,
                DimPallet, WeightPallet,
                MaxPalletHeight, BoxPositions,
                ChkbMirrorLength.Checked, ChkbMirrorWidth.Checked,
                ChkbInterlayerBottom.Checked, ChkbInterlayersIntermediate.Checked, ChkbInterlayerTop.Checked,
                ref fileBytes);

            if (FtpHelpers.Upload(fileBytes, ConfigSettings.FtpDirectory, fileName, ConfigSettings.FtpUsername, ConfigSettings.FtpPassword))
            {
                ScriptManager.RegisterStartupScript(this, GetType(), "alertMessage", $"alert('{fileName} was successfully exported!');", true);
            }
        }
        catch (Exception ex)
        {
            ScriptManager.RegisterStartupScript(this, GetType(), "alertMessage", $"alert('{ex.Message}');", true);
        }
    }
示例#3
0
        public override IAsyncOperation <IReadOnlyList <IStorageItem> > GetItemsAsync()
        {
            return(AsyncInfo.Run(async(cancellationToken) =>
            {
                using var ftpClient = new FtpClient();
                ftpClient.Host = FtpHelpers.GetFtpHost(Path);
                ftpClient.Port = FtpHelpers.GetFtpPort(Path);
                ftpClient.Credentials = FtpManager.Credentials.Get(ftpClient.Host, FtpManager.Anonymous);

                if (!await ftpClient.EnsureConnectedAsync())
                {
                    return null;
                }

                var items = new List <IStorageItem>();
                var list = await ftpClient.GetListingAsync(FtpPath);
                foreach (var item in list)
                {
                    if (item.Type == FtpFileSystemObjectType.File)
                    {
                        items.Add(new FtpStorageFile(Path, item));
                    }
                    else if (item.Type == FtpFileSystemObjectType.Directory)
                    {
                        items.Add(new FtpStorageFolder(Path, item));
                    }
                }
                ;
                return (IReadOnlyList <IStorageItem>)items;
            }));
        }
示例#4
0
 public FtpStorageFile(string path, string name, DateTimeOffset dateCreated)
 {
     Path        = path;
     Name        = name;
     FtpPath     = FtpHelpers.GetFtpPath(path);
     DateCreated = dateCreated;
 }
示例#5
0
        public override IAsyncOperation <BaseStorageFile> CreateFileAsync(string desiredName, CreationCollisionOption options)
        {
            return(AsyncInfo.Run <BaseStorageFile>(async(cancellationToken) =>
            {
                using var ftpClient = new FtpClient();
                ftpClient.Host = FtpHelpers.GetFtpHost(Path);
                ftpClient.Port = FtpHelpers.GetFtpPort(Path);
                ftpClient.Credentials = FtpManager.Credentials.Get(ftpClient.Host, FtpManager.Anonymous);

                if (!await ftpClient.EnsureConnectedAsync())
                {
                    return null;
                }

                using var stream = new MemoryStream();
                var result = await ftpClient.UploadAsync(stream, $"{FtpPath}/{desiredName}", options == CreationCollisionOption.ReplaceExisting ? FtpRemoteExists.Overwrite : FtpRemoteExists.Skip);

                if (result == FtpStatus.Success)
                {
                    return new FtpStorageFile(new StorageFileWithPath(null, $"{Path}/{desiredName}"));
                }

                if (result == FtpStatus.Skipped)
                {
                    if (options == CreationCollisionOption.FailIfExists)
                    {
                        throw new IOException("File already exists.");
                    }

                    return null;
                }

                throw new IOException($"Failed to create file {FtpPath}/{desiredName}.");
            }));
        }
示例#6
0
 public FtpStorageFolder(FtpItem ftpItem)
 {
     DateCreated = ftpItem.ItemDateCreatedReal;
     Name        = ftpItem.ItemName;
     Path        = ftpItem.ItemPath;
     FtpPath     = FtpHelpers.GetFtpPath(ftpItem.ItemPath);
 }
示例#7
0
        private async void FtpDataStreamingHandler(StreamedFileDataRequest request)
        {
            try
            {
                using var ftpClient   = new FtpClient();
                ftpClient.Host        = FtpHelpers.GetFtpHost(Path);
                ftpClient.Port        = FtpHelpers.GetFtpPort(Path);
                ftpClient.Credentials = FtpManager.Credentials.Get(ftpClient.Host, FtpManager.Anonymous);

                if (!await ftpClient.EnsureConnectedAsync())
                {
                    request.FailAndClose(StreamedFileFailureMode.CurrentlyUnavailable);
                    return;
                }

                using (var outStream = request.AsStreamForWrite())
                {
                    await ftpClient.DownloadAsync(outStream, FtpPath);

                    await outStream.FlushAsync();
                }
                request.Dispose();
            }
            catch
            {
                request.FailAndClose(StreamedFileFailureMode.Incomplete);
            }
        }
示例#8
0
        public override IAsyncOperation <BaseStorageFile> CopyAsync(IStorageFolder destinationFolder, string desiredNewName, NameCollisionOption option)
        {
            return(AsyncInfo.Run(async(cancellationToken) =>
            {
                using var ftpClient = new FtpClient();
                ftpClient.Host = FtpHelpers.GetFtpHost(Path);
                ftpClient.Port = FtpHelpers.GetFtpPort(Path);
                ftpClient.Credentials = FtpManager.Credentials.Get(ftpClient.Host, FtpManager.Anonymous);

                if (!await ftpClient.EnsureConnectedAsync())
                {
                    return null;
                }

                BaseStorageFolder destFolder = destinationFolder.AsBaseStorageFolder();
                BaseStorageFile file = await destFolder.CreateFileAsync(desiredNewName, option.Convert());
                var stream = await file.OpenStreamForWriteAsync();

                if (await ftpClient.DownloadAsync(stream, FtpPath, token: cancellationToken))
                {
                    return file;
                }

                return null;
            }));
        }
示例#9
0
        public override IAsyncAction RenameAsync(string desiredName, NameCollisionOption option)
        {
            return(AsyncInfo.Run(async(cancellationToken) =>
            {
                using var ftpClient = new FtpClient();
                ftpClient.Host = FtpHelpers.GetFtpHost(Path);
                ftpClient.Port = FtpHelpers.GetFtpPort(Path);
                ftpClient.Credentials = FtpManager.Credentials.Get(ftpClient.Host, FtpManager.Anonymous);

                if (!await ftpClient.EnsureConnectedAsync())
                {
                    return;
                }

                if (!await ftpClient.MoveDirectoryAsync(FtpPath,
                                                        $"{PathNormalization.GetParentDir(FtpPath)}/{desiredName}",
                                                        option == NameCollisionOption.ReplaceExisting ? FtpRemoteExists.Overwrite : FtpRemoteExists.Skip,
                                                        cancellationToken))
                {
                    if (option == NameCollisionOption.GenerateUniqueName)
                    {
                        // TODO: handle name generation
                    }
                }
            }));
        }
示例#10
0
        public override IAsyncOperation <IRandomAccessStream> OpenAsync(FileAccessMode accessMode)
        {
            return(AsyncInfo.Run <IRandomAccessStream>(async(cancellationToken) =>
            {
                var ftpClient = new FtpClient();
                ftpClient.Host = FtpHelpers.GetFtpHost(Path);
                ftpClient.Port = FtpHelpers.GetFtpPort(Path);
                ftpClient.Credentials = FtpManager.Credentials.Get(ftpClient.Host, FtpManager.Anonymous);

                if (!await ftpClient.EnsureConnectedAsync())
                {
                    return null;
                }

                if (accessMode == FileAccessMode.Read)
                {
                    var inStream = await ftpClient.OpenReadAsync(FtpPath, cancellationToken);
                    return new NonSeekableRandomAccessStreamForRead(inStream, (ulong)inStream.Length)
                    {
                        DisposeCallback = () => ftpClient.Dispose()
                    };
                }
                else
                {
                    return new NonSeekableRandomAccessStreamForWrite(await ftpClient.OpenWriteAsync(FtpPath, cancellationToken))
                    {
                        DisposeCallback = () => ftpClient.Dispose()
                    };
                }
            }));
        }
示例#11
0
 public FtpStorageFolder(string folder, FtpListItem ftpItem)
 {
     DateCreated = ftpItem.RawCreated < DateTime.FromFileTimeUtc(0) ? DateTimeOffset.MinValue : ftpItem.RawCreated;
     Name        = ftpItem.Name;
     Path        = PathNormalization.Combine(folder, ftpItem.Name);
     FtpPath     = FtpHelpers.GetFtpPath(Path);
 }
示例#12
0
        public override IAsyncOperation <IStorageItem> GetItemAsync(string name)
        {
            return(AsyncInfo.Run <IStorageItem>(async(cancellationToken) =>
            {
                using var ftpClient = new FtpClient();
                ftpClient.Host = FtpHelpers.GetFtpHost(Path);
                ftpClient.Port = FtpHelpers.GetFtpPort(Path);
                ftpClient.Credentials = FtpManager.Credentials.Get(ftpClient.Host, FtpManager.Anonymous);

                if (!await ftpClient.EnsureConnectedAsync())
                {
                    return null;
                }

                var item = await ftpClient.GetObjectInfoAsync(FtpHelpers.GetFtpPath(PathNormalization.Combine(Path, name)));
                if (item != null)
                {
                    if (item.Type == FtpFileSystemObjectType.File)
                    {
                        return new FtpStorageFile(Path, item);
                    }
                    else if (item.Type == FtpFileSystemObjectType.Directory)
                    {
                        return new FtpStorageFolder(Path, item);
                    }
                }
                return null;
            }));
        }
示例#13
0
        private FtpClient GetFtpClient()
        {
            string host        = FtpHelpers.GetFtpHost(Path);
            ushort port        = FtpHelpers.GetFtpPort(Path);
            var    credentials = FtpManager.Credentials.Get(host, FtpManager.Anonymous);

            return(new(host, port, credentials));
        }
示例#14
0
 public static IAsyncOperation <BaseStorageFolder> FromPathAsync(string path)
 {
     if (FtpHelpers.IsFtpPath(path) && FtpHelpers.VerifyFtpPath(path))
     {
         return(Task.FromResult <BaseStorageFolder>(new FtpStorageFolder(new StorageFolderWithPath(null, path))).AsAsyncOperation());
     }
     return(Task.FromResult <BaseStorageFolder>(null).AsAsyncOperation());
 }
示例#15
0
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            DropDownListFiles.DataSource = FtpHelpers.GetListOfFiles(ConfigSettings.FtpDirectory, ConfigSettings.FtpUsername, ConfigSettings.FtpPassword);
            DropDownListFiles.DataBind();

            DimCase         = new Vector3D(300.0, 280.0, 275.0);
            WeightCase      = 1.0;
            DimPallet       = new Vector3D(1200.0, 1000.0, 155.0);
            WeightPallet    = 23.0;
            MaxPalletHeight = 1700.0;
            BoxPositions    = new List <BoxPosition>();
        }
    }
示例#16
0
        public override IAsyncAction DeleteAsync()
        {
            return(AsyncInfo.Run(async(cancellationToken) =>
            {
                using var ftpClient = new FtpClient();
                ftpClient.Host = FtpHelpers.GetFtpHost(Path);
                ftpClient.Port = FtpHelpers.GetFtpPort(Path);
                ftpClient.Credentials = FtpManager.Credentials.Get(ftpClient.Host, FtpManager.Anonymous);

                if (!await ftpClient.EnsureConnectedAsync())
                {
                    return;
                }

                await ftpClient.DeleteDirectoryAsync(FtpPath, cancellationToken);
            }));
        }
示例#17
0
    protected void OnOpenProject(object sender, EventArgs e)
    {
        // get selected file name
        Vector3D           dimCase = Vector3D.Zero;
        double             weightCase = 0.0;
        Vector3D           dimPallet = Vector3D.Zero;
        double             weightPallet = 0.0;
        double             maxPalletHeight = 0.0;
        bool               MirrorX = false, MirrorY = false;;
        bool               interlayerBottom = false, interlayerTop = false, interlayerMiddle = false;
        List <BoxPosition> boxPositions = new List <BoxPosition>();

        string filePath = DropDownListFiles.SelectedValue;

        byte[] fileContent = null;
        FtpHelpers.Download(ref fileContent, ConfigSettings.FtpDirectory, filePath, ConfigSettings.FtpUsername, ConfigSettings.FtpPassword);
        ExporterCSV_TechBSA.Import(new MemoryStream(fileContent),
                                   ref boxPositions,
                                   ref dimCase, ref weightCase,
                                   ref dimPallet, ref weightPallet,
                                   ref maxPalletHeight,
                                   ref MirrorX, ref MirrorY,
                                   ref interlayerBottom, ref interlayerTop, ref interlayerMiddle);

        DimCase                 = dimCase; WeightCase = weightCase;
        DimPallet               = dimPallet; WeightPallet = weightPallet;
        MaxPalletHeight         = maxPalletHeight;
        BoxPositions            = boxPositions;
        LayersMirrorX           = MirrorX;
        LayersMirrorY           = MirrorY;
        InterlayerBottom        = interlayerBottom;
        InterlayerTop           = interlayerTop;
        InterlayersIntermadiate = interlayerMiddle;
        FileName                = filePath;

        if (ConfigSettings.WebGLMode)
        {
            Response.Redirect("ValidationWebGL.axpx");
        }
        else
        {
            Response.Redirect("Validation.aspx");
        }
    }
示例#18
0
        public override IAsyncOperation <IInputStream> OpenSequentialReadAsync()
        {
            return(AsyncInfo.Run <IInputStream>(async(cancellationToken) =>
            {
                var ftpClient = new FtpClient();
                ftpClient.Host = FtpHelpers.GetFtpHost(Path);
                ftpClient.Port = FtpHelpers.GetFtpPort(Path);
                ftpClient.Credentials = FtpManager.Credentials.Get(ftpClient.Host, FtpManager.Anonymous);

                if (!await ftpClient.EnsureConnectedAsync())
                {
                    return null;
                }

                var inStream = await ftpClient.OpenReadAsync(FtpPath, cancellationToken);
                return new InputStreamWithDisposeCallback(inStream)
                {
                    DisposeCallback = () => ftpClient.Dispose()
                };
            }));
        }
示例#19
0
        public override IAsyncOperation <BaseBasicProperties> GetBasicPropertiesAsync()
        {
            return(AsyncInfo.Run <BaseBasicProperties>(async(cancellationToken) =>
            {
                using var ftpClient = new FtpClient();
                ftpClient.Host = FtpHelpers.GetFtpHost(Path);
                ftpClient.Port = FtpHelpers.GetFtpPort(Path);
                ftpClient.Credentials = FtpManager.Credentials.Get(ftpClient.Host, FtpManager.Anonymous);

                if (!await ftpClient.EnsureConnectedAsync())
                {
                    return new BaseBasicProperties();
                }

                var item = await ftpClient.GetObjectInfoAsync(FtpPath);
                if (item != null)
                {
                    return new FtpFolderBasicProperties(item);
                }
                return new BaseBasicProperties();
            }));
        }
示例#20
0
        public override IAsyncOperation <IRandomAccessStreamWithContentType> OpenReadAsync()
        {
            return(AsyncInfo.Run <IRandomAccessStreamWithContentType>(async(cancellationToken) =>
            {
                var ftpClient = new FtpClient();
                ftpClient.Host = FtpHelpers.GetFtpHost(Path);
                ftpClient.Port = FtpHelpers.GetFtpPort(Path);
                ftpClient.Credentials = FtpManager.Credentials.Get(ftpClient.Host, FtpManager.Anonymous);

                if (!await ftpClient.EnsureConnectedAsync())
                {
                    return null;
                }

                var inStream = await ftpClient.OpenReadAsync(FtpPath, cancellationToken);
                var nsStream = new NonSeekableRandomAccessStreamForRead(inStream, (ulong)inStream.Length)
                {
                    DisposeCallback = () => ftpClient.Dispose()
                };
                return new StreamWithContentType(nsStream);
            }));
        }
 public virtual void CopyPathOfSelectedItem(RoutedEventArgs e)
 {
     try
     {
         if (SlimContentPage != null)
         {
             var path = SlimContentPage.SelectedItem != null ? SlimContentPage.SelectedItem.ItemPath : associatedInstance.FilesystemViewModel.WorkingDirectory;
             if (FtpHelpers.IsFtpPath(path))
             {
                 path = path.Replace("\\", "/", StringComparison.Ordinal);
             }
             DataPackage data = new DataPackage();
             data.SetText(path);
             Clipboard.SetContent(data);
             Clipboard.Flush();
         }
     }
     catch (Exception)
     {
         Debugger.Break();
     }
 }
示例#22
0
 public static IAsyncOperation <BaseStorageFile> FromPathAsync(string path)
 => FtpHelpers.IsFtpPath(path) && FtpHelpers.VerifyFtpPath(path)
         ? Task.FromResult <BaseStorageFile>(new FtpStorageFile(new StorageFileWithPath(null, path))).AsAsyncOperation()
         : Task.FromResult <BaseStorageFile>(null).AsAsyncOperation();
示例#23
0
 public FtpStorageFolder(IStorageItemWithPath item)
 {
     Name    = System.IO.Path.GetFileName(item.Path);
     Path    = item.Path;
     FtpPath = FtpHelpers.GetFtpPath(item.Path);
 }
示例#24
0
        public async Task <IStorageHistory> RestoreFromTrashAsync(IStorageItemWithPath source, string destination, IProgress <float> progress, IProgress <FileSystemStatusCode> errorCode, CancellationToken cancellationToken)
        {
            var connection = await AppServiceConnectionHelper.Instance;

            if (connection == null || string.IsNullOrWhiteSpace(source.Path) || source.Path.StartsWith(@"\\?\", StringComparison.Ordinal) || string.IsNullOrWhiteSpace(destination) || destination.StartsWith(@"\\?\", StringComparison.Ordinal) || FtpHelpers.IsFtpPath(destination))
            {
                // Fallback to builtin file operations
                return(await filesystemOperations.RestoreFromTrashAsync(source, destination, progress, errorCode, cancellationToken));
            }

            var operationID = Guid.NewGuid().ToString();

            using var r = cancellationToken.Register(CancelOperation, operationID, false);

            EventHandler <Dictionary <string, object> > handler = (s, e) => OnProgressUpdated(s, e, operationID, progress);

            connection.RequestReceived += handler;

            var moveResult = new ShellOperationResult();

            var(status, response) = await connection.SendMessageForResponseAsync(new ValueSet()
            {
                { "Arguments", "FileOperation" },
                { "fileop", "MoveItem" },
                { "operationID", operationID },
                { "filepath", source.Path },
                { "destpath", destination },
                { "overwrite", false },
                { "HWND", NativeWinApiHelper.CoreWindowHandle.ToInt64() }
            });

            var result = (FilesystemResult)(status == AppServiceResponseStatus.Success &&
                                            response.Get("Success", false));
            var shellOpResult = JsonConvert.DeserializeObject <ShellOperationResult>(response.Get("Result", ""));

            moveResult.Items.AddRange(shellOpResult?.Items ?? Enumerable.Empty <ShellOperationItemResult>());

            if (connection != null)
            {
                connection.RequestReceived -= handler;
            }

            result &= (FilesystemResult)moveResult.Items.All(x => x.Succeeded);

            if (result)
            {
                progress?.Report(100.0f);
                errorCode?.Report(FileSystemStatusCode.Success);
                var movedSources = moveResult.Items.Where(x => new[] { source }.Select(s => s.Path).Contains(x.Source)).Where(x => x.Succeeded && x.Destination != null && x.Source != x.Destination);
                if (movedSources.Any())
                {
                    // Recycle bin also stores a file starting with $I for each item
                    await DeleteItemsAsync(movedSources.Select(src => StorageHelpers.FromPathAndType(
                                                                   Path.Combine(Path.GetDirectoryName(src.Source), Path.GetFileName(src.Source).Replace("$R", "$I", StringComparison.Ordinal)),
                                                                   new[] { source }.Single(s => s.Path == src.Source).ItemType)), null, null, true, cancellationToken);

                    return(new StorageHistory(FileOperationType.Restore, source,
                                              StorageHelpers.FromPathAndType(movedSources.Single().Destination, source.ItemType)));
                }
                return(null); // Cannot undo overwrite operation
            }
            else
            {
                // Retry failed operations
                return(await filesystemOperations.RestoreFromTrashAsync(source, destination, progress, errorCode, cancellationToken));
            }
        }
示例#25
0
        public async Task <IStorageHistory> CopyItemsAsync(IEnumerable <IStorageItemWithPath> source, IEnumerable <string> destination, IEnumerable <FileNameConflictResolveOptionType> collisions, IProgress <float> progress, IProgress <FileSystemStatusCode> errorCode, CancellationToken cancellationToken)
        {
            var connection = await AppServiceConnectionHelper.Instance;

            if (connection == null || source.Any(x => string.IsNullOrWhiteSpace(x.Path) || x.Path.StartsWith(@"\\?\", StringComparison.Ordinal)) || destination.Any(x => string.IsNullOrWhiteSpace(x) || x.StartsWith(@"\\?\", StringComparison.Ordinal) || FtpHelpers.IsFtpPath(x)))
            {
                // Fallback to builtin file operations
                return(await filesystemOperations.CopyItemsAsync(source, destination, collisions, progress, errorCode, cancellationToken));
            }

            source      = source.Where((src, index) => collisions.ElementAt(index) != FileNameConflictResolveOptionType.Skip).ToList();
            destination = destination.Where((src, index) => collisions.ElementAt(index) != FileNameConflictResolveOptionType.Skip).ToList();
            collisions  = collisions.Where(c => c != FileNameConflictResolveOptionType.Skip).ToList();

            var operationID = Guid.NewGuid().ToString();

            using var r = cancellationToken.Register(CancelOperation, operationID, false);

            EventHandler <Dictionary <string, object> > handler = (s, e) => OnProgressUpdated(s, e, operationID, progress);

            connection.RequestReceived += handler;

            var sourceReplace      = source.Where((src, index) => collisions.ElementAt(index) == FileNameConflictResolveOptionType.ReplaceExisting);
            var destinationReplace = destination.Where((src, index) => collisions.ElementAt(index) == FileNameConflictResolveOptionType.ReplaceExisting);
            var sourceRename       = source.Where((src, index) => collisions.ElementAt(index) != FileNameConflictResolveOptionType.ReplaceExisting);
            var destinationRename  = destination.Where((src, index) => collisions.ElementAt(index) != FileNameConflictResolveOptionType.ReplaceExisting);

            var result     = (FilesystemResult)true;
            var copyResult = new ShellOperationResult();

            if (sourceRename.Any())
            {
                var(status, response) = await connection.SendMessageForResponseAsync(new ValueSet()
                {
                    { "Arguments", "FileOperation" },
                    { "fileop", "CopyItem" },
                    { "operationID", operationID },
                    { "filepath", string.Join('|', sourceRename.Select(s => s.Path)) },
                    { "destpath", string.Join('|', destinationRename) },
                    { "overwrite", false },
                    { "HWND", NativeWinApiHelper.CoreWindowHandle.ToInt64() }
                });

                result &= (FilesystemResult)(status == AppServiceResponseStatus.Success &&
                                             response.Get("Success", false));
                var shellOpResult = JsonConvert.DeserializeObject <ShellOperationResult>(response.Get("Result", ""));
                copyResult.Items.AddRange(shellOpResult?.Items ?? Enumerable.Empty <ShellOperationItemResult>());
            }
            if (sourceReplace.Any())
            {
                var(status, response) = await connection.SendMessageForResponseAsync(new ValueSet()
                {
                    { "Arguments", "FileOperation" },
                    { "fileop", "CopyItem" },
                    { "operationID", operationID },
                    { "filepath", string.Join('|', sourceReplace.Select(s => s.Path)) },
                    { "destpath", string.Join('|', destinationReplace) },
                    { "overwrite", true },
                    { "HWND", NativeWinApiHelper.CoreWindowHandle.ToInt64() }
                });

                result &= (FilesystemResult)(status == AppServiceResponseStatus.Success &&
                                             response.Get("Success", false));
                var shellOpResult = JsonConvert.DeserializeObject <ShellOperationResult>(response.Get("Result", ""));
                copyResult.Items.AddRange(shellOpResult?.Items ?? Enumerable.Empty <ShellOperationItemResult>());
            }

            if (connection != null)
            {
                connection.RequestReceived -= handler;
            }

            result &= (FilesystemResult)copyResult.Items.All(x => x.Succeeded);

            if (result)
            {
                progress?.Report(100.0f);
                errorCode?.Report(FileSystemStatusCode.Success);
                var copiedSources = copyResult.Items.Where(x => sourceRename.Select(s => s.Path).Contains(x.Source)).Where(x => x.Succeeded && x.Destination != null && x.Source != x.Destination);
                if (copiedSources.Any())
                {
                    return(new StorageHistory(FileOperationType.Copy, copiedSources.Select(x => sourceRename.Single(s => s.Path == x.Source)),
                                              copiedSources.Select(item => StorageHelpers.FromPathAndType(item.Destination, sourceRename.Single(s => s.Path == item.Source).ItemType))));
                }
                return(null); // Cannot undo overwrite operation
            }
            else
            {
                // Retry failed operations
                var failedSources = copyResult.Items.Where(x => source.Select(s => s.Path).Contains(x.Source)).Where(x => !x.Succeeded);
                var copyZip       = source.Zip(destination, (src, dest) => new { src, dest }).Zip(collisions, (z1, coll) => new { z1.src, z1.dest, coll });
                return(await filesystemOperations.CopyItemsAsync(
                           failedSources.Select(x => copyZip.Single(s => s.src.Path == x.Source).src),
                           failedSources.Select(x => copyZip.Single(s => s.src.Path == x.Source).dest),
                           failedSources.Select(x => copyZip.Single(s => s.src.Path == x.Source).coll), progress, errorCode, cancellationToken));
            }
        }
示例#26
0
        public async Task <IStorageHistory> RenameAsync(IStorageItemWithPath source, string newName, NameCollisionOption collision, IProgress <FileSystemStatusCode> errorCode, CancellationToken cancellationToken)
        {
            var connection = await AppServiceConnectionHelper.Instance;

            if (connection == null || string.IsNullOrWhiteSpace(source.Path) || source.Path.StartsWith(@"\\?\", StringComparison.Ordinal) || FtpHelpers.IsFtpPath(source.Path))
            {
                // Fallback to builtin file operations
                return(await filesystemOperations.RenameAsync(source, newName, collision, errorCode, cancellationToken));
            }

            var renameResult = new ShellOperationResult();

            var(status, response) = await connection.SendMessageForResponseAsync(new ValueSet()
            {
                { "Arguments", "FileOperation" },
                { "fileop", "RenameItem" },
                { "operationID", Guid.NewGuid().ToString() },
                { "filepath", source.Path },
                { "newName", newName },
                { "overwrite", collision == NameCollisionOption.ReplaceExisting }
            });

            var result = (FilesystemResult)(status == AppServiceResponseStatus.Success &&
                                            response.Get("Success", false));
            var shellOpResult = JsonConvert.DeserializeObject <ShellOperationResult>(response.Get("Result", ""));

            renameResult.Items.AddRange(shellOpResult?.Items ?? Enumerable.Empty <ShellOperationItemResult>());

            result &= (FilesystemResult)renameResult.Items.All(x => x.Succeeded);

            if (result)
            {
                errorCode?.Report(FileSystemStatusCode.Success);
                var renamedSources = renameResult.Items.Where(x => new[] { source }.Select(s => s.Path).Contains(x.Source)).Where(x => x.Succeeded && x.Destination != null && x.Source != x.Destination);
                if (renamedSources.Any())
                {
                    return(new StorageHistory(FileOperationType.Rename, source,
                                              StorageHelpers.FromPathAndType(renamedSources.Single().Destination, source.ItemType)));
                }
                return(null); // Cannot undo overwrite operation
            }
            else
            {
                // Retry failed operations
                return(await filesystemOperations.RenameAsync(source, newName, collision, errorCode, cancellationToken));
            }
        }
示例#27
0
 public FtpStorageFile(IStorageItemWithPath item)
 {
     Path    = item.Path;
     Name    = IO.Path.GetFileName(item.Path);
     FtpPath = FtpHelpers.GetFtpPath(item.Path);
 }
示例#28
0
        public async Task <IStorageHistory> DeleteItemsAsync(IEnumerable <IStorageItemWithPath> source, IProgress <float> progress, IProgress <FileSystemStatusCode> errorCode, bool permanently, CancellationToken cancellationToken)
        {
            var connection = await AppServiceConnectionHelper.Instance;

            if (connection == null || source.Any(x => string.IsNullOrWhiteSpace(x.Path) || x.Path.StartsWith(@"\\?\", StringComparison.Ordinal) || FtpHelpers.IsFtpPath(x.Path)))
            {
                // Fallback to builtin file operations
                return(await filesystemOperations.DeleteItemsAsync(source, progress, errorCode, permanently, cancellationToken));
            }

            source = source.DistinctBy(x => x.Path); // #5771
            var deleleFilePaths = source.Select(s => s.Path);

            var deleteFromRecycleBin = source.Any() ? recycleBinHelpers.IsPathUnderRecycleBin(source.ElementAt(0).Path) : false;

            permanently |= deleteFromRecycleBin;

            if (deleteFromRecycleBin)
            {
                // Recycle bin also stores a file starting with $I for each item
                deleleFilePaths = deleleFilePaths.Concat(source.Select(x => Path.Combine(Path.GetDirectoryName(x.Path), Path.GetFileName(x.Path).Replace("$R", "$I", StringComparison.Ordinal)))).Distinct();
            }

            var operationID = Guid.NewGuid().ToString();

            using var r = cancellationToken.Register(CancelOperation, operationID, false);

            EventHandler <Dictionary <string, object> > handler = (s, e) => OnProgressUpdated(s, e, operationID, progress);

            connection.RequestReceived += handler;

            var deleteResult = new ShellOperationResult();

            var(status, response) = await connection.SendMessageForResponseAsync(new ValueSet()
            {
                { "Arguments", "FileOperation" },
                { "fileop", "DeleteItem" },
                { "operationID", operationID },
                { "filepath", string.Join('|', deleleFilePaths) },
                { "permanently", permanently },
                { "HWND", NativeWinApiHelper.CoreWindowHandle.ToInt64() }
            });

            var result = (FilesystemResult)(status == AppServiceResponseStatus.Success &&
                                            response.Get("Success", false));
            var shellOpResult = JsonConvert.DeserializeObject <ShellOperationResult>(response.Get("Result", ""));

            deleteResult.Items.AddRange(shellOpResult?.Items ?? Enumerable.Empty <ShellOperationItemResult>());

            if (connection != null)
            {
                connection.RequestReceived -= handler;
            }

            result &= (FilesystemResult)deleteResult.Items.All(x => x.Succeeded);

            if (result)
            {
                progress?.Report(100.0f);
                errorCode?.Report(FileSystemStatusCode.Success);
                foreach (var item in deleteResult.Items)
                {
                    await associatedInstance.FilesystemViewModel.RemoveFileOrFolderAsync(item.Source);
                }
                var recycledSources = deleteResult.Items.Where(x => source.Select(s => s.Path).Contains(x.Source)).Where(x => x.Succeeded && x.Destination != null && x.Source != x.Destination);
                if (recycledSources.Any())
                {
                    return(new StorageHistory(FileOperationType.Recycle, recycledSources.Select(x => source.Single(s => s.Path == x.Source)),
                                              recycledSources.Select(item => StorageHelpers.FromPathAndType(item.Destination, source.Single(s => s.Path == item.Source).ItemType))));
                }
                return(new StorageHistory(FileOperationType.Delete, source, null));
            }
            else
            {
                // Retry failed operations
                var failedSources = deleteResult.Items.Where(x => source.Select(s => s.Path).Contains(x.Source))
                                    .Where(x => !x.Succeeded && x.HResult != HResult.COPYENGINE_E_USER_CANCELLED && x.HResult != HResult.COPYENGINE_E_RECYCLE_BIN_NOT_FOUND);
                return(await filesystemOperations.DeleteItemsAsync(
                           failedSources.Select(x => source.Single(s => s.Path == x.Source)), progress, errorCode, permanently, cancellationToken));
            }
        }