public void InvokeIsInitialisedFalseThrowsContractException()
        {
            // Arrange
            var jobResult = new JobResult();
            var sut = new DefaultPlugin();
            //sut.Initialise(new DictionaryParameters(), new Logger(), true);

            // Act
            sut.Invoke(new DictionaryParameters(), jobResult);

            // Assert
            // N/A
        }
示例#2
0
		private void AddJob(DeviceTask.AppTask task)
		{
			if (_Jobs == null) {
				_Jobs = new ConcurrentDictionary<string, JobResult> ();
			}				

			var temp = new JobResult { IsRunning = true };

			_Jobs.AddOrUpdate(task.JobID,  temp,  (z, x) => {
				return temp;
			});

			this._Task = task;
		}
        public void InvokeWithIsActiveFalseReturnsFalse()
        {
            // Arrange
            var jobResult = new JobResult();
            var logger = new Logger();
            var sut = new DefaultPlugin();
            sut.Initialise(new DictionaryParameters(), logger, false);

            // Act
            var result = sut.Invoke(new DictionaryParameters(), jobResult);

            // Assert
            Assert.IsFalse(result);
        }
        private void AddJob(AppTask task)
		{
			if (_Jobs == null) {
				_Jobs = new ConcurrentDictionary<string, JobResult> ();
				var intentFilter = new IntentFilter (TaskBinder.JobEnded){Priority = (int)IntentFilterPriority.HighPriority};
				Xamarin.Forms.Forms.Context.RegisterReceiver (this, intentFilter);
			}				

			var temp = new JobResult { IsRunning = true };

			_Jobs.AddOrUpdate(task.JobID,  temp,  (z, x) => {
				return temp;
			});
		}
 public JobResult DeleteSnapshotSubtree(string snapshotId)
 {
     try
     {
         Log.WriteStart("'{0}' DeleteSnapshotSubtree", ProviderSettings.ProviderName);
         JobResult result = VirtualizationForPC.DeleteSnapshotSubtree(snapshotId);
         Log.WriteEnd("'{0}' DeleteSnapshotSubtree", ProviderSettings.ProviderName);
         return(result);
     }
     catch (Exception ex)
     {
         Log.WriteError(String.Format("'{0}' DeleteSnapshotSubtree", ProviderSettings.ProviderName), ex);
         throw;
     }
 }
 public JobResult EjectDVD(string vmId)
 {
     try
     {
         Log.WriteStart("'{0}' EjectDVD", ProviderSettings.ProviderName);
         JobResult result = VirtualizationForPC.EjectDVD(vmId);
         Log.WriteEnd("'{0}' EjectDVD", ProviderSettings.ProviderName);
         return(result);
     }
     catch (Exception ex)
     {
         Log.WriteError(String.Format("'{0}' EjectDVD", ProviderSettings.ProviderName), ex);
         throw;
     }
 }
示例#7
0
 public JobResult ExpandVirtualHardDisk(string vhdPath, UInt64 sizeGB)
 {
     try
     {
         Log.WriteStart("'{0}' ExpandVirtualHardDisk", ProviderSettings.ProviderName);
         JobResult result = VirtualizationProvider.ExpandVirtualHardDisk(vhdPath, sizeGB);
         Log.WriteEnd("'{0}' ExpandVirtualHardDisk", ProviderSettings.ProviderName);
         return(result);
     }
     catch (Exception ex)
     {
         Log.WriteError(String.Format("'{0}' ExpandVirtualHardDisk", ProviderSettings.ProviderName), ex);
         throw;
     }
 }
示例#8
0
        /// <summary>
        /// Received a result for one of the jobs from a client
        /// </summary>
        public void ReceiveResult(JobResult result)
        {
            var success = _handlerManager.ProcessResult(result);

            // Update statistics
            _knownClients[result.ClientId].JobsInProgress--;
            if (success)
            {
                _knownClients[result.ClientId].TotalJobsProcessed++;
            }
            else
            {
                _knownClients[result.ClientId].TotalJobsFailed++;
            }
        }
示例#9
0
 public JobResult InsertDVD(string vmId, string isoPath)
 {
     try
     {
         Log.WriteStart("'{0}' InsertDVD", ProviderSettings.ProviderName);
         JobResult result = VirtualizationProvider.InsertDVD(vmId, isoPath);
         Log.WriteEnd("'{0}' InsertDVD", ProviderSettings.ProviderName);
         return(result);
     }
     catch (Exception ex)
     {
         Log.WriteError(String.Format("'{0}' InsertDVD", ProviderSettings.ProviderName), ex);
         throw;
     }
 }
        public void Subscribe_NullNotificationTriggersLogging()
        {
            var durableJobStorage  = A.Fake <IDurableJobQueue <int, object> >();
            var jobResultInspector = A.Fake <IJobResultInspector <int, int, object> >();
            var results            = new JobResult <int, int>[] { null };
            var observable         = results.ToObservable();
            var log = A.Fake <ILog>();

            using (var writer = new JobResultJournalWriter <int, int, object>(observable, jobResultInspector, durableJobStorage,
                                                                              log, Scheduler.Immediate))
            {
                A.CallTo(() => log.Error(CultureInfo.CurrentCulture, A <Action <FormatMessageHandler> > .Ignored))
                .MustHaveHappened(Repeated.Exactly.Times(results.Count(n => null == n)));
            }
        }
示例#11
0
 public JobResult RemoveKVPItems(string vmId, string[] itemNames)
 {
     try
     {
         Log.WriteStart("'{0}' RemoveKVPItems", ProviderSettings.ProviderName);
         JobResult result = VirtualizationProvider.RemoveKVPItems(vmId, itemNames);
         Log.WriteEnd("'{0}' RemoveKVPItems", ProviderSettings.ProviderName);
         return(result);
     }
     catch (Exception ex)
     {
         Log.WriteError(String.Format("'{0}' RemoveKVPItems", ProviderSettings.ProviderName), ex);
         throw;
     }
 }
 public JobResult ApplySnapshot(string vmId, string snapshotId)
 {
     try
     {
         Log.WriteStart("'{0}' ApplySnapshot", ProviderSettings.ProviderName);
         JobResult result = VirtualizationForPC.ApplySnapshot(vmId, snapshotId);
         Log.WriteEnd("'{0}' ApplySnapshot", ProviderSettings.ProviderName);
         return(result);
     }
     catch (Exception ex)
     {
         Log.WriteError(String.Format("'{0}' ApplySnapshot", ProviderSettings.ProviderName), ex);
         throw;
     }
 }
示例#13
0
        private MockDownloadJob GetJob_Successful(string songHash, string songDir)
        {
            var downloadResult = new DownloadResult(@"C:\Test", DownloadResultStatus.Success, 200);
            var zipResult      = new ZipExtractResult()
            {
                ResultStatus = ZipExtractResultStatus.Success
            };
            var finalResult = new JobResult()
            {
                SongHash = songHash, DownloadResult = downloadResult, ZipResult = zipResult, SongDirectory = songDir
            };
            var job = new MockDownloadJob(songHash, finalResult);

            return(job);
        }
 public JobResult DeleteVirtualMachineExtended(string vmId, string clusterName)
 {
     try
     {
         Log.WriteStart("'{0}' DeleteVirtualMachineExtended", ProviderSettings.ProviderName);
         JobResult result = VirtualizationProvider.DeleteVirtualMachineExtended(vmId, clusterName);
         Log.WriteEnd("'{0}' DeleteVirtualMachineExtended", ProviderSettings.ProviderName);
         return(result);
     }
     catch (Exception ex)
     {
         Log.WriteError(String.Format("'{0}' DeleteVirtualMachineExtended", ProviderSettings.ProviderName), ex);
         throw;
     }
 }
 public JobResult CreateVirtualHardDisk(string destinationPath, VirtualHardDiskType diskType, uint blockSizeBytes, UInt64 sizeGB)
 {
     try
     {
         Log.WriteStart("'{0}' CreateVirtualHardDisk", ProviderSettings.ProviderName);
         JobResult result = VirtualizationProvider.CreateVirtualHardDisk(destinationPath, diskType, blockSizeBytes, sizeGB);
         Log.WriteEnd("'{0}' CreateVirtualHardDisk", ProviderSettings.ProviderName);
         return(result);
     }
     catch (Exception ex)
     {
         Log.WriteError(String.Format("'{0}' CreateVirtualHardDisk", ProviderSettings.ProviderName), ex);
         throw;
     }
 }
 public JobResult InjectIPs(string vmId, GuestNetworkAdapterConfiguration guestNetworkAdapterConfiguration)
 {
     try
     {
         Log.WriteStart("'{0}' InjectIPs", ProviderSettings.ProviderName);
         JobResult result = VirtualizationProvider.InjectIPs(vmId, guestNetworkAdapterConfiguration);
         Log.WriteEnd("'{0}' InjectIPs", ProviderSettings.ProviderName);
         return(result);
     }
     catch (Exception ex)
     {
         Log.WriteError(String.Format("'{0}' InjectIPs", ProviderSettings.ProviderName), ex);
         throw;
     }
 }
示例#17
0
 public JobResult ConvertVirtualHardDisk(string sourcePath, string destinationPath, VirtualHardDiskType diskType)
 {
     try
     {
         Log.WriteStart("'{0}' ConvertVirtualHardDisk", ProviderSettings.ProviderName);
         JobResult result = VirtualizationProvider.ConvertVirtualHardDisk(sourcePath, destinationPath, diskType);
         Log.WriteEnd("'{0}' ConvertVirtualHardDisk", ProviderSettings.ProviderName);
         return(result);
     }
     catch (Exception ex)
     {
         Log.WriteError(String.Format("'{0}' ConvertVirtualHardDisk", ProviderSettings.ProviderName), ex);
         throw;
     }
 }
 public JobResult ChangeVirtualMachineState(string vmId, VirtualMachineRequestedState newState)
 {
     try
     {
         Log.WriteStart("'{0}' ChangeVirtualMachineState", ProviderSettings.ProviderName);
         JobResult result = VirtualizationForPC.ChangeVirtualMachineState(vmId, newState);
         Log.WriteEnd("'{0}' ChangeVirtualMachineState", ProviderSettings.ProviderName);
         return(result);
     }
     catch (Exception ex)
     {
         Log.WriteError(String.Format("'{0}' ChangeVirtualMachineState", ProviderSettings.ProviderName), ex);
         throw;
     }
 }
 public JobResult RenameVirtualMachine(string vmId, string name)
 {
     try
     {
         Log.WriteStart("'{0}' RenameVirtualMachine", ProviderSettings.ProviderName);
         JobResult result = VirtualizationForPC.RenameVirtualMachine(vmId, name);
         Log.WriteEnd("'{0}' RenameVirtualMachine", ProviderSettings.ProviderName);
         return(result);
     }
     catch (Exception ex)
     {
         Log.WriteError(String.Format("'{0}' RenameVirtualMachine", ProviderSettings.ProviderName), ex);
         throw;
     }
 }
示例#20
0
 public JobResult ExportVirtualMachine(string vmId, string exportPath)
 {
     try
     {
         Log.WriteStart("'{0}' ExportVirtualMachine", ProviderSettings.ProviderName);
         JobResult result = VirtualizationProvider.ExportVirtualMachine(vmId, exportPath);
         Log.WriteEnd("'{0}' ExportVirtualMachine", ProviderSettings.ProviderName);
         return(result);
     }
     catch (Exception ex)
     {
         Log.WriteError(String.Format("'{0}' ExportVirtualMachine", ProviderSettings.ProviderName), ex);
         throw;
     }
 }
示例#21
0
 public JobResult ModifyKVPItems(string vmId, KvpExchangeDataItem[] items)
 {
     try
     {
         Log.WriteStart("'{0}' ModifyKVPItems", ProviderSettings.ProviderName);
         JobResult result = VirtualizationProvider.ModifyKVPItems(vmId, items);
         Log.WriteEnd("'{0}' ModifyKVPItems", ProviderSettings.ProviderName);
         return(result);
     }
     catch (Exception ex)
     {
         Log.WriteError(String.Format("'{0}' ModifyKVPItems", ProviderSettings.ProviderName), ex);
         throw;
     }
 }
示例#22
0
        public void TestResultHasErrorWhenExtractorFails()
        {
            object    data             = new object();
            string    errorMessage     = "Expected exception.";
            string    extractorID      = "extractor_175";
            Exception exceptionToThrow = new Exception(errorMessage);

            Mock <IExtractor <object> > extractorMock = new Mock <IExtractor <object> >();
            Mock <ILoader <object> >    loaderMock    = new Mock <ILoader <object> >();

            extractorMock.Setup(_ => _.Extract()).Throws(exceptionToThrow);
            extractorMock.Setup(_ => _.GetID()).Returns(extractorID);

            ProcessorBuilder <object> builder = new ProcessorBuilder <object>(loaderMock.Object);

            IProcessor faillingProcessor =
                builder.AddSource("FailingProcessor", extractorMock.Object).Build();

            IEnumerable <Task <JobResult> > tasks = faillingProcessor.Process();

            Task.WaitAll(new List <Task>(tasks).ToArray());

            IEnumerator <Task <JobResult> > enumerator = tasks.GetEnumerator();

            Assert.IsTrue(enumerator.MoveNext());

            Task <JobResult> result = enumerator.Current;

            Assert.IsTrue(result.IsCompletedSuccessfully);

            JobResult jobResult = result.Result;

            Assert.IsNotNull(jobResult);
            Assert.IsFalse(jobResult.CompletedWithouErrors);
            Assert.IsNotNull(jobResult.Errors);

            IEnumerator <JobException> errorsEnumerator = jobResult.Errors.GetEnumerator();

            Assert.IsTrue(errorsEnumerator.MoveNext());

            JobException jobException = errorsEnumerator.Current;

            Assert.AreEqual(Phase.EXTRACTION, jobException.JobPhase);
            Assert.AreEqual(extractorID, jobException.FaillingComponentID);

            Assert.IsFalse(errorsEnumerator.MoveNext());
            Assert.IsFalse(enumerator.MoveNext());
        }
示例#23
0
        public async Task ReleaseJobAsync(Guid jobId, JobResult result)
        {
            const string sql = @"
                BEGIN TRAN

                    UPDATE Jobs WITH (TABLOCK, HOLDLOCK)
                        SET 
                            State = @State, 
                            StatusInfo = @StatusInfo, 
                            DueTime = @DueTime,
                            ExecTime = @ExecTime

                    WHERE 
                        Id = @Id

                    IF @State = @FinishedState
                        UPDATE Jobs WITH (TABLOCK, HOLDLOCK)
                            SET 
                                WaitCount = WaitCount - 1 
                            WHERE 
                                PrevId = @Id or 
                                Id = (
                                    select 
                                        top 1 NextId 
                                    From 
                                        Jobs WITH (TABLOCK, HOLDLOCK)
                                    Where 
                                        Id = @Id
                                )

                COMMIT";

            using (var connection = new SqlConnection(_connectionString))
            {
                await connection.OpenWithRetryAsync(conn =>
                                                    conn.ExecuteAsync(sql,
                                                                      new
                {
                    State         = (int)result.State,
                    StatusInfo    = result.StatusInfo,
                    DueTime       = GetSqlSafeDate(result.DueTime),
                    ExecTime      = result.ExecutionTime.Ticks,
                    FinishedState = (int)ExecutionState.Finished,
                    Id            = jobId
                })
                                                    );
            }
        }
示例#24
0
        public override async Task <JobResult> Execute(DBContext db, SqlService sql, AppSettings settings)
        {
            var doc  = new HtmlDocument();
            var body = await new HttpClient().GetStringAsync(new Uri(
                                                                 "https://forum.step-project.com/topic/13894-dyndolod-beta-for-skyrim-special-edition-and-skyrim-vr-279/"));

            doc.LoadHtml(body);

            var matches =
                doc.DocumentNode
                .Descendants()
                .Where(d => d.NodeType == HtmlNodeType.Element && d.Attributes.Contains("href"))
                .Select(d => d.Attributes["href"].Value)
                .Select(m => Uri.TryCreate(m.ToString(), UriKind.Absolute, out var result) ? result : null)
                .Where(uri => uri != null && uri.Host == "mega.nz")
                .Select(url => new Job()
            {
                Payload = new IndexJob
                {
                    Archive = new Archive
                    {
                        Name  = Guid.NewGuid() + ".7z",
                        State = new MegaDownloader.State
                        {
                            Url = url.ToString()
                        }
                    }
                }
            })
                .ToList();


            foreach (var job in matches)
            {
                var key   = ((MegaDownloader.State)((IndexJob)job.Payload).Archive.State).PrimaryKeyString;
                var found = await db.DownloadStates.AsQueryable().Where(s => s.Key == key).FirstOrDefaultAsync();

                if (found != null)
                {
                    continue;
                }

                Utils.Log($"Queuing {key} for indexing");
                await db.Jobs.InsertOneAsync(job);
            }

            return(JobResult.Success());
        }
        public void InvokeWithMissingWorkingDirectoryThrowsContractException()
        {
            // Arrange
            var parameters = new DictionaryParameters();
            parameters.Add("CommandLine", "arbitrary-string");
            parameters.Add("missing-parameter-WorkingDirectory", "arbitrary-string");
            parameters.Add("Credential", CredentialCache.DefaultCredentials);
            var jobResult = new JobResult();

            // Act
            var sut = new ProgrammePlugin();
            var result = sut.Invoke(parameters, jobResult);

            // Assert
            // N/A
        }
示例#26
0
        private MockDownloadJob GetJob_FailedExtraction_Source(string songHash, string songDir)
        {
            var       downloadResult = new DownloadResult(@"C:\Test", DownloadResultStatus.Success, 200);
            Exception zipException   = new IOException();
            var       zipResult      = new ZipExtractResult()
            {
                ResultStatus = ZipExtractResultStatus.SourceFailed, Exception = zipException
            };
            var finalResult = new JobResult()
            {
                SongHash = songHash, DownloadResult = downloadResult, ZipResult = zipResult, SongDirectory = null
            };
            var job = new MockDownloadJob(songHash, finalResult);

            return(job);
        }
示例#27
0
        /// <summary>
        /// Received a result for one of the jobs from a client
        /// </summary>
        public void ReceiveResult(JobResult result)
        {
            var success = _handlerManager.ProcessResult(result);
            // Update statistics
            var clientInfo = _clientManager.GetOrCreate(result.ClientId);

            clientInfo.JobsInProgress--;
            if (success)
            {
                clientInfo.TotalJobsProcessed++;
            }
            else
            {
                clientInfo.TotalJobsFailed++;
            }
        }
示例#28
0
        public override void Start()
        {
            Dictionary <long, ElectricalHierarchyData> parentChild = GDAHelper.GetContainerHeirarchy(GdaQuery, new List <ModelCode>(), HierarchyNetworkType);

            containerHierarchyTree = new HierarchicalFilter(parentChild, HierarchyNetworkType);
            lfMeasureQuality       = new Dictionary <long, MeasurementValueQuality>();

            if (NetworkModelQuery == null)
            {
                NetworkModelQuery = JobService.OpenNetworkModelQuery();
            }

            JobResult result = CreateResult();

            ResultsReady(Guid, result);
        }
示例#29
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="func"></param>
        /// <param name="method"></param>
        /// <returns></returns>
        private JobResult Execute(Func <bool> func, [CallerMemberName] string method = null)
        {
            var result = new JobResult {
                Code = 200
            };

            try
            {
                result.Code = func.Invoke() ? 200 : 400;
            }
            catch (Exception ex)
            {
                result.Msg = ex.Message;
            }
            return(result);
        }
示例#30
0
        private void DownloadThread()
        {
            Thread.Sleep(10);

            this.ThreadSafe(new MethodInvoker(delegate()
            {
                listViewStatus.Items.Clear();
                foreach (DownloadRequest objDownloadRequest in _objDownloadRequests)
                {
                    string strFileName           = Path.GetFileName(objDownloadRequest.Source);
                    ListViewItem objListViewItem = new ListViewItem(objDownloadRequest.Destination);
                    objListViewItem.SubItems.Add("Queued");
                    listViewStatus.Items.Add(objListViewItem);
                }

                buttonCancel.Enabled        = _objDownloadDialogSettings.AllowCancel;
                buttonPauseContinue.Enabled = _objDownloadDialogSettings.AllowPause;
                this.Refresh();
            }));

            _intTaskIndex = 0;
            _intTaskCount = _objDownloadRequests.Count;
            _objJobResult = null;

            IEnumerable <ITask> objTasks = _objDownloadRequests.GetTasks();

            _objJob                      = new Job(objTasks);
            _objJob.TaskBegin           += new Job.OnTaskBeginDelegate(objDownloadJob_TaskBegin);
            _objJob.TaskEnd             += new Job.OnTaskEndDelegate(objDownloadJob_TaskEnd);
            _objJob.JobEnd              += new Job.OnJobEndDelegate(objDownloadJob_JobEnd);
            _objJob.TaskProgressChanged += new Job.TaskProgressChangedDelegate(objDownloadJob_TaskProgressChanged);
            _objJob.Start();
            _objJob.Wait();

            _objDownloadResults = new DownloadResultList();
            if (_objJobResult != null)
            {
                _objDownloadResults = new DownloadResultList(_objJobResult.TaskResults);
            }

            Thread.Sleep(10);

            this.ThreadSafe(new MethodInvoker(delegate()
            {
                this.Close();
            }));
        }
示例#31
0
        public void Successful()
        {
            var downloader = GetDefaultDownloader();
            var testHash   = "A7SDF6A86SDF9ASDF";

            var song     = new PlaylistSong(testHash, "Successful Song", "fff2", "Other");
            var songPath = Path.Combine(TestSongsDir, "fff2 (Successful Song)");

            downloader.HistoryManager.TryAdd(song, 0);

            var testDownloadResult         = new DownloadResult(songPath, DownloadResultStatus.Success, 200);
            ZipExtractResult testZipResult = new ZipExtractResult()
            {
                CreatedOutputDirectory = true,
                Exception       = null,
                OutputDirectory = songPath,
                ExtractedFiles  = new string[] { "info.dat", "expert.dat", "song.egg" },
                ResultStatus    = ZipExtractResultStatus.Success,
                SourceZip       = "fff2.zip"
            };
            var testJob = new JobResult()
            {
                DownloadResult = testDownloadResult,
                ZipResult      = testZipResult,
                BeatSaverHash  = song.Hash,
                Song           = song,
                SongDirectory  = null
            };
            var recentPlaylist = PlaylistManager.GetPlaylist(BuiltInPlaylist.BeatSyncRecent);

            recentPlaylist.TryAdd(song);
            var bSaberPlaylist = PlaylistManager.GetPlaylist(BuiltInPlaylist.BeastSaberCurator);

            bSaberPlaylist.TryAdd(song);
            // Verify setup
            Assert.IsTrue(recentPlaylist.Songs.Any(s => song.Hash.Equals(s.Hash)));
            Assert.IsTrue(bSaberPlaylist.Songs.Any(s => song.Hash.Equals(s.Hash)));
            Assert.IsTrue(downloader.HistoryManager.TryGetValue(song.Hash, out var entry));
            Assert.AreEqual(HistoryFlag.None, entry.Flag);

            // Run test
            downloader.ProcessJob(testJob);
            Assert.IsTrue(downloader.HistoryManager.TryGetValue(song.Hash, out entry));
            Assert.AreEqual(HistoryFlag.Downloaded, entry.Flag);
            Assert.IsTrue(recentPlaylist.Songs.Any(s => song.Hash.Equals(s.Hash)));
            Assert.IsTrue(bSaberPlaylist.Songs.Any(s => song.Hash.Equals(s.Hash)));
        }
 public JobResult ExecuteCustomPsScript(string script)
 {
     try
     {
         Log.WriteStart("'{0}' ExecuteCustomPsScript", ProviderSettings.ProviderName);
         JobResult result = VirtualizationProvider.ExecuteCustomPsScript(script);
         Log.WriteEnd("'{0}' ExecuteCustomPsScript", ProviderSettings.ProviderName);
         return(result);
     }
     catch (Exception ex)
     {
         Log.WriteError(String.Format("'{0}' ExecuteCustomPsScript", ProviderSettings.ProviderName), ex);
         var jobResult = new JobResult();
         jobResult.ReturnValue = ReturnCode.Failed;
         return(jobResult);
     }
 }
        private JobResult Run(IAutomatedJob job)
        {
            JobResult result = null;

            result = ErrorHandle.Expect(() => job.Doable(),
                                        out bool anyError,
                                        string.Format(_msgWError, Current.Id.Id, Current.Id.Name),
                                        string.Format(_msgJobError, job.Id.Id, job.Id.Name));

            if (anyError)
            {
                result = new JobResult(JobStatus.CompletedWithError, new AutoJobException(job.Id, null, _msgError));
            }

            _jobStatus[job.Id.ToString()] = result;
            return(result);
        }
示例#34
0
        public ResultWindow(JobResult <UrlResult> result)
        {
            InitializeComponent();
            Result = result;

            TotalRequests.Text     = result.Count.ToString(CultureInfo.InvariantCulture);
            RequestsPerSecond.Text = string.Format("{0:0}", result.JobsPerSecond);
            ResponseTime.Text      = string.Format("{0:0}", result.Results.Where(r => !r.IsError).DefaultIfEmpty(new UrlResult(0, 0, DateTime.Now, null, 0)).Average(r => r.ResponseTime));
            Elapsed.Text           = string.Format("{0:0}", result.ElapsedMilliseconds);
            Bandwidth.Text         = string.Format("{0:0}", Math.Round(result.BytesPrSecond * 8 / 1024 / 1024, MidpointRounding.AwayFromZero));
            Errors.Text            = result.Errors.ToString(CultureInfo.InvariantCulture);

            //Title = string.Format("{0} threads, {1:0.#} seconds duration & {2} URLs", result.Threads, result.ElapsedMilliseconds / 1000, result.Results.Select(r => r.Url).Distinct().Count());

            LoadUrlSummary();
            LoadGraphs();
        }
示例#35
0
        public ResultWindow(JobResult<UrlResult> result)
        {
            InitializeComponent();
            Result = result;

            TotalRequests.Text = result.Count.ToString(CultureInfo.InvariantCulture);
            RequestsPerSecond.Text = string.Format("{0:0}", result.JobsPerSecond);
            ResponseTime.Text = string.Format("{0:0}", result.Results.Where(r => !r.IsError).DefaultIfEmpty(new UrlResult(0, 0, DateTime.Now, null, 0)).Average(r => r.ResponseTime));
            Elapsed.Text = string.Format("{0:0}", result.ElapsedMilliseconds);
            Bandwidth.Text = string.Format("{0:0}", Math.Round(result.BytesPrSecond * 8 / 1024 / 1024, MidpointRounding.AwayFromZero));
            Errors.Text = result.Errors.ToString(CultureInfo.InvariantCulture);

            //Title = string.Format("{0} threads, {1:0.#} seconds duration & {2} URLs", result.Threads, result.ElapsedMilliseconds / 1000, result.Results.Select(r => r.Url).Distinct().Count());

            LoadUrlSummary();
            LoadGraphs();
        }
示例#36
0
        public bool ReceivedResult(JobResult result)
        {
            // Catch case where we receive results for an already stopped handler
            if (_handlerState == HandlerState.Stopped)
            {
                _logger.Warn("Handler: Got job '{0}' result for stopped handler", result.JobId);
                return(false);
            }
            var success = _handlerProxy.ReceivedResult(result);

            if (!success && HandlerSettings.MaxSequencedErrors > 0 && _handlerProxy.GetInfo().SequencedJobsFailed > HandlerSettings.MaxSequencedErrors)
            {
                _handlerMessage = "Too many sequenced errors";
                SetFailed();
            }
            return(success);
        }
示例#37
0
        public ResultWindow(JobResult<UrlResult> result)
        {
            InitializeComponent();
            Result = result;

            TotalRequests.Text = string.Format("{0:#,0}", result.Count);
            RequestsPerSecond.Text = string.Format("{0:#,0}", result.JobsPerSecond);
            Elapsed.Text = string.Format("{0:#,0}", result.ElapsedMilliseconds);
            Bandwidth.Text = string.Format("{0:0}", Math.Round(result.BytesPrSecond * 8 / 1024 / 1024, MidpointRounding.AwayFromZero));
            Errors.Text = string.Format("{0:#,0}", result.Errors);

            var avgResponseTime = result.Results.Where(r => !r.IsError).DefaultIfEmpty(new UrlResult(0, 0, DateTime.Now, null, 0)).Average(r => r.ResponseTime);

            if (avgResponseTime > 5)
                ResponseTime.Text = string.Format("{0:#,0}", avgResponseTime);
            else
                ResponseTime.Text = string.Format("{0:0.00}", avgResponseTime);

            LoadUrlSummary();
            LoadGraphs();
        }
        public void InvokeConfigurationSucceeds()
        {
            // Arrange
            var parameters = new DictionaryParameters();
            var key1 = "arbitrary-key1";
            var value1 = "arbitrary-value";
            parameters.Add(key1, value1);
            var key2 = "arbitrary-key2";
            var value2 = 42;
            parameters.Add(key2, value2);
            var key3 = "arbitrary-key3";
            var value3 = new object();
            parameters.Add(key3, value3);

            var jobResult = new JobResult();

            var schedulerPluginBase = Mock.Create<SchedulerPluginBase>();
            Mock.Arrange(() => schedulerPluginBase.Invoke(Arg.IsAny<DictionaryParameters>(), Arg.IsAny<IInvocationResult>()))
                .IgnoreInstance()
                .CallOriginal()
                .MustBeCalled();

            // Act
            var sut = new DefaultPlugin();
            sut.Initialise(new DictionaryParameters(), new Logger(), true);
            var result = sut.Invoke(parameters, jobResult);

            // Assert
            Assert.IsTrue(result);
            Assert.IsNotNull(jobResult);
            Assert.IsTrue(jobResult.Description.Contains(key1));
            Assert.IsTrue(jobResult.Description.Contains(value1.ToString()));
            Assert.IsTrue(jobResult.Description.Contains(key2));
            Assert.IsTrue(jobResult.Description.Contains(value2.ToString()));
            Assert.IsTrue(jobResult.Description.Contains(key3));
            Assert.IsTrue(jobResult.Description.Contains(value3.ToString()));

            Mock.Assert(schedulerPluginBase);
        }
示例#39
0
 public void Subscribe_IgnoresNullNotifications()
 {
     var durableJobStorage = A.Fake<IDurableJobQueue<int, object>>();
     var jobResultInspector = A.Fake<IJobResultInspector<int, int, object>>();
     var items = new JobResult<int, int>[]
     {
         null,
         new JobResult<int, int>(1, 1),
         null,
         null,
         new JobResult<int, int>(1, 1)
     };
     var observable = items.ToObservable();
     using (var queue = new JobResultJournalWriter<int, int, object>(observable, jobResultInspector, durableJobStorage, A.Fake<ILog>(), Scheduler.Immediate))
     {
         A.CallTo(() => jobResultInspector.Inspect(A<JobResult<int, int>>.Ignored))
             .MustHaveHappened(Repeated.Exactly.Times(items.Count(n => null != n)));
     }
 }
示例#40
0
        public void Subscribe_EmptyObservableNeverTriggersInspection()
        {
            var durableJobStorage = A.Fake<IDurableJobQueue<int, object>>();
            var jobResultInspector = A.Fake<IJobResultInspector<int, int, object>>();
            var observable = new JobResult<int, int>[]
            { }.ToObservable();

            using (var writer = new JobResultJournalWriter<int, int, object>(observable, jobResultInspector, durableJobStorage,
                A.Fake<ILog>(), Scheduler.Immediate))
            {
                A.CallTo(() => jobResultInspector.Inspect(A<JobResult<int, int>>.Ignored)).MustNotHaveHappened();
            }
        }
示例#41
0
 // UI thread
 private void GetImageCompleted(JobResult result)
 {
     TumblrPost post = (TumblrPost)(result.Object);
     if (posts[currentView].ImageUri == post.ImageUri)
     {
         UpdateView();
     }
 }
示例#42
0
 private void ReblogCompleted(JobResult result)
 {
     TumblrPost post = (TumblrPost)(result.Object);
     Utils.DebugLog("reblog job done: guid=" + result.Guid.ToString());
     this.progressStatusBar.RemoveNotify(result.Guid);
     //this.progressStatusBar.ChangeNotify(result.Guid, "Done", 1);
 }
示例#43
0
 private void LikeCompleted(JobResult result)
 {
     TumblrPost post = (TumblrPost)(result.Object);
     this.progressStatusBar.RemoveNotify(result.Guid);
 }
 /// <summary>
 /// Called when the <see cref="SaveResourceJob"/> has terminated.
 /// </summary>
 /// <param name="result">The <see cref="JobResult"/>.</param>
 /// <remarks>
 /// Runs on the UI thread.
 /// </remarks>
 void SaveResourceCallback(JobResult result)
 {
     ResourceTree.FinishSaveToRemote(result);
 }
示例#45
0
 /// <summary>
 /// 当JOB出现异常时运行,默认动作为"抛出异常 throw ex"
 /// </summary>
 /// <param name="ex"></param>
 protected void OnException(Exception ex)
 {
     this.jobResult = JobResult.Exception;
 }
示例#46
0
 /// <summary>
 /// Notifies that the job is stopped.
 /// </summary>
 /// <returns>
 /// Whether a master should continue with a new job (closing otherwise).
 /// </returns>
 protected override bool OnJobStopped(JobResult result)
 {
     return false;
 }
 /// <summary>
 /// Called when a job has terminated on a Resource.
 /// </summary>
 /// <param name="result">The <see cref="JobResult"/>.</param>
 /// <remarks>
 /// Runs on the UI thread.
 /// </remarks>
 void ReleaseResourceCallback(JobResult result)
 {
     if (result.Job.IsFinished)
     {
         ResourceTree.RemoveLocalResource(result.Resource);
         FileSystem.Delete(result.Resource.MetaAsset.RelativePath);
         FileSystem.Delete(result.Resource.DataAsset.RelativePath);
     }
 }
示例#48
0
        /// <summary>
        /// Retrieves from the SEDE query the results.
        /// </summary>
        /// <returns>The tag's name and the count in a Dictionary.</returns>
        public Dictionary<string, int> GetTags(JobResult jobResult)
        {
            var dict = new Dictionary<string, int>();
            if (jobResult == null)
            {
                dict.Add("No tags found", 42);
            }
            else
            {
                if (jobResult.ResultSets != null &&
                    jobResult.ResultSets.Length > 0)
                {
                    foreach (var row in jobResult.ResultSets[0].Rows)
                    {
                        int value;
                        Int32.TryParse(row.Values.First(), out value);
                        dict.Add(row.Keys.First(), value);
                    }
                }
                else
                {
                    dict.Add("No resultsets found", 42);
                }
            }

            return dict;
        }
示例#49
0
        // This call is blocking, while doing work on a timer thread.
        private JobResult GetQueryResultByPolling(JobResult jobResult)
        {
            // We need to poll.
            if (jobResult.Running)
            {
                var serializeTimer = new Object();
                var done = new ManualResetEvent(false); // Wait handle.
                // We use a timer that runs every second.
                using (var timer = new Timer((state) =>
                {
                    // Make sure we are single threaded.
                    lock (serializeTimer)
                    {
                        // If we are not running, don't override our result.
                        if (jobResult.Running)
                        {
                            // Poll result.
                            Console.WriteLine(jobResult.Job_id);
                            using (var pollStream = GetAsStream(String.Format(baseUrlJobFormat, jobResult.Job_id)))
                            {
                                jobResult = JsonSerializer.DeserializeFromStream<JobResult>(pollStream);
                            }
                        }
                        // If we have a result, get out!
                        if (!jobResult.Running)
                        {
                            done.Set(); // Signal main thread.
                        }
                    }
                }
                    ))
                {
                    timer.Change(100, 1000);

                    bool signaled = done.WaitOne(new TimeSpan(0, 1, 0));
                    if (!signaled)
                    {
                        Console.WriteLine("no response in 1 minute");
                    }
                }
            }
            return jobResult;
        }
示例#50
0
 /// <summary>
 /// 当JOB被强止中止时运行
 /// </summary>
 protected virtual void OnAbort()
 {
     this.JobResult = JobResult.Abort;
 }
示例#51
0
        public void Subscribe_NullNotificationTriggersLogging()
        {
            var durableJobStorage = A.Fake<IDurableJobQueue<int, object>>();
            var jobResultInspector = A.Fake<IJobResultInspector<int, int, object>>();
            var results = new JobResult<int, int>[]	{ null };
            var observable = results.ToObservable();
            var log = A.Fake<ILog>();

            using (var writer = new JobResultJournalWriter<int, int, object>(observable, jobResultInspector, durableJobStorage,
            log, Scheduler.Immediate))
            {
                A.CallTo(() => log.Error(CultureInfo.CurrentCulture, A<Action<FormatMessageHandler>>.Ignored))
                    .MustHaveHappened(Repeated.Exactly.Times(results.Count(n => null == n)));
            }
        }
        public void InvokeJobResultNullOnReturnThrowsContractException()
        {
            // Arrange
            var sut = new SchedulerPluginImpl();
            var parameters = new DictionaryParameters();
            var jobResult = new JobResult();

            // Act
            sut.Invoke(parameters, jobResult);

            // Assert
            Assert.Fail("CodeContracts are not enabled.");
        }
        public void InvokeFails()
        {
            // Arrange
            var commandLine = "arbitrary-string";
            var workingDirectory = "arbitrary-string";
            var credential = new NetworkCredential("arbitrary-user", "arbitrary-password", "arbitrary-domain");
            var parameters = new DictionaryParameters();
            parameters.Add("JobId", 42);
            parameters.Add("CommandLine", commandLine);
            parameters.Add("WorkingDirectory", workingDirectory);
            parameters.Add("Credential", credential);
            var jobResult = new JobResult();

            Mock.SetupStatic(typeof(biz.dfch.CS.Utilities.Process));

            Mock.Arrange(
                () => biz.dfch.CS.Utilities.Process.StartProcess(
                    Arg.Is<string>(commandLine),
                    Arg.Is<string>(workingDirectory),
                    Arg.Is<NetworkCredential>(credential))
                )
                .Throws<InvalidOperationException>()
                .OccursOnce();

            // Act
            var sut = new ProgrammePlugin();
            sut.Initialise(new DictionaryParameters(), new Logger(), true);
            var result = sut.Invoke(parameters, jobResult);

            // Assert
            Mock.Assert(
                () => biz.dfch.CS.Utilities.Process.StartProcess(
                    Arg.Is<string>(commandLine), 
                    Arg.Is<string>(workingDirectory), 
                    Arg.Is<NetworkCredential>(credential))
                );
            Assert.IsFalse(result);
            Assert.IsFalse(jobResult.Succeeded);
            Assert.AreNotEqual(0, jobResult.Code);
            Assert.IsFalse(string.IsNullOrWhiteSpace(jobResult.Message));
            Assert.IsFalse(string.IsNullOrWhiteSpace(jobResult.Description));
        }
示例#54
0
 internal virtual void Stop()
 {
     this.JobStatus = JobStatus.Stopping;
     if (this.JobStatus != JobStatus.Stoped)
     {
         this.JobResult = JobResult.Abort;
         this.Abort();
         this.JobStatus = JobStatus.Stoped;
     }
 }
        /// <summary>
        /// Called when a <see cref="CheckUpdateStatus"/> has terminated.
        /// </summary>
        /// <param name="result">The <see cref="JobResult"/>.</param>
        /// <remarks>
        /// Runs on the UI thread.
        /// </remarks>
        void CheckUpdateStatus(JobResult result)
        {
            string localResourceMd5 = null;

            if (result.Job.IsFinished)
            {
                localResourceMd5 = new Common.FileSystem.DataResource(result.Resource.DataAsset, FileSystem).ComputeMd5();
                ResourceTree.FinishStatusCheck(result, localResourceMd5);
            }
            else
                ResourceTree.FinishStatusCheck(result, null);
        }
        public void InvokeSucceeds()
        {
            // Arrange
            var commandLine = "arbitrary-string";
            var workingDirectory = "arbitrary-string";
            var credential = new NetworkCredential("arbitrary-user", "arbitrary-password", "arbitrary-domain");
            var parameters = new DictionaryParameters();
            parameters.Add("JobId", 42);
            parameters.Add("CommandLine", commandLine);
            parameters.Add("WorkingDirectory", workingDirectory);
            parameters.Add("Credential", credential);
            var jobResult = new JobResult();

            Mock.SetupStatic(typeof(biz.dfch.CS.Utilities.Process));

            Mock.Arrange(
                () => biz.dfch.CS.Utilities.Process.StartProcess(
                    Arg.Is<string>(commandLine), 
                    Arg.Is<string>(workingDirectory), 
                    Arg.Is<NetworkCredential>(credential))
                )
                .Returns(default(Dictionary<string, string>))
                .OccursOnce();

            // Act
            var sut = new ProgrammePlugin();
            sut.Initialise(new DictionaryParameters(), new Logger(), true);
            var result = sut.Invoke(parameters, jobResult);

            // Assert
            Mock.Assert(
                () => biz.dfch.CS.Utilities.Process.StartProcess(
                    Arg.Is<string>(commandLine), 
                    Arg.Is<string>(workingDirectory), 
                    Arg.Is<NetworkCredential>(credential))
                );
            Assert.IsTrue(result);
            Assert.IsTrue(jobResult.Succeeded);
            Assert.AreEqual(0, jobResult.Code);
        }
 /// <summary>
 /// Called when a job has terminated on a Resource.
 /// </summary>
 /// <param name="job">The <see cref="LoadResourceJob"/>.</param>
 /// <param name="fullAsset">The <see cref="FullAsset"/>.</param>
 /// <remarks>Runs on the UI thread.</remarks>
 void GetResourceCallback(JobResult result)
 {
     ResourceTree.FinishDownload(result);
 }
        public void InvokeWithInvalidTypeCredentialThrowsContractException()
        {
            // Arrange
            var parameters = new DictionaryParameters();
            parameters.Add("CommandLine", "arbitrary-string");
            parameters.Add("WorkingDirectory", "arbitrary-string");
            parameters.Add("Credential", new object());
            var jobResult = new JobResult();

            // Act
            var sut = new ProgrammePlugin();
            var result = sut.Invoke(parameters, jobResult);

            // Assert
            // N/A
        }
 /// <summary>
 /// WorkReport accepts a UpdateUIDelegate and its associated arguments and should handle pumping this message to the UI
 /// </summary>
 /// <param name="result">The <see cref="JobResult"/>.</param>
 /// <remarks>
 /// Runs on the job's thread.
 /// </remarks>
 public void WorkReport(JobResult result)
 {
     Dispatcher.BeginInvoke(result.InputArgs.UpdateUICallback, result);
 }
        public void InvokeDataNullThrowsContractException()
        {
            // Arrange
            var sut = new SchedulerPluginImpl();
            sut.Initialise(new DictionaryParameters(), new Logger(), true);
            var parameters = default(DictionaryParameters);
            var jobResult = new JobResult();

            // Act
            sut.Invoke(parameters, jobResult);

            // Assert
            Assert.Fail("CodeContracts are not enabled.");
        }