public override async Task <IScriptCommand> ExecuteAsync(ParameterDic pm)
        {
            Func <IEntryModel, bool> filter;

            if (pm.ContainsKey("Mask"))
            {
                string mask = pm["Mask"] as string;
                filter = (em => _filter(em) && PathFE.MatchFileMask(em.Name, mask));
            }
            else
            {
                filter = _filter;
            }
            _lookupFilter = _lookupFilter ?? (em => em.IsDirectory);

            bool refresh = pm.ContainsKey("Refresh") && (bool)pm["Refresh"];

            List <IEntryModel> result = new List <IEntryModel>();

            foreach (var directory in _directories)
            {
                result.AddRange(await listAsync(directory, pm.CancellationToken, filter, _lookupFilter, refresh));
            }

            return(_nextCommandFunc(result.ToArray()));
        }
Beispiel #2
0
        protected override IScriptCommand executeInner(ParameterDic pm, ItemsControl ic, RoutedEventArgs evnt, IUIInput input, IList <IUIInputProcessor> inpProcs)
        {
            var scp            = ControlUtils.GetScrollContentPresenter(ic);
            var selectedIdList = pm.ContainsKey("SelectedIdList") ? pm["SelectedIdList"] as List <int> : null;
            var selectedList   = pm.ContainsKey("SelectedList") ? pm["SelectedList"] as List <object> : null;

            if (pm.ContainsKey("UnselectCommand"))
            {
                ICommand unselectCommand = pm["UnselectCommand"] as ICommand;
                if (unselectCommand != null && unselectCommand.CanExecute(ic))
                {
                    unselectCommand.Execute(ic);
                }
            }


            bool isISelectable = ic.Items.Count > 0 && ic.Items[0] is ISelectable;


            //Action<int, object, ListBoxItem> updateSelected = null;
            Func <int, FrameworkElement, bool> returnSelected = (idx, item) => false;

            if (selectedIdList != null)
            {
                returnSelected = (idx, item) => selectedIdList.Contains(idx);
            }
            else if (selectedList != null)
            {
                returnSelected = (idx, item) => selectedList.Contains(item);
            }

            logger.Debug(String.Format("Selecting {0} items", selectedIdList != null ? selectedIdList.Count() :
                                       selectedList.Count()));

            //updateSelected = (idx, vm, item) => _processor.Select(
            //    ExtensionMethods.ToISelectable(vm, item), returnSelected(idx, item));

            for (int i = 0; i < ic.Items.Count; i++)
            {
                FrameworkElement ele = ic.ItemContainerGenerator.ContainerFromIndex(i) as FrameworkElement;

                ISelectable item = ic.Items[i] as ISelectable;
                item.IsSelected  = returnSelected(i, ele);
                item.IsSelecting = false;
                //if (ele != null)
                //    AttachedProperties.SetIsSelecting(ele, false);
            }
            return(NextCommand);
        }
        public override async Task <IScriptCommand> ExecuteAsync(ParameterDic pm)
        {
            try
            {
                var srcProfile  = _srcModel.Profile as IDiskProfile;
                var destProfile = _destDirModel.Profile as IDiskProfile;
                var progress    = pm.ContainsKey("Progress") ? pm["Progress"] as IProgress <TransferProgress> : NullTransferProgress.Instance;

                var    destMapping  = (_destDirModel.Profile as IDiskProfile).DiskIO.Mapper[_destDirModel];
                var    srcMapping   = (_srcModel.Profile as IDiskProfile).DiskIO.Mapper[_srcModel];
                string destName     = PathFE.GetFileName(srcMapping.IOPath);
                string destFullName = destProfile.Path.Combine(_destDirModel.FullPath, destName); //PathFE.Combine(destMapping.IOPath, destName);


                if (_srcModel.IsDirectory)
                {
                    Func <IEntryModel, bool> filter       = em => !em.IsDirectory || (em is SzsRootModel);
                    Func <IEntryModel, bool> lookupFilter = em => em.IsDirectory && !(em is SzsRootModel);
                    return(WPFScriptCommands.List(_srcModel, filter, lookupFilter, true, ems =>
                                                  new SimpleScriptCommandAsync("BatchTransfer", pd => transferAsync(pm, ems, progress,
                                                                                                                    new NotifyChangedCommand(_destDirModel.Profile, destFullName,
                                                                                                                                             _srcModel.Profile, _srcModel.FullPath, Defines.ChangeType.Changed)))));
                }
                else
                {
                    return(IOScriptCommands.DiskTransfer(_srcModel, _destDirModel, _removeOriginal));
                }

                return(ResultCommand.NoError);
            }
            catch (Exception ex)
            {
                return(ResultCommand.Error(ex));
            }
        }
        public static async Task Test_DiskCreatePath()
        {
            //Prepare
            DiskCreatePath cmd         = new DiskCreatePath();
            var            mockProfile = new Mock <IDiskProfile>();
            var            mockModel   = new Mock <IEntryModel>();

            mockProfile.Setup(p => p.Path).Returns(PathHelper.Disk);
            mockProfile.Setup(p => p.DiskIO.CreateAsync(dummyPath, false, It.IsAny <System.Threading.CancellationToken>()))
            .Returns(() => Task.FromResult(mockModel.Object))
            .Verifiable();

            ParameterDic pd = new ParameterDic()
            {
                { cmd.ProfileKey, mockProfile.Object },
                { cmd.PathKey, dummyPath }
            };

            //Action
            await cmd.ExecuteAsync(pd);

            //Assert
            Assert.IsTrue(pd.ContainsKey(cmd.DestinationKey));
            Assert.AreEqual(mockModel.Object, pd[cmd.DestinationKey]);
            mockProfile.Verify();
        }
        protected override IScriptCommand executeInner(ParameterDic pm, ItemsControl ic, RoutedEventArgs evnt, IUIInput input, IList <IUIInputProcessor> inpProcs)
        {
            if (!_update)
            {
                var selectedIdList = pm.ContainsKey("SelectedIdList") ? pm["SelectedIdList"] as List <int>
                    : new List <int>();

                logger.Debug(String.Format("Highlighting {0} items", selectedIdList.Count()));

                for (int i = 0; i < ic.Items.Count; i++)
                {
                    DependencyObject item = ic.ItemContainerGenerator.ContainerFromIndex(i);
                    if (item != null)
                    {
                        bool isSelecting = selectedIdList.Contains(i);
                        //UIEventHubProperties.SetIsSelecting(item, isSelecting);
                        var selectable = (item as FrameworkElement).DataContext as ISelectable;
                        if (selectable != null)
                        {
                            selectable.IsSelecting = isSelecting;
                        }
                    }
                }
            }
            else
            {
                List <object> unselectedList   = pm["UnselectedList"] as List <object>;
                List <int>    unselectedIdList = pm["UnselectedIdList"] as List <int>;

                List <object> selectedList   = pm["SelectedList"] as List <object>;
                List <int>    selectedIdList = pm["SelectedIdList"] as List <int>;

                logger.Debug(String.Format("Highlighting {0} items", selectedIdList.Count()));
                logger.Debug(String.Format("De-highlighting {0} items", unselectedIdList.Count()));

                for (int i = 0; i < ic.Items.Count; i++)
                {
                    DependencyObject ele  = ic.ItemContainerGenerator.ContainerFromIndex(i);
                    ISelectable      item = ic.Items[i] as ISelectable;


                    if (ele != null)
                    {
                        bool isSelecting = UIEventHubProperties.GetIsSelecting(ele);
                        if (isSelecting && unselectedList.Contains(ele))
                        {
                            item.IsSelecting = false;
                        }
                        //AttachedProperties.SetIsSelecting(item, false);
                        else if (!isSelecting && selectedList.Contains(ele))
                        {
                            item.IsSelecting = true;
                        }
                        //AttachedProperties.SetIsSelecting(ele, true);
                    }
                }
            }

            return(NextCommand);
        }
Beispiel #6
0
        public override async Task <IScriptCommand> ExecuteAsync(ParameterDic pm)
        {
            var    pdv = pm.GetValue <IProgress <TransferProgress> >("{Progress}", NullTransferProgress.Instance);
            string url = pm.GetValue <string>(UrlKey);

            if (url == null)
            {
                return(ResultCommand.Error(new ArgumentException("Unspecified Url.")));
            }

            try
            {
                using (var httpClient =
                           pm.ContainsKey(HttpClientKey) && pm[HttpClientKey] is Func <HttpClient>?((Func <HttpClient>)pm[HttpClientKey])() :
                               new HttpClient())
                {
                    var response = await httpClient.GetAsync(url, HttpCompletionOption.ResponseHeadersRead, pm.CancellationToken);

                    if (!response.IsSuccessStatusCode)
                    {
                        throw new WebException(String.Format("{0} when downloading {1}", response.StatusCode, url));
                    }

                    MemoryStream destStream = new MemoryStream();
                    logger.Info(String.Format("{0} = Stream of {1}", DestinationKey, url));
                    using (Stream srcStream = await response.Content.ReadAsStreamAsync())
                    {
                        pdv.Report(TransferProgress.From(url));
                        byte[] buffer         = new byte[1024];
                        ulong  totalBytesRead = 0;
                        ulong  totalBytes     = 0;
                        try { totalBytes = (ulong)srcStream.Length; }
                        catch (NotSupportedException) { }

                        int byteRead = await srcStream.ReadAsync(buffer, 0, buffer.Length, pm.CancellationToken);

                        while (byteRead > 0)
                        {
                            await destStream.WriteAsync(buffer, 0, byteRead, pm.CancellationToken);

                            totalBytesRead = totalBytesRead + (uint)byteRead;
                            short percentCompleted = (short)((float)totalBytesRead / (float)totalBytes * 100.0f);
                            pdv.Report(TransferProgress.UpdateCurrentProgress(percentCompleted));

                            byteRead = await srcStream.ReadAsync(buffer, 0, buffer.Length, pm.CancellationToken);
                        }
                        await destStream.FlushAsync();
                    }

                    pm.SetValue(DestinationKey, destStream.ToByteArray());
                    return(NextCommand);
                }
            }
            catch (Exception ex)
            {
                return(ResultCommand.Error(ex));
            }
        }
 public ProgressDialogViewModel(ParameterDic pd, CancellationTokenSource cts = null)
 {
     _pd = pd;
     if (_pd.ContainsKey("ProgressHeader"))
     {
         DisplayName = Header = _pd["ProgressHeader"] as string;
     }
     _cts           = cts ?? new CancellationTokenSource();
     _timeRemain    = new EstimateTimeRemainViewModel();
     _cancelCommand = new RelayCommand((o) => _cts.Cancel());
     _closeCommand  = new RelayCommand((o) => TryClose());
 }
        public static async Task Test_OpenStream()
        {
            //Prepare
            var            streamCmd  = new Mock <ScriptCommandBase>();
            var            thenCmd    = new Mock <ScriptCommandBase>();
            DiskOpenStream openStream = new DiskOpenStream()
            {
                NextCommand = streamCmd.Object, ThenCommand = thenCmd.Object
            };
            var mockProfile = new Mock <IDiskProfile>();
            var mockModel   = new Mock <IEntryModel>();

            mockModel.Setup(em => em.Profile).Returns(() => mockProfile.Object);
            mockProfile.Setup(p => p.DiskIO.OpenStreamAsync(mockModel.Object, openStream.Access,
                                                            It.IsAny <CancellationToken>())).Returns(Task.FromResult <Stream>(new MemoryStream())).Verifiable();

            ParameterDic pd = new ParameterDic()
            {
                { openStream.EntryKey, mockModel.Object },
            };

            streamCmd.Setup(cmd => cmd.CanExecute(It.IsAny <ParameterDic>())).Returns(true);
            streamCmd.Setup(cmd => cmd.ExecuteAsync(It.IsAny <ParameterDic>()))
            .Returns <ParameterDic>(pm => Task.Run(() =>
            {
                Assert.IsTrue(pm.ContainsKey(openStream.StreamKey));
                Assert.IsTrue(pm[openStream.StreamKey] is MemoryStream);
                return((IScriptCommand)ResultCommand.NoError);
            })).Verifiable();

            //Action
            IScriptCommand retCmd = await openStream.ExecuteAsync(pd);

            //Assert
            mockProfile.Verify();
            streamCmd.Verify();
            Assert.IsFalse(pd.ContainsKey(openStream.StreamKey));
            Assert.AreEqual(thenCmd.Object, retCmd);
        }
        public static async Task Test_ParsePath()
        {
            //Prepare
            ParsePath cmd         = new ParsePath();
            var       mockProfile = new Mock <IProfile>();
            var       mockModel   = new Mock <IEntryModel>();

            mockProfile.Setup(p => p.ParseAsync(dummyPath)).Returns(Task.FromResult <IEntryModel>(mockModel.Object));

            ParameterDic pd = new ParameterDic()
            {
                { cmd.ProfileKey, mockProfile.Object },
                { cmd.PathKey, dummyPath }
            };

            //Action
            await cmd.ExecuteAsync(pd);

            //Assert
            Assert.IsTrue(pd.ContainsKey(cmd.DestinationKey));
            Assert.AreEqual(mockModel.Object, pd[cmd.DestinationKey]);
        }
        public override async Task <IScriptCommand> ExecuteAsync(ParameterDic pm)
        {
            CancellationToken ct = pm.CancellationToken;
            var progress         = pm.ContainsKey("Progress") ? pm["Progress"] as IProgress <TransferProgress> : NullTransferProgress.Instance;
            var _srcModels       = _srcModelFunc(pm);

            if (_srcModels != null)
            {
                progress.Report(TransferProgress.IncrementTotalEntries(_srcModels.Count()));
                Task[] tasks = _srcModels.Select(m =>
                                                 (m.Profile as IDiskProfile).DiskIO.DeleteAsync(m, ct)
                                                 .ContinueWith(
                                                     tsk => progress.Report(TransferProgress.IncrementProcessedEntries()))
                                                 ).ToArray();
                await Task.WhenAll(tasks);

                return(new RunInSequenceScriptCommand(
                           _srcModels.Select(m => new NotifyChangedCommand(m.Profile, m.FullPath, ChangeType.Deleted))
                           .ToArray()));
            }

            return(ResultCommand.NoError);
        }
        public override async Task <IScriptCommand> ExecuteAsync(ParameterDic pm)
        {
            try
            {
                var srcProfile  = _srcModel.Profile as IDiskProfile;
                var destProfile = _destDirModel.Profile as IDiskProfile;
                var progress    = pm.ContainsKey("Progress") ? pm["Progress"] as IProgress <TransferProgress> : NullTransferProgress.Instance;

                var    destMapping  = (_destDirModel.Profile as IDiskProfile).DiskIO.Mapper[_destDirModel];
                var    srcMapping   = (_srcModel.Profile as IDiskProfile).DiskIO.Mapper[_srcModel];
                string destName     = PathFE.GetFileName(srcMapping.IOPath);
                string destFullName = destProfile.Path.Combine(_destDirModel.FullPath, destName); //PathFE.Combine(destMapping.IOPath, destName);


                if (!srcMapping.IsVirtual && !destMapping.IsVirtual && _removeOriginal)
                {
                    //Disk based transfer
                    progress.Report(TransferProgress.From(_srcModel.FullPath, destFullName));
                    if (_srcModel.IsDirectory)
                    {
                        if (Directory.Exists(destFullName))
                        {
                            Directory.Delete(destFullName, true);
                        }
                        Directory.Move(srcMapping.IOPath, destFullName); //Move directly.
                        progress.Report(TransferProgress.IncrementProcessedEntries());
                    }
                    else
                    {
                        if (File.Exists(destFullName))
                        {
                            File.Delete(destFullName);
                        }
                        File.Move(srcMapping.IOPath, destFullName);
                    }
                    progress.Report(TransferProgress.IncrementProcessedEntries());
                    return(new NotifyChangedCommand(_destDirModel.Profile, destFullName, _srcModel.Profile,
                                                    _srcModel.FullPath, ChangeType.Moved));
                }
                else
                {
                    if (_srcModel.IsDirectory)
                    {
                        return(new CopyDirectoryTransferCommand(_srcModel, _destDirModel, _removeOriginal, progress));
                    }
                    else
                    {
                        return(new StreamFileTransferCommand(_srcModel, _destDirModel, _removeOriginal, progress));
                    }
                }



                //switch (_transferMode)
                //{
                //    case DragDropEffects.Move:
                //
                //

                //    case DragDropEffects.Copy:
                //        Directory.CreateDirectory(destFullName);
                //        _destDirModel.Profile.Events.Publish(new EntryChangedEvent(destFullName, ChangeType.Created));

                //        var destModel = (await _destDirModel.Profile.ListAsync(_destDirModel, em =>
                //                em.FullPath.Equals(destFullName,
                //                StringComparison.CurrentCultureIgnoreCase))).FirstOrDefault();
                //        var srcSubModels = (await _srcModel.Profile.ListAsync(_srcModel)).ToList();

                //        var resultCommands = srcSubModels.Select(m =>
                //            (IScriptCommand)new FileTransferScriptCommand(m, destModel, _transferMode)).ToList();
                //        resultCommands.Insert(0, new NotifyChangedCommand(_destDirModel.Profile, destFullName, ChangeType.Created));

                //        return new RunInSequenceScriptCommand(resultCommands.ToArray());
                //    default:
                //        throw new NotImplementedException();
                //}

                //}
                //else
                //{

                //}

                return(ResultCommand.NoError);
            }
            catch (Exception ex)
            {
                return(ResultCommand.Error(ex));
            }
        }
Beispiel #12
0
        private async Task <IScriptCommand> transferSystemIOAsync(ParameterDic pm, IEntryModel[] srcEntries, IEntryModel destEntry, string destinationKey)
        {
            return(await Task.Run <IScriptCommand>(async() =>
            {
                var progress = pm.ContainsKey("Progress") ? pm["Progress"] as IProgress <TransferProgress> : NullTransferProgress.Instance;

                var srcProfile = srcEntries.First().Profile as IDiskProfile;
                var destProfile = destEntry.Profile as IDiskProfile;

                var srcMapper = srcProfile.DiskIO.Mapper;
                var destMapping = destProfile.DiskIO.Mapper[destEntry];


                List <string> createdPath = new List <string>();
                List <string> changedPath = new List <string>();

                progress.Report(TransferProgress.IncrementTotalEntries(srcEntries.Count()));
                foreach (var srcEntry in srcEntries)
                {
                    var srcMapping = srcMapper[srcEntry];
                    string destName = PathFE.GetFileName(srcMapping.IOPath);
                    string destFullName = destProfile.Path.Combine(destEntry.FullPath, destName);

                    progress.Report(TransferProgress.From(srcEntry.FullPath, destEntry.FullPath));

                    if (srcEntry.IsDirectory)
                    {
                        if (Directory.Exists(destFullName))
                        {
                            changedPath.Add(destFullName);
                            //Directory.Delete(destFullName, true);
                        }
                        else
                        {
                            createdPath.Add(destFullName);
                        }

                        Directory.Move(srcMapping.IOPath, destFullName);     //Move directly.
                        progress.Report(TransferProgress.IncrementProcessedEntries());
                    }
                    else
                    {
                        if (File.Exists(destFullName))
                        {
                            changedPath.Add(destFullName);
                            File.Delete(destFullName);
                        }
                        else
                        {
                            createdPath.Add(destFullName);
                        }
                        File.Move(srcMapping.IOPath, destFullName);
                    }
                    progress.Report(TransferProgress.IncrementProcessedEntries());
                }

                logger.Info(String.Format("{0} {1} -> {2} using System.IO",
                                          RemoveOriginal ? "Move" : "Copy", srcEntries.GetDescription(), destEntry.Name));


                return
                await GetAssignDestinationCommandAsync(pm, srcEntries, destEntry, destinationKey,
                                                       ScriptCommands.RunParallel(NextCommand,

                                                                                  CoreScriptCommands.NotifyEntryChangedPath(ChangeType.Created, destEntry.Profile, createdPath.ToArray()),
                                                                                  CoreScriptCommands.NotifyEntryChangedPath(ChangeType.Changed, destEntry.Profile, changedPath.ToArray())
                                                                                  ));
            }));
        }