public void ConsoleProgressExample()
        {
            var firstProgress  = new ConsoleProgress(title: "ConsoleProgress", length: 50);
            var secondProgress = new SimpleProgress(title: "SimpleProgress", length: 50);

            var flow = new ConsoleFlow
                       (
                firstProgress,
                secondProgress
                       );

            flow.Display();

            while (true)
            {
                var key = Console.ReadKey(true).Key;
                if (key == ConsoleKey.Escape)
                {
                    break;
                }
                else if (key == ConsoleKey.UpArrow)
                {
                    firstProgress.Value = Math.Clamp(firstProgress.Value + 0.1f, 0f, 1f);
                }
                else if (key == ConsoleKey.DownArrow)
                {
                    secondProgress.Value = Math.Clamp(secondProgress.Value + 0.1f, 0f, 1f);
                }
            }
        }
        private async Task ExecuteInternal(TaskExecutionOptions options)
        {
            // Cancel the current execution, if any
            if (CurrentCancellationTokenSource != null)
            {
                throw new InvalidOperationException("Cannot execute a Task that is already running");
            }

            var progress = new SimpleProgress <double>();

            CurrentCancellationTokenSource = new CancellationTokenSource();

            Logger.Info("Executing {0}", Name);

            ((TaskManager)TaskManager).OnTaskExecuting(this);

            progress.ProgressChanged += progress_ProgressChanged;

            TaskCompletionStatus status;

            CurrentExecutionStartTime = DateTime.UtcNow;

            Exception failureException = null;

            try
            {
                if (options != null && options.MaxRuntimeMs.HasValue)
                {
                    CurrentCancellationTokenSource.CancelAfter(options.MaxRuntimeMs.Value);
                }

                var localTask = ScheduledTask.Execute(CurrentCancellationTokenSource.Token, progress);

                await localTask.ConfigureAwait(false);

                status = TaskCompletionStatus.Completed;
            }
            catch (OperationCanceledException)
            {
                status = TaskCompletionStatus.Cancelled;
            }
            catch (Exception ex)
            {
                Logger.ErrorException("Error", ex);

                failureException = ex;

                status = TaskCompletionStatus.Failed;
            }

            var startTime = CurrentExecutionStartTime;
            var endTime   = DateTime.UtcNow;

            progress.ProgressChanged -= progress_ProgressChanged;
            CurrentCancellationTokenSource.Dispose();
            CurrentCancellationTokenSource = null;
            CurrentProgress = null;

            OnTaskCompleted(startTime, endTime, status, failureException);
        }
        public void SimpleProgressExample()
        {
            var firstProgress  = new SimpleProgress(title: "First", length: 100);
            var secondProgress = new SimpleProgress(title: "Second", length: 100);

            var flow = new ConsoleFlow
                       (
                firstProgress,
                secondProgress,
                new ConsoleText("Press [f] to increment First"),
                new ConsoleText("Press [s] to increment Second")
                       );

            flow.Display();

            while (true)
            {
                var key = Console.ReadKey(true).Key;
                if (key == ConsoleKey.Escape)
                {
                    break;
                }
                else if (key == ConsoleKey.F)
                {
                    firstProgress.Value = Math.Clamp(firstProgress.Value + 0.1f, 0f, 1f);
                }
                else if (key == ConsoleKey.S)
                {
                    secondProgress.Value = Math.Clamp(secondProgress.Value + 0.1f, 0f, 1f);
                }
            }
        }
示例#4
0
        public void Run(KexplorerFtpNode xfolder, string[] xfiles)
        {
            if (xfiles == null)
            {
                MessageBox.Show("FTP Delete only supported for individual files", "Kexplorer");
                return;
            }

            folder = xfolder;
            files  = xfiles;

            this.workerThread = new Thread(new ThreadStart(this.StartFtpDeleteInThread));
            this.workerThread.Start();
            this.cancelled = false;


            progress = SimpleProgress.StartProgress(this.FtpCancelled
                                                    , "Kexplorer FTP Delete"
                                                    , "Starting...");



            while (!this.cancelled && this.workerThread.ThreadState == ThreadState.Running)
            {
                Thread.Sleep(250);
            }

            this.ScriptHelper.RefreshFolder(folder, false);
        }
示例#5
0
        public void Utils_CompleteIfNotNull_Simple_NotCancelled()
        {
            var progress = new SimpleProgress();

            Utils.CompleteIfNotNull(progress, CancellationToken.None);

            Assert.AreEqual(100, progress.Value);
        }
示例#6
0
        public void Utils_CompleteIfNotNull_Simple()
        {
            var progress = new SimpleProgress();

            Utils.CompleteIfNotNull(progress);

            Assert.AreEqual(100, progress.Value);
        }
示例#7
0
        public void Utils_CompleteIfNotNull_Simple_Cancelled()
        {
            var progress = new SimpleProgress();

            var cts = new CancellationTokenSource();

            cts.Cancel();

            Utils.CompleteIfNotNull(progress, cts.Token);

            Assert.AreEqual(0, progress.Value);
        }
示例#8
0
        /// <summary>
        /// Returns the task to be executed
        /// </summary>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <param name="progress">The progress.</param>
        /// <returns>Task.</returns>
        public async Task Execute(CancellationToken cancellationToken, IProgress <double> progress)
        {
            EventHandler <double> innerProgressHandler = (sender, e) => progress.Report(e * .1);

            // Create a progress object for the update check
            var innerProgress = new SimpleProgress <double>();

            innerProgress.ProgressChanged += innerProgressHandler;

            var updateInfo = await _appHost.CheckForApplicationUpdate(cancellationToken, innerProgress).ConfigureAwait(false);

            // Release the event handler
            innerProgress.ProgressChanged -= innerProgressHandler;

            progress.Report(10);

            if (!updateInfo.IsUpdateAvailable)
            {
                Logger.Debug("No application update available.");
                progress.Report(100);
                return;
            }

            cancellationToken.ThrowIfCancellationRequested();

            if (!_appHost.CanSelfUpdate)
            {
                return;
            }

            if (ConfigurationManager.CommonConfiguration.EnableAutoUpdate)
            {
                Logger.Info("Update Revision {0} available.  Updating...", updateInfo.AvailableVersion);

                innerProgressHandler = (sender, e) => progress.Report(e * .9 + .1);

                innerProgress = new SimpleProgress <double>();
                innerProgress.ProgressChanged += innerProgressHandler;

                await _appHost.UpdateApplication(updateInfo.Package, cancellationToken, innerProgress).ConfigureAwait(false);

                // Release the event handler
                innerProgress.ProgressChanged -= innerProgressHandler;
            }
            else
            {
                Logger.Info("A new version of " + _appHost.Name + " is available.");
            }

            progress.Report(100);
        }
示例#9
0
        private void UploadFtpFiles(KexplorerFtpNode destNode, KExplorerNode sourceNode, FileInfo[] files)
        {
            ftpDestNode       = destNode;
            folderSourceNode  = sourceNode;
            sourceFiles       = files;
            this.workerThread = new Thread(new ThreadStart(this.StartFtpUploadInThread));
            this.workerThread.Start();
            this.cancelled = false;


            progress = SimpleProgress.StartProgress(this.FtpCancelled
                                                    , "Kexplorer FTP Upload"
                                                    , "Starting...");



            while (!this.cancelled && this.workerThread.ThreadState == ThreadState.Running)
            {
                Thread.Sleep(250);
            }
        }
示例#10
0
        private void DownloadFtpFiles(KExplorerNode xdestNode
                                      , KexplorerFtpNode xsourceNode
                                      , string[] xfiles
                                      )
        {
            destNode          = xdestNode;
            sourceNode        = xsourceNode;
            files             = xfiles;
            this.workerThread = new Thread(new ThreadStart(this.StartFtpDownLoadInThread));
            this.workerThread.Start();
            this.cancelled = false;


            progress = SimpleProgress.StartProgress(this.FtpCancelled
                                                    , "Kexplorer FTP Download"
                                                    , "Starting...");



            while (!this.cancelled && this.workerThread.ThreadState == ThreadState.Running)
            {
                Thread.Sleep(250);
            }
        }
示例#11
0
 // Start is called before the first frame update
 void Start()
 {
     m_lineRenderer    = GetComponent <LineRenderer>();
     m_progressHandler = new SimpleProgress();
 }
        protected override ImporterConverterAbstract GetNext(IEventListener iel, CancellationToken iCancellationToken)
        {
            int CDnumber = _IMusicConverter.GetDriverNumber(_Driver);

            if (!CDHelper.CanOpenCDDoor(CDnumber))
            {
                //ca pue un lecteur de cd qu'on ne peut pas ouvrir
                //je ne fair rien dans ce cas (cle 3G?)
                Trace.WriteLine("Problem due to device detected as CD driver");
                return null;
            }

            using (CDLocker cdl = CDLocker.GetLocker(CDnumber))
            {
                if (!cdl.IsOK)
                {
                    iel.Report(new NoCDInsertedArgs());
                    Trace.WriteLine("CD driver not ready");
                    return null;
                }

                if (!CDHelper.IsCDAudio(CDnumber))
                {
                    iel.Report(new NoCDAudioInsertedArgs());
                    System.Diagnostics.Trace.WriteLine("CD not audio");
                    return null;
                }

                iel.Report(new CDIndentifyingProgessEventArgs());

                CDInfoHandler cih = new CDInfoHandler(CDnumber);

                IEnumerable<MatchAlbum> albums = Context.FindFromHashes(cih.IDs.RawHash);
                if (albums.Any())
                {
                    OtherAlbumsConfirmationNeededEventArgs error = new OtherAlbumsConfirmationNeededEventArgs(albums);
                    iel.Report(error);

                    System.Diagnostics.Trace.WriteLine("CD potentially aleady imported");

                    if (!error.Continue)
                    {
                        System.Diagnostics.Trace.WriteLine("stopping import");
                        return null;
                    }
                }

                IWebQuery webq = Context.Session.WebQueryFactory.FromCDInfo(cih);
                webq.NeedCoverArt = false;
                IInternetFinder ifn = Context.Session.GetInternetFinder(webq);
                ifn.Compute(iCancellationToken,null);

                AmbigueousCDInformationArgs acfi = new AmbigueousCDInformationArgs(ifn.Result.Found, AlbumDescriptor.CreateBasicFromCD(cih, Context));

                iel.Report(acfi);

                if (!acfi.Continue)
                    return null;

                AlbumDescriptor ifad = acfi.SelectedInfo as AlbumDescriptor;

                iel.Report(new CDImportingProgessEventArgs(ifad.Name));

                ifad.MergeIDsFromCDInfos(cih);

                IMusicfilesConverter IMC = _IMusicConverter.GetCDMusicConverter(ifad, Context.Folders.File, false, CDnumber);

                if (IMC == null)
                {
                    TimeSpan ts = TimeSpan.FromSeconds(7);
                    int repeat = 0;
                    int Maxtent = 3;
                    while ((IMC == null) && (repeat < Maxtent))
                    {
                        bool Forcebute = repeat == (Maxtent - 1);
                        Thread.Sleep(ts);
                        IMC = _IMusicConverter.GetCDMusicConverter(ifad, Context.Folders.File, Forcebute, CDnumber);
                        repeat++;
                        Trace.WriteLine(string.Format("Trial {0} to get CDMusicConverter, Forcebute {1} success {2}", repeat, Forcebute, (IMC == null)));
                        ts = TimeSpan.FromSeconds(ts.TotalSeconds * 3);
                    }

                    if (IMC == null)
                    {
                        System.Diagnostics.Trace.WriteLine("no importer returned");
                        iel.Report(new CDInUse());
                        return null;
                    }
                }

                Action ParrallelCoverLoading = null;

                IList<WebMatch<IFullAlbumDescriptor>> resultwithimage = null;

                if (acfi.PreprocessedWebInfo != null)
                {
                    resultwithimage = acfi.PreprocessedWebInfo;
                    ParrallelCoverLoading = () => acfi.PreprocessedWebInfo.Apply(wr => wr.FindItem.LoadImages());
                }
                else
                {
                    IWebQuery webqim = new WebQueryFactory(Context.Session).FromAlbumDescriptor(ifad);
                    webqim.NeedCoverArt = true;

                    IInternetFinder ifni = Context.Session.GetInternetFinder(webqim);

                    resultwithimage = new List<WebMatch<IFullAlbumDescriptor>>();

                    if (ifad.HasImage())
                    {
                        resultwithimage.Add(new WebMatch<IFullAlbumDescriptor>(ifad, MatchPrecision.Suspition, acfi.Provider));
                    }

                    ParrallelCoverLoading = () => { ifad.LoadImages(); ifni.Compute(iCancellationToken,null); resultwithimage.AddCollection(ifni.Result.Found); };
                }

                int TN = ifad.TrackDescriptors.Count;

                IAsyncResult ias = ParrallelCoverLoading.BeginInvoke(null, null);

                bool feedbacknegative = false;

                IProgress<TrackConverted> progress = new SimpleProgress<TrackConverted>
                ( (e) =>
                    {
                        iel.Report(new ConvertProgessEventArgs(ifad.Name, (int)e.Track.TrackNumber, TN));
                        if (e.OK)
                        {
                            _TDs.Add(e.Track);
                        }
                        else
                        {
                            feedbacknegative = true;
                            iel.OnFactorisableError<UnableToConvertFile>(e.Track.Name);
                        }
                    }
                );

                bool convres = IMC.ConvertTomp3(progress, iCancellationToken);

                if ((convres == false) && (_TDs.Count == 0) && (feedbacknegative == false))
                {
                    iel.Report(new CDUnknownErrorArgs());
                    return null;
                }

                if (iCancellationToken.IsCancellationRequested)
                {
                    return null;
                }

                if (!ias.IsCompleted)
                {
                    iel.Report(new CDImportingProgessAdditionalCoverInfoEventArgs(ifad));
                }

                if (_OpenCDDoorOnComplete)
                    CDHelper.OpenCDDoor();

                bool okfound = ias.AsyncWaitHandle.WaitOne(TimeSpan.FromMinutes(3), false);
                //j'attends pas plus de 1 minute apres avoir grave le cd pour trouver
                //les pochettes sur internet
 
                Trace.WriteLine(string.Format("CD import cover from internet time out result (false:timedout): {0}!", okfound));

                if (resultwithimage != null)
                {             
                    int tracknumber = ifad.RawTrackDescriptors.Count;           
                    var images = resultwithimage.Where(wr => ((wr.FindItem.MatchTrackNumberOnDisk(tracknumber)) && (wr.FindItem.Images != null) && (wr.FindItem.Images.Count > 0))).ToList();

                    if (images.Count > 0)
                    {
                        Trace.WriteLine(string.Format("{0} Image(s) found!!", images.Count));

                        CDCoverInformationArgs cdfi = new CDCoverInformationArgs(images, ifad);
                        iel.Report(cdfi);
                    }
                    else
                    {
                        Trace.WriteLine(string.Format("Information found but no matching image found for CD:{0} !",ifad));
                    }
                }
                else
                {
                    Trace.WriteLine("No image found for CD!");
                }

                Trace.WriteLine("Import CD OK");

                return new MusicWithMetadaImporter(_TDs.ToArray(), new List<string>(), new ICDInfosHelperAdpt(ifad));
            }
        }
        protected override ImporterConverterAbstract GetNext(IEventListener iel, CancellationToken iCancellationToken)
        {
            if (_Done)
                throw new InvalidOperationException("reentrance");

            _Done = true;

            if (!Analyse())
            {
                //Cue does not match..let's do the easy way.
                return new MusicConverterImporter(_IMusicConverter, _MusicandCueFile.Select(i => i.Item1).ToList(), _ListImage, _ClueName);
            }

            foreach (Tuple<string, AlbumDescriptor> MAC in _MusicandCueFile)
            {
                _MusicConverted.Add(MAC.Item1);
                _MusicConverted.Add(MAC.Item2.CUESheetFileName);
            }

            List<TrackConverted> tracks = new List<TrackConverted>();

            SpaceChecker sc = new SpaceChecker(Context.ConvertManager.PathFromOutput(_MusicandCueFile[0].Item1, _ClueName),
                from mac in _MusicandCueFile select mac.Item1);

            if (!sc.OK)
            {
                iel.Report(new NotEnougthSpace(sc.ToString()));
                return null;
            }

            if (iCancellationToken.IsCancellationRequested)
            {
                return null;
            }

            foreach (Tuple<string, AlbumDescriptor> MAC in _MusicandCueFile)
            {
                string MusicPath = MAC.Item1;
                AlbumDescriptor Cs = MAC.Item2;

                int Current = 1;
                iel.Report(new ConvertProgessEventArgs(_ClueName.DisplayName, Current, Cs.RawTrackDescriptors.Count));

                bool OK = false;

                using (IMusicfilesConverter imcc = _IMusicConverter.GetMusicConverter(MusicPath, Cs.RawTrackDescriptors, Context.ConvertManager.PathFromOutput(MusicPath, _ClueName), Context.Folders.Temp))
                {

                    IProgress<TrackConverted> progress = new SimpleProgress<TrackConverted>
                    ( (e) =>
                    {
                        iel.Report(new ConvertProgessEventArgs(_ClueName.DisplayName, ++Current, Cs.RawTrackDescriptors.Count));
                        if (e.OK)
                        {
                            tracks.Add(e);
                            AddConvertedFiles(MusicPath, e.Track.Path);
                        }
                        else
                            iel.OnFactorisableError<UnableToConvertFile>(e.Track.Name);
                    });

                    OK = imcc.ConvertTomp3(progress, iCancellationToken);
                }
            }

            if (iCancellationToken.IsCancellationRequested)
            {
                return null;
            }

            return new MusicWithMetadaImporter((from t in tracks select t.Track).ToArray<ITrackDescriptor>(), _ListImage, _ClueName); ;
        }