Exemple #1
0
    void Update()
    {
        switch (progressState)
        {
        case ProgressState.OnProgressEnter:
            SetValues();
            progressState = ProgressState.OnProgress;
            break;

        case ProgressState.OnProgress:
            if (PlayerTransform.position.z <= _distance && PlayerTransform.position.z <= FinishTransform.position.z)
            {
                float distance = 1 - (getDistance() / _distance);
                progressbarSlider.value = distance;
            }

            break;

        case ProgressState.OnProgressExit:
            break;
        }

        currentLevelText.text = Convert.ToString(LevelController.CurrentLevelIndexStatic + 1);
        nextLevelText.text    = Convert.ToString(LevelController.CurrentLevelIndexStatic + 2);
    }
Exemple #2
0
        private void CopyDirectory(DirectoryInfo sourceDir, string destination, ProgressState progressState)
        {
            string        path    = Path.Combine(destination, sourceDir.Name);
            DirectoryInfo destDir = new DirectoryInfo(path);

            if (Directory.Exists(path))
            {
                var result = MessageBox.Show("Директория с таким именем уже существует. Выполнить слияние файлов и папок?", "", MessageBoxButtons.YesNo);
                if (result == DialogResult.No)
                {
                    _cts.Cancel();
                    _cts.Token.ThrowIfCancellationRequested();
                }
            }
            else
            {
                destDir.Create();
            }
            foreach (DirectoryInfo dir in sourceDir.GetDirectories())
            {
                CopyDirectory(dir, destDir.FullName, progressState);
            }

            foreach (FileInfo file in sourceDir.GetFiles())
            {
                //file.CopyTo(Path.Combine(destDir.FullName,Path.GetFileName(file.Name)),true);
                CopyFile(file.FullName, Path.Combine(destDir.FullName, Path.GetFileName(file.Name)), progressState);
            }
        }
Exemple #3
0
        private bool SetProgressValueCore(ulong completed, ulong total)
        {
            if (this.TaskbarList == null)
            {
                return(false);
            }

            this.currentProgressState = ProgressState.Normal;

            try
            {
                this.TaskbarList.SetProgressValue(this.MainWindowHandle, completed, total);
            }
            catch (InvalidComObjectException)
            {
                return(false);
            }
            catch (COMException ex)
            {
                // HRESULT = E_FAIL
                if (ex.ErrorCode == -2147467259)
                {
                    return(false);
                }
                else
                {
                    throw;
                }
            }

            return(true);
        }
Exemple #4
0
        private bool SetProgressStateCore(ProgressState state)
        {
            if (this.TaskbarList == null)
            {
                return(false);
            }

            this.currentProgressState = state;

            try
            {
                this.TaskbarList.SetProgressState(this.MainWindowHandle, (TBPFLAG)state);
            }
            catch (InvalidComObjectException)
            {
                return(false);
            }
            catch (COMException ex)
            {
                // HRESULT = E_FAIL
                if (ex.ErrorCode == -2147467259)
                {
                    return(false);
                }
                else
                {
                    throw;
                }
            }

            return(true);
        }
Exemple #5
0
        protected override void ShowPreviewItems(ProgressState state)
        {
            m_bv.BrowseView.Vc.MultiColumnPreview = false;
            var          itemsToChange  = ItemsToChange(false);
            BulkEditItem bei            = m_beItems[m_itemIndex];
            var          phonFeatEditor = bei.BulkEditControl as PhonologicalFeatureEditor;

            if (phonFeatEditor == null)
            {             // User chose to remove the targeted feature
                bei.BulkEditControl.FakeDoit(itemsToChange, XMLViewsDataCache.ktagAlternateValue,
                                             XMLViewsDataCache.ktagItemEnabled, state);
            }
            else
            {
                if (!phonFeatEditor.SelectedItemIsFsFeatStruc)
                {                 // User chose one of the values of the targeted feature
                    phonFeatEditor.FakeDoit(itemsToChange, XMLViewsDataCache.ktagAlternateValue,
                                            XMLViewsDataCache.ktagItemEnabled, state);
                }
                else
                {                   // User built a FsFeatStruc with the features and values to change.
                    // This means we have to find the columns for each feature in the FsFeatStruc and
                    // then show the change for that feature in that column.
                    int    selectedHvo   = phonFeatEditor.SelectedHvo;
                    string selectedLabel = phonFeatEditor.SelectedLabel;

                    string[] featureValuePairs    = phonFeatEditor.FeatureValuePairsInSelectedFeatStruc;
                    var      featureAbbreviations = featureValuePairs.Select(s =>
                    {
                        int i = s.IndexOf(":");
                        return(s.Substring(0, i));
                    });
                    m_bv.BrowseView.Vc.MultiColumnPreview = true;
                    for (int iColumn = 0; iColumn < m_beItems.Count(); iColumn++)
                    {
                        if (m_beItems[iColumn] == null)
                        {
                            continue;
                        }

                        var pfe = m_beItems[iColumn].BulkEditControl as PhonologicalFeatureEditor;
                        if (pfe != null)
                        {
                            pfe.ClearPreviousPreviews(itemsToChange, XMLViewsDataCache.ktagAlternateValueMultiBase + iColumn + 1);
                            if (featureAbbreviations.Contains(pfe.FeatDefnAbbr))
                            {
                                int tempSelectedHvo = pfe.SelectedHvo;
                                pfe.SelectedHvo = selectedHvo;
                                string tempSelectedLabel = pfe.SelectedLabel;
                                pfe.SelectedLabel = selectedLabel;
                                pfe.FakeDoit(itemsToChange, XMLViewsDataCache.ktagAlternateValueMultiBase + iColumn + 1,
                                             XMLViewsDataCache.ktagItemEnabled, state);
                                pfe.SelectedHvo   = tempSelectedHvo;
                                pfe.SelectedLabel = tempSelectedLabel;
                            }
                        }
                    }
                }
            }
        }
Exemple #6
0
        public LiftDataMapper(string liftFilePath, ProgressState progressState, ILiftReaderWriterProvider <T> ioProvider)
        {
            //set to true so that an exception in the constructor does not cause the destructor to throw
            _disposed = true;
            Guard.AgainstNull(progressState, "progressState");

            _backend       = new MemoryDataMapper <T>();
            _liftFilePath  = liftFilePath;
            _progressState = progressState;
            _ioProvider    = ioProvider;

            try
            {
                CreateEmptyLiftFileIfNeeded(liftFilePath);
                MigrateLiftIfNeeded(progressState);
                LoadAllLexEntries();
            }
            catch (Exception error)
            {
                // Dispose anything that we've created already.
                _backend.Dispose();
                throw;
            }
            //Now that the constructor has not thrown we can set this back to false
            _disposed = false;
        }
Exemple #7
0
        /// <summary>
        /// Loads the model.
        /// </summary>
        public void LoadModel()
        {
            Dataservices = DataContextObject.Services;
            var providerFactory = new DataproviderFactory(Dataservices);

            providerFactory.InitDataProvider();
            Feedback = string.Format(@"Press ""{0}"" to begin", ButtonCaption);
            Application.Current.DoEvents();
            Feedback = String.Empty;
            using (var conn = Dataservices.ConnectionFactory())
            {
                try
                {
                    using (var cmd = conn.CreateCommand())
                    {
                        cmd.CommandText = string.Format("select count(*) from [{0}]", Dataservices.Configuration.SelectFrom);
                        conn.Open();
                        var temp = (int)cmd.ExecuteScalar();
                        CurrentProgress = new ProgressState(0, temp); // TODO: based on line count and then perform multi-threading for validating and importing dataset.
                    }
                }
                finally
                {
                    conn.Close();
                }
            }
        }
 public void SetValue(int value)
 {
     //if中的代码判断是不是异步刷新UI,如果是的话,就Invoke到主线程执行else
     if (InvokeRequired)
     {
         if (Disposing || IsDisposed)
         {
             return;
         }
         DelegateValue @delegate = new DelegateValue(SetValue);
         Invoke(@delegate, value);
     }
     else
     {
         Value = value;
         if (value == 0)
         {
             Maximum       = 100;
             ChuckColor    = Color.FromArgb(0, 142, 250);
             progressState = ProgressState.Progress;
         }
         else if (value == Maximum)
         {
             progressState = ProgressState.Success;
             Visible       = false;
         }
         StateChange();
         Refresh();
     }
 }
Exemple #9
0
        private void setTaskBarState(ProgressState state)
        {
            switch (state)
            {
            case ProgressState.Indeterminate:
                TaskbarItemInfo.ProgressState = TaskbarItemProgressState.Indeterminate;
                break;

            case ProgressState.None:
                TaskbarItemInfo.ProgressState = TaskbarItemProgressState.None;
                break;

            case ProgressState.Normal:
                TaskbarItemInfo.ProgressState = TaskbarItemProgressState.Normal;
                break;

            case ProgressState.Error:
                TaskbarItemInfo.ProgressState = TaskbarItemProgressState.Error;
                break;

            case ProgressState.Wait:
                TaskbarItemInfo.ProgressState = TaskbarItemProgressState.Paused;
                break;

            default:
                TaskbarItemInfo.ProgressState = TaskbarItemProgressState.Normal;
                break;
            }
        }
 /// <summary>
 ///     Initializes a new instance of the <see cref="ProgressReport{TMessage}"/> class.
 /// </summary>
 /// <param name="message">
 ///     The message describing the status of the long-running operation.
 /// </param>
 /// <param name="state">
 ///     The state of the long-running operation.
 /// </param>
 public ProgressReport(
     TMessage message,
     ProgressState state = ProgressState.Indeterminate)
 {
     this.Message = message;
     this.State   = state;
 }
Exemple #11
0
        public IDisposable StartSubProgress()
        {
            var result = new ProgressState(0, 1, _progressStack);

            _progressStack.Add(result);
            return(result);
        }
        /// <summary>
        /// Applies the summary record.
        /// </summary>
        protected override void ApplySummaryRecord(bool mappingOnly = false)
        {
            //var currentContentItem = DatasetItem ?? new Dataset();

            if (DatasetItem == null)
            {
                return;
            }

            if (!DatasetItem.Infoset.Element.IsEmpty)
            {
                DatasetItem.Infoset.Element.RemoveNodes();
            }

            //if (!string.IsNullOrEmpty(currentContentItem.SummaryData))
            //    currentContentItem.SummaryData = null;

            ProgressState progress = null;

            if (!mappingOnly && ValidationSummary != null)
            {
                progress = new ProgressState(ValidationSummary.CountValid, ValidationSummary.Total);
            }

            var element = new DatasetSummaryHelper(this, progress, RequiredMappings, OptionalMappings).AsElement;

            DatasetItem.Infoset.Element.Add(element);
        }
Exemple #13
0
        /// ------------------------------------------------------------------------------------
        private bool InstallDownloadedFile(string downloadedZipFile)
        {
            var errorMsg = string.Format(LocalizationManager.GetString(
                                             "DialogBoxes.FFmpegDownloadDlg.InstallingDownloadedFileErrorMsg",
                                             "The file '{0}'\r\n\r\neither does not contain ffmpeg or is not a valid zip file."),
                                         downloadedZipFile);

            if (!FFmpegDownloadHelper.GetIsValidFFmpegForSayMoreFile(downloadedZipFile, errorMsg))
            {
                _state = ProgressState.DownloadCanceled;
                return(false);
            }

            _progressControl.SetStatusMessage(LocalizationManager.GetString(
                                                  "DialogBoxes.FFmpegDownloadDlg.InstallingDownloadedFileMsg", "Installing..."));

            Application.DoEvents();

            errorMsg = string.Format(LocalizationManager.GetString(
                                         "DialogBoxes.FFmpegDownloadDlg.InstallingDownloadedFileErrorMsg",
                                         "There was an error installing the downloaded file:\r\n\r\n{0}"),
                                     downloadedZipFile);

            return(FFmpegDownloadHelper.ExtractDownloadedZipFile(downloadedZipFile, errorMsg));
        }
        private void InitOtherComponentDetails()
        {
            _logger.Trace("Start InitOtherComponentDetails.");
            var timeStart = DateTime.Now;

            _crawlerWorker         = new BackgroundWorker();
            _crawlerWorker.DoWork += _crawlerWorker_DoWork;

            _visaRegistrations =
                new Dictionary <AlertControl, VisaRegistrationCzech>();

            clientDataRowBindingSource.DataSource =
                InstanceProvider.DataSet.ClientData;
            repositoryItemTextEditPassword.PasswordChar = '*';

            _progressState = ProgressState.GoToUrl;

            gridView1.ValidateRow            += GridView1_ValidateRow;
            gridView1.InvalidRowException    += GridView1_InvalidRowException;
            gridView1.CustomDrawRowIndicator += gridView1_CustomDrawRowIndicator;
            gridView1.InitNewRow             += GridView1_InitNewRow;
            gridView1.RowCountChanged        += GridView1_RowCountChanged;
            gridView1.BestFitColumns();

            InitColumnNames();
            InitFieldNames();
            InitRepositoryNames();

            _logger.Info(
                $"Time for InitOtherComponentDetails = {DateTime.Now - timeStart}");
            _logger.Trace("End InitOtherComponentDetails.");
        }
 public static void Report(
     this IProgress <IProgressReport> progress,
     string message,
     ProgressState state)
 {
     progress.Report(new ProgressReport(message, state));
 }
Exemple #16
0
        public void RunWorker(BackgroundWorker worker, DoWorkEventArgs args)
        {
            var getProgress = args.Argument as Func <ProgressState>
                              ?? new Func <ProgressState>(() => ProgressState.Empty);

            CurrentProgress = getProgress() ?? ProgressState.Empty;
            ImportStarted(this, EventArgs.Empty);
            var type           = Type.GetType(DataContextObject.SelectedDataType.Target.ClrType);
            var sessionFactory = DataContextObject.ShellContext.SessionFactoryHolder.GetSessionFactory();

            CurrentProgress = new ProgressState(0, DataContextObject.TargetsToImport.Count);
            using (NHibernate.ISession session = sessionFactory.OpenSession())
            {
                var current   = 0;
                var total     = DataContextObject.TargetsToImport.Count;
                int batchSize = Settings.Default.BatchSize;
                using (var tx = session.BeginTransaction())
                {
                    while (current < total && !args.Cancel && !Cancelled)
                    {
                        if (worker.CancellationPending)
                        {
                            args.Cancel = true;
                        }
                        else
                        {
                            var target = DataContextObject.TargetsToImport[current];
                            (target as ContentPartRecord).ContentItemRecord = DataContextObject.CurrentContentItem;
                            try
                            {
                                session.Save(DataContextObject.TargetsToImport[current]);
                            }
                            catch (Exception ex)
                            {
                                GuardError(current, ex);
                            }
                            finally
                            {
                                if (current % batchSize == 0)
                                { //20, same as the ADO batch size
                                    session.Flush();
                                    session.Clear();
                                }
                                current++;
                                var progress = new ProgressState(current, total);
                                worker.ReportProgress((int)Math.Floor(progress.Ratio * 100d), progress);
                                if (current % 1000 == 0)
                                {
                                    Application.Current.DoEvents();
                                }
                            }
                        }
                    }
                    session.Flush();
                    session.Clear();
                    tx.Commit();
                }
                session.Close();
            }
        }
Exemple #17
0
        private void CallEnded(AgentEntry agent, CustomerEntry customer, ProgressState state)
        {
            Interlocked.Decrement(ref CurrentConcurrentWorkers);
            Interlocked.Increment(ref CompletedWorks);

            if (agent != null)
            {
                agent.State = AgentState.Free;
            }

            if (customer != null)
            {
                customer.State = new CustomerState(state, customer.State.HandlingAgent);
            }

            _eventLock.Set();
            OnOneWorkCompleted(new WorkResult {
                IsSuccess = true
            });

            if (CurrentConcurrentWorkers < MaxConcurrentWorkers)
            {
                _eventLock.Set();
            }
        }
Exemple #18
0
    // Update is called once per frame
    void Update()
    {
        switch (this.State)
        {
        case ProgressState.Invalid:
            this.State = ProgressState.Initializing;
            break;

        case ProgressState.Initializing:
            Flow_Initializing();
            break;

        case ProgressState.Checking:
            Flow_Checking();
            break;

        case ProgressState.Pending:
            Flow_Pending();
            break;

        case ProgressState.ChangeScene:
            Flow_ChangeScene();
            break;
            // case ProgressState.End : break ; // do nothing
        }
    }
 protected virtual void ProgressStateChange(ProgressState trigState)
 {
     if (trigState == state)
     {
         Debug.Log("TRIGGERED");
     }
 }
 public ProgressEventArgs(int processedSize, long totalSize, string guid, ProgressState status)
 {
     m_processedSize = processedSize;
     m_totalSize     = totalSize;
     m_guid          = guid;
     m_state         = status;
 }
Exemple #21
0
        /// <summary>
        /// Execute the change requested by the current selection in the combo.
        /// Basically we want the PartOfSpeech indicated by m_selectedHvo, even if 0,
        /// to become the POS of each record that is appropriate to change.
        /// We do nothing to records where the check box is turned off,
        /// and nothing to ones that currently have an MSA other than an IMoStemMsa.
        /// (a) If the owning entry has an IMoStemMsa with the
        /// right POS, set the sense to use it.
        /// (b) If the sense already refers to an IMoStemMsa, and any other senses
        /// of that entry which point at it are also to be changed, change the POS
        /// of the MSA.
        /// (c) If the entry has an IMoStemMsa which is not used at all, change it to the
        /// required POS and use it.
        /// (d) Make a new IMoStemMsa in the ILexEntry with the required POS and point the sense at it.
        /// </summary>
        public override void DoIt(IEnumerable <int> itemsToChange, ProgressState state)
        {
            CheckDisposed();

            m_cache.DomainDataByFlid.BeginUndoTask(LexEdStrings.ksUndoBulkEditRevPOS,
                                                   LexEdStrings.ksRedoBulkEditRevPOS);
            int i        = 0;
            int interval = Math.Min(100, Math.Max(itemsToChange.Count() / 50, 1));

            foreach (int entryId in itemsToChange)
            {
                i++;
                if (i % interval == 0)
                {
                    state.PercentDone = i * 80 / itemsToChange.Count() + 20;
                    state.Breath();
                }
                IReversalIndexEntry entry = m_cache.ServiceLocator.GetInstance <IReversalIndexEntryRepository>().GetObject(entryId);
                if (m_selectedHvo == 0)
                {
                    entry.PartOfSpeechRA = null;
                }
                else
                {
                    entry.PartOfSpeechRA = m_cache.ServiceLocator.GetInstance <IPartOfSpeechRepository>().GetObject(m_selectedHvo);
                }
            }
            m_cache.DomainDataByFlid.EndUndoTask();
        }
        public void AddNotificationToTable(ProgressState request)
        {
            var ne = new NotificationEntity(request);

            TableOperation insertOperation = TableOperation.InsertOrReplace(ne);
            TableResult    result          = Table.Execute(insertOperation);
        }
Exemple #23
0
        //
        void NeighbourSetThreadCall()
        {
            CurrentNeighbourState = ProgressState.InProgress;
            Thread NeighbourSetThread = new Thread(SetTileNeighbours);

            NeighbourSetThread.Start();
        }
Exemple #24
0
 /// <summary>
 /// Initializes the model.
 /// </summary>
 private void InitModel()
 {
     if (DataContextObject.Histogram != null)
     {
         Status = "Data Loaded";
         return;
     }
     Status = "Initializing dataset...";
     Application.Current.DoEvents();
     Feedback = String.Empty;
     FileSize = new FileInfo(CurrentFile).Length;
     using (var conn = Dataservices.ConnectionFactory())
     {
         try
         {
             using (var cmd = conn.CreateCommand())
             {
                 cmd.CommandText = string.Format("select count(*) from [{0}]", Dataservices.Configuration.SelectFrom);
                 conn.Open();
                 var temp = (int)cmd.ExecuteScalar();
                 CurrentProgress = new ProgressState(0, temp);
             }
         }
         finally
         {
             conn.Close();
         }
     }
 }
Exemple #25
0
    private void SwitchState(ProgressState state)
    {
        if (_currProgressState == state)
        {
            return;
        }

        _currProgressState = state;
        _timer             = 0f;
        switch (_currProgressState)
        {
        case ProgressState.NONE:
            InitNoneState();
            break;

        case ProgressState.SHOW_PREVIOUS_PROGRESS:
            InitShowPreviousProgressState();
            break;

        case ProgressState.PREPARE_NEW_PROGRESS:
            InitPrepareNewProgressState();
            break;

        case ProgressState.SHOW_NEW_PROGRESS:
            InitShowNewProgressState();
            break;

        case ProgressState.SHOW_WORD:
            InitShowWordState();
            break;
        }
    }
Exemple #26
0
 /// <summary>
 /// Sets the progress state of the specified window's
 /// taskbar button.
 /// </summary>
 /// <param name="hwnd">The window handle.</param>
 /// <param name="state">The progress state.</param>
 public static void SetProgressState(IntPtr hwnd, ProgressState state)
 {
     if (Windows7OrGreater)
     {
         Taskbar.SetProgressState(hwnd, state);
     }
 }
Exemple #27
0
 /// <summary>
 /// Sets the type and state of the progress indicator displayed on a taskbar button.
 /// </summary>
 /// <param name="windowHandle">The handle of the window in which the progress of an operation is being shown. This window's associated taskbar button will display the progress bar.</param>
 /// <param name="state">Flags that control the current state of the progress button.</param>
 public static void SetProgressState(IntPtr windowHandle, ProgressState state)
 {
     if (TaskbarList != null)
     {
         TaskbarList.SetProgressState(windowHandle, state);
     }
 }
        /// <summary>
        /// Applies the summary record.
        /// </summary>
        /// <param name="mappingOnly">if set to <c>true</c> [mapping only].</param>
        protected override void ApplySummaryRecord(bool mappingOnly = false)
        {
            if (DatasetItem == null)
            {
                return;
            }

            if (!DatasetItem.Infoset.Element.IsEmpty)
            {
                DatasetItem.Infoset.Element.RemoveNodes();
            }

            ProgressState progress = null;

            if (!mappingOnly && ValidationSummary != null)
            {
                progress = new ProgressState(ValidationSummary.CountValid, ValidationSummary.Total);
            }

            if (/*DatasetItem.IsReImport &&*/ ValidationSummary != null)
            {
                if (DatasetItem.File.Contains(" (#"))
                {
                    DatasetItem.File = DatasetItem.File.SubStrBefore(" (#");
                }

                //DatasetItem.File += " (# Rows Imported: " +  ValidationSummary.CountValid + ")";
                DatasetItem.TotalRows    = ValidationSummary.Total;
                DatasetItem.RowsImported = ValidationSummary.CountValid;
            }

            var element = new DatasetSummaryHelper(this, progress, RequiredMappings, OptionalMappings).AsElement;

            DatasetItem.Infoset.Element.Add(element);
        }
Exemple #29
0
 public SynchronicRepository(IDataMapper <T> primary,
                             IDataMapper <T> secondary,
                             CopyStrategy copyStrategy,
                             ProgressState progressState)
 {
     if (primary == null)
     {
         Dispose();
         throw new ArgumentNullException("primary");
     }
     if (secondary == null)
     {
         Dispose();
         throw new ArgumentNullException("secondary");
     }
     if (copyStrategy == null)
     {
         Dispose();
         throw new ArgumentNullException("copyStrategy");
     }
     if (ReferenceEquals(primary, secondary))
     {
         Dispose();
         throw new ArgumentException("primary and secondary must not be equal");
     }
     _primary             = primary;
     _secondary           = secondary;
     _copyStrategy        = copyStrategy;
     _primarySecondaryMap = new Dictionary <RepositoryId, RepositoryId>();
     SynchronizeRepositories();
 }
Exemple #30
0
 public static void UpdateArtCache(Types.PosterWidth pWidth, MainForm form, ProgressState progress)
 {
     int width = Types.GetPosterWidthByEnum(pWidth);
     int i = 0;
     int count = Program.Context.Movies.Count(p => p.Status == Types.ItemStatus.Synced);
     foreach (Movie file in Program.Context.Movies.Include(p => p.Art).Where(p => p.Status == Types.ItemStatus.Synced))
     {
         progress.SetSubText("(" + ((++i) + 1) + "/" + count + ") " + file.Title);
         form.scanningBackgroundWorker.ReportProgress(progress.Value, progress);
         if (file.Art?.WebPath != null && (file.Art.CachePath == null || !File.Exists(file.Art.CachePath) || file.Art.Quality != pWidth))
         {
             if (File.Exists(file.Art.CachePath))
             {
                 File.Delete(file.Art.CachePath);
             }
             using (WebClient webClient = new WebClient())
             {
                 file.Art.Quality = pWidth;
                 try
                 {
                     string url = Program.ImageCacheUrl + @"\" + file.Art.WebPath.GetHashCode() + ".jpg";
                     webClient.DownloadFile(file.Art.WebPath.Replace("V1_SX300.jpg", $"V1_SX{width}.jpg"), url);
                     file.Art.CachePath = url;
                 }
                 catch (Exception)
                 {
                     file.Art.CachePath = null;
                 }
             }
         }
     }
     Program.Context.SaveChanges();
 }
Exemple #31
0
        public static void UpdateGUI(MainForm form, ProgressState progress = null)
        {
            int i = 0;
            int count = Program.Context.Movies.Distinct().Count();
            float perc = 100 / (float)count;
            foreach (Movie file in Program.Context.Movies.Where(p => p.Status == Types.ItemStatus.Synced).OrderBy(p => p.Title).Include(p => p.Art).Include(p => p.Genres))
            {
                progress.SetSubText("(" + (i+1) + "/" + Program.Context.Movies.Count() + ") " + file.Title);
                form.scanningBackgroundWorker.ReportProgress(progress.Value, progress);

                form.Invoke(new Action(() =>
                {

                    PosterCard pc = form.MovieCards.ContainsKey(file.ImdbId) ? form.MovieCards[file.ImdbId] : new PosterCard();

                    pc.Title = file.Title + (file.Year.HasValue ? $" ({file.Year.Value})" : "");
                    pc.Synopsis = file.Plot;
                    pc.Genres = "Genres: " + string.Join(", ", file.Genres.Select(p => p.Name));
                    pc.Rating = "Rating: " + (file.Rating?.Name);

                    if (!string.IsNullOrWhiteSpace(file.Art?.CachePath))
                        pc.Image = Bitmap.FromFile(file.Art.CachePath);

                    if (!form.MovieCards.ContainsKey(file.ImdbId))
                    {
                        pc.Dock = DockStyle.Fill;
                        form.tlOverview.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, perc));
                        form.tlOverview.Controls.Add(pc, i++, 0);
                        form.MovieCards.Add(file.ImdbId, pc);
                    }
                    pc.Movie = file;
                    pc.CustomClick += form.Poster_click;
                }));
            }
        }
Exemple #32
0
        public HttpResponseMessage Post([FromBody] JToken jsonbody)
        {
            // Process the jsonbody
            var requestStream = HttpContext.Current.Request.InputStream;

            Stream req = requestStream;

            req.Seek(0, System.IO.SeekOrigin.Begin);

            string json = jsonbody.ToString();

            ActionRequest ar = null;

            try
            {
                // assuming JSON.net/Newtonsoft library from http://json.codeplex.com/
                ar = JsonConvert.DeserializeObject <ActionRequest>(json);
            }
            catch
            {
                // Try and handle malformed POST body
                return(new HttpResponseMessage(HttpStatusCode.BadRequest));
            }

            _notificationService = new NotificationService();
            ProgressState ps = ar.ToProgressObject(ar, ar.StateString);

            _notificationService.SendNotification(ps);

            _progressHub.sendProgressUpdate(ps);

            return(new HttpResponseMessage(HttpStatusCode.Created));
        }
 public EventProgress(ProgressState state)
 {
     this.State   = state;
     this.Total   = 0;
     this.Current = 0;
     this.Percent = 0;
     this.Message = string.Empty;
 }
Exemple #34
0
 void balanceDal_OnBalancing(object sender, ProgressState state)
 {
     if (state.IsFinish)
         pnlStep.Visible = false;
     else
     {
         lblProgress.Text = state.StateDescription;
         progressBar.Maximum = state.TotalStep;
         progressBar.Value = state.CurrentStep;
         Application.DoEvents();
     }
 }
 public void SetCurrentState(string message, ProgressState type)
 {
     if (type == ProgressState.Normal)
     {
         interactor.UpdateWaitScreen(message);
     }
     else if (type == ProgressState.Error || type == ProgressState.Fatal)
     {
         interactor.RemoveWaitScreen();
         interactor.ShowError("Error Occurred", message);
     }
 }
        public BackgroundWorkerForm()
        {
            InitializeComponent();
            textBox_bound.Focus();

            //bw = new BackgroundWorker();
            bw.WorkerReportsProgress = true;
            //bw.DoWork += new DoWorkEventHandler(bw_DoWork);
            //bw.ProgressChanged += new ProgressChangedEventHandler(bw_ProgressChanged);
            //
            bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw_RunWorkerCompleted);
            progressState = new ProgressState();
        }
Exemple #37
0
		public bool BeginInvoke(ProgressState progress)
		{
			if( !enabled )
			{
				return false;
			}
			// Disable the operation while it is started, notifying everyone
			// of that fact
			Enabled = false;
			_canceling = false;
			BeginInvokeCore2(progress);
			return true;
		}
        private void SetSystemState(ProgressState state)
        {
            switch (state)
            {
                case ProgressState.Pause:
                    this.ForeColor = Color.Olive;
                    break;

                case ProgressState.Error:
                    this.ForeColor = Color.Maroon;
                    break;

                default:
                    this.ResetForeColor();
                    break;
            }
        }
 public void SetState(ProgressState state)
 {
     switch(state)
     {
         case ProgressState.Paused:
             _manager.SetProgressState(TaskbarProgressBarState.Indeterminate, _handle);
             break;
         case ProgressState.Red:
             _manager.SetProgressState(TaskbarProgressBarState.Error, _handle);
             break;
         case ProgressState.Yellow:
             _manager.SetProgressState(TaskbarProgressBarState.Paused, _handle);
             break;
         case ProgressState.Green:
             _manager.SetProgressState(TaskbarProgressBarState.Normal, _handle);
             break;
     }
 }
Exemple #40
0
        public void SetProgressState(ProgressState state)
        {
            IsPaused = state == ProgressState.Paused;

            switch(state)
            {
                case ProgressState.Red:
                    ProgressColor = Brushes.Red;
                    break;
                case ProgressState.Yellow:
                    ProgressColor = Brushes.Yellow;
                    break;
                case ProgressState.Green:
                default:
                    ProgressColor = Brushes.Green;
                    break;
            }
        }
Exemple #41
0
 public static char ArrayValueToRunningStatus(ProgressState value)
 {
     switch (value)
     {
         case ProgressState.NotStarted:
             return '·';
         case ProgressState.Running:
             return '*';
         case ProgressState.Finished:
             return '=';
         case ProgressState.TestFailure:
             return 'x';
         case ProgressState.RunFailure:
             return '?';
         default:
             return 'e';
     }
 }
 /// <summary>
 /// Sets the progress state of the specified window's
 /// taskbar button.
 /// </summary>
 /// <param name="hwnd">The window handle.</param>
 /// <param name="state">The progress state.</param>
 public static void SetProgressState(IntPtr hwnd, ProgressState state)
 {
     if (Windows7OrGreater)
         Taskbar.SetProgressState(hwnd, state);
 }
Exemple #43
0
 public MessageSink(long taskId, string backupId)
 {
     m_state = new ProgressState(taskId, backupId);
 }
Exemple #44
0
 public char ArrayValueToRunningStatusChar(ProgressState value)
 {
     return ArrayValueToRunningStatus(value);
 }
Exemple #45
0
 public StartState(ProgressState baseProgressState)
     : base(baseProgressState)
 {
 }
Exemple #46
0
 public ChooseState(ProgressState baseProgressState)
     : base(baseProgressState)
 {
 }
        protected virtual void OnStateChanged(ProgressState oldState, ProgressState newState)
        {
            var peer = UIElementAutomationPeer.FromElement(this) as ProgressAutomationPeer;
            if (peer != null)
            {
                peer.InvalidatePeer();
            }

            if (IsEnabled)
            {
                switch (newState)
                {
                    case ProgressState.Busy:
                        VisualStateManager.GoToState(this, "Busy", true);
                        if (IndeterminateAnimation != null && IndeterminateAnimation.GetCurrentState() != ClockState.Stopped)
                        {
                            IsIndeterminateAnimationRunning = false;
                            IndeterminateAnimation.Stop(this);
                        }
                        if (BusyAnimation != null)
                        {
                            BusyAnimation.Begin(this, Template, true);
                            IsBusyAnimationRunning = true;
                        }
                        break;
                    case ProgressState.Indeterminate:
                        VisualStateManager.GoToState(this, "Indeterminate", true);
                        if (BusyAnimation != null && BusyAnimation.GetCurrentState() != ClockState.Stopped)
                        {
                            IsBusyAnimationRunning = false;
                            BusyAnimation.Stop(this);
                        }
                        if (IndeterminateAnimation != null)
                        {
                            IndeterminateAnimation.Begin(this, Template, true);
                            IsIndeterminateAnimationRunning = true;
                        }
                        break;
                    case ProgressState.Normal:
                        VisualStateManager.GoToState(this, "Normal", true);
                        if (IndeterminateAnimation != null && IndeterminateAnimation.GetCurrentState() != ClockState.Stopped)
                        {
                            IsIndeterminateAnimationRunning = false;
                            IndeterminateAnimation.Stop(this);
                        }
                        if (BusyAnimation != null && BusyAnimation.GetCurrentState() != ClockState.Stopped)
                        {
                            IsBusyAnimationRunning = false;
                            BusyAnimation.Stop(this);
                        }
                        break;
                }
            }
        }
Exemple #48
0
 public CountdownState(ProgressState baseProgressState)
     : base(baseProgressState)
 {
 }
Exemple #49
0
 private void setTaskBarState(ProgressState state)
 {
     switch (state) {
         case ProgressState.Indeterminate:
             TaskbarItemInfo.ProgressState = TaskbarItemProgressState.Indeterminate;
             break;
         case ProgressState.None:
             TaskbarItemInfo.ProgressState = TaskbarItemProgressState.None;
             break;
         case ProgressState.Normal:
             TaskbarItemInfo.ProgressState = TaskbarItemProgressState.Normal;
             break;
         case ProgressState.Error:
             TaskbarItemInfo.ProgressState = TaskbarItemProgressState.Error;
             break;
         case ProgressState.Wait:
             TaskbarItemInfo.ProgressState = TaskbarItemProgressState.Paused;
             break;
         default:
             TaskbarItemInfo.ProgressState = TaskbarItemProgressState.Normal;
             break;
     }
 }
Exemple #50
0
 public MemorizeState(ProgressState baseProgressState)
     : base(baseProgressState)
 {
 }
Exemple #51
0
 public ResultState(ProgressState baseProgressState)
     : base(baseProgressState)
 {
 }
 /// <summary>
 /// This method is called for long running events, such as recovering,
 /// scanning a file or building an index.
 /// </summary>
 /// <param name="state">the state</param>
 /// <param name="name">the object name</param>
 /// <param name="x">the current position</param>
 /// <param name="max">the highest value</param>
 protected abstract void OnSetProgress(ProgressState state, String name, int x, int max);
Exemple #53
0
        public void OnClientProgress(object sender, SvnProgressEventArgs e)
        {
            ProgressState state;

            long received;
            lock (_instanceLock)
            {
                if (_progressCalc.TryGetValue(e.TotalProgress, out state))
                {
                    if (e.Progress < state.LastCount)
                        state.LastCount = 0;

                    received = e.Progress - state.LastCount;
                    if (e.TotalProgress == e.Progress)
                        _progressCalc.Remove(e.TotalProgress);
                    else
                        state.LastCount = e.Progress;
                }
                else
                {
                    state = new ProgressState();
                    state.LastCount = e.Progress;
                    _progressCalc.Add(e.TotalProgress, state);
                    received = e.Progress;
                }
            }
            _bytesReceived += received;

            TimeSpan ts = DateTime.UtcNow - _start;

            int totalSeconds = (int)ts.TotalSeconds;
            if (totalSeconds < 0)
                return;

            // Clear all buckets of previous seconds where nothing was received
            while (_curBuck < totalSeconds)
            {
                _curBuck++;
                int n = _curBuck % _bucketCount;
                _buckets[n] = 0;
            }

            // Add the amount of this second to the right bucket
            _buckets[_curBuck % _bucketCount] += received;

            int avg = -1;

            int calcBuckets;

            if (_curBuck < 3)
                calcBuckets = 0;
            else
                calcBuckets = Math.Min(5, _curBuck - 1);

            if (calcBuckets > 0)
            {
                long tot = 0;
                for (int n = _curBuck - 1; n > (_curBuck - calcBuckets - 1); n--)
                {
                    tot += _buckets[n % _bucketCount];
                }

                avg = (int)(tot / (long)calcBuckets);
            }

            Enqueue(delegate()
            {
                string text = string.Format("{0} transferred", SizeStr(_bytesReceived));

                if (avg > 0)
                    text += string.Format(" at {0}/s.", SizeStr(avg));
                else if (totalSeconds >= 1)
                    text += string.Format(" in {0} seconds.", totalSeconds);
                else
                    text += ".";

                progressLabel.Text = text;
            });
        }
Exemple #54
0
 protected ConcreteState(ProgressState baseProgressState)
 {
     BaseProgressState = baseProgressState;
 }
        protected virtual void ChangeProgressState(ProgressState newState)
        {
            this.barTotalProgress.State = newState;
            if (this.ButtonProgress != null)
            {
                switch (newState)
                {
                    case ProgressState.Normal:
                        this.ButtonProgress.State = (this.barTotalProgress.Style == ProgressBarStyle.Marquee) ? TaskbarProgressState.Marquee : TaskbarProgressState.Normal;
                        break;

                    case ProgressState.Pause:
                        this.ButtonProgress.State = TaskbarProgressState.Pause;
                        break;

                    case ProgressState.Error:
                        this.ButtonProgress.State = TaskbarProgressState.Error;
                        break;
                }
            }
        }
        private static void setSubProgress(int value, int max, ProgressState progstate) {
            ProgressUpdatedEventArgs e = new ProgressUpdatedEventArgs();
            e.max = max;
            e.message = null;
            e.value = value;
            e.state = progstate;

            ICommunicationReceiver receiver = getReceiver();
            if (receiver == null)
                return;

			if (receiver.ThreadBridge != null) {
				receiver.ThreadBridge.Post(delegate() {
                    ProgressChangedEventHandler handler = receiver.updateProgress;
                    if (handler != null) {
                        handler(e);
                    }
                });
            } else {
                receiver.updateProgress(e);
            }
        }
Exemple #57
0
		protected override void BeginInvokeCore2(ProgressState progress)
		{
			WorkInvoker2 worker = new WorkInvoker2(DoWork2);
			worker.BeginInvoke(progress, new AsyncCallback(EndWork2), null);
		}
Exemple #58
0
		protected abstract void BeginInvokeCore2(ProgressState progress);
Exemple #59
0
        protected static void UpdateImdbInformation(MainForm form, ProgressState progress)
        {
            int i = 1;
            int count = Program.Context.Movies.Count(p => p.Status == Types.ItemStatus.Unsynced);
            foreach (Movie movie in Program.Context.Movies.Where(p => p.Status == Types.ItemStatus.Unsynced).ToArray())
            {
                progress.SetSubText(("(" + (i++) + "/" + count + ") " + movie.Title));
                form.scanningBackgroundWorker.ReportProgress(progress.Value, progress);

                SearchResult searchRes = Omdb.Search(movie.Title, movie.Year, Types.SearchType.Movie);
                if (searchRes != null && (!searchRes.Response.HasValue || searchRes.Response.Value))
                {
                    movie.SearchResult = searchRes;

                    if (searchRes.Search.Length == 0)
                    {
                        movie.Status = Types.ItemStatus.Ignored;
                    }
                    else if (searchRes.Search.Length == 1 || searchRes.Search.Any(p => p.Title.Equals(movie.Title, StringComparison.InvariantCultureIgnoreCase)))
                    {
                        if (searchRes.Search.Count(p => p.Title.Equals(movie.Title, StringComparison.InvariantCultureIgnoreCase)) > 1)
                        {
                            movie.Status = Types.ItemStatus.Conflicted;
                            continue;
                        }

                        SearchEntry searchEntry = searchRes.Search.Length == 1 ? searchRes.Search.First() : searchRes.Search.Single(p => p.Title.Equals(movie.Title, StringComparison.InvariantCultureIgnoreCase));
                        InformationResult infoRes = !string.IsNullOrWhiteSpace(searchEntry.imdbID)
                            ? Omdb.GetInformationByImdbId(searchEntry.imdbID, null, Types.SearchType.Movie, false, true)
                            : Omdb.GetInformationByTitle(searchEntry.Title, movie.Year, Types.SearchType.Movie, false, true);

                        if (infoRes != null)
                        {
                            if (Program.Context.Movies.Any(p => p.ImdbId == infoRes.imdbID))
                            {
                                Movie m = Program.Context.Movies.Include(p => p.Paths).Single(p => p.ImdbId == infoRes.imdbID);
                                m.Paths.Add(movie.Paths.First());
                                Program.Context.Movies.Remove(movie);
                            }
                            else
                            {
                                movie.ParseApiResults(infoRes);
                                movie.Status = Types.ItemStatus.Synced;
                            }
                        }
                    }
                    else
                    {
                        movie.Status = Types.ItemStatus.Conflicted;
                    }
                }
                Program.Context.SaveChanges();
            }
            Program.Context.SaveChanges();
        }
Exemple #60
0
		protected abstract void DoWork2(ProgressState progress);