/// <summary> /// Creates and cleans the pack file directories then downloads a new pack file from the server location. /// </summary> /// <returns></returns> public async Task <bool> DownloadPack() { try { if (!Directory.Exists(Paths.GKPackFileFDir)) { Directory.CreateDirectory(Paths.GKPackFileFDir); } if (Directory.Exists(Paths.GKExtractDir)) { Directory.Delete(Paths.GKExtractDir, true); } if (File.Exists(Paths.GKPackFileFullPath)) { File.Delete(Paths.GKPackFileFullPath); } Progress = new ProgressCounter(); return(await CopyPackFile(Paths.GKRemotePackFilePath, Paths.GKPackFileFullPath)); } catch (Exception ex) { ErrorHandling.ErrHandle(ex, System.Reflection.MethodBase.GetCurrentMethod()); return(false); } }
static void AggregeteFolder(string folderPath, string fileName, string errorsFileName) { ProgressCounter progress = new ProgressCounter(); List <AppData> apps = new List <AppData>(); List <Exception> exceptions = new List <Exception>(); foreach (string app_file_name in Directory.EnumerateFiles(folderPath, "*.htm")) { progress.LogEvery(10); progress.Increment(); try { HtmlDocument document = new HtmlDocument(); document.LoadHtml(File.ReadAllText(app_file_name)); AppData appData = new AppData(document, ""); apps.Add(appData); } catch (Exception e) { e.Data["path"] = app_file_name; exceptions.Add(e); Console.WriteLine("errors: {0}", exceptions.Count()); } } MultithreadedCrawler.SaveExceptions(errorsFileName, exceptions); AppData.save_to_file(apps, fileName); }
public IList <AssemblyNode> InitMutantsForOperators(ProgressCounter percentCompleted) { var root = new MutationRootNode(); int[] id = { 1 }; Func <int> genId = () => id[0]++; //var originalModules = _choices.WhiteSource;//_whiteCache.GetWhiteModules(); percentCompleted.Initialize(_originalCodebase.ModulesToMutate.Count); var subProgress = percentCompleted.CreateSubprogress(); var sw = new Stopwatch(); var assNodes = new List <AssemblyNode>(); foreach (var module in _originalCodebase.ModulesToMutate) { sw.Restart(); var mergedTargets = _mutationExecutor.FindTargets(module, subProgress); var assemblyNode = BuildMutantsTree(module.Module.Name, mergedTargets); _log.Info("Found total of: " + mergedTargets.Values.Count() + " mutation targets in " + assemblyNode.Name); assNodes.Add(assemblyNode); percentCompleted.Progress(); } assNodes = modifyAssNodes(assNodes); root.State = MutantResultState.Untested; return(assNodes); }
public async Task TestPlayAsync() { using (Csound6Net cs = new Csound6Net()) { var parms = cs.GetParameters(); parms.MaximumThreadCount = 1;//tried cranking up to 4 cores, but this simple case actually slows down when > 1 parms.IsRealtimeMode = true; var progress = new ProgressCounter(); m_timenow = 0.0f; //should increase as progress is reported var cancel = new CancellationTokenSource(); cancel.CancelAfter(500); //force a cancelation after 2 seconds of processing (full xanadu takes 7 seconds to render) try { CsoundStatus result = await cs.PlayAsync(new FileInfo("csdFiles\\xanadu.csd"), progress, cancel.Token); Assert.Fail("Reached unexpected completion in TestPlayAsync: expected cancellation not executed."); //shouldn't execute } catch (OperationCanceledException e) { var token = e.CancellationToken; Assert.AreEqual(cancel.Token, token); Assert.IsTrue(token.IsCancellationRequested); } catch (Exception se) { Assert.Fail("System Exception: {0}", se.Message); } Assert.IsTrue(cancel.IsCancellationRequested); Assert.IsTrue(m_timenow > 0.0f); //confirm that there was progress bar activity Assert.IsTrue(m_timenow > 2.0f); //confirm that we got at least the first 2 seconds processed. Assert.IsTrue(m_timenow < 40.0f); //xanadu lasts just under 60 seconds verify that final value well under that. } }
public IList<AssemblyNode> InitMutantsForOperators(ProgressCounter percentCompleted) { var root = new MutationRootNode(); int[] id = { 1 }; Func<int> genId = () => id[0]++; //var originalModules = _choices.WhiteSource;//_whiteCache.GetWhiteModules(); percentCompleted.Initialize(_originalCodebase.ModulesToMutate.Count); var subProgress = percentCompleted.CreateSubprogress(); var sw = new Stopwatch(); var assNodes = new List<AssemblyNode>(); foreach (var module in _originalCodebase.ModulesToMutate) { sw.Restart(); var mergedTargets = _mutationExecutor.FindTargets(module, subProgress); var assemblyNode = BuildMutantsTree(module.Module.Name, mergedTargets); _log.Info("Found total of: " + mergedTargets.Values.Count() + " mutation targets in " + assemblyNode.Name); assNodes.Add(assemblyNode); percentCompleted.Progress(); } root.State = MutantResultState.Untested; return assNodes; }
public void Test0() { var cci = new CciModuleSource(TestProjects.DsaPath); var cci2 = new CciModuleSource(TestProjects.DsaPath); var type = cci.Modules.Single().Module.GetAllTypes().Single(t => t.Name.Value == "Deque") as NamedTypeDefinition; var method = type.Methods.Single(m => m.Name.Value == "EnqueueFront"); var choices = new MutationSessionChoices { Filter = new MutationFilter( new List <TypeIdentifier>(), new MethodIdentifier(method).InList()), SelectedOperators = new AOR_ArithmeticOperatorReplacement().InList <IMutationOperator>(), }; var exec = new MutationExecutor(null, choices, null); var container = new MutantsContainer(exec, new OriginalCodebase(cci.InList(), new List <string>()), new OptionsModel()); IList <AssemblyNode> assemblies = container.InitMutantsForOperators(ProgressCounter.Inactive()); var mut = assemblies.Cast <CheckedNode>() .SelectManyRecursive(n => n.Children ?? new NotifyingCollection <CheckedNode>()) .OfType <Mutant>().First(); var sourceMethod = type.Methods.Single(m => m.Name.Value == "EnqueueFront"); MutationResult executeMutation = exec.ExecuteMutation(mut, cci2).Result; // var viss = new Viss(cci2.Host, sourceMethod); // IModule newMod = viss.Rewrite(executeMutation.MutatedModules.Modules.Single().Module); cci2.ReplaceWith(executeMutation.MutatedModules.Modules.Single().Module); MutationResult executeMutation2 = exec.ExecuteMutation(mut, cci2).Result; }
/// <summary> /// Creates a new pack file and hash file and copies them to the server location. /// </summary> /// <returns></returns> public async Task <bool> CreateNewPackFile() { try { bool success = false; OnStatusMessage("Creating Pack File..."); Progress = new ProgressCounter(); success = await PackGKDir(); OnStatusMessage("Generating Hash..."); success = await CreateHashFile(); success = await UploadPackFiles(); if (success) { OnStatusMessage("Done."); } else { OnStatusMessage("Something went wrong..."); } return(success); } catch (Exception ex) { OnStatusMessage("ERROR!"); ErrorHandling.ErrHandle(ex, System.Reflection.MethodBase.GetCurrentMethod()); return(false); } }
/// <summary> /// Compresses the local Gatekeeper directory into a new pack file. /// </summary> /// <returns></returns> public async Task <bool> PackGKDir() { try { Progress = new ProgressCounter(); var gzip = new GZipCompress(Progress); if (!Directory.Exists(Paths.GKPackFileFDir)) { Directory.CreateDirectory(Paths.GKPackFileFDir); } if (File.Exists(Paths.GKPackFileFullPath)) { File.Delete(Paths.GKPackFileFullPath); } await Task.Run(() => { gzip.CompressDirectory(Paths.GKLocalInstallDir, Paths.GKPackFileFullPath); }); return(true); } catch (Exception ex) { ErrorHandling.ErrHandle(ex, System.Reflection.MethodBase.GetCurrentMethod()); return(false); } }
} // constructor private void Run() { m_oEventsProgress = new ProgressCounter("{0} user events processed.", m_oLog, 100); m_oDB.ForEachRow( SaveEvent, Query(true), CommandSpecies.Text ); m_oEventsProgress.Log(); m_oAddressProgress = new ProgressCounter("{0} address events processed.", m_oLog, 100); m_oDB.ForEachRow( ProcessAddress, Query(false), CommandSpecies.Text ); m_oAddressProgress.Log(); m_oLog.Info("Last known events - begin:"); foreach (string s in m_oLastKnown) { m_oLog.Info(s); } m_oLog.Info("Last known events - end"); } // Run
public void Test() { var gen = new XmlResultsGenerator(null, null, null, null, null); var muSession = new MutationTestingSession(); var mutar = new MutationTarget(new MutationVariant()); var ass = new AssemblyNode("Assembly"); muSession.MutantsGrouped.Add(ass); var nodeNamespace = new TypeNamespaceNode(ass, "Namespace"); ass.Children.Add(nodeNamespace); var nodeType = new TypeNode(nodeNamespace, "Type"); nodeNamespace.Children.Add(nodeType); var nodeMethod = new MethodNode(nodeType, "Method", null, true); nodeType.Children.Add(nodeMethod); var nodeGroup = new MutantGroup("Gr1", nodeMethod); nodeMethod.Children.Add(nodeGroup); var nodeMutant = new Mutant("m1", nodeGroup, mutar); nodeGroup.Children.Add(nodeMutant); XDocument generateResults = gen.GenerateResults(muSession, false, false, ProgressCounter.Inactive(), CancellationToken.None).Result; Console.WriteLine(generateResults.ToString()); //gen. }
// Start is called before the first frame update void Start() { GameObject canvas = GameObject.Find("Canvas"); ProgressCounter progressCounter = canvas.GetComponent <ProgressCounter>(); progressCounter.potatoCounter += 1; }
} // constructor public override void Execute() { Prerequisite(); List <SourceData> lst = DB.Fill <SourceData>(LoadSourceQuery, CommandSpecies.Text); var pc = new ProgressCounter("{0} of " + lst.Count + " history items processed.", Log, 100); foreach (SourceData sd in lst) { if (!this.types.ContainsKey(sd.InternalId)) { Log.Alert("Unexpected marketplace type internal id: {0}", sd.InternalId); pc++; continue; } // if ServiceInfo si = this.types[sd.InternalId]; Log.Info("Start to update for {0} with history id {1}...", si.Info.DisplayName, sd.Id); try { DB.ExecuteNonQuery(si.SpName, CommandSpecies.StoredProcedure, new QueryParameter("HistoryID", sd.Id)); Log.Info("End to update for {0} with history id {1} completed.", si.Info.DisplayName, sd.Id); } catch (Exception ex) { Log.Warn(ex, "Update for {0} with history id {1} failed.", si.Info.DisplayName, sd.Id); } // try pc++; } // for each pc.Log(); } // Execute
/// <summary> /// Creates the deep zoom image. /// </summary> /// <param name="itemId">The item id.</param> /// <param name="sourceImagePath">The source image path.</param> private void CreateDeepZoomImage(Guid itemId, String sourceImagePath) { String dziTargetPath = Path.Combine(m_outputDirectory, itemId + DziFileExtension); bool shouldCreateImage = true; lock (m_dziPaths) { shouldCreateImage = (m_dziPaths.Contains(dziTargetPath) == false); m_dziPaths.Add(dziTargetPath); try { if (this.ProgressServiceClient != null) { ProgressCounter progCounter = new ProgressCounter { Total = this.TotalImages, Completed = m_dziPaths.Count }; this.ProgressServiceClient.ReportProgress(this.InstanceId, PublishStage.CreatingDeepZoomImages, progCounter); } } catch (Exception ex) { Globals.TraceMessage(TraceEventType.Error, ex.ToString(), ex.Message); } Globals.TraceMessage(TraceEventType.Information, Properties.Messages.StatusMessage, string.Format(Properties.Messages.ImageCreated, m_dziPaths.Count)); } if (shouldCreateImage) { imageCreator.Create(sourceImagePath, dziTargetPath); } lock (m_dziPaths) { Monitor.Pulse(m_dziPaths); } }
void Start() { //at the start of each level, find the progressCounter, and set the maxLevel if (GameObject.FindGameObjectWithTag(Tags.DontDestroyOnLoad.ToString()) != null) { progressCounter = GameObject.FindGameObjectWithTag(Tags.DontDestroyOnLoad.ToString()).GetComponent <ProgressCounter>(); } }
//public LongRunningJob(Action<T> action, string title) //{ // _action = action; // _progressWindowModelView = new ProgressWindowModelView(null); // //_progressWindowModelView.Title = title; // _progressWindow = WindowsManager.GetInstance().ShowDialog<ProgressWindow>(_progressWindowModelView); // //_progressWindow.DataContext = _progressWindowModelView; //} public LongRunningJob(Action <ProgressCounter, T> action, ProgressCounter progressCounter) { _action = action; _progressWindowModelView = new ProgressWindowModelView(progressCounter); _progressWindow = WindowsManager.GetInstance().ShowDialog <ProgressWindow>(_progressWindowModelView); //_progressWindow.DataContext = _progressWindowModelView; }
protected override void DoPersist(ProgressCounter progressCounter, ProjectDto projectDto) { _isDatabaseFileAlreadyExisting = IsDatabaseFileExisting(projectDto.Name); Connection.GetInstance().CreateConnection(GetPathToDatabaseFile(projectDto.Name)); _crudService = (IProjectCRUDService)ServiceActivator.Get(typeof(IProjectCRUDService)); _persister = new ProjectPersister(_crudService, progressCounter, projectDto); _persister.Persist(); }
public void IntegrationTestingMiscUtilLight() { string filePath = Path.GetFullPath(Path.Combine(Path.GetDirectoryName(new Uri(System.Reflection.Assembly.GetExecutingAssembly().CodeBase).LocalPath), @"..\..\..\..\Tests\SampleTestProjectsForTestDiscoveryAndExecution\SampleLogicNunit3Tests\bin\SampleLogic.dll")); string filePathTests = Path.GetFullPath(Path.Combine(Path.GetDirectoryName(new Uri(System.Reflection.Assembly.GetExecutingAssembly().CodeBase).LocalPath), @"..\..\..\..\Tests\SampleTestProjectsForTestDiscoveryAndExecution\SampleLogicNunit3Tests\bin\SampleLogicNunit3Tests.dll")); var cci = new CciModuleSource(filePath); var choices = new MutationSessionChoices(); var tt = cci.Module.Module.GetAllTypes(); // var type = (NamedTypeDefinition)cci.Module.Module.GetAllTypes().Single(t => t.Name.Value == "Range"); // var method = new MethodIdentifier(type.Methods.First(m => m.Name.Value == "Contains")); MethodIdentifier method = null; choices.SelectedOperators.Add(new IdentityOperator2()); choices.Filter = method == null?MutationFilter.AllowAll() : new MutationFilter( new List <TypeIdentifier>(), method.InList()); var options = new OptionsModel(); var muexe = new MutationExecutor(options, choices, null); var mucon = new MutantsContainer(muexe, new OriginalCodebase(cci.InList()), new OptionsModel()); var nodes = mucon.InitMutantsForOperators(ProgressCounter.Inactive()); Mutant mutant = nodes.Cast <CheckedNode>() .SelectManyRecursive(n => n.Children ?? new NotifyingCollection <CheckedNode>()) .OfType <Mutant>().First();//.Take(4); var cciWhite = new CciModuleSource(filePath); var resu = muexe.ExecuteMutation(mutant, cciWhite).Result; using (var file = File.OpenWrite(filePath)) { resu.MutatedModules.WriteToStream(resu.MutatedModules.Modules.Single(), file, filePath); } var runContext = new NUnitTestsRunContext( options, _kernel.Get <IProcesses>(), _kernel.Get <CommonServices>(), new NUnitResultsParser(), TestProjects.NUnitConsolePath, filePathTests, new TestsSelector()); var testResult = runContext.RunTests().Result; var count = testResult.ResultMethods .GroupBy(t => t.State) .ToDictionary(t => t.Key); var countStrings = count.Select(pair => pair.Key.ToString() + ": " + pair.Value.Count()); _log.Info(string.Format("All test results: " + string.Join(" ", countStrings))); count[TestNodeState.Failure].Count().ShouldEqual(0); }
private void Start() { updateUIText = GetComponent <UpdateUIText>(); if (GameObject.FindGameObjectWithTag(Tags.DontDestroyOnLoad.ToString()) != null) { progressCounter = GameObject.FindGameObjectWithTag(Tags.DontDestroyOnLoad.ToString()).GetComponent <ProgressCounter>(); progressCounter.deadCounterAdded += HandleNewDeadCounter; updateUIText.UpdateText(progressCounter.DeadCounter.ToString()); } }
protected virtual void OnFinishCommand(object obj) { _wizard = (Wizard)obj; ProgressCounter progressCounter = new ProgressCounter(Title, "Persisting object...", 1); LongRunningJob <T> projectCreationJob = new LongRunningJob <T>(DoFinish, progressCounter); projectCreationJob.AddAction(delegate { _wizard.Dispatcher.Invoke(DispatcherPriority.Normal, new ThreadStart(CloseWizardOnFinish)); }); projectCreationJob.Execute(Dto); }
public void Import(ProgressCounter progressCounter, ProjectDto projectDto) { ProjectDto persistedProjectDto = _projectCRUDService.Persist(projectDto); projectDto.Id = persistedProjectDto.Id; foreach (ITransferService <ProjectDto> transferService in _transferServices) { progressCounter.Message = transferService.GetMessage(); transferService.DoWork(_connection, projectDto); } }
public void CreateMutants() { var counter = ProgressCounter.Invoking(RaiseMinorStatusUpdate, OperationsState.Mutating); var mutantModules = _mutantsContainer.InitMutantsForOperators(counter); _currentSession.MutantsGrouped = mutantModules; _sessionEventsSubject.OnNext(new MutationFinishedEventArgs(OperationsState.MutationFinished) { MutantsGrouped = _currentSession.MutantsGrouped, }); }
private ActionResult HandleRow(DbDataReader oRow, bool bRowSetStart) { if (bRowSetStart) { switch (oRow["TableName"].ToString()) { case "UiControls": if (VerboseLogging) { Debug("UiReportExt: current row handler set to SaveUiControl."); } m_oCurHandler = SaveUiControl; break; case "Customer": if (VerboseLogging) { Debug("UiReportExt: current row handler set to SaveCustomer."); } m_oCurHandler = SaveCustomer; break; case "UiEvents": if (VerboseLogging) { Debug("UiReportExt: current row handler set to ProcessEvent."); } m_oCurHandler = ProcessEvent; m_oProgress = new ProgressCounter("{0} events processed", this); break; default: Alert("UiReportExt: no handler found for table {0}!", oRow["TableName"]); m_oCurHandler = null; break; } // switch } // if if (m_oCurHandler == null) { throw new ArgumentException("No current row handler set."); } m_oCurHandler(oRow); return(ActionResult.Continue); } // HandleRow
/// <summary> /// Copies the pack file and hash file to the server directory. /// </summary> /// <returns></returns> private async Task <bool> UploadPackFiles() { bool done = false; OnStatusMessage("Uploading Pack File..."); Progress = new ProgressCounter(); done = await CopyPackFile(Paths.GKPackFileFullPath, Paths.GKRemotePackFilePath); OnStatusMessage("Uploading Hash File..."); Progress = new ProgressCounter(); done = await CopyPackFile(Paths.GKPackFileFDir + Paths.GKPackHashName, Paths.GKRemotePackFileDir + Paths.GKPackHashName); return(done); }
/// <summary> /// Decompresses the pack file into a local working directory. /// </summary> /// <returns></returns> private async Task <bool> UnPackGKDir() { try { OnStatusMessage("Unpacking...."); Progress = new ProgressCounter(); var gzip = new GZipCompress(Progress); await Task.Run(() => { gzip.DecompressToDirectory(Paths.GKPackFileFullPath, Paths.GKExtractDir); }); return(true); } catch (Exception ex) { ErrorHandling.ErrHandle(ex, System.Reflection.MethodBase.GetCurrentMethod()); return(false); } }
protected override void DoExecute(ExecutionEvent executionEvent) { _projectId = executionEvent.GetFirstSelectedTreeNavigationItem().ProjectId; try { ProgressCounter progressCounter = new ProgressCounter("Generate", "Generating the CSV files...", 1); LongRunningJob <GenerateDto> projectCreationJob = new LongRunningJob <GenerateDto>(GenerateAction, progressCounter); projectCreationJob.AddAction(delegate { _generateWindow.Dispatcher.Invoke(AfterGenerateAction, DispatcherPriority.Normal); }); projectCreationJob.Execute(_generateDto); } catch (Exception ex) { OnFailure(executionEvent); } }
public async Task SaveResults(string path = null) { if (path == null) { if (string.IsNullOrEmpty(_viewModel.TargetPath) || !Path.IsPathRooted(_viewModel.TargetPath)) { _svc.Logging.ShowError("Invalid path"); return; } path = _viewModel.TargetPath; } _viewModel.SavingInProgress = true; _cts = new CancellationTokenSource(); var progress = ProgressCounter.Invoking(i => _viewModel.Progress = i); XDocument document = await _generator.GenerateResults(_currentSession, _viewModel.IncludeDetailedTestResults, _viewModel.IncludeCodeDifferenceListings, progress, _cts.Token); try { using (var writer = _fs.File.CreateText(path)) { writer.Write(document.ToString()); } _svc.Settings["MutationResultsFilePath"] = path; _viewModel.Close(); var p = new Process(); p.StartInfo.FileName = path; p.Start(); } catch (IOException) { _svc.Logging.ShowError("Cannot write file: " + path); } }
public MultiDictionary<IMutationOperator, MutationTarget> FindTargets(CciModuleSource module, ProgressCounter subProgress) { _log.Info("Finding targets for module: " + module.Module.Name); _log.Info("Using mutation operators: " + _mutOperators.Select(_ => _.Info.Id) .MayAggregate((a, b) => a + "," + b).Else("None")); var mergedTargets = new MultiDictionary<IMutationOperator, MutationTarget>(); _sharedTargets = new MultiDictionary<IMutationOperator, MutationTarget>(); subProgress.Initialize(_mutOperators.Count); foreach (var mutationOperator in _mutOperators) { try { subProgress.Progress(); var ded = mutationOperator.CreateVisitor(); IOperatorCodeVisitor operatorVisitor = ded; operatorVisitor.Host = module.Host; operatorVisitor.OperatorUtils = _operatorUtils; operatorVisitor.Initialize(); var visitor = new VisualCodeVisitor(mutationOperator.Info.Id, operatorVisitor, module.Module.Module); var traverser = new VisualCodeTraverser(_filter, visitor, module); traverser.Traverse(module.Module.Module); visitor.PostProcess(); IEnumerable<MutationTarget> mutations = LimitMutationTargets(visitor.MutationTargets); mergedTargets.Add(mutationOperator, new HashSet<MutationTarget>(mutations)); _sharedTargets.Add(mutationOperator, new HashSet<MutationTarget>(visitor.SharedTargets)); } catch (Exception e) { _svc.Logging.ShowError("Finding targets operation failed in operator: {0}. Exception: {1}".Formatted(mutationOperator.Info.Name, e.ToString())); //throw new MutationException("Finding targets operation failed in operator: {0}.".Formatted(mutationOperator.Info.Name), e); } } return mergedTargets; }
public XElement CreateDetailedTestingResults(List <Mutant> mutants, ProgressCounter progress, CancellationToken token) { return(new XElement("DetailedTestingResults", from mutant in mutants where mutant.MutantTestSession.IsComplete let x = progressAction(progress, token) let namespaces = _testsContainer.CreateMutantTestTree(mutant) let groupedTests = namespaces.GroupBy(m => m.State).ToList() select new XElement("TestedMutant", new XAttribute("MutantId", mutant.Id), new XAttribute("TestingTimeMiliseconds", mutant.MutantTestSession.TestingTimeMiliseconds), new XElement("Tests", new XAttribute("NumberOfFailedTests", groupedTests.SingleOrDefault(g => g.Key == TestNodeState.Failure).ToEmptyIfNull().Count()), new XAttribute("NumberOfPassedTests", groupedTests.SingleOrDefault(g => g.Key == TestNodeState.Success).ToEmptyIfNull().Count()), new XAttribute("NumberOfInconlusiveTests", groupedTests.SingleOrDefault(g => g.Key == TestNodeState.Inconclusive).ToEmptyIfNull().Count()), from testClass in namespaces .Cast <CheckedNode>().SelectManyRecursive(n => n.Children ?? new NotifyingCollection <CheckedNode>()).OfType <TestNodeClass>() let xx = cancellationCheck(token) select new XElement("TestClass", new XAttribute("Name", testClass.Name), new XAttribute("FullName", testClass.FullName), from testMethod in testClass.Children.Cast <TestNodeMethod>() where testMethod.State == TestNodeState.Failure select new XElement("TestMethod", new XAttribute("Name", testMethod.Name), new XAttribute("Outcome", "Failed"), new XElement("Message", testMethod.Message)), from testMethod in testClass.Children.Cast <TestNodeMethod>() where testMethod.State.IsIn(TestNodeState.Success, TestNodeState.Inconclusive) select new XElement("TestMethod", new XAttribute("Name", testMethod.Name), new XAttribute("Outcome", FunctionalExt.ValuedSwitch <TestNodeState, string>(testMethod.State) .Case(TestNodeState.Success, "Passed") .Case(TestNodeState.Inconclusive, "Inconclusive") .GetResult()) ) ) ) ) )); }
} // ExtractAndProcess private void ProcessFileContent(StreamReader rdr, DateTime time) { var pc = new ProgressCounter("{0} lines processed.", this.log, 25000UL); for ( ; ;) { string line = rdr.ReadLine(); if (line == null) { break; } ProcessLine(line, time); pc.Next(); } // for pc.Log(); rdr.Dispose(); } // ProcessFileContent
protected virtual void DoFinish(ProgressCounter progressCounter, T dto) { if (!dto.IsValid) { Log.Warning(string.Format("The object type({0}) client side validation exception", typeof(T))); OnClientSideFailed(dto.GetValidationResult()); return; } try { DoPersist(progressCounter, dto); Log.Info(string.Format("The object type({0}) was created/updated", typeof(T))); _successFinish = true; } catch (ValidationException ex) { Log.Warning(string.Format("The object type({0}) server side validation exception", typeof(T))); OnServerSideFailed(dto, ex.GetValidationResult()); } }
///更改当前文件夹并重载文件夹 public async static Task <bool> SaveImage(File f, StorageFolder folder, string extype, Guid imageid) { try { var newFile = await folder.CreateFileAsync(f.Name + extype); var preFile = (StorageFile)(f.item); ///新建写入文件并获取读入图片文件 var WriteStream = await newFile.OpenAsync(FileAccessMode.ReadWrite); var ReadStream = await preFile.OpenReadAsync(); ///打开读写流 var bitmapDecoder = await BitmapDecoder.CreateAsync(ReadStream); var bitmapEncoder = await BitmapEncoder.CreateAsync(imageid, WriteStream); ///建立解码器和编码器 var bitmap = await bitmapDecoder.GetSoftwareBitmapAsync(); bitmapEncoder.SetSoftwareBitmap(bitmap); ///读取图片并存入至编码器 await bitmapEncoder.FlushAsync(); ///提交图片数据至流中 } catch (Exception ee) { ProgressCounter.failed++; ProgressCounter.failedlist.Add(f.Name); } var opened = ProgressCounter.add(); return(opened); }
public void StartTransfer(NetworkCredential credentials) { if (credentials == null) { throw new Win32Exception(1326); } if (!copyWorker.IsBusy) { Logger("------------------------------------------------"); Logger("Starting " + transferDescription + " to: " + targetHostname + "..."); errorList.Clear(); var workArgs = new WorkerArgs(0, 0, credentials); adminCreds = credentials; progress = new ProgressCounter(); elapTime = new Stopwatch(); elapTime.Start(); copyWorker.RunWorkerAsync(workArgs); } }
public ContourAnimationInfo getContourAnimations(ContourQuery contourQuery) { List<List<TrendingDataLocation>> frames = GetFramesFromHistorian(contourQuery); PiecewiseLinearFunction colorScale = GetColorScale(contourQuery); Func<double, double> colorFunc = colorScale; // The actual startDate is the timestamp of the // first frame after contourQuery.GetStartDate() DateTime startDate = contourQuery.GetStartDate(); int stepSize = contourQuery.StepSize; int startTimeOffset = (int)Math.Ceiling((startDate - startDate.Date).TotalMinutes / stepSize); startDate = startDate.Date.AddMinutes(startTimeOffset * stepSize); double minLat = frames.Min(frame => frame.Min(location => location.Latitude)) - GetLatFromMiles(50.0D); double maxLat = frames.Min(frame => frame.Max(location => location.Latitude)) + GetLatFromMiles(50.0D); double minLng = frames.Min(frame => frame.Min(location => location.Longitude)) - GetLngFromMiles(50.0D, 0.0D); double maxLng = frames.Min(frame => frame.Max(location => location.Longitude)) + GetLngFromMiles(50.0D, 0.0D); GeoCoordinate topLeft = new GeoCoordinate(maxLat, minLng); GeoCoordinate bottomRight = new GeoCoordinate(minLat, maxLng); GSF.Drawing.Point topLeftPoint = s_crs.Translate(topLeft, contourQuery.Resolution); GSF.Drawing.Point bottomRightPoint = s_crs.Translate(bottomRight, contourQuery.Resolution); topLeftPoint = new GSF.Drawing.Point(Math.Floor(topLeftPoint.X), Math.Floor(topLeftPoint.Y)); bottomRightPoint = new GSF.Drawing.Point(Math.Ceiling(bottomRightPoint.X), Math.Ceiling(bottomRightPoint.Y)); topLeft = s_crs.Translate(topLeftPoint, contourQuery.Resolution); bottomRight = s_crs.Translate(bottomRightPoint, contourQuery.Resolution); int width = (int)(bottomRightPoint.X - topLeftPoint.X + 1); int height = (int)(bottomRightPoint.Y - topLeftPoint.Y + 1); int animationID; string timeZoneID = null; using (AdoDataConnection connection = new AdoDataConnection(connectionstring, typeof(SqlConnection), typeof(SqlDataAdapter))) { connection.ExecuteNonQuery("INSERT INTO ContourAnimation(ColorScaleName, StartTime, EndTime, StepSize) VALUES({0}, {1}, {2}, {3})", contourQuery.ColorScaleName, contourQuery.GetStartDate(), contourQuery.GetEndDate(), contourQuery.StepSize); animationID = connection.ExecuteScalar<int>("SELECT @@IDENTITY"); if (contourQuery.IncludeWeather) timeZoneID = connection.ExecuteScalar<string>("SELECT Value FROM Setting WHERE Name = 'XDATimeZone'"); } GSF.Threading.CancellationToken cancellationToken = new GSF.Threading.CancellationToken(); s_cancellationTokens[animationID] = cancellationToken; ProgressCounter progressCounter = new ProgressCounter(frames.Count); s_progressCounters[animationID] = progressCounter; Action<int> createFrame = i => { List<TrendingDataLocation> frame = frames[i]; IDWFunc idwFunction = GetIDWFunction(contourQuery, frame); uint[] pixelData; if (contourQuery.IncludeWeather) { TimeZoneInfo tzInfo = !string.IsNullOrEmpty(timeZoneID) ? TimeZoneInfo.FindSystemTimeZoneById(timeZoneID) : TimeZoneInfo.Local; // Weather data is only available in 5-minute increments DateTime frameTime = TimeZoneInfo.ConvertTimeToUtc(startDate.AddMinutes(stepSize * i), tzInfo); double minutes = (frameTime - frameTime.Date).TotalMinutes; int weatherMinutes = (int)Math.Ceiling(minutes / 5) * 5; NameValueCollection queryString = HttpUtility.ParseQueryString(string.Empty); queryString["service"] = "WMS"; queryString["request"] = "GetMap"; queryString["layers"] = "nexrad-n0r-wmst"; queryString["format"] = "image/png"; queryString["transparent"] = "true"; queryString["version"] = "1.1.1"; queryString["time"] = frameTime.Date.AddMinutes(weatherMinutes).ToString("o"); queryString["height"] = height.ToString(); queryString["width"] = width.ToString(); queryString["srs"] = "EPSG:3857"; GSF.Drawing.Point topLeftProjected = s_crs.Projection.Project(topLeft); GSF.Drawing.Point bottomRightProjected = s_crs.Projection.Project(bottomRight); queryString["bbox"] = string.Join(",", topLeftProjected.X, bottomRightProjected.Y, bottomRightProjected.X, topLeftProjected.Y); string weatherURL = "http://mesonet.agron.iastate.edu/cgi-bin/wms/nexrad/n0r-t.cgi?" + queryString.ToString(); using (WebClient client = new WebClient()) using (MemoryStream stream = new MemoryStream(client.DownloadData(weatherURL))) using (Bitmap bitmap = new Bitmap(stream)) { pixelData = bitmap.ToPixelData(); } } else { pixelData = new uint[width * height]; } if (cancellationToken.IsCancelled) return; for (int x = 0; x < width; x++) { if (cancellationToken.IsCancelled) return; for (int y = 0; y < height; y++) { if (cancellationToken.IsCancelled) return; if (pixelData[y * width + x] > 0) continue; GSF.Drawing.Point offsetPixel = new GSF.Drawing.Point(topLeftPoint.X + x, topLeftPoint.Y + y); GeoCoordinate pixelCoordinate = s_crs.Translate(offsetPixel, contourQuery.Resolution); double interpolatedValue = idwFunction(pixelCoordinate.Longitude, pixelCoordinate.Latitude); pixelData[y * width + x] = (uint)colorFunc(interpolatedValue); } } if (cancellationToken.IsCancelled) return; using (Bitmap bitmap = BitmapExtensions.FromPixelData(width, pixelData)) using (MemoryStream stream = new MemoryStream()) { bitmap.Save(stream, ImageFormat.Png); using (AdoDataConnection connection = new AdoDataConnection(connectionstring, typeof(SqlConnection), typeof(SqlDataAdapter))) { connection.ExecuteNonQuery("INSERT INTO ContourAnimationFrame VALUES({0}, {1}, {2})", animationID, i, stream.ToArray()); } } progressCounter.Increment(); }; Task.Run(() => { ICancellationToken token; ProgressCounter counter; Parallel.For(0, frames.Count, createFrame); s_cancellationTokens.TryRemove(animationID, out token); s_progressCounters.TryRemove(animationID, out counter); if (cancellationToken.IsCancelled) { using (AdoDataConnection connection = new AdoDataConnection(connectionstring, typeof(SqlConnection), typeof(SqlDataAdapter))) { connection.ExecuteNonQuery("DELETE FROM ContourAnimationFrame WHERE ContourAnimationID = {0}", animationID); connection.ExecuteNonQuery("DELETE FROM ContourAnimation WHERE ID = {0}", animationID); } } }); s_cleanUpAnimationOperation.TryRunOnceAsync(); return new ContourAnimationInfo() { AnimationID = animationID, ColorDomain = colorScale.Domain, ColorRange = colorScale.Range, MinLatitude = bottomRight.Latitude, MaxLatitude = topLeft.Latitude, MinLongitude = topLeft.Longitude, MaxLongitude = bottomRight.Longitude, Infos = frames.Select((frame, index) => new ContourInfo() { Locations = frame, URL = string.Format("./mapService.asmx/getContourAnimationFrame?animation={0}&frame={1}", animationID, index), Date = contourQuery.GetStartDate().AddMinutes(index * contourQuery.StepSize).ToString() }).ToList() }; }
public async Task<XElement> CreateCodeDifferenceListings(List<Mutant> mutants, ProgressCounter progress, CancellationToken token) { var list = new List<XElement>(); foreach (var mutant in mutants) { progressAction(progress, token); var mutresult = await _mutantsCache.GetMutatedModulesAsync(mutant); var diff = await _codeVisualizer.CreateDifferenceListing(CodeLanguage.CSharp, mutant, mutresult); var el = new XElement("MutantCodeListing", new XAttribute("MutantId", mutant.Id), new XElement("Code", Environment.NewLine + diff.Code)); list.Add(el); } return new XElement("CodeDifferenceListings", list); }
public XElement CreateDetailedTestingResults(List<Mutant> mutants, ProgressCounter progress, CancellationToken token) { return new XElement("DetailedTestingResults", from mutant in mutants where mutant.MutantTestSession.IsComplete let x = progressAction(progress, token) let namespaces = _testsContainer.CreateMutantTestTree(mutant) let groupedTests = namespaces.GroupBy(m => m.State).ToList() select new XElement("TestedMutant", new XAttribute("MutantId", mutant.Id), new XAttribute("TestingTimeMiliseconds", mutant.MutantTestSession.TestingTimeMiliseconds), new XElement("Tests", new XAttribute("NumberOfFailedTests", groupedTests.SingleOrDefault(g => g.Key == TestNodeState.Failure).ToEmptyIfNull().Count()), new XAttribute("NumberOfPassedTests", groupedTests.SingleOrDefault(g => g.Key == TestNodeState.Success).ToEmptyIfNull().Count()), new XAttribute("NumberOfInconlusiveTests", groupedTests.SingleOrDefault(g => g.Key == TestNodeState.Inconclusive).ToEmptyIfNull().Count()), from testClass in namespaces .Cast<CheckedNode>().SelectManyRecursive(n => n.Children ?? new NotifyingCollection<CheckedNode>()).OfType<TestNodeClass>() let xx = cancellationCheck(token) select new XElement("TestClass", new XAttribute("Name", testClass.Name), new XAttribute("FullName", testClass.FullName), from testMethod in testClass.Children.Cast<TestNodeMethod>() where testMethod.State == TestNodeState.Failure select new XElement("TestMethod", new XAttribute("Name", testMethod.Name), new XAttribute("Outcome", "Failed"), new XElement("Message", testMethod.Message)), from testMethod in testClass.Children.Cast<TestNodeMethod>() where testMethod.State.IsIn(TestNodeState.Success, TestNodeState.Inconclusive) select new XElement("TestMethod", new XAttribute("Name", testMethod.Name), new XAttribute("Outcome", FunctionalExt.ValuedSwitch<TestNodeState, string>(testMethod.State) .Case(TestNodeState.Success, "Passed") .Case(TestNodeState.Inconclusive, "Inconclusive") .GetResult()) ) ) ) ) ); }
public async Task<XDocument> GenerateResults(MutationTestingSession session, bool includeDetailedTestResults, bool includeCodeDifferenceListings, ProgressCounter progress, CancellationToken token) { _log.Info("Generating session results to file."); int multiplier = 1; if (includeDetailedTestResults) { multiplier++; } if (includeCodeDifferenceListings) { multiplier++; } List<Mutant> mutants = session.MutantsGrouped.Cast<CheckedNode>() .SelectManyRecursive(n => n.Children ?? new NotifyingCollection<CheckedNode>(), leafsOnly:true).OfType<Mutant>().ToList(); List<Mutant> mutantsWithErrors = mutants.Where(m => m.State == MutantResultState.Error).ToList(); List<Mutant> testedMutants = mutants.Where(m => m.MutantTestSession.IsComplete).ToList(); List<Mutant> live = testedMutants.Where(m => m.State == MutantResultState.Live).ToList(); progress.Initialize(mutants.Count * multiplier); var mutantsNode = new XElement("Mutants", new XAttribute("Total", mutants.Count), new XAttribute("Live", live.Count), new XAttribute("Killed", testedMutants.Count - live.Count), new XAttribute("Untested", mutants.Count - testedMutants.Count), new XAttribute("WithError", mutantsWithErrors.Count), new XAttribute("AverageCreationTimeMiliseconds", testedMutants .AverageOrZero(mut => mut.CreationTimeMilis)), new XAttribute("AverageTestingTimeMiliseconds", testedMutants .AverageOrZero(mut => mut.MutantTestSession.TestingTimeMiliseconds)), from assemblyNode in session.MutantsGrouped select new XElement("Assembly", new XAttribute("Name", assemblyNode.Name), from type in assemblyNode.Children.SelectManyRecursive( n => n.Children?? new NotifyingCollection<CheckedNode>()) .OfType<TypeNode>() select new XElement("Type", new XAttribute("Name", type.Name), new XAttribute("Namespace", type.Namespace), from method in type.Children.Cast<MethodNode>()//TODO: what if nested type? select new XElement("Method", new XAttribute("Name", method.Name), from mutant in method.Children.SelectManyRecursive( n=>n.Children ?? new NotifyingCollection<CheckedNode>()).OfType<Mutant>() select new XElement("Mutant", new XAttribute("Id", mutant.Id), new XAttribute("Description", mutant.Description), new XAttribute("State", mutant.State), new XAttribute("IsEquivalent", mutant.IsEquivalent), new XAttribute("CreationTimeMiliseconds", mutant.CreationTimeMilis), new XAttribute("TestingTimeMiliseconds", mutant.MutantTestSession.TestingTimeMiliseconds), new XAttribute("TestingEndRelativeSeconds", (mutant.MutantTestSession.TestingEnd - _sessionController.SessionStartTime).TotalSeconds), new XElement("ErrorInfo", new XElement("Description", mutant.MutantTestSession.ErrorDescription), new XElement("ExceptionMessage", mutant.MutantTestSession.ErrorMessage) ).InArrayIf(mutant.State == MutantResultState.Error) ) ) ) ) ); var optionalElements = new List<XElement>(); if (includeCodeDifferenceListings) { var res = await CreateCodeDifferenceListings(mutants, progress, token); optionalElements.Add(res); } if (includeDetailedTestResults) { var res = await Task.Run(() => CreateDetailedTestingResults(mutants, progress, token)); optionalElements.Add(res); } return new XDocument( new XElement("MutationTestingSession", new XAttribute("SessionCreationWindowShowTime", _choices.SessionCreationWindowShowTime), new XAttribute("SessionStartTime", _sessionController.SessionStartTime), new XAttribute("SessionEndTime", _sessionController.SessionEndTime), new XAttribute("SessionRunTimeSeconds", (_sessionController.SessionEndTime - _sessionController.SessionStartTime).TotalSeconds), new XAttribute("MutationScore", ((int)(session.MutationScore*100)).ToString()), mutantsNode, optionalElements)); }