public async Task LoadProject(string filename)
        {
            ReportProgress?.Invoke(this, new ReportProgressEventArgs(StatusName.MarqueeProgressBarStyle, "Loading project...", OperationTag.Active | OperationTag.Cancellable));

            var stopwatch = new System.Diagnostics.Stopwatch();

            stopwatch.Start();

            Project proj = null;
            await Task.Run(() => proj = ConfigurationBase.Deserialize <Project>(System.IO.File.ReadAllText(filename), new PluginSerializationBinder()));

            proj.Name = System.IO.Path.GetFileName(filename);

            stopwatch.Stop();
            logger.Debug($"Project loaded in {stopwatch.Elapsed}.");

            var curmod           = 0;
            var loadAwareModules = proj.Modules.OfType <ISaveLoadAware>();

            foreach (var module in loadAwareModules)
            {
                ReportProgress?.Invoke(this, new ReportProgressEventArgs(++curmod, loadAwareModules.Count(), "Loading project...", OperationTag.Active | OperationTag.Cancellable));
                module.AfterLoad();
            }

            proj.Modules.ToList().ForEach(m => m.StatusChanged += Module_StatusChanged);
            Project    = proj;
            IsModified = false;
            await RefreshModuleStatus();
        }
Example #2
0
 public async Task <double> TrainNetwork(double[][] inputs, double[][] outputs, double learningrate, double momentum, int iterations, double minerror)
 {
     try
     {
         _run = true;
         SetMomentum(momentum);
         for (_iteration = 0; _iteration < iterations; _iteration++)
         {
             double error = 0;
             for (int s = 0; s < inputs.Length; s++)
             {
                 if (!_run)
                 {
                     return(_error);
                 }
                 error += await TrainSample(inputs[s], outputs[s], learningrate);
             }
             _error = error / inputs.Length;
             ReportProgress?.Invoke(this, EventArgs.Empty);
             if (_error < minerror)
             {
                 break;
             }
         }
         return(_error);
     }
     finally
     {
         ReportProgress = null;
     }
 }
 public async Task LoadModules(string path, string filter)
 {
     await Task.Run(() =>
     {
         try
         {
             var curplug     = 0;
             var pluginFiles = System.IO.Directory.GetFiles(path, filter, System.IO.SearchOption.TopDirectoryOnly);
             foreach (var filename in pluginFiles)
             {
                 ReportProgress?.Invoke(this, new ReportProgressEventArgs(++curplug, pluginFiles.Length, "Loading plugins...", OperationTag.Active));
                 var types = AssemblyLoader.LoadClassesFromFile <IInstallerModule>(System.IO.Path.GetFullPath(filename)).Where(t => t != null);
                 if (types.Any())
                 {
                     PluginLoaded?.Invoke(this, new PluginLoadedEventArgs(types));
                 }
             }
         }
         catch (Exception ex)
         {
             ErrorOccured?.Invoke(this, new ErrorOccuredEventArgs(ex, "Error loading modules"));
         }
         finally
         {
             ReportProgress?.Invoke(this, new ReportProgressEventArgs(0, StatusName.Idle, OperationTag.None));
             LoadingFinished?.Invoke(this, EventArgs.Empty);
         }
     });
 }
Example #4
0
        public static Bitmap ToGrayscale(
            Bitmap source,
            CancellationToken token,
            ReportProgress onProgress = null)
        {
            Bitmap result = new Bitmap(source);

            for (int y = 0; y < source.Height; y++)
            {
                int currentProgress = (int)(((double)y / source.Height) * 100);
                onProgress?.Invoke(currentProgress);

                for (int x = 0; x < source.Width; x++)
                {
                    if (token.IsCancellationRequested)
                    {
                        return(result);
                    }

                    Color c    = source.GetPixel(x, y);
                    var   gray = (int)
                                 (c.R * 0.299 +
                                  c.G * 0.587 +
                                  c.B * 0.114);
                    var grayColor = Color.FromArgb(gray, gray, gray);
                    result.SetPixel(x, y, grayColor);
                }
            }
            return(result);
        }
Example #5
0
        public void Publish(DeployConfigurationModel deployConfiguration, TelemetryWrapper telemetry, string singleResourceName, string project, string projectPath, string basePath)
        {
            try
            {
                Action <string> reportAction        = (m) => { ReportProgress?.Invoke(this, m); };
                var             context             = new XrmService(deployConfiguration.DynamicsSettings, deployConfiguration.Solution, telemetry, reportAction);
                var             sourceControl       = new VersioningService(projectPath, basePath, deployConfiguration.Branch, reportAction, telemetry);
                var             sourceControlResult = sourceControl.QueryLocalRepository();

                // Must resolve conflicts or something went wrong with TFS interaction
                if (!sourceControlResult.Continue && sourceControlResult.Changes == null)
                {
                    return;
                }

                var changeList = sourceControlResult.Changes;
                if (!string.IsNullOrEmpty(singleResourceName))
                {
                    var filteredChangeList = sourceControlResult.Changes.Where(x => x.FileName.Equals(singleResourceName)).ToArray();
                    changeList = filteredChangeList;
                }

                PublishImpl(context, sourceControl, deployConfiguration, telemetry, changeList, project);
            }
            catch (Exception exception)
            {
                ReportProgress?.Invoke(this, $"[ERROR] => {exception.Message}\n");
                if (!(exception is ToolkitException))
                {
                    telemetry.TrackExceptionWithCustomMetrics(exception);
                }
            }
        }
Example #6
0
        private async void GetData(CancellationToken cancelationToken)
        {
            try
            {
                m_Source.MessageRecieved += ProcessMessage;

                int count = 0;
                if (!m_Source.SupportProgress)
                {
                    ProgressArgs args = new ProgressArgs("This DataSource does not support Progress updates.", false, (int)50);
                    ReportProgress?.Invoke(this, args);
                }

                await foreach (IFrame frame in m_Source.GetData(m_sourceSignals, m_start, m_end))
                {
                    frame.Timestamp = Ticks.AlignToMicrosecondDistribution(frame.Timestamp, m_commonFrameRate);
                    await m_sourceQueue.Writer.WriteAsync(frame, cancelationToken);

                    count++;
                    if (count % 1000 == 0 && m_Source.SupportProgress)
                    {
                        ReportDatasourceProgress(m_Source.GetProgress());
                    }
                }
            }
            finally
            {
                MessageRecieved?.Invoke(this, new MessageArgs("Finished Loading Data from DataSource", MessageArgs.MessageLevel.Info));
                m_sourceQueue.Writer.Complete();
            }
        }
 public async Task RefreshModuleStatus(IEnumerable <IInstallerModule> pickModules = null, bool throwIfCancelled = false)
 {
     await Task.Run(() =>
     {
         var options = new ParallelOptions()
         {
             //CancellationToken = GetCancellationToken()
         };
         try
         {
             IEnumerable <IInstallerModule> modules;
             if (pickModules != null)
             {
                 modules = pickModules;
             }
             else
             {
                 modules = Project.ModuleList;
             }
             var currow = 0;
             Parallel.ForEach(modules, options, module =>
             {
                 Interlocked.Add(ref currow, 1);
                 ReportProgress?.Invoke(this, new ReportProgressEventArgs(++currow, modules.Count(), "Refreshing list...", OperationTag.Active));
                 try
                 {
                     options.CancellationToken.ThrowIfCancellationRequested();
                     //logger.Info($"Module {module.Name} - Checking status...");
                     if (module != null && module.Status != InstallerModuleStatus.Refreshing)
                     {
                         module.CheckStatus();
                     }
                 }
                 catch (Exception ex)
                 {
                     logger.Error($"Error checking status of module {module.FriendlyName}.", ex);
                 }
             });
         }
         catch (OperationCanceledException)
         {
             if (throwIfCancelled)
             {
                 throw;
             }
         }
         finally
         {
             ReportProgress?.Invoke(this, new ReportProgressEventArgs(0, StatusName.Idle, OperationTag.None));
         }
     });
 }
Example #8
0
        private void ReportDatasourceProgress(double dataSourceProgress)
        {
            double totalProgress = dataSourceProgress * 0.5D;
            double wFactor       = 1.0D / (double)m_writers.Count() * 0.5D;

            foreach (KeyValuePair <string, SignalWritter> writer in m_writers)
            {
                totalProgress += dataSourceProgress * wFactor * ((-1.0D / 10000.0D) * (double)writer.Value.Backlog + 1.0D);
            }

            ProgressArgs args = new ProgressArgs("Loading Data.", false, (int)totalProgress);

            ReportProgress?.Invoke(this, args);
        }
Example #9
0
 private void PrefetchingTask_ProgressChanged(object sender, ProgressChangedEventArgs e)
 {
     if (Items.Count > 0)
     {
         if (ReportProgressSlim is Action)
         {
             ReportProgressSlim.Invoke(async: false);
         }
         else if (ReportProgress is Action <double, string, TaskStatus> )
         {
             ReportProgress.Invoke(Percentage, Comments, State);
         }
     }
 }
Example #10
0
 private int NotifyProgress(long currentBytes, long totalBytes, int skip)
 {
     skip++;
     if (skip >= 10)
     {
         skip = 0;
         int percent = (int)((currentBytes * 100) / totalBytes);
         if (percent > _lastProgress)
         {
             _lastProgress = percent;
             ReportProgress?.Invoke(_lastProgress);
         }
     }
     return(skip);
 }
        public void Execute(Action action)
        {
            string key = Guid.NewGuid().ToString();
            int    res = RmStartSession(out IntPtr handle, 0, key);

            if (res == 0)
            {
                ReportProgress?.Invoke($"Restart Manager session created with ID {key}");

                RM_UNIQUE_PROCESS[] processes = GetProcesses("explorer");
                res = RmRegisterResources(
                    handle,
                    0, null,
                    (uint)processes.Length, processes,
                    0, null
                    );

                if (res == 0)
                {
                    ReportProgress?.Invoke("Successfully registered resources.");

                    res = RmShutdown(handle, RM_SHUTDOWN_TYPE.RmForceShutdown, (percent) => ReportPercentage?.Invoke(percent));

                    if (res == 0)
                    {
                        ReportProgress?.Invoke("Applications stopped successfully.");
                        action();

                        res = RmRestart(handle, 0, (percent) => ReportPercentage?.Invoke(percent));

                        if (res == 0)
                        {
                            ReportProgress?.Invoke("Applications restarted successfully.");
                        }
                    }
                }

                res = RmEndSession(handle);

                if (res == 0)
                {
                    ReportProgress?.Invoke("Restart Manager session ended.");
                }
            }
        }
 private void CopyRun()
 {
     CopyQueue              = new Queue <Uri>();
     CopyQueue.OnItemAdded += () =>
     {
         ReportProgress?.Invoke(FileAction.Copy, CopyQueue.Count);
         Uri nextFile;
         while ((nextFile = CopyQueue.GetNext()) != null)
         {
             List <Uri> outputs = workspace.GetSlavesPaths(nextFile);
             foreach (var file in outputs)
             {
                 File.Copy(nextFile.AbsolutePath, file.AbsolutePath, true);
             }
             ReportProgress?.Invoke(FileAction.Copy, CopyQueue.Count);
         }
     };
 }
Example #13
0
        public void Sort(ref Color[] color)
        {
            for (int i = 0; i < color.Length; i++)
            {
                for (int j = 0; j < color.Length - i - 1; j++)
                {
                    int A_Hue  = (int)Math.Round(color[j].GetHue());
                    int A1_Hue = (int)Math.Round(color[j + 1].GetHue());
                    if (A_Hue > A1_Hue)
                    {
                        Swap(color, j, j + 1);
                    }

                    ReportProgress?.Invoke();
                }
                Thread.Sleep((int)Utility.SleepTime);
            }
        }
Example #14
0
 private void Work(object ithread)
 {
     ReportProgress?.Invoke(0);
     while (true)
     {
         int x;
         lock (locker) {
             if (toBeProcessed.Count == 0)
             {
                 break;
             }
             x = toBeProcessed.Pop();
         }
         calculation(x, (int)ithread);
         lock (locker) {
             tasksDone++;
             ReportProgress?.Invoke(tasksDone / (double)nTasks);
         }
     }
 }
Example #15
0
 private void PrefetchingTask_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
 {
     if (Items.Count > 0)
     {
         if (State == TaskStatus.Faulted || State == TaskStatus.Canceled)
         {
             if (ReportProgressSlim is Action)
             {
                 ReportProgressSlim.Invoke(async: false);
             }
             else if (ReportProgress is Action <double, string, TaskStatus> )
             {
                 ReportProgress.Invoke(Percentage, Comments, State);
             }
         }
         //Application.Current.MergeToSystemPrefetchedList(PrefetchedList);
     }
     if (CanPrefetching is SemaphoreSlim && CanPrefetching.CurrentCount < 1)
     {
         CanPrefetching.Release();
     }
 }
Example #16
0
        private void PublishImpl(XrmService context, VersioningService gitvc, DeployConfigurationModel deployConfiguration, TelemetryWrapper telemetry, RawChanges[] changes, string project)
        {
            try
            {
                ChangeManagerService container = new ChangeManagerService(changes, deployConfiguration.Prefix, context);
                telemetry.TrackCustomEventWithCustomMetrics("Deploy Started", new MetricData("Project Name", project));

                if (container.WebResources.Count > 0)
                {
                    ReportProgress?.Invoke(this, $"[DYNAMICS] => Found {container.WebResources.Count} Web Resource.");
                    ReportProgress?.Invoke(this, $"[DYNAMICS] => '{deployConfiguration.Prefix}' used as base path.");
                    ReportProgress?.Invoke(this, $"[DYNAMICS] => Fetching '{deployConfiguration.Solution}' solution from CRM.");
                    container.EnsureContinue(deployConfiguration.Solution, deployConfiguration.Prefix);

                    ReportProgress?.Invoke(this, $"[DYNAMICS] => Publishing changes to the CRM.");
                    var faultedFlushResult = context.Flush(container.BuildRequestList(deployConfiguration.Solution));

                    if (!faultedFlushResult && deployConfiguration.CheckInEnabled)
                    {
                        ReportProgress?.Invoke(this, $"[AZOPS] => Commit & Push in progress.");
                        gitvc.CommitAndPush(deployConfiguration.Password);
                    }

                    ReportProgress?.Invoke(this, $"[AZOPS] => Publish completed.");
                }

                telemetry.TrackCustomEventWithCustomMetrics("Deploy Finished", new MetricData("Project Name", project));
            }
            catch (Exception exception)
            {
                ReportProgress?.Invoke(this, $"[ERROR] => {exception.Message}\n");
                if (!(exception is ToolkitException))
                {
                    telemetry.TrackExceptionWithCustomMetrics(exception);
                }
            }
        }
        public void SaveProject(string filename)
        {
            var saveAwareModules = Project.Modules.OfType <ISaveLoadAware>();
            var curmod           = 0;
            var allmods          = saveAwareModules.Count() * 2;

            foreach (var module in saveAwareModules)
            {
                ReportProgress?.Invoke(this, new ReportProgressEventArgs(++curmod, allmods, "Saving project..", OperationTag.Active | OperationTag.Cancellable));
                module.BeforeSave();
            }

            System.IO.File.WriteAllText(filename, Project.Serialize());

            foreach (var module in Project.Modules.OfType <ISaveLoadAware>())
            {
                ReportProgress?.Invoke(this, new ReportProgressEventArgs(++curmod, allmods, "Saving project...", OperationTag.Active | OperationTag.Cancellable));
                module.AfterSave();
            }

            Project.Name = System.IO.Path.GetFileName(filename);
            NotifyProjectChange();
            IsModified = false;
        }
        public void Download()
        {
            WebRequest request = WebRequest.Create(downloadItem.SourceName);

            request.Credentials = CredentialCache.DefaultCredentials;

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();

            Stream stream = response.GetResponseStream();

            Int64     fileSize = response.ContentLength;
            const int size     = 65535;//4096;

            byte[] bytes    = new byte[size];
            int    numBytes = 0;

            using (FileStream fileStream = new FileStream(downloadItem.DestinationName, FileMode.Create, FileAccess.Write))
            {
                while ((numBytes = stream.Read(bytes, 0, size)) > 0)
                {
                    ReportProgress.Invoke(downloadItem);
                    if (fileStream.Length > 0)
                    {
                        downloadItem.Persentage = (int)((float)fileStream.Length / (float)fileSize * 100);
                    }

                    downloadItem.State = TaskState.Processing;

                    fileStream.Write(bytes, 0, numBytes);
                }
            }

            downloadItem.Persentage = 100;
            downloadItem.State      = TaskState.Completed;
            ReportProgress.Invoke(downloadItem);


            //const int startPoint = 0;
            //Stream strResponse = null;
            //Stream strLocal = null;

            //HttpWebRequest webRequest = null;
            //HttpWebResponse webResponse = null;

            //try
            //{
            //    // Put the object argument into an int variable
            //    int startPointInt = Convert.ToInt32(startPoint);
            //    // Create a request to the file we are downloading
            //    webRequest = (HttpWebRequest)WebRequest.Create(downloadItem.SourceName);
            //    // Set the starting point of the request
            //    webRequest.AddRange(startPointInt);

            //    // Set default authentication for retrieving the file
            //    webRequest.Credentials = CredentialCache.DefaultCredentials;
            //    // Retrieve the response from the server
            //    webResponse = (HttpWebResponse)webRequest.GetResponse();
            //    // Ask the server for the file size and store it
            //    Int64 fileSize = webResponse.ContentLength;

            //    // Open the URL for download
            //    strResponse = webResponse.GetResponseStream();

            //    // Create a new file stream where we will be saving the data (local drive)
            //    if (startPointInt == 0)
            //    {
            //        strLocal = new FileStream(downloadItem.DestinationName, FileMode.Create, FileAccess.Write, FileShare.None);
            //    }
            //    else
            //    {
            //        strLocal = new FileStream(downloadItem.DestinationName, FileMode.Append, FileAccess.Write, FileShare.None);
            //    }

            //    // It will store the current number of bytes we retrieved from the server
            //    int bytesSize = 0;
            //    // A buffer for storing and writing the data retrieved from the server
            //    byte[] downBuffer = new byte[2048];
            //    int i = 0;
            //    // Loop through the buffer until the buffer is empty
            //    while ((bytesSize = strResponse.Read(downBuffer, 0, downBuffer.Length)) > 0)
            //    {
            //        // Write the data from the buffer to the local hard drive
            //        ReportProgress.Invoke(downloadItem);
            //        downloadItem.Persentage++;
            //        downloadItem.State = TaskState.Processing;
            //        strLocal.Write(downBuffer, 0, bytesSize);
            //        // Invoke the method that updates the form's label and progress bar
            //    }
            //}
            //finally
            //{
            //    // When the above code has ended, close the streams
            //    strResponse.Close();
            //    strLocal.Close();

            //    downloadItem.Persentage = 100;
            //    downloadItem.State = TaskState.Completed;
            //    ReportProgress.Invoke(downloadItem);
            //}
        }
 private void BackgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
 {
     ReportProgress?.Invoke(this, e);
 }
Example #20
0
 /// <summary>
 /// Reveals, unlocks or increment achievement.
 /// </summary>
 /// <remarks>
 /// Call after setting <see cref="id" />, <see cref="completed" />,
 /// as well as <see cref="currentSteps" /> and <see cref="totalSteps" />
 /// for incremental achievements. Equivalent to calling
 /// <see cref="PlayGamesPlatform.ReportProgress" />.
 /// </remarks>
 public void ReportProgress(Action <bool> callback)
 {
     mProgressCallback.Invoke(mId, mPercentComplete, callback);
 }
Example #21
0
        /// <summary>
        /// Gets the files based on the class initialization.
        /// </summary>
        /// <param name="path">The path to start enumerating the files from.</param>
        /// <param name="subDirectories">if set to <c>true</c> the files in subdirectories are also included in the result.</param>
        /// <returns>IEnumerable&lt;System.String&gt;.</returns>
        private IEnumerable <string> GetFiles(string path, bool subDirectories)
        {
            List <string> result = new List <string>();

            // a SecurityException or a UnauthorizedAccessException may intrude the enumeration
            // process any time and it will also result in exception if the files where enumerated
            // solely depending on the Directory.EnumerateFiles(path, ...,SearchOption.AllDirectories)..
            try
            {
                // based on the search type append to the result..
                if (SearchType == SearchTypeMatch.Regex)
                {
                    foreach (var file in Directory.EnumerateFiles(path).Where(f => FileExtensionMatch.IsMatch(f)))
                    {
                        // the process was requested to be canceled..
                        if (Canceled)
                        {
                            return(result);
                        }

                        // report the progress if subscribed..
                        ReportProgress?.Invoke(this,
                                               new DirectoryCrawlerEventArgs
                        {
                            CurrentDirectory = path, FileName = file, Directory = string.Empty
                        });

                        // add to the result..
                        result.Add(file);
                    }
                }
                else if (SearchType == SearchTypeMatch.AllFiles || SearchType == SearchTypeMatch.FileMask ||
                         SearchType == SearchTypeMatch.FilesNoExtension)
                {
                    foreach (var file in  Directory.EnumerateFiles(path, SearchMask))
                    {
                        // the process was requested to be canceled..
                        if (Canceled)
                        {
                            return(result);
                        }

                        // report the progress if subscribed..
                        ReportProgress?.Invoke(this,
                                               new DirectoryCrawlerEventArgs
                        {
                            CurrentDirectory = path, FileName = file, Directory = string.Empty
                        });

                        // add to the result..
                        result.Add(file);
                    }
                }

                if (subDirectories)
                {
                    // a SecurityException or a UnauthorizedAccessException may intrude the enumeration
                    // process any time and it will also result in exception if the directories where
                    // enumerated solely depending on the Directory.EnumerateDirectories(path, ...,SearchOption.AllDirectories)..
                    try
                    {
                        foreach (var directory in  Directory.EnumerateDirectories(path))
                        {
                            // the process was requested to be canceled..
                            if (Canceled)
                            {
                                return(result);
                            }

                            // report the progress if subscribed..
                            ReportProgress?.Invoke(this,
                                                   new DirectoryCrawlerEventArgs
                            {
                                CurrentDirectory = path, FileName = string.Empty, Directory = directory
                            });

                            // add to the result..
                            result.AddRange(GetFiles(directory, true));
                        }
                    }
                    catch (Exception ex)
                    {
                        // log the exception..
                        ExceptionLogAction?.Invoke(ex);
                    }
                }
            }
            catch (Exception ex)
            {
                // log the exception..
                ExceptionLogAction?.Invoke(ex);
            }

            return(result);
        }
Example #22
0
        /// <summary>
        /// Gets the directories based on the class initialization.
        /// </summary>
        /// <param name="path">The path to start enumerating the directories from.</param>
        /// <param name="subDirectories">if set to <c>true</c> the subdirectories are also included in the result.</param>
        /// <returns>IEnumerable&lt;System.String&gt;.</returns>
        private IEnumerable <string> GetDirectories(string path, bool subDirectories)
        {
            List <string> result = new List <string>();

            // a SecurityException or a UnauthorizedAccessException may intrude the enumeration
            // process any time and it will also result in exception if the directories where
            // enumerated solely depending on the Directory.EnumerateDirectories(path, ...,SearchOption.AllDirectories)..
            try
            {
                List <string> directories = new List <string>();

                foreach (var directory in Directory.EnumerateDirectories(path))
                {
                    // the process was requested to be canceled..
                    if (Canceled)
                    {
                        return(result);
                    }

                    // report the progress if subscribed..
                    ReportProgress?.Invoke(this,
                                           new DirectoryCrawlerEventArgs
                    {
                        CurrentDirectory = path, FileName = string.Empty, Directory = directory
                    });
                    result.Add(directory);
                    directories.Add(directory);
                }

                if (subDirectories)
                {
                    // a SecurityException or a UnauthorizedAccessException may intrude the enumeration
                    // process any time and it will also result in exception if the directories where
                    // enumerated solely depending on the Directory.EnumerateDirectories(path, ...,SearchOption.AllDirectories)..
                    try
                    {
                        foreach (var directory in directories)
                        {
                            // the process was requested to be canceled..
                            if (Canceled)
                            {
                                return(result);
                            }

                            result.AddRange(GetDirectories(directory, true));
                        }
                    }
                    catch (Exception ex)
                    {
                        // log the exception..
                        ExceptionLogAction?.Invoke(ex);
                    }
                }
            }
            catch (Exception ex)
            {
                // log the exception..
                ExceptionLogAction?.Invoke(ex);
            }

            return(result);
        }
Example #23
0
        public bool Solve()
        {
            Solution = null;
            EnqueuePossibleMovements(_initialState, _rows - 1, new List <Movement>());

            while (Solution == null)
            {
                var dequeued = _movementQueue.Dequeue();
                var movement = dequeued.Item1;
                var visited  = dequeued.Item2;

                Progress newProgress          = new Progress(visited.Count, _movementQueue.Count);
                int      queueSizeGranularity = 10_000;
                if (newProgress.Steps > _currentProgress.Steps || newProgress.QueueSize > _currentProgress.QueueSize + queueSizeGranularity)
                {
                    _currentProgress = new Progress(newProgress.Steps, newProgress.QueueSize - newProgress.QueueSize % queueSizeGranularity);
                    ReportProgress?.Invoke(this, newProgress);
                }

                var state = movement.State.Clone();

                int dY;
                if (movement.MovementDirection == MovementDirection.Up)
                {
                    dY = -1;
                }
                else
                {
                    dY = 1;
                }

                var newYPos = movement.ElevatorYPosBefore + dY;
                if (newYPos < 0 || newYPos >= _rows)
                {
                    continue;
                }

                foreach (int x in movement.SelectionXPositions)
                {
                    string tmp = state.GetData(x, movement.ElevatorYPosBefore);
                    state.MoveOrAdd(x, newYPos, tmp);
                    state.MoveOrAdd(0, newYPos, "E");
                }

                var        rawState   = state.Expand();
                List <int> friedChips = new List <int>();
                friedChips.AddRange(CheckForFriedMicrochips(rawState, movement.ElevatorYPosBefore));
                friedChips.AddRange(CheckForFriedMicrochips(rawState, newYPos));

                if (friedChips.Count != 0)
                {
                    continue;
                }
                else
                {
                    var visitedClone = visited.Clone();
                    visitedClone.Add(movement);
                    EnqueuePossibleMovements(state, newYPos, visitedClone);

                    if (CheckForFinishedState(rawState))
                    {
                        visited.Add(movement);
                        Solution = visited;
                    }
                }

                if (_cancellationToken.IsCancellationRequested)
                {
                    break;
                }
            }

            return(Solution != null);
        }
Example #24
0
        protected override void ParseAsXmlStream(Stream stream, ReportProgress ProgressReport)
        {
            using (XmlTextReader reader = new XmlTextReader(stream))
            {
                ItemInfo item = new ItemInfo();
                string value = null;

                while (reader.Read())
                {
                    ProgressReport.Invoke();
                    switch (reader.NodeType)
                    {
                        case XmlNodeType.Element:
                            switch (reader.Name.ToUpperInvariant())
                            {
                                case "ROW": item = new ItemInfo(); continue;
                                default: value = null; break;
                            }
                            break;

                        case XmlNodeType.Text:
                            value = reader.Value;
                            break;

                        case XmlNodeType.EndElement:
                            switch (reader.Name.ToUpperInvariant())
                            {
                                case "ID": item.item = uint.Parse(value, NumberFormatInfo.InvariantInfo); break;
                                case "ADDITION": item.addition = uint.Parse(value, NumberFormatInfo.InvariantInfo); break;
                                case "PART": item.part = uint.Parse(value, NumberFormatInfo.InvariantInfo); break;
                                case "TYPE": item.type = uint.Parse(value, NumberFormatInfo.InvariantInfo); break;
                                case "PRICE": item.price = uint.Parse(value, NumberFormatInfo.InvariantInfo); break;
                                case "TRADE": item.trade = uint.Parse(value, NumberFormatInfo.InvariantInfo); break;
                                case "DROP": item.drop = uint.Parse(value, NumberFormatInfo.InvariantInfo); break;
                                case "NAME": item.name = value; break;
                                case "QUEST": item.quest = uint.Parse(value, NumberFormatInfo.InvariantInfo); break;
                                case "REQ_CLV": item.req_clvl = byte.Parse(value, NumberFormatInfo.InvariantInfo); break;
                                case "REQ_MALE": item.req_male = byte.Parse(value, NumberFormatInfo.InvariantInfo); break;
                                case "REQ_FEMALE": item.req_female = byte.Parse(value, NumberFormatInfo.InvariantInfo); break;
                                case "REQ_NORMAN": item.req_norman = byte.Parse(value, NumberFormatInfo.InvariantInfo); break;
                                case "REQ_ELLR": item.req_ellr = byte.Parse(value, NumberFormatInfo.InvariantInfo); break;
                                case "REQ_DIMAGO": item.req_dimago = byte.Parse(value, NumberFormatInfo.InvariantInfo); break;
                                case "REQ_STR": item.req_str = byte.Parse(value, NumberFormatInfo.InvariantInfo); break;
                                case "REQ_DEX": item.req_dex = byte.Parse(value, NumberFormatInfo.InvariantInfo); break;
                                case "REQ_INT": item.req_int = byte.Parse(value, NumberFormatInfo.InvariantInfo); break;
                                case "REQ_CON": item.req_con = byte.Parse(value, NumberFormatInfo.InvariantInfo); break;
                                case "REQ_LUC": item.req_luc = byte.Parse(value, NumberFormatInfo.InvariantInfo); break;
                                case "MAX_STACK": item.max_stack = byte.Parse(value, NumberFormatInfo.InvariantInfo); break;
                                case "MAX_DUR": item.max_durability = uint.Parse(value, NumberFormatInfo.InvariantInfo); break;
                                case "SKILL": item.skill = uint.Parse(value, NumberFormatInfo.InvariantInfo); break;
                                case "OPTION_ID": item.option_id = uint.Parse(value, NumberFormatInfo.InvariantInfo); break;
                                case "CATEGORIE": item.categorie = uint.Parse(value, NumberFormatInfo.InvariantInfo); break;
                                case "JOBREQUIREMENT":
                                    string[] values = value.Split(',');
                                    item.JobRequirement = new byte[]
                                    {
                                        byte.Parse(values[0],  NumberFormatInfo.InvariantInfo),  //NOVICE
                                        byte.Parse(values[1],  NumberFormatInfo.InvariantInfo),  //SWORDSMAN
                                        byte.Parse(values[3],  NumberFormatInfo.InvariantInfo),  //RECRUIT
                                        byte.Parse(values[2],  NumberFormatInfo.InvariantInfo),  //THIEF
                                        byte.Parse(values[4],  NumberFormatInfo.InvariantInfo),  //ENCHANTER
                                        byte.Parse(values[5],  NumberFormatInfo.InvariantInfo),  //CLOWN
                                        byte.Parse(values[6],  NumberFormatInfo.InvariantInfo),  //KNIGHT
                                        byte.Parse(values[7],  NumberFormatInfo.InvariantInfo),  //ASSASIN
                                        byte.Parse(values[8],  NumberFormatInfo.InvariantInfo),  //SPECIALIST
                                        byte.Parse(values[9],  NumberFormatInfo.InvariantInfo),  //SAGE
                                        byte.Parse(values[10],  NumberFormatInfo.InvariantInfo), //GAMBLER
                                        byte.Parse(values[11],  NumberFormatInfo.InvariantInfo), //FALCATA
                                        byte.Parse(values[12],  NumberFormatInfo.InvariantInfo), //FPRSYTHIE
                                        byte.Parse(values[13],  NumberFormatInfo.InvariantInfo), //NEMOPHILA
                                        byte.Parse(values[14],  NumberFormatInfo.InvariantInfo)  //VEILCHENBLAU
                                    };
                                    break;

                                case "ROW": goto Add;
                            }
                            break;
                    }

                    continue;
                Add:
                    this.item_drops.Add(item.item, item);
                }
            }
        }
 private void ResetStatus()
 {
     ReportProgress?.Invoke(this, new ReportProgressEventArgs_OLD(0, StatusName.Idle, OperationTrait.Inactive));
 }
 private void SetStatus(int num, int qty, string messaage)
 {
     ReportProgress?.Invoke(this, new ReportProgressEventArgs_OLD(num, qty, messaage, OperationTrait.Active,
                                                                  OperationTrait.NoGetProjectAllowed,
                                                                  OperationTrait.NoSetProjectAllowed));
 }
 /// <summary>
 ///     Reveals, unlocks or increment achievement.
 /// </summary>
 /// <remarks>
 ///     Call after setting <see cref="id" />, <see cref="completed" />,
 ///     as well as <see cref="currentSteps" /> and <see cref="totalSteps" />
 ///     for incremental achievements. Equivalent to calling
 ///     <see cref="PlayGamesPlatform.ReportProgress" />.
 /// </remarks>
 public void ReportProgress(Action <bool> callback)
 {
     mProgressCallback.Invoke(id, percentCompleted, callback);
 }
 // This event handler updates the progress bar.
 private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
 {
     percentCompleted = e.ProgressPercentage;
     ReportProgress?.Invoke(sender, e);
 }
Example #29
0
        protected override void ParseAsXmlStream(Stream stream, ReportProgress ProgressReport)
        {
            using (XmlTextReader reader = new XmlTextReader(stream))
            {
                ItemInfo item  = new ItemInfo();
                string   value = null;

                while (reader.Read())
                {
                    ProgressReport.Invoke();
                    switch (reader.NodeType)
                    {
                    case XmlNodeType.Element:
                        switch (reader.Name.ToUpperInvariant())
                        {
                        case "ROW": item = new ItemInfo(); continue;

                        default: value = null; break;
                        }
                        break;

                    case XmlNodeType.Text:
                        value = reader.Value;
                        break;

                    case XmlNodeType.EndElement:
                        switch (reader.Name.ToUpperInvariant())
                        {
                        case "ID": item.item = uint.Parse(value, NumberFormatInfo.InvariantInfo); break;

                        case "ADDITION": item.addition = uint.Parse(value, NumberFormatInfo.InvariantInfo); break;

                        case "PART": item.part = uint.Parse(value, NumberFormatInfo.InvariantInfo); break;

                        case "TYPE": item.type = uint.Parse(value, NumberFormatInfo.InvariantInfo); break;

                        case "PRICE": item.price = uint.Parse(value, NumberFormatInfo.InvariantInfo); break;

                        case "TRADE": item.trade = uint.Parse(value, NumberFormatInfo.InvariantInfo); break;

                        case "DROP": item.drop = uint.Parse(value, NumberFormatInfo.InvariantInfo); break;

                        case "NAME": item.name = value; break;

                        case "QUEST": item.quest = uint.Parse(value, NumberFormatInfo.InvariantInfo); break;

                        case "REQ_CLV": item.req_clvl = byte.Parse(value, NumberFormatInfo.InvariantInfo); break;

                        case "REQ_MALE": item.req_male = byte.Parse(value, NumberFormatInfo.InvariantInfo); break;

                        case "REQ_FEMALE": item.req_female = byte.Parse(value, NumberFormatInfo.InvariantInfo); break;

                        case "REQ_NORMAN": item.req_norman = byte.Parse(value, NumberFormatInfo.InvariantInfo); break;

                        case "REQ_ELLR": item.req_ellr = byte.Parse(value, NumberFormatInfo.InvariantInfo); break;

                        case "REQ_DIMAGO": item.req_dimago = byte.Parse(value, NumberFormatInfo.InvariantInfo); break;

                        case "REQ_STR": item.req_str = byte.Parse(value, NumberFormatInfo.InvariantInfo); break;

                        case "REQ_DEX": item.req_dex = byte.Parse(value, NumberFormatInfo.InvariantInfo); break;

                        case "REQ_INT": item.req_int = byte.Parse(value, NumberFormatInfo.InvariantInfo); break;

                        case "REQ_CON": item.req_con = byte.Parse(value, NumberFormatInfo.InvariantInfo); break;

                        case "REQ_LUC": item.req_luc = byte.Parse(value, NumberFormatInfo.InvariantInfo); break;

                        case "MAX_STACK": item.max_stack = byte.Parse(value, NumberFormatInfo.InvariantInfo); break;

                        case "MAX_DUR": item.max_durability = uint.Parse(value, NumberFormatInfo.InvariantInfo); break;

                        case "SKILL": item.skill = uint.Parse(value, NumberFormatInfo.InvariantInfo); break;

                        case "OPTION_ID": item.option_id = uint.Parse(value, NumberFormatInfo.InvariantInfo); break;

                        case "CATEGORIE": item.categorie = uint.Parse(value, NumberFormatInfo.InvariantInfo); break;

                        case "JOBREQUIREMENT":
                            string[] values = value.Split(',');
                            item.JobRequirement = new byte[]
                            {
                                byte.Parse(values[0], NumberFormatInfo.InvariantInfo),           //NOVICE
                                byte.Parse(values[1], NumberFormatInfo.InvariantInfo),           //SWORDSMAN
                                byte.Parse(values[3], NumberFormatInfo.InvariantInfo),           //RECRUIT
                                byte.Parse(values[2], NumberFormatInfo.InvariantInfo),           //THIEF
                                byte.Parse(values[4], NumberFormatInfo.InvariantInfo),           //ENCHANTER
                                byte.Parse(values[5], NumberFormatInfo.InvariantInfo),           //CLOWN
                                byte.Parse(values[6], NumberFormatInfo.InvariantInfo),           //KNIGHT
                                byte.Parse(values[7], NumberFormatInfo.InvariantInfo),           //ASSASIN
                                byte.Parse(values[8], NumberFormatInfo.InvariantInfo),           //SPECIALIST
                                byte.Parse(values[9], NumberFormatInfo.InvariantInfo),           //SAGE
                                byte.Parse(values[10], NumberFormatInfo.InvariantInfo),          //GAMBLER
                                byte.Parse(values[11], NumberFormatInfo.InvariantInfo),          //FALCATA
                                byte.Parse(values[12], NumberFormatInfo.InvariantInfo),          //FPRSYTHIE
                                byte.Parse(values[13], NumberFormatInfo.InvariantInfo),          //NEMOPHILA
                                byte.Parse(values[14], NumberFormatInfo.InvariantInfo)           //VEILCHENBLAU
                            };
                            break;

                        case "ROW": goto Add;
                        }
                        break;
                    }

                    continue;
Add:
                    this.item_drops.Add(item.item, item);
                }
            }
        }
Example #30
0
 private void _RaiseReportProgress(int value) => ReportProgress?.Invoke(this, new UpdateProgressEventArgs(value));
        public async Task InstallAllModules()
        {
            try
            {
                await RefreshModuleStatus(throwIfCancelled : true);
            }
            catch (OperationCanceledException)
            {
                return;
            }

            await Task.Run(() =>
            {
                try
                {
                    var options = new ParallelOptions()
                    {
                        //CancellationToken = GetCancellationToken()
                    };
                    Parallel.ForEach(Project.ModuleList.Where(m => m.Status == InstallerModuleStatus.NotInstalled), options, module =>
                    {
                        try
                        {
                            options.CancellationToken.ThrowIfCancellationRequested();
                            module.PrepareInstall();
                        }
                        catch (Exception ex)
                        {
                            logger.Error($"Error preparing module {module.FriendlyName} for install.", ex);
                        }
                    });
                }
                catch (OperationCanceledException)
                {
                    return;
                }

                var refreshTasks = new List <Task>();
                //var token = GetCancellationToken();
                var pending = Project.ModuleList.Where(m => m.Status == InstallerModuleStatus.InstallationPending);
                var curmod  = 0;
                var allmods = pending.Count();
                foreach (var module in pending)
                {
                    ReportProgress?.Invoke(this, new ReportProgressEventArgs(++curmod, allmods, $"Installing module {module.FriendlyName ?? module.Name}...", OperationTag.Active));
                    try
                    {
                        //token.ThrowIfCancellationRequested();
                        module.Install();
                        refreshTasks.Add(Task.Run(() => module.CheckStatus()));
                    }
                    catch (OperationCanceledException)
                    {
                        break;
                    }
                    catch (Exception ex)
                    {
                        logger.Error($"Error installing module {module.FriendlyName}.", ex);
                    }
                }
                Task.WaitAll(refreshTasks.ToArray());
                ReportProgress?.Invoke(this, new ReportProgressEventArgs(0, StatusName.Idle, OperationTag.None));
            });
        }