Ejemplo n.º 1
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);
                }
            }
        }
Ejemplo n.º 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);
         }
     });
 }
Ejemplo n.º 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);
        }
Ejemplo n.º 5
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 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();
        }
Ejemplo n.º 7
0
        private void SendProgress(string message, int?processedCount = null)
        {
            var progress = new ReportProgress
            {
                Message            = message,
                WorkItemsProcessed = processedCount
            };

            this.broadcastService.ReportProgress(progress);
        }
Ejemplo n.º 8
0
        private async Task <TfsInfo> ProcessWorkItemRevisions(WorkItemReference workItemRef)
        {
            var revisions = await this.workItemClient.GetRevisionsAsync(
                workItemRef.Id,
                expand : WorkItemExpand.Fields);

            string lastState = null;
            var    revs      = new WorkItemRevisionBuilder();

            foreach (var workItemRev in revisions)
            {
                var state = workItemRev.State();

                if (state != null && lastState != state)
                {
                    lastState = state;
                    await ProcessWorkItemRevision(workItemRev, revs);
                }
            }

            if (revs.States.Count > 1)
            {
                var sbTemp = new StringBuilder();

                for (int i = 0; i < revs.States.Count; i++)
                {
                    sbTemp.Append(revs.States[i].Summary);

                    if (i + 1 < revs.States.Count)
                    {
                        sbTemp.AppendLine();
                    }

                    revs.TfsInfo.Transitions = sbTemp.ToString().Trim();
                }

                revs.TfsInfo.TransitionCount = revs.States.Count;
            }

            lock (this.lockObject)
            {
                this.processedCount++;

                var progress = new ReportProgress
                {
                    Message            = $"{revs.TfsInfo.Title}",
                    WorkItemsProcessed = this.processedCount,
                    TotalCount         = this.totalCount
                };

                this.broadcastService.ReportProgress(progress);
            }

            return(revs.TfsInfo);
        }
 internal PlayGamesAchievement(ReportProgress progressCallback)
 {
     mId = string.Empty;
     mLastModifiedTime = new DateTime(1970, 1, 1, 0, 0, 0, 0);
     mTitle            = string.Empty;
     mRevealedImageUrl = string.Empty;
     mUnlockedImageUrl = string.Empty;
     mDescription      = string.Empty;
     base._002Ector();
     mProgressCallback = progressCallback;
 }
Ejemplo n.º 10
0
        void ReadStdErr()
        {
            var            buffer   = new char[1];
            ReportProgress progress = new ReportProgress(AVRdudeWorker.ReportProgress);

            while (process.StandardError.Read(buffer, 0, 1) > 0 && AVRdudeWorker.IsBusy)
            {
                try { form1.Invoke(progress, new object[] { 0, new string(buffer) }); }
                catch { Errors.Add("Program output truncated!"); }
            }
        }
 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));
         }
     });
 }
Ejemplo n.º 12
0
 /// <summary>
 /// 建構式,將Validator的Validate方法參數傳入
 /// </summary>
 /// <param name="ValidatorPairs"></param>
 /// <param name="OutputFile"></param>
 /// <param name="OutputOptions"></param>
 public OutputBuilder(IEnumerable<ValidatePair> ValidatorPairs,
     string OutputFile,
     OutputOptions OutputOptions,
     ReportProgress ReportProgress)
 {
     //初始化從Validator傳來的參數
     mValidatorPairs = ValidatorPairs.ToList();
     mOutputFile = OutputFile;
     //預設讀取第一個Excel
     mSheet = new SheetHelper(mValidatorPairs[0].DataFile, mValidatorPairs[0].DataSheet);
     mCurrentPair = mValidatorPairs[0];
     mReportProgress = ReportProgress;
 }
Ejemplo n.º 13
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);
         }
     }
 }
Ejemplo n.º 14
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);
        }
Ejemplo n.º 15
0
        protected void LoadParameterizedStreamContent(string parameter, string format)
        {
            long end = Environment.TickCount;

            try
            {
                using (Stream DerivedFileStream = ObtainStream(parameter))
                {
                    ReportProgress ReportProgress = delegate()
                    {
                        if (Environment.TickCount - end > 25)
                        {
                            ConsoleUtils.ProgressBarShow((uint)DerivedFileStream.Position, (uint)DerivedFileStream.Length, this.Notification);
                            end = Environment.TickCount;
                        }
                    };


                    ConsoleUtils.ProgressBarShow((uint)DerivedFileStream.Position, (uint)DerivedFileStream.Length, this.Notification);
                    switch (format.ToLowerInvariant())
                    {
                    case "text/csv":
                        ParseAsCsvStream(DerivedFileStream, ReportProgress); break;

                    case "text/xml":
                        ParseAsXmlStream(DerivedFileStream, ReportProgress); break;

                    default:
                        if (!ParseAsOtherStream(DerivedFileStream, ReportProgress, format))
                        {
                            HostContext.AddUnhandeldException(new Exception(string.Format("Unsupported fileformat: {0}", this)));
                        }
                        break;
                    }
                    ConsoleUtils.ProgressBarHide(this.ReadyState);
                }
            }
            catch (IOException e)
            {
                //Trace.TraceError("Error opening: {0}", Filename);
                e.Source += this.ToString();
                HostContext.AddUnhandeldException(e);
            }
            catch (Exception e)
            {
                //Trace.TraceError("Unhandeld exception {0}", e);
                e.Source += this.ToString();
                HostContext.AddUnhandeldException(new SystemException(string.Format("Unhandeld exception occured on {0} {1}", parameter, format), e));
            }
        }
Ejemplo n.º 16
0
 private async void Progress_ProgressChanged(object sender, ReportProgress e)
 {
     if (!Dispatcher.CheckAccess())
     {
         await Dispatcher.BeginInvoke((Action)(() =>
         {
             UpdateProgress(e.Percent, e.Progress, e.SiteReady);
         }));
     }
     else
     {
         UpdateProgress(e.Percent, e.Progress, e.SiteReady);
     }
 }
Ejemplo n.º 17
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);
 }
Ejemplo n.º 18
0
        public WaitingDialog(Func <IProgress <Tuple <string, int> >, CancellationToken, object> worker_func, Func <string, string> format_label)
        {
            if (format_label == null)
            {
                format_label = s => String.Format("Currently Processing {0}. Please Wait.", s);
            }
            m_cancellation = new CancellationTokenSource();
            CancellationToken token = m_cancellation.Token;

            m_progress                   = new ReportProgress(SetProgress, token, format_label);
            m_worker                     = new BackgroundWorker();
            m_worker.DoWork             += (sender, e) => Result = worker_func(m_progress, token);
            m_worker.RunWorkerCompleted += RunWorkerCompletedCallback;
            InitializeComponent();
            SetProgress(String.Empty, 0);
        }
        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.");
                }
            }
        }
Ejemplo n.º 20
0
        public WebDownload(string url, ReportProgress progress = null)
        {
            using(WebClient client = new WebClient())
            {
                var req = WebRequest.CreateHttp(url);
                using (var response = req.GetResponse())
                {
                    var fileSize = response.ContentLength;

                    FileName = response.ResponseUri.Segments.Last();

                    var part = new byte[1024 * 1024];

                    using(var stream = response.GetResponseStream())
                    using(var ms = new MemoryStream())
                    {
                        //stream.CopyTo(ms)

                        int len;

                        do
                        {
                            len = stream.Read(part, 0, part.Length);
                            ms.Write(part, 0, len);

                            System.Diagnostics.Debug.WriteLine(len);

                            if (progress != null)
                            {
                                if (fileSize > 0)
                                {
                                    long percentage = ms.Length * 100;
                                    percentage /= fileSize;

                                    progress((int)percentage);
                                }
                            }

                        } while (len > 0);

                        Content = ms.ToArray();
                    }
                }
            }
        }
Ejemplo n.º 21
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);
            }
        }
 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);
         }
     };
 }
Ejemplo n.º 23
0
        public SwitcherControl(System.Windows.Threading.Dispatcher dispatcher, ReportView reportProgrammView, ReportProgress progress)
        {
            m_switcherMonitor = new SwitcherMonitor();
            m_switcherMonitor.SwitcherDisconnected += new SwitcherEventHandler((s, a) => dispatcher.Invoke((Action)(() => SwitcherDisconnected())));
            m_mixEffectBlockMonitor = new MixEffectBlockMonitor();
            m_mixEffectBlockMonitor.TransitionPositionChanged += new SwitcherEventHandler((s, a) => dispatcher.Invoke((Action)(() => UpdateSliderPosition())));
            m_mixEffectBlockMonitor.InTransitionChanged       += new SwitcherEventHandler((s, a) => dispatcher.Invoke((Action)(() => OnInTransitionChanged())));

            m_switcherDiscovery = new CBMDSwitcherDiscovery();
            if (m_switcherDiscovery == null)
            {
                MessageBox.Show("Could not create Switcher Discovery Instance.\nATEM Switcher Software may not be installed.", "Error");
                Environment.Exit(1);
            }

            SwitcherDisconnected();     // start with switcher disconnected
            _reportProgrammView = reportProgrammView;
            _progress           = progress;
        }
Ejemplo n.º 24
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);
         }
     }
 }
Ejemplo n.º 25
0
 /// <summary>
 /// 进度条
 /// </summary>
 /// <param name="progress"></param>
 private void ReportProgressHandler(double progress)
 {
     if (this.progressBar.InvokeRequired)
     {
         ReportProgress d = new ReportProgress(ReportProgressHandler);
         this.progressBar.Invoke(d, new object[] { progress });
     }
     else
     {
         int value = (int)((progress + 1) * 100 / (this.grabFrames.MediaInfo.Duration * this.grabFrames.MediaInfo.FPS));
         if (value >= 100)
         {
             this.progressBar.Value   = 0;
             this.progressBar.Visible = false;
             SetResult(true);
             this.btnSelect.Enabled = true;
         }
         this.progressBar.Value = value;
     }
 }
Ejemplo n.º 26
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();
     }
 }
Ejemplo n.º 27
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;
        }
Ejemplo n.º 29
0
        private string StartPanoCaptureProcessor(IEnumerable <string> inputFiles, ReportProgress argProgress, bool crop)
        {
            var files = inputFiles.Where(f => f != null && (f.EndsWith(".jpeg") || f.EndsWith(".jpg") || f.EndsWith(".tif") || f.EndsWith(".tiff")));

            if (!files.Any())
            {
                return(null);
            }

            var outputFolder = Path.GetDirectoryName(inputFiles.First());

            var outputFileName = files.Last().Split('.').First() + "-pano.tif";
            var outputFile     = Path.Combine(outputFolder, outputFileName);

            var builtFile = new PanoramaBuilder(outputFile, inputFiles.ToArray())
                            .SetHuginBinPath(_settings.HuginBinPath)
                            .SetTempDir(outputFolder)
                            .SetLogDir(_logDir)
                            .ConfigureProgressUpdater((update) => argProgress(update.StepNumber, update.StepTotal, update.StepText))
                            .Build()
                            .GetGeneratedFile();

            return(builtFile);
        }
Ejemplo n.º 30
0
 private void ReportProgressHandler(double progress)
 {
     if (this.progressPanel1.ProgressBar.InvokeRequired)
     {
         ReportProgress d = new ReportProgress(ReportProgressHandler);
         this.progressPanel1.ProgressBar.Invoke(d, new object[] { progress });
     }
     else
     {
         int value = (int)(100 * (progress + 1) / this._grabFrames.MediaInfo.Duration);
         if (value >= 100)
         {
             value = 100;
             this.progressPanel1.IsVisible(false);
             this.snapShots.LoadFrames(_grabFrames.Frames);
             this.btnSave.Enabled      = true;
             this.btnVideoPlay.Enabled = true;
             this.btnVideoStop.Enabled = true;
             this.btnVideoSave.Enabled = true;
             InitilizeFps();
         }
         this.progressPanel1.ProgressBar.Value = value;
     }
 }
Ejemplo n.º 31
0
        public static void AddItem(NewItem param, ReportProgress progressReport)
        {
            // 0%
            ReportProgress(progressReport, 0);

            string[] sc = {";", " ", ","};

            string[] tags = param.Tags.Split(sc, StringSplitOptions.RemoveEmptyEntries);

            // check uri
            bool isUriLocal = IsUriLocal(param.Uri);

            /*
             * Local URI
             *  [keep local] store to database
             *  [not keep] only link
             *
             * Web file
             *  [keep local] store to database
             *  [not keep] only link
            */

            var item = new DocItem()
            {
                Uri = param.Uri,
                Name = param.Name,
                Rating = 3
            };

            // Download file
            // 90%
            if (isUriLocal)
            {
                // local filesystem

                item.FileName = Path.GetFileName(param.Uri);
                item.HashCode = HashCalc.GetHash(param.Uri);
            }
            else
            {
                var download = new WebDownload(param.Uri, (int p, string d) =>
                {
                    int percentage = p * 90;
                    percentage /= 100;
                    ReportProgress(progressReport, percentage);
                });

                item.FileName = download.FileName;
                item.HashCode = HashCalc.GetHash(download.Content);
            }
            ReportProgress(progressReport, 90);

            // add DB record
            // 100%
            using (var db = new AppDataBase())
            using(var transaction = db.Database.BeginTransaction())
            {
                // try to select existing tags
                //var registeredTags = db.Tags.Select(x => x.Name).Intersect(tags, StringComparer.InvariantCultureIgnoreCase).ToArray();

                var registeredTags = from i in db.Tags
                                     where tags.Contains(i.Name.ToLower())
                                     select i;

                // save new tags
                var newTags = tags.Except(registeredTags.Select(x => x.Name), StringComparer.InvariantCultureIgnoreCase);

                item.Tags = new List<Tag>();

                // add link to existing tags
                foreach(var i in registeredTags)
                {
                    item.Tags.Add(i);
                }

                // add new tags and link with document
                foreach(var i in newTags)
                {
                    var newTagRecord = db.Tags.Add(new Tag()
                    {
                        Name = i
                    });

                    item.Tags.Add(newTagRecord);
                }

                // save tags
                db.SaveChanges();

                // add item
                db.Items.Add(item);

                // save item
                db.SaveChanges();

                transaction.Commit();
            }
        }
Ejemplo n.º 32
0
 private static void ReportProgress(ReportProgress progressReport, int percentage)
 {
     if (progressReport != null)
     {
         progressReport(percentage);
     }
 }
Ejemplo n.º 33
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);
                }
            }
        }
Ejemplo n.º 34
0
 private void BackgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
 {
     ReportProgress?.Invoke(this, e);
 }
Ejemplo n.º 35
0
        /// <summary>
        /// After configuring the .cscfg file, this function publishes the package to Azure
        /// </summary>
        public bool PublishServiceToAzure(ReportProgress reportDelegate, ReDoInitializeDB reDoInitializeDB)
        {
            this.reportDelegate = reportDelegate;

            report(10, "Creating a broker object ...");

            AzureManagementBroker broker;

            try
            {
                // Create hostedservice if it does not exist in Azure
                broker = new AzureManagementBroker(_settings.DeploymentName,
                                                   _settings.ManagementCert.Thumbprint,
                                                   new Guid(_settings.SubscriptionId),
                                                   _settings.ServiceName,
                                                   _settings.StorageName,
                                                   _settings.StorageKey,
                                                   null,
                                                   null);

                try
                {
                    broker.CreateHostedServiceIfNotExist(_settings.ServiceName, _settings.Location);
                }
                catch (Exception ex)
                {
                    report(10, "Error: " + ex.Message + ". Please check and try later.");
                    return false;
                }

                report(20, "Adding the certificate to service ...");

                IAsyncAzureOperation opServiceCert = broker.AddCertificateToService(_settings.ServiceCert, Password, CertificateLocation.AzureManagement);
                opServiceCert.WaitForCompletion(TimeSpan.MaxValue);
                if (opServiceCert.GetOperationStatus() == AzureOperationStatus.Failed)
                {
                    report(20, "Error: " + opServiceCert.ErrorMessage());
                    return false;
                }

                /***************************************************************************************
                //**** Create two default firewall filters for the newly-created SQL server
                //1:   0.0.0.0  to 0.0.0.0
                //2.   IP address to IP address
                ***************************************************************************************/
                report(30, "Creating firewall rules ...");

                broker.CreateFirewallRule(_settings.SqlServerName);
                string localIP = broker.CreateFirewallRuleWithIPDetect(_settings.SqlServerName, "FirewallWithIP");
                string[] IPRange = GenerateIPRange(localIP);
                broker.CreateFirewallRule(_settings.SqlServerName, "RangeFireWall", IPRange[0], IPRange[1]);

                // If a user sets InitializeDBOnline = false, then do the initializeDB from local machine
                // or else, create database and InitializeDB at Azure
                if (!_settings.InitializeDBOnline)
                {
                    report(40, "Creating database ...");

                    // Create a new database under the newly-created SQL Server
                    try
                    {
                        List<string> listOfDB = GetExistingDatabases(_settings.SqlServerName, _settings.SqlServerUser, _settings.SqlServerPassword);

                        // If no database named as settings.DBName is found, create one
                        if (listOfDB.IndexOf(_settings.DBName) == -1)
                        {
                            CreateDatabase(_settings.SqlServerName, _settings.DBName, _settings.SqlServerUser, _settings.SqlServerPassword, Maxsize);
                        }
                    }
                    catch (SqlException e)
                    {
                        report(40, "Error from SQL server " + e.Server + ": " + e.Message);
                        return false;
                    }
                    catch (Exception e)
                    {
                        report(40, "Error: " + e.Message);
                        return false;
                    }

                    report(50, "Initializing database ...");

                    if (DoInitializeDB(report, reDoInitializeDB, true) == false)
                    {
                        report(50, "Error: Initializing database failed. Please check AzureSampleService.log for details.");
                        return false;
                    }
                }

                // Start to deploy the service
                AzureDeployment deployment = new AzureDeployment();

                FileInfo localFile;

                // Verify whether CspkgFile exists
                if (File.Exists(CspkgFile))
                {
                    // Upload package file to Azure first
                    localFile = new FileInfo(CspkgFile);
                }
                else
                {
                    report(50, "Error: Please copy the .cspkg file to the current working folder.");
                    return false;
                }

                try
                {
                    report(70, "Copying HPC package to blob storage ...");

                    broker.CopyHpcPackageToBlobStorage(localFile, DestinationName);

                    report(90, "Creating Azure deployment ...");

                    // Start to deploy the service now.
                    IAsyncAzureOperation op = broker.CreateAzureDeployment(File.ReadAllText(_settings.ServiceCscfg), DestinationName, out deployment);
                    op.WaitForCompletion(TimeSpan.MaxValue);
                    if (op.GetOperationStatus() != AzureOperationStatus.Succeeded)
                    {
                        report(90, "Error: " + op.ErrorMessage());
                        return false;
                    }

                    // Delete the service cscfg file
                    File.Delete((_settings.ServiceCscfg));
                }
                catch (Exception ex)
                {
                    report(90, "Error: " + ex.Message);
                    return false;
                }
            }
            catch (Exception exception)
            {
                report(90, "Error: " + exception.Message);
                return false;
            }

            report(100, "Client Portion Complete (Azure deploying now).");
            return true;
        }
Ejemplo n.º 36
0
        public PluginActionImageResult StartEditingTask(FileHandlingPluginTask argPluginTask, ReportProgress argProgress)
        {
            var paths = new List <string>();

            if (argPluginTask.PluginAction.Identifier == _openConfiguratorAction.Identifier)
            {
                // Clear down after last run.
                var dir = new DirectoryInfo(TempImagesPath);
                foreach (FileInfo file in dir.GetFiles())
                {
                    file.Delete();
                }

                // Populate with new temp images.
                foreach (var path in argPluginTask.Files)
                {
                    var filename = Path.GetFileName(path);
                    var tempPath = Path.Combine(TempImagesPath, filename);
                    File.Copy(path, tempPath);

                    paths.Add(tempPath);
                }

                StartPostCaptureStudio(paths);

                return(new PluginActionImageResult());
            }

            if (argPluginTask.PluginAction.Identifier == _runProcessAction.Identifier)
            {
                StartPostCaptureProcessor(argPluginTask);
                return(new PluginActionImageResult(argPluginTask.Files.ToArray()));
            }

            return(new PluginActionImageResult());
        }
Ejemplo n.º 37
0
        /// <summary>
        /// This is a wrapper function 
        /// if there is an existing database in use, let the user choose whether
        /// to forcibly initialize it
        /// </summary>
        private bool DoInitializeDB(ReportProgress report, ReDoInitializeDB reDoInitializeDB, bool firstTry)
        {
            // Initialize database for service deployment
            int status = 0;

            // Force at the 2nd time
            bool forceOverride = !firstTry;

            status = InitializeDB(forceOverride);

            if (status == 0)
            {
                // Succeed
                return true;
            }
            // Need user's decision on whether to forcibly initialize database
            else if (status == -2)
            {
                // Pop up a messageBox for user to decide whether to forcibly initialize the database
                bool willRedoInitializeDB = ((bool)_form.Invoke(reDoInitializeDB) && firstTry);

                if (willRedoInitializeDB == true)
                {
                    return DoInitializeDB(report,reDoInitializeDB, false);
                }
                else
                {
                    return false;
                }
            }
            else
            {
                return false;
            }
        }
Ejemplo n.º 38
0
 public void SetReportProgressDelegate(ReportProgress reportProress)
 {
     this.m_ReportProgress = reportProress;
 }
 internal PlayGamesAchievement(ReportProgress progressCallback)
 {
     mProgressCallback = progressCallback;
 }
Ejemplo n.º 40
0
        public void Scan(string baseDir, string[] extensions, ReportProgress progressReport)
        {
            const int MAX_THREADS = 50;
            var dirs = new Stack<string>();
            dirs.Push(baseDir);

            Semaphore sync = new Semaphore(MAX_THREADS, MAX_THREADS);

            while(dirs.Count > 0)
            {
                var dir = dirs.Pop();

                if (progressReport != null)
                {
                    progressReport(-1, string.Format(Properties.Resources.FormatAddDir, dir));
                }

                try
                {
                    foreach(var i in Directory.EnumerateDirectories(dir))
                    {
                        dirs.Push(i);
                    }
                }
                catch
                { }

                try
                {
                    var files = EnumFiles(dir, extensions);

                    foreach(var f in files)
                    {
                        System.Diagnostics.Debug.WriteLine(f);

                        while (!sync.WaitOne())
                        {

                        }

                        while (!ThreadPool.QueueUserWorkItem((object a) =>
                        {
                            try
                            {
                                string fileName = a as string;
                                if (fileName != null)
                                {
                                    ProcessSingleFile(fileName);
                                }
                            }
                            finally
                            {
                                sync.Release();
                            }

                        }, f)) ;

                    }
                }
                catch
                { }
            }

            for(int i = 0; i < MAX_THREADS; )
            {
                if (sync.WaitOne(-1))
                {
                    i++;
                }
            }
        }
Ejemplo n.º 41
0
        public void Add(IEnumerable<DocItem> items, string commonTags, ReportProgress progressReport)
        {
            string[] sc = { ";", " ", "," };

            string[] tags = commonTags.Split(sc, StringSplitOptions.RemoveEmptyEntries);

            using(var db = new AppDataBase())
            {
                var registeredTags = from i in db.Tags
                                     where tags.Contains(i.Name.ToLower())
                                     select i;

                List<Tag> allTags = new List<Tag>(registeredTags);

                if (progressReport != null)
                {
                    progressReport(-1, Properties.Resources.AddTags);
                }

                using (var transaction = db.Database.BeginTransaction())
                {
                    var newTags = tags.Except(registeredTags.Select(x => x.Name), StringComparer.InvariantCultureIgnoreCase);

                    // add new tags and link with document
                    foreach (var i in newTags)
                    {
                        var newTagRecord = db.Tags.Add(new Tag()
                        {
                            Name = i
                        });

                        allTags.Add(newTagRecord);
                    }

                    db.SaveChanges();

                    transaction.Commit();
                }

                using (var transaction = db.Database.BeginTransaction())
                {
                    int totalItems = items.Count();
                    int c = 0;

                    foreach (var i in items)
                    {
                        c++;

                        i.Tags = allTags;
                        db.Items.Add(i);

                        if (progressReport != null)
                        {
                            int percentage = c * 100;
                            percentage /= totalItems;

                            progressReport(percentage, string.Format(Properties.Resources.FormatAddFile, i.FileName));
                        }
                    }

                    progressReport(-1, Properties.Resources.MsgCommitingChanges);

                    db.SaveChanges();

                    transaction.Commit();
                }
            }
        }
Ejemplo n.º 42
0
 public void SetReportProgressDelegate(ReportProgress reportProress)
 {
     this.m_ReportProgress = reportProress;
     this.m_ProgressHandle.SetReportProgressDelegate(reportProress);
 }