/// <summary> /// Compara dois arquivos de mesmo tamanho. /// </summary> /// <param name="left">Primeiro dado</param> /// <param name="right">Segundo dado</param> /// <returns>Relatório da diferença dos bytes com suas posições ou se são iguais</returns> public ResultReport CompareBytes(string left, string right) { var result = new ResultReport(); var resultOffset = new List <ResultOffsetDifferences>(); var leftData = OpenFile(left); var rightData = OpenFile(right); // Percorre os bytes para comparação dos dados. for (int i = 0; i < leftData.Length; i++) { // Atribui o byte do primeiro arquivo. var byte1 = leftData[i]; // Atribui o byte do segundo arquivo. var byte2 = rightData[i]; // Se achar um Byte diferente, adiciona ao resultado com a posição e os valores. if (byte1 != byte2) { resultOffset.Add(new ResultOffsetDifferences(i, byte1, byte2)); } } result.OffsetDifferences = resultOffset; result.FileSize = leftData.Length; // Caso não encontre offsets, os dados comparados são iguais. if (!result.OffsetDifferences.Any()) { result.Report = ReportEnum.DadosIguais; } return(result); }
public ActionResult <ResultReport> Diff() { if (!ModelState.IsValid) { return(BadRequest()); } var response = new ResultReport(); var leftFile = $"{Directory.GetCurrentDirectory()}\\inputs\\left"; var rightFile = $"{Directory.GetCurrentDirectory()}\\inputs\\right"; var fileComparer = new DataComparer(); // Verifica se os dados são de diferente tamanho. if (!fileComparer.CompareLenght(leftFile, rightFile)) { response.Report = ReportEnum.DadosDiferentes; } // Comparar cada byte, já que são do mesmo tamanho. response = fileComparer.CompareBytes(leftFile, rightFile); return(Ok(response)); }
public void DeleteFolder() { EngineState s = EngineTests.CreateEngineState(); string originScriptPath = Path.Combine(StringEscaper.Preprocess(s, "%TestBench%"), "EncodedFile", "ExtractFileTests.script"); // ReSharper disable once ParameterOnlyUsedForPreconditionCheck.Local void Template(string folderName, bool result) { string destDir = FileHelper.GetTempDir(); string destScript = Path.Combine(destDir, "DeleteFolderTest.script"); try { File.Copy(originScriptPath, destScript, true); Script sc = s.Project.LoadScriptRuntime(destScript, new LoadScriptRuntimeOptions()); Dictionary <string, string> fileDict = null; if (result) { fileDict = sc.Sections[folderName].IniDict; } ResultReport <Script> report = EncodedFile.DeleteFolder(sc, folderName); if (!report.Success) { Assert.IsFalse(result); return; } Assert.IsTrue(result); sc = report.Result; Assert.IsFalse(sc.Sections.ContainsKey(folderName)); Assert.IsFalse(IniReadWriter.ContainsSection(destScript, folderName)); string[] folders = sc.Sections[EncodedFolders].Lines; Assert.IsFalse(folders.Contains(folderName, StringComparer.OrdinalIgnoreCase)); foreach (string fileName in fileDict.Keys) { Assert.IsFalse(sc.Sections.ContainsKey(GetSectionName(folderName, fileName))); } } finally { if (Directory.Exists(destDir)) { Directory.Delete(destDir, true); } } } Template("FolderExample", true); Template("BannerImage", true); Template(AuthorEncoded, true); Template(InterfaceEncoded, true); Template("ShouldFail", false); }
private byte[] GetResultReport(Dictionary <string, string> dictionary) { var resultReport = new ResultReport(_resultService, _budgetService, _accountInfoService) { Dictionary = dictionary }; return(resultReport.GeneratePdf()); }
private void Hyperlink_RequestNavigate(object sender, RequestNavigateEventArgs e) { string uri = e.Uri.AbsoluteUri; ResultReport result = FileHelper.OpenUri(uri); if (!result.Success) { MessageBox.Show(this, $"URL [{uri}] could not be opened.\r\n\r\n{result.Message}.", "Error Opening URL", MessageBoxButton.OK, MessageBoxImage.Error); } }
public void Handle(CoreProjectionStatusMessage.ResultReport message) { var command = new ResultReport { Id = message.ProjectionId.ToString("N"), Result = message.Result, CorrelationId = message.CorrelationId.ToString("N"), Position = message.Position, Partition = message.Partition }; _writer.PublishCommand("$result", command); }
public void CreateScriptMetaJson() { string destDir = FileHelper.GetTempDir(); try { // Prepare running FileUpdater string srcScriptFile = Path.Combine(TestSetup.WebRoot, "Updater", "Standalone", "PreserveInterface_r2.script"); string workScriptFile = Path.Combine(destDir, "PreserveInterface.script"); string workScriptTreePath = Path.Combine("TestSuite", "Updater", "PreserveInterface.script"); string destJson = Path.Combine(destDir, "PreserveInterface_r2.meta.json"); File.Copy(srcScriptFile, workScriptFile); Project p = EngineTests.Project; Script sc = p.LoadScriptRuntime(workScriptFile, workScriptTreePath, new LoadScriptRuntimeOptions { AddToProjectTree = true, IgnoreMain = false, OverwriteToProjectTree = true, }); // Create a script meta json UpdateJson.CreateScriptUpdateJson(sc, destJson); // Print metaJsonText (Log) string metaJsonText; using (StreamReader sr = new StreamReader(destJson, new UTF8Encoding(false), false)) { metaJsonText = sr.ReadToEnd(); } Console.WriteLine(metaJsonText); // Check sanity of created script meta json ResultReport <UpdateJson.Root> readReport = UpdateJson.ReadUpdateJson(destJson); Assert.IsNotNull(readReport.Result); Assert.IsTrue(readReport.Success); UpdateJson.Root root = readReport.Result; ResultReport checkReport = root.Validate(); Assert.IsTrue(readReport.Success); } finally { if (Directory.Exists(destDir)) { Directory.Delete(destDir, true); } } }
public void DeleteFile() { EngineState s = EngineTests.CreateEngineState(); string originScriptPath = Path.Combine(StringEscaper.Preprocess(s, "%TestBench%"), "EncodedFile", "ExtractFileTests.script"); // ReSharper disable once ParameterOnlyUsedForPreconditionCheck.Local void Template(string folderName, string fileName, bool result) { string destDir = FileHelper.GetTempDir(); string destScript = Path.Combine(destDir, "DeleteFileTest.script"); try { File.Copy(originScriptPath, destScript, true); Script sc = s.Project.LoadScriptRuntime(destScript, new LoadScriptRuntimeOptions()); ResultReport <Script> report = EncodedFile.DeleteFile(sc, folderName, fileName); if (!report.Success) { Assert.IsFalse(result); return; } Assert.IsTrue(result); sc = report.Result; Assert.IsFalse(sc.Sections.ContainsKey(GetSectionName(folderName, fileName))); Dictionary <string, string> fileDict = sc.Sections[folderName].IniDict; Assert.IsFalse(fileDict.ContainsKey(fileName)); } finally { if (Directory.Exists(destDir)) { Directory.Delete(destDir, true); } } } Template("FolderExample", "Type1.jpg", true); Template("FolderExample", "Type2.7z", true); Template("FolderExample", "Type3.pdf", true); Template(AuthorEncoded, "Logo.jpg", true); Template(InterfaceEncoded, "PEBakeryAlphaMemory.jpg", true); Template("BannerImage", "Should.fail", false); Template("ShouldFail", "Should.fail", false); }
public void GetLogoInfo() { EngineState s = EngineTests.CreateEngineState(); string scriptDir = Path.Combine(StringEscaper.Preprocess(s, "%TestBench%"), "EncodedFile"); string logoScriptFile = Path.Combine(scriptDir, "Blank.script"); Script logoScript = s.Project.LoadScriptRuntime(logoScriptFile, new LoadScriptRuntimeOptions()); string noLogoScriptFile = Path.Combine(scriptDir, "CompleteBlank.script"); Script noLogoScript = s.Project.LoadScriptRuntime(noLogoScriptFile, new LoadScriptRuntimeOptions()); // ReSharper disable once ParameterOnlyUsedForPreconditionCheck.Local void Template(Script testScript, bool detail, EncodedFileInfo comp) { ResultReport <EncodedFileInfo> report = EncodedFile.GetLogoInfo(testScript, detail); if (comp == null) { Assert.IsFalse(report.Success); Assert.IsNull(report.Result); } else { Assert.IsTrue(report.Success); Assert.IsTrue(report.Result.Equals(comp)); } } Template(logoScript, true, new EncodedFileInfo { FolderName = "AuthorEncoded", FileName = "logo.jpg", RawSize = 973, EncodedSize = 1298, EncodeMode = EncodedFile.EncodeMode.ZLib }); Template(logoScript, false, new EncodedFileInfo { FolderName = "authorEncoded", FileName = "Logo.jpg", RawSize = 973, EncodedSize = 1298, EncodeMode = null }); Template(noLogoScript, true, null); Template(noLogoScript, false, null); }
public void DummyTestOperation() { string currentExecutingMethod = Utilities.GetCurrentMethod(); var resultsWriter = new ResultsWriter(Constants.ParameterizedTest, currentExecutingMethod, true); var loginTestData = DummyOperationData.GetTestData(); Parallel.ForEach(WebDrivers, (driver, loopState) => { var testAsserter = new TestCaseAsserts(); string currentWebBrowserString = Utilities.GetWebBrowser(driver); if (loginTestData != null) { ResultReport testResultReport = new ResultReport(); string testFixtureName = Utilities.GenerateTestFixtureName(this.GetType(), currentExecutingMethod, currentWebBrowserString); testResultReport.StartMethodTimerAndInitiateCurrentTestCase(testFixtureName, true); try { /* * Call page flow respective method here. */ /* * Call necessary assertion from TestCaseAsserts class here. */ testResultReport.SetCurrentTestCaseOutcome(true, testAsserter.AssertionCount.ToString()); } catch (Exception e) { string screenShotIdentifier = String.Format("{0} - {1}", "{ENTER AN IDENTIFIER (E.G. USER NAME}", currentExecutingMethod); base.HandleException(e, screenShotIdentifier, driver, testResultReport, testAsserter, resultsWriter); Assert.Fail("***** DummyTest Failed *****"); } finally { testResultReport.StopMethodTimerAndFinishCurrentTestCase(); base.TestCases.Add(testResultReport.currentTestCase); } } }); resultsWriter.WriteResultsToFile(this.GetType().Name, TestCases); }
public DetailedReportSharedData(ResultReport resultReport) { this.ErrorMessage = resultReport.ErrorMessage; this.TestName = resultReport.TestName; this.Result = resultReport.Severity; this.TestDescription = resultReport.TestDescription; this.IdentifiedDataBehaviors = new HashSet <string>(LogManager.IdentifiedBehaviorsDescriptions.Where(x => resultReport.IdentifedDataBehaviors.Contains(x.Key)).Select(x => x.Value)); this.UnstructuredOldValues = resultReport.UnstructuredOldValues; this.UnstructuredNewValues = resultReport.UnstructuredNewValues; this.OldOrganizationValues = resultReport.OldOrganizationValues; this.NewOrganizationValues = resultReport.NewOrganizationValues; this.StructuredOldValues = resultReport.StructuredOldValues; this.StructuredNewValues = resultReport.StructuredNewValues; this.OldTreeRoot = resultReport.OldTreeRoot; this.NewTreeRoot = resultReport.NewTreeRoot; this.Duration = resultReport.Duration; this.TreeComparisonIndexError = resultReport.TreeComparisonIndexError; this.OldId = resultReport.OldId; this.UserId = resultReport.UserId; }
protected void HandleException( Exception ex, string screenshotIdentifier, IWebDriver webDriver, ResultReport resultReport, TestCaseAsserts asserts, ResultsWriter writer) { ScreenShotImage.CaptureScreenShot( webDriver, Utilities.CombineTestOutcomeString(Constants.ScreenshotError, screenshotIdentifier)); resultReport.SetCurrentTestCaseOutcome( false, asserts.AssertionCount.ToString(), ex.Message, ex.StackTrace); resultReport.StopMethodTimerAndFinishCurrentTestCase(); this.TestCases.Add(resultReport.currentTestCase); writer.WriteResultsToFile(this.GetType().Name, TestCases); }
public void DeleteLogo() { EngineState s = EngineTests.CreateEngineState(); string scriptDir = Path.Combine(StringEscaper.Preprocess(s, "%TestBench%"), "EncodedFile"); string logoScriptPath = Path.Combine(scriptDir, "Blank.script"); string noLogoScriptPath = Path.Combine(scriptDir, "CompleteBlank.script"); // ReSharper disable once ParameterOnlyUsedForPreconditionCheck.Local void Template(string testScriptPath, bool result) { string destDir = FileHelper.GetTempDir(); string destScript = Path.Combine(destDir, "DeleteLogoTest.script"); try { File.Copy(testScriptPath, destScript, true); Script sc = s.Project.LoadScriptRuntime(destScript, new LoadScriptRuntimeOptions()); ResultReport <Script> report = EncodedFile.DeleteLogo(sc); if (!report.Success) { Assert.IsFalse(result); return; } Assert.IsTrue(result); Assert.IsFalse(EncodedFile.ContainsLogo(report.Result)); } finally { if (Directory.Exists(destDir)) { Directory.Delete(destDir, true); } } } Template(logoScriptPath, true); Template(noLogoScriptPath, false); }
public ResultReport RetrieveResult(int experimentID) { const string STRLOG_MethodName = "RetrieveResult"; Logfile.WriteCalled(STRLOG_ClassName, STRLOG_MethodName); // // Create a ResultReport to return // ResultReport resultReport = new ResultReport(); if (experimentID > 0) { // Update result report resultReport.statusCode = (int)StatusCodes.Completed; resultReport.experimentResults = "<xmlExperimentResult />"; } Logfile.WriteCompleted(STRLOG_ClassName, STRLOG_MethodName); return(resultReport); }
public ResultReport RetrieveResult(int experimentID) { const string STRLOG_MethodName = "RetrieveResult"; Logfile.WriteCalled(STRLOG_ClassName, STRLOG_MethodName); ResultReport resultReport = null; // Get the identity of the caller string sbName = GetCallerName(authHeader); // Check caller access is authorised if (sbName != null) { // Pass on to experiment manager resultReport = Global.experimentManager.RetrieveResult(experimentID, sbName); } else { resultReport = new ResultReport((int)StatusCodes.Failed, STRLOG_AccessDenied); } string logMessage = STRLOG_statusCode + ((StatusCodes)resultReport.statusCode).ToString(); if ((StatusCodes)resultReport.statusCode == StatusCodes.Completed) { logMessage += Logfile.STRLOG_Spacer + STRLOG_experimentResults + resultReport.experimentResults; } else { logMessage += Logfile.STRLOG_Spacer + STRLOG_errorMessage + resultReport.errorMessage; } Logfile.WriteCompleted(STRLOG_ClassName, STRLOG_MethodName, logMessage); return(resultReport); }
private async void ExportCommand_Executed(object sender, ExecutedRoutedEventArgs e) { Microsoft.Win32.SaveFileDialog dialog = new Microsoft.Win32.SaveFileDialog { Title = "Save Log As", }; switch (_m.FileFormat) { case LogExportType.Text: dialog.Filter = "Text Format (*.txt)|*.txt"; break; case LogExportType.Html: dialog.Filter = "HTML Format (*.html)|*.html"; break; default: Debug.Assert(false, "Internal Logic Error at LogExportWindow.ExportCommand_Executed"); break; } if (_m.ExportSystemLog) { // Local time should be ok because the filename is likely only useful to the person exporting the log DateTime localTime = DateTime.Now; dialog.FileName = $"SystemLog_{localTime.ToString("yyyy_MM_dd_HHmmss", CultureInfo.InvariantCulture)}"; } else if (_m.ExportBuildLog) { Debug.Assert(0 < _m.BuildEntries.Count, "Internal Logic Error at LogExportWindow.ExportCommand_Executed"); LogModel.BuildInfo bi = _m.BuildEntries[_m.SelectedBuildEntryIndex]; // Filter invalid filename chars List <char> filteredChars = new List <char>(bi.Name.Length); List <char> invalidChars = Path.GetInvalidFileNameChars().ToList(); invalidChars.Add('['); // Remove [ and ] invalidChars.Add(']'); invalidChars.Add(' '); // Spaces are not very script or web friendly, let's remove them too. foreach (char ch in bi.Name) { if (invalidChars.Contains(ch)) { filteredChars.Add(Convert.ToChar("_")); // Replace invalid chars and spaces with an underscore } else { filteredChars.Add(ch); } } string filteredName = new string(filteredChars.ToArray()); // The log stores dateTime as UTC so its safe to use ToLocalTime() to convert to the users timezone dialog.FileName = $"BuildLog_{bi.StartTime.ToLocalTime().ToString("yyyy_MM_dd_HHmmss", CultureInfo.InvariantCulture)}_{filteredName}"; } bool?result = dialog.ShowDialog(); // If user cancelled SaveDialog, do nothing if (result != true) { return; } string destFile = dialog.FileName; _m.InProgress = true; try { await Task.Run(() => { if (_m.ExportSystemLog) { _m.Logger.ExportSystemLog(_m.FileFormat, destFile); } else if (_m.ExportBuildLog) { Debug.Assert(0 < _m.BuildEntries.Count, "Internal Logic Error at LogExportWindow.ExportCommand_Executed"); int buildId = _m.BuildEntries[_m.SelectedBuildEntryIndex].Id; _m.Logger.ExportBuildLog(_m.FileFormat, destFile, buildId, new BuildLogOptions { IncludeComments = _m.BuildLogIncludeComments, IncludeMacros = _m.BuildLogIncludeMacros, ShowLogFlags = _m.BuildLogShowLogFlags, }); } }); } finally { _m.InProgress = false; } // Open log file Application.Current.Dispatcher.Invoke(() => { if (_m.FileFormat == LogExportType.Html) { // Call FileHelper.OpenUri (instead of OpenPath) to open .html files with the default browser. ResultReport result = FileHelper.OpenUri(destFile); if (!result.Success) { MessageBox.Show(this, $"URL [{destFile}] could not be opened.\r\n\r\n{result.Message}.", "Error Opening URL", MessageBoxButton.OK, MessageBoxImage.Error); } } else { MainViewModel.OpenTextFile(destFile); } }); // Close LogExportWindow Close(); }
//-------------------------------------------------------------------------------------------------// private ResultReport ConvertType(Proxy.ResultReport proxyResultReport) { ResultReport resultReport = null; if (proxyResultReport != null) { resultReport = new ResultReport(); resultReport.ErrorMessage = proxyResultReport.errorMessage; resultReport.XmlExperimentResults = proxyResultReport.experimentResults; resultReport.StatusCode = (StatusCodes)proxyResultReport.statusCode; resultReport.XmlBlobExtension = proxyResultReport.xmlBlobExtension; resultReport.XmlResultExtension = proxyResultReport.xmlResultExtension; resultReport.WarningMessages = proxyResultReport.warningMessages; } return resultReport; }
public void GetFileInfo() { // ReSharper disable once InconsistentNaming const string FolderExample = "FolderExample"; const string folderExample = "folderExample"; EngineState s = EngineTests.CreateEngineState(); string pbOriginScript = Path.Combine("%TestBench%", "EncodedFile", "ExtractFileTests.script"); string originScript = StringEscaper.Preprocess(s, pbOriginScript); Script sc = s.Project.LoadScriptRuntime(originScript, new LoadScriptRuntimeOptions()); // ReSharper disable once ParameterOnlyUsedForPreconditionCheck.Local void Template(string fileName, bool detail, EncodedFileInfo comp) { ResultReport <EncodedFileInfo> report = EncodedFile.GetFileInfo(sc, folderExample, fileName, detail); Assert.IsTrue(report.Success); Assert.IsTrue(comp.Equals(report.Result)); } Template("Type1.jpg", true, new EncodedFileInfo { FolderName = FolderExample, FileName = "Type1.jpg", RawSize = 7683, EncodedSize = 10244, EncodeMode = EncodedFile.EncodeMode.ZLib }); Template("type1.jpg", false, new EncodedFileInfo { FolderName = folderExample, FileName = "Type1.jpg", RawSize = 7683, EncodedSize = 10244, EncodeMode = null }); Template("Type2.7z", true, new EncodedFileInfo { FolderName = FolderExample, FileName = "Type2.7z", RawSize = 1631, EncodedSize = 2175, EncodeMode = EncodedFile.EncodeMode.Raw }); Template("Type2.7z", false, new EncodedFileInfo { FolderName = FolderExample, FileName = "type2.7z", RawSize = 1631, EncodedSize = 2175, EncodeMode = null }); Template("Type3.pdf", true, new EncodedFileInfo { FolderName = FolderExample, FileName = "Type3.pdf", RawSize = 88692, EncodedSize = 102908, EncodeMode = EncodedFile.EncodeMode.XZ }); Template("Type3.pdf", false, new EncodedFileInfo { FolderName = folderExample, FileName = "type3.pdf", RawSize = 88692, EncodedSize = 102908, EncodeMode = null }); }
public async Task <IActionResult> Results(int?StLg) { if (StLg != null && StLg is int) { var user = await userManager.GetUserAsync(User); // проверим есть ли результат var result = await dataContext.ResultReports.FirstOrDefaultAsync(x => x.StartedTestLog.Id == StLg && x.User == user && x.DateAnsw.Date == DateTime.Now.Date); // добавим если резульат не записан if (result == null) { var fact = await dataContext.FactTitleLog.Include(x => x.StartedTestLog).ThenInclude(x => x.TitleUserAccess).Include(m => m.FactQuestCollection).ThenInclude(a => a.FactAnswersLog).Include(x => x.AnswerUserResultLog).FirstOrDefaultAsync(x => x.DateAdd.Date == DateTime.Now.Date && x.StartedTestLog.Id == StLg && x.StartedTestLog.UserId == user); if (fact != null) { var uAnswer = fact.AnswerUserResultLog.Where(x => x.User == user).Count(); var fAnswer = fact.FactQuestCollection.Select(x => x.FactAnswersLog.Count()).Sum(); var r = fact.FactQuestCollection.Select(x => x.FactAnswersLog); if (uAnswer == fAnswer) { // коллекция правильных ответов ICollection <FactAnswersLog> answColl = new List <FactAnswersLog>(); foreach (var quest in fact.FactQuestCollection) { foreach (var answ in quest.FactAnswersLog) { answColl.Add(answ); } } List <FactQuestLog> trueAnsw = new List <FactQuestLog>(); foreach (var AnswerResult in fact.AnswerUserResultLog) { foreach (var factAnswerLog in answColl) { // сравним вопросы if (AnswerResult.factQuestLog == factAnswerLog.FactQuestLog) { var flag = true; var fansw = AnswerResult.factQuestLog.FactAnswersLog; var uansw = AnswerResult.factQuestLog.AnswerUserResultLog; // сравним кол-во ответов //if (fansw.Count() == uansw.Count()) //{ // var fanswState = fansw.Select(x => x.State).ToList(); // var uanswState = uansw.Select(x => x.State).ToList(); // for (int i = 0; i < fanswState.Count(); i++) // { // if (fanswState[i] != uanswState[i]) // { // flag = false; // break; // } // } // if (flag) // { // if (!trueAnsw.Contains(AnswerResult.factQuestLog)) // { // trueAnsw.Add(AnswerResult.factQuestLog); // } // } //} foreach (var userFactAnwers in factAnswerLog.FactQuestLog.FactAnswersLog) { var answUser = AnswerResult.factQuestLog.AnswerUserResultLog.FirstOrDefault(x => x.factAnswersLog == userFactAnwers); if (userFactAnwers == answUser.factAnswersLog) { if (userFactAnwers.State != answUser.State) { flag = false; break; } } } if (flag) { if (!trueAnsw.Contains(AnswerResult.factQuestLog)) { trueAnsw.Add(AnswerResult.factQuestLog); } } } } } ResultReport report = new ResultReport { User = user, FactTitleLog = fact, StartedTestLog = fact.StartedTestLog, Percent = (trueAnsw.Count() * 100) / fact.FactQuestCollection.Count() }; await dataContext.ResultReports.AddAsync(report); await dataContext.SaveChangesAsync(); return(View("Result", report.Percent)); } } } else { return(View("Result", result.Percent)); } } return(RedirectToAction("Index")); }
//---------------------------------------------------------------------------------------// public ResultReport Load(int experimentId, string sbName) { const string STRLOG_MethodName = "Load"; string logMessage = STRLOG_experimentId + experimentId.ToString() + Logfile.STRLOG_Spacer + STRLOG_sbName + Logfile.STRLOG_Quote + sbName + Logfile.STRLOG_Quote; Logfile.WriteCalled(STRLOG_ClassName, STRLOG_MethodName, logMessage); // // Create a ResultReport to return (not nullable) // ResultReport resultReport = new ResultReport(); string xmlWarningMessages = string.Empty; // // Catch all exceptions so that a valid result report can be returned // lock (this.resultsLock) { try { SqlCommand sqlCommand = new SqlCommand(STRSQLCMD_RetrieveResults, this.sqlConnection); sqlCommand.CommandType = CommandType.StoredProcedure; sqlCommand.Parameters.Add(new SqlParameter(STRSQLPRM_ExperimentId, experimentId)); sqlCommand.Parameters.Add(new SqlParameter(STRSQLPRM_SbName, sbName)); try { this.sqlConnection.Open(); SqlDataReader sqlDataReader = sqlCommand.ExecuteReader(); while (sqlDataReader.Read() == true) { object sdrObject = null; if ((sdrObject = sqlDataReader[STRSQL_Status]) != System.DBNull.Value) { StatusCodes status = (StatusCodes)Enum.Parse(typeof(StatusCodes), (string)sdrObject); resultReport.statusCode = (int)status; } if ((sdrObject = sqlDataReader[STRSQL_XmlExperimentResult]) != System.DBNull.Value) resultReport.experimentResults = (string)sdrObject; if ((sdrObject = sqlDataReader[STRSQL_XmlResultExtension]) != System.DBNull.Value) resultReport.xmlResultExtension = (string)sdrObject; if ((sdrObject = sqlDataReader[STRSQL_XmlBlobExtension]) != System.DBNull.Value) resultReport.xmlBlobExtension = (string)sdrObject; if ((sdrObject = sqlDataReader[STRSQL_WarningMessages]) != System.DBNull.Value) xmlWarningMessages = (string)sdrObject; if ((sdrObject = sqlDataReader[STRSQL_ErrorMessage]) != System.DBNull.Value) resultReport.errorMessage = (string)sdrObject; } sqlDataReader.Close(); } catch (SqlException ex) { throw new Exception(STRERR_SqlException + ex.Message); } catch (Exception ex) { throw new Exception(STRERR_Exception + ex.Message); } finally { this.sqlConnection.Close(); } // // Convert warning messages from XML format to string array // if (xmlWarningMessages != null && xmlWarningMessages.Length > 0) { try { XmlDocument xmlDocument = XmlUtilities.GetXmlDocument(xmlWarningMessages); XmlNode xmlRootNode = XmlUtilities.GetXmlRootNode(xmlDocument, STRXML_warningMessages); resultReport.warningMessages = XmlUtilities.GetXmlValues(xmlRootNode, STRXML_warningMessage, true); } catch { } } } catch (Exception ex) { // Place the exception message in the result report resultReport.errorMessage = ex.Message; Logfile.WriteError(ex.Message); } } logMessage = STRLOG_statusCode + ((StatusCodes)resultReport.statusCode).ToString(); Logfile.WriteCompleted(STRLOG_ClassName, STRLOG_MethodName, logMessage); return resultReport; }
public void Notify(int experimentID) { const string STRLOG_MethodName = "Notify"; string logMessage = STRLOG_ExperimentId + experimentID.ToString(); Logfile.WriteCalled(STRLOG_ClassName, STRLOG_MethodName, logMessage); bool success = false; try { // // Check LabServer's header information is valid // if (sbHeader == null) { throw new ArgumentNullException("sbHeader"); } if (sbHeader.couponPassKey == null) { throw new ArgumentNullException("couponPassKey"); } // // Determine LabServer // string strLabServerId = sbHeader.couponID.ToString("X"); string strCsvLabServer = Utilities.GetAppSetting(strLabServerId); string[] strSplit = strCsvLabServer.Split(new char[] { ',' }); if (strSplit.Length < 3) { throw new ArgumentException("CSV LabServer string has insufficient parameters"); } // // Check for valid passkey // if (sbHeader.couponPassKey.Equals(strSplit[0].Trim(), StringComparison.OrdinalIgnoreCase) == false) { throw new ArgumentException("couponPassKey is invalid"); } // // Create LabServer interface // string labserverUrl = strSplit[1].Trim(); LabServerWebService labServer = new LabServerWebService(); labServer.Url = labserverUrl; // // Create and fill in authorisation information // string sbGuid = Utilities.GetAppSetting(Consts.STRCFG_ServiceBrokerGuid); string sbToLsPasskey = strSplit[2].Trim(); AuthHeader authHeader = new AuthHeader(); authHeader.identifier = sbGuid; authHeader.passKey = sbToLsPasskey; labServer.AuthHeaderValue = authHeader; // // Retrieve result from LabServer // LabExperimentStatus labExperimentStatus = labServer.GetExperimentStatus(experimentID); if ((labExperimentStatus != null) && (labExperimentStatus.statusReport != null) && (labExperimentStatus.statusReport.statusCode >= (int)StatusCodes.Completed) && (labExperimentStatus.statusReport.statusCode != (int)StatusCodes.Unknown)) { ResultReport resultReport = labServer.RetrieveResult(experimentID); } success = true; } catch (Exception ex) { Logfile.WriteError(ex.Message); } logMessage = STRLOG_Success + success.ToString(); Logfile.WriteCompleted(STRLOG_ClassName, STRLOG_MethodName, logMessage); }
//-------------------------------------------------------------------------------------------------// protected void btnRetrieve_Click(object sender, EventArgs e) { // // Clear hidden labels and disable buttons // lblHiddenResults.Text = null; lblHiddenApplet.Text = null; btnSave.Enabled = false; btnDisplay.Enabled = false; btnDisplay.Visible = false; // // Get the experiment ID // int experimentID = ParseExperimentNumber(txbExperimentID.Text); if (experimentID <= 0) { return; } // // Get the experiment results for the selected experiment // try { StatusCodes statusCode; string errorMessage = null; string experimentResults = null; // // Get ServiceBrokerAPI from session state and retrieve the result // try { ResultReport resultReport = Master.ServiceBroker.RetrieveResult(experimentID); statusCode = (StatusCodes)resultReport.statusCode; errorMessage = resultReport.errorMessage; experimentResults = resultReport.experimentResults; } catch (Exception ex) { // LabServer error Logfile.WriteError(ex.Message); statusCode = StatusCodes.Unknown; } // // Display the status code // ShowMessageNormal(STR_ExperimentNumber + experimentID.ToString() + STR_Spacer + statusCode.ToString()); if (statusCode != StatusCodes.Unknown && experimentResults != null) { // // Get result information // Result result = new Result(experimentResults); ResultInfo resultInfo = result.GetResultInfo(); // // Check experiment type // if (resultInfo != null && resultInfo.title != null && resultInfo.title.Equals(Master.Title, StringComparison.OrdinalIgnoreCase) == false) { // // Wrong experiment type // ShowMessageWarning(STRERR_IncorrectExperimentType + Master.Title); return; } // // Build table to display results on the webpage // string strResultsTable = BuildTableResult(resultInfo, statusCode, errorMessage); phResultsTable.Controls.Add(new LiteralControl(strResultsTable)); if (statusCode == StatusCodes.Completed) { try { // // Build a CSV string from the result report and store in a hidden label // lblHiddenResults.Text = BuildCsvResult(resultInfo); // Enable button btnSave.Enabled = true; // // Create HTML applet tag for insertion into the webpage // string appletParams = BuildAppletParams(resultInfo); string applet = CreateHtmlAppletTag(appletParams); if (applet != null) { // Save applet for displaying in a hidden label lblHiddenApplet.Text = applet; // Enable applet display btnDisplay.Enabled = true; btnDisplay.Visible = true; } } catch (Exception ex) { ShowMessageWarning(ex.Message); } } // // Completed experiment is no longer needed // if (Master.MultiSubmit == true) { } else { Session[Consts.STRSSN_CompletedID] = null; } } } catch (Exception ex) { ShowMessageWarning(ex.Message); return; } }
public ResultReport RetrieveResult(int experimentID) { const string STRLOG_MethodName = "RetrieveResult"; Logfile.WriteCalled(STRLOG_ClassName, STRLOG_MethodName); ResultReport resultReport = null; // Get the identity of the caller string sbName = GetCallerName(authHeader); // Check caller access is authorised if (sbName != null) { // Pass on to experiment manager resultReport = Global.experimentManager.RetrieveResult(experimentID, sbName); } else { resultReport = new ResultReport((int)StatusCodes.Failed, STRLOG_AccessDenied); } string logMessage = STRLOG_statusCode + ((StatusCodes)resultReport.statusCode).ToString(); if ((StatusCodes)resultReport.statusCode == StatusCodes.Completed) { logMessage += Logfile.STRLOG_Spacer + STRLOG_experimentResults + resultReport.experimentResults; } else { logMessage += Logfile.STRLOG_Spacer + STRLOG_errorMessage + resultReport.errorMessage; } Logfile.WriteCompleted(STRLOG_ClassName, STRLOG_MethodName, logMessage); return resultReport; }
public void GetFolderInfo() { // ReSharper disable once InconsistentNaming const string FolderExample = "FolderExample"; EngineState s = EngineTests.CreateEngineState(); string pbOriginScript = Path.Combine("%TestBench%", "EncodedFile", "ExtractFileTests.script"); string originScript = StringEscaper.Preprocess(s, pbOriginScript); Script sc = s.Project.LoadScriptRuntime(originScript, new LoadScriptRuntimeOptions()); // ReSharper disable once ParameterOnlyUsedForPreconditionCheck.Local void Template(bool detail, List <EncodedFileInfo> comps) { ResultReport <EncodedFileInfo[]> report = EncodedFile.GetFolderInfo(sc, FolderExample, detail); Assert.IsTrue(report.Success); EncodedFileInfo[] infos = report.Result; Assert.AreEqual(comps.Count, infos.Length); for (int i = 0; i < comps.Count; i++) { Assert.IsTrue(comps[i].Equals(infos[i])); } } List <EncodedFileInfo> compDetailList = new List <EncodedFileInfo> { new EncodedFileInfo { FolderName = FolderExample, FileName = "Type1.jpg", RawSize = 7683, EncodedSize = 10244, EncodeMode = EncodedFile.EncodeMode.ZLib }, new EncodedFileInfo { FolderName = FolderExample, FileName = "Type2.7z", RawSize = 1631, EncodedSize = 2175, EncodeMode = EncodedFile.EncodeMode.Raw }, new EncodedFileInfo { FolderName = FolderExample, FileName = "Type3.pdf", RawSize = 88692, EncodedSize = 102908, EncodeMode = EncodedFile.EncodeMode.XZ } }; List <EncodedFileInfo> compNoDetailList = new List <EncodedFileInfo>(); foreach (EncodedFileInfo info in compDetailList) { EncodedFileInfo clone = info.Clone() as EncodedFileInfo; Assert.IsTrue(clone != null); clone.EncodeMode = null; compNoDetailList.Add(clone); } Template(true, compDetailList); Template(false, compNoDetailList); }
public void GetAllFilesInfo() { // ReSharper disable once InconsistentNaming const string FolderExample = "FolderExample"; EngineState s = EngineTests.CreateEngineState(); string pbOriginScript = Path.Combine("%TestBench%", "EncodedFile", "ExtractFileTests.script"); string originScript = StringEscaper.Preprocess(s, pbOriginScript); Script sc = s.Project.LoadScriptRuntime(originScript, new LoadScriptRuntimeOptions()); // ReSharper disable once ParameterOnlyUsedForPreconditionCheck.Local void Template(bool inspectEncodedSize, Dictionary <string, List <EncodedFileInfo> > compDict) { EncodedFile.GetFileInfoOptions opts = new EncodedFile.GetFileInfoOptions { InspectEncodeMode = inspectEncodedSize, }; ResultReport <Dictionary <string, List <EncodedFileInfo> > > report = EncodedFile.GetAllFilesInfo(sc, opts); Assert.IsTrue(report.Success); Dictionary <string, List <EncodedFileInfo> > infoDict = report.Result; Assert.AreEqual(compDict.Count, infoDict.Count); foreach (var kv in compDict) { Assert.IsTrue(infoDict.ContainsKey(kv.Key)); Assert.AreEqual(kv.Value.Count, infoDict[kv.Key].Count); foreach (EncodedFileInfo fileInfo in kv.Value) { Assert.IsTrue(infoDict[kv.Key].Contains(fileInfo)); } } } Dictionary <string, List <EncodedFileInfo> > compDetailDict = new Dictionary <string, List <EncodedFileInfo> > { ["FolderExample"] = new List <EncodedFileInfo> { new EncodedFileInfo { FolderName = FolderExample, FileName = "Type1.jpg", RawSize = 7683, EncodedSize = 10244, EncodeMode = EncodedFile.EncodeMode.ZLib }, new EncodedFileInfo { FolderName = FolderExample, FileName = "Type2.7z", RawSize = 1631, EncodedSize = 2175, EncodeMode = EncodedFile.EncodeMode.Raw }, new EncodedFileInfo { FolderName = FolderExample, FileName = "Type3.pdf", RawSize = 88692, EncodedSize = 102908, EncodeMode = EncodedFile.EncodeMode.XZ } }, ["FolderRun"] = new List <EncodedFileInfo> { new EncodedFileInfo { FolderName = "FolderRun", FileName = "TestBatch.cmd", RawSize = 34, EncodedSize = 144, EncodeMode = EncodedFile.EncodeMode.Raw } }, ["BannerImage"] = new List <EncodedFileInfo> { new EncodedFileInfo { FolderName = "BannerImage", FileName = "Banner.bmp", RawSize = 17626, EncodedSize = 23502, EncodeMode = EncodedFile.EncodeMode.ZLib }, new EncodedFileInfo { FolderName = "BannerImage", FileName = "Banner.svg", RawSize = 4715, EncodedSize = 6287, EncodeMode = EncodedFile.EncodeMode.ZLib }, } }; Dictionary <string, List <EncodedFileInfo> > compNoDetailDict = new Dictionary <string, List <EncodedFileInfo> >(); foreach (var kv in compDetailDict) { compNoDetailDict[kv.Key] = new List <EncodedFileInfo>(); foreach (EncodedFileInfo info in kv.Value) { EncodedFileInfo clone = info.Clone() as EncodedFileInfo; Assert.IsTrue(clone != null); clone.EncodeMode = null; compNoDetailDict[kv.Key].Add(clone); } } Template(true, compDetailDict); Template(false, compNoDetailDict); }
public CompareStrategyUnstructuredLists(HashSet <StringDescriptor> oldValues, HashSet <StringDescriptor> newValues, ResultReport resultReport) : base(oldValues, newValues, resultReport) { if (oldValues != null) { this.oldValues = oldValues; } else { this.oldValues = new HashSet <StringDescriptor>(); } if (newValues != null) { this.newValues = newValues; } else { this.newValues = new HashSet <StringDescriptor>(); } }