public IActionResult StartTest(string UniqueId) { TestDetailsViewModel model = new TestDetailsViewModel(); model = _candidateService.StartTest(UniqueId); return(View(model)); }
public ActionResult TestMode(int?id) { if (id == null) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } Test test = _context.Tests.Find(id); if (test == null) { return(HttpNotFound()); } var QuestionsList = new List <QuestionAndAnswer>(); QuestionsList.AddRange(_context.QuestionAndAnswers.Where(g => g.TestId == id)); var testVM = new TestDetailsViewModel { TestId = id.Value, TestSubject = test.Subject, Questions = QuestionsList }; return(View(testVM)); }
public ActionResult Create([Bind(Include = "SubCode,InternalNumber,QuestionNumber,Marks,CO")] TestDetailsViewModel testDetails) { var user = db.AspNetUsers.FirstOrDefault(u => u.Email == User.Identity.Name); var teacher = db.Teachers.FirstOrDefault(u => u.REFID == user.Id); var internalNumber = testDetails.InternalNumber; if (ModelState.IsValid) { using (SqlConnection connection = new SqlConnection("Data Source=DEV\\SQLEXPRESS;Initial Catalog=AttendanceManagementDB;Integrated Security=True")) { var subject = testDetails.SubCode[0].ToString(); if (subject != null) { var tableName = teacher.Name + "_" + subject; string createtableCommandString = "IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[" + tableName + "]') AND type in (N'U'))" + " BEGIN CREATE TABLE [dbo].[" + tableName + "](Id int IDENTITY PRIMARY KEY, InternalNo int not null, QNo varchar(3) not null, Marks int, CO int) END"; SqlCommand command = new SqlCommand(createtableCommandString, connection); command.Connection.Open(); command.ExecuteNonQuery(); int count = testDetails.QuestionNumber.Count(); for (int i = 0; i < count; i++) { string qno = testDetails.QuestionNumber[i]; int marks = testDetails.Marks[i]; int co = testDetails.CO[i]; string insertCommandString = "INSERT INTO " + tableName + " (InternalNo,QNo,Marks,CO) VALUES (" + internalNumber + ",'" + qno + "'," + marks + "," + co + ")"; SqlCommand insertCommand = new SqlCommand(insertCommandString, connection); insertCommand.ExecuteNonQuery(); } } } } LoadViewBag(); return(View(testDetails)); }
// GET: Tests/Edit/5 public ActionResult Edit(string id) { TestDetailsViewModel model = new TestDetailsViewModel(); TestDto response = webClient.ExecuteGet <TestDto>(new Models.ApiRequest() { EndPoint = string.Format("tests/{0}", id) }); model.AuthToken = response.AuthToken; model.Code = response.Code; model.Name = response.Name; model.Desctiption = response.Description; model.SelectedQuestions = response.Questions.Select(q => new SelectListItem() { Selected = false, Text = q.Text, Value = q.Id.ToString() }).ToList(); model.AvailableQuiestions = webClient.ExecuteGet <IEnumerable <QuestionDto> >(new Models.ApiRequest() { EndPoint = string.Format("questions?skip=0&take={0}", int.MaxValue - 1) }) .Select(q => new SelectListItem() { Selected = false, Text = q.Text, Value = q.Id.ToString() }).ToList(); return(View(model)); }
public ActionResult Edit(string id, TestDetailsViewModel model) { if (ModelState.IsValid) { try { var response = webClient.ExecutePut <object>(new Models.ApiRequest() { EndPoint = string.Format("tests/{0}", model.Code), Request = new TestDto() { AuthToken = model.AuthToken ?? "MyToken", Code = model.Code, Description = model.Desctiption, Name = model.Name, Questions = model.QuestionIds.Select(q => new QuestionDto() { Id = q }).ToList() } }); return(RedirectToAction("Index")); } catch (Exception e) { ModelState.AddModelError("generalError", e.Message); return(View(model)); } } return(View(model)); }
/*public ObjectResult Details() * { * EmployeeModel employee = _employeeRepository.GetEmployee(1); * return new ObjectResult(employee); * }*/ public ViewResult Details(int?id) { //throw new Exception("Error in details view"); _logger.LogTrace("Trace Log"); _logger.LogDebug("Debug Log"); _logger.LogInformation("Information Log"); _logger.LogWarning("Warning Log"); _logger.LogError("Error Log"); _logger.LogCritical("Critical Log"); EmployeeModel employee = _employeeRepository.GetEmployee(id.Value); if (employee == null) { Response.StatusCode = 404; return(View("EmployeeNotFound", id.Value)); } //return View(employee); //return View("Test"); //return View("Test", employee); //return View("MyViews/myviews.cshtml"); //ViewData["pageTitle"] = "Details"; //ViewData["employee"] = employee; /*ViewBag.pageTitle = "ViewBag Index"; * ViewBag.employee = employee; * return View("Strongly", employee);*/ TestDetailsViewModel testDetailsViewModel = new TestDetailsViewModel() { PageTitle = "Mon titre", Employee = employee }; return(View("Example", testDetailsViewModel)); }
public TestDetails(Domain.Entities.Teste teste) { InitializeComponent(); ViewModel = new TestDetailsViewModel(); ViewModel = Mapper.Map <TestDetailsViewModel>(teste); this.BindingContext = ViewModel; Navigation.PushAsync(App.LoadingPage); try { Uri urinho = new Uri($@"http://apilabclick.mflogic.com.br/imagem/getByTesteId={teste.Id}"); var result = App.Client.GetAsync(urinho); if (result.Result.IsSuccessStatusCode) { var content = result.Result.Content.ReadAsStringAsync(); var testeImagem = JsonConvert.DeserializeObject <TesteImagemViewModel>(content.Result); Stream stm = new MemoryStream(testeImagem.Imagem); ImgTeste.Source = ImageSource.FromStream(() => { return(stm); }); } else { Navigation.RemovePage(App.LoadingPage); Navigation.RemovePage(this); DisplayAlert("Erro", "Não foi possível recuperar as informações do exame.", "Fechar"); } } catch (Exception ex) { Navigation.RemovePage(App.LoadingPage); Navigation.RemovePage(this); DisplayAlert("Erro", $"Não foi possível recuperar as informações do exame. {ex.Message}", "Fechar"); } if (Device.Idiom == TargetIdiom.Phone) { //labelsStack.Margin = new Thickness(25, 5, 5, 10); lblNomePaciente.FontSize = 12; lblDataTeste.FontSize = 12; lblResultado.FontSize = 12; lblNomePacienteDados.FontSize = 12; lblDataCadastroDados.FontSize = 12; lblResultadoDados.FontSize = 12; lblImagemTeste.FontSize = 12; ImgTeste.WidthRequest = 130; ImgTeste.HeightRequest = 280; } Navigation.RemovePage(App.LoadingPage); }
public CandidateExamWrapperModel GetCandidateExamList() { CandidateExamWrapperModel model = new CandidateExamWrapperModel(); model = _candidateExamRepository.GetAllSubmittedTests(); foreach (var rec in model.CandidateExamList) { CandidateDetailsViewModel candidate = _candidateRepository.GetCandidateDetails(rec.CandidateId); rec.CandidateName = candidate.Name; TestDetailsViewModel test = _testRepository.GetTestDetails(rec.TestId); rec.TestName = test.Name; List <CandidateExamQuestionLogModel> list = _candidateExamQuestionLogRepository.FindByCandidateExamId(rec.Id); int CorrectAnswers = 0; int TotalQuestions = test.QuestionList.Count(); foreach (var obj in list) { if (obj.IsAnswerCorrect == true) { CorrectAnswers = CorrectAnswers + 1; } } rec.Score = CorrectAnswers + "/" + TotalQuestions; } return(model); }
public ActionResult Details(int ID, int?TestGroupID) { try { REF_TEST_TB test = _uow.Repository <REF_TEST_TB>().GetById(ID); TestDetailsViewModel model = new TestDetailsViewModel() { AnalysisMethod = test.SZ_ANALYSIS_METHOD == null ? "" : test.SZ_ANALYSIS_METHOD, SampleMedia = test.SZ_SAMPLE_MEDIA == null ? "" : test.SZ_SAMPLE_MEDIA, SampleType = test.SZ_SAMPLE_TYPE == null ? "" : test.SZ_SAMPLE_TYPE, ShortDescription = test.SZ_DESCRIPTION == null ? "" : test.SZ_DESCRIPTION, TestGroupID = Convert.ToInt32(TestGroupID), TestID = test.N_TEST_SYSID, Unit = test.SZ_TITLE == null ? "" : test.SZ_TITLE, EffectiveDate = test.DT_EFFECTIVE == null ? "" : test.DT_EFFECTIVE.Value.ToShortDateString(), ExpiredDate = test.DT_EXPIRED == null ? "" : test.DT_EXPIRED.Value.ToShortDateString() }; return(View(model)); } catch (Exception ex) { if (ex.InnerException == null) { ViewBag.Message = "Function: TestController.Details_GET\n\nError: " + ex.Message; } else { ViewBag.Message = "Function: TestController.Details_GET\n\nError: " + (ex.Message + "\n\nInnerException: " + ex.InnerException.Message); }; Session["ErrorMessage"] = ViewBag.Message; return(RedirectToAction("InternalServerError", "Error")); }; }
public void SearchItemsCommandTest() { var db = DataRepository.GetDataRepository; Assert.NotNull(db); var user = db.Load <UserDetail>("steph"); var userManager = new UserManager(db); UserManager.GetUserManager.LoginUser(user); var searchFilter = new SearchFilterOptions { User = UserManager.GetUserManager.CurrentUser(), SiteLocationEnabled = false, SearchFilterEnabled = true, SearchText = "Airway Kit", SelectEquipmentUnitsEnabled = false, SelectItemStatusValuesEnabled = false, SelectItemCategoryValuesEnabled = false }; Assert.NotNull(searchFilter, nameof(SearchFilterOptions)); var resultVM = new TestDetailsViewModel(); Assert.NotNull(resultVM, nameof(TestDetailsViewModel)); var onSelectionChangedCommand = new OnSelectionChangedCommand(resultVM); Assert.NotNull(onSelectionChangedCommand, nameof(OnSelectionChangedCommand)); var searchResultViewModel = new SearchResultViewModel(onSelectionChangedCommand); Assert.NotNull(searchResultViewModel, nameof(SearchResultViewModel)); var searchCmd = new SearchItemsCommand(QueryResultEntitySelector.ItemType, searchResultViewModel); Assert.NotNull(searchCmd, nameof(SearchItemsCommand)); Assert.IsTrue(searchCmd.CanExecute(searchFilter)); Assert.IsNull(resultVM.CurrentItem); // nothing selected to display details of Assert.That(searchResultViewModel.Items.Count, Is.EqualTo(0)); // no search results or empty search results searchCmd.Execute(searchFilter); searchCmd.WaitForSearchToComplete(); Assert.That(searchResultViewModel.Items.Count, Is.GreaterThan(0)); searchResultViewModel.SelectedItem = searchResultViewModel.Items.First(); Assert.NotNull(searchResultViewModel.SelectedItem); Assert.NotNull(resultVM.CurrentItem); Assert.AreNotEqual(Guid.Empty, resultVM.CurrentItem.id); Assert.NotNull(resultVM.CurrentItem.entityType); Assert.NotNull(resultVM.CurrentItem.entity); }
public CandidateExamModel GetCandidateExamDetails(int id) { CandidateExamModel model = new CandidateExamModel(); model = _candidateExamRepository.GetExamDetails(id); CandidateDetailsViewModel candidate = _candidateRepository.GetCandidateDetails(model.CandidateId); model.CandidateName = candidate.Name; TestDetailsViewModel test = _testRepository.GetTestDetails(model.TestId); model.TestName = test.Name; model.list = new List <CandidateExamQuestionLogModel>(); model.list = _candidateExamQuestionLogRepository.FindByCandidateExamId(id); int CorrectAnswers = 0; int TotalQuestions = test.QuestionList.Count(); foreach (var obj in model.list) { if (obj.IsAnswerCorrect == true) { CorrectAnswers = CorrectAnswers + 1; } } model.Score = CorrectAnswers + "/" + TotalQuestions; model.TotalNumberOfQuestions = TotalQuestions; model.AttemptedQuestions = model.list.Count(); model.CorrectAnswers = CorrectAnswers; model.WrongAnswers = model.list.Count() - CorrectAnswers; foreach (var que in test.QuestionList) { bool IsPresent = false; foreach (var item in model.list) { if (que.Id == item.QuestionId) { IsPresent = true; } } if (IsPresent == false) { CandidateExamQuestionLogModel rec = new CandidateExamQuestionLogModel(); rec.Question = que.Question; rec.SelectedAnswer = "NA"; rec.IsAnswerCorrect = false; model.list.Add(rec); } } return(model); }
public TestDetailsViewModel StartTest(string UniqueId) { TestDetailsViewModel model = new TestDetailsViewModel(); int CandidateId = _candidateUniqueIdRepository.FindCandidateId(UniqueId); CandidateViewModel candidate = _candidateRepository.GetCandidateForEdit(CandidateId); model = _testRepository.GetTestDetails(candidate.TestId); CandidateExamModel obj = new CandidateExamModel() { StartedTime = DateTime.Now, IsTestEnded = false, TestId = candidate.TestId, CandidateId = CandidateId }; int candidateExamId = _candidateExamRepository.AddExam(obj); model.CandidateExamId = candidateExamId; return(model); }
public ActionResult Create(TestDetailsViewModel model) { TestDto exisctingTest = webClient.ExecuteGet <TestDto>(new Models.ApiRequest() { EndPoint = string.Format("tests/{0}", model.Code) }); if (exisctingTest != null) { ModelState.AddModelError("Code", "Code already exists"); } if (ModelState.IsValid) { try { var response = webClient.ExecutePost <object>(new Models.ApiRequest() { EndPoint = "tests", Request = new TestDto() { AuthToken = model.AuthToken ?? "MyToken", Code = model.Code, Description = model.Desctiption, Name = model.Name, Questions = new List <QuestionDto>() } }); return(RedirectToAction("Edit", new { id = model.Code })); } catch (Exception e) { ModelState.AddModelError("generalError", e.Message); return(View(model)); } } return(View(model)); }
public TestDetailsViewModel GetTestDetails(int id) { TestDetailsViewModel model = _testRepository.GetTestDetails(id); return(model); }
public void ReplaceItemCommand() { var db = DataRepository.GetDataRepository; Assert.NotNull(db); var user = db.Load <UserDetail>("steph"); var userManager = new UserManager(db); UserManager.GetUserManager.LoginUser(user); var cmd = new ReplaceItemCommand(); Assert.NotNull(cmd, nameof(ReplaceItemCommand)); var item = db.Load <ItemInstance>(SampleItemInstance); Assert.NotNull(item); // force known value item.status = db.ReferenceData[nameof(ItemStatus)].ByName <ItemStatus>("Available"); db.Save(item); item = db.Load <ItemInstance>(SampleItemInstance); Assert.That(item.status.name, Is.EqualTo("Available")); Assert.IsTrue(cmd.CanExecute(item)); cmd.Execute(item); Assert.That(item.status.name, Is.EqualTo("Out for Service")); // verify a new item created var searchFilter = new SearchFilterOptions { User = UserManager.GetUserManager.CurrentUser(), SiteLocationEnabled = false, SearchFilterEnabled = true, SearchText = SampleItemNumber, ItemTypeMatching = SearchFilterItemMatching.OnlyExact, //AllowItemsRemovedFromService = false, // required or query below may return old item instead of new one SelectEquipmentUnitsEnabled = false, SelectItemStatusValuesEnabled = false, SelectItemCategoryValuesEnabled = false }; Assert.NotNull(searchFilter, nameof(SearchFilterOptions)); var resultVM = new TestDetailsViewModel(); Assert.NotNull(resultVM, nameof(TestDetailsViewModel)); var onSelectionChangedCommand = new OnSelectionChangedCommand(resultVM); Assert.NotNull(onSelectionChangedCommand, nameof(OnSelectionChangedCommand)); var searchResultViewModel = new SearchResultViewModel(onSelectionChangedCommand); Assert.NotNull(searchResultViewModel, nameof(SearchResultViewModel)); var searchCmd = new SearchItemsCommand(QueryResultEntitySelector.ItemType, searchResultViewModel); Assert.NotNull(searchCmd, nameof(SearchItemsCommand)); //var searchFilterOptionsViewModel = new SearchFilterOptionsViewModel(searchFilter, QueryResultEntitySelector.ItemInstance, searchResultViewModel); //Assert.NotNull(searchFilterOptionsViewModel); Assert.IsTrue(searchCmd.CanExecute(searchFilter)); Assert.IsNull(resultVM.CurrentItem); // nothing selected to display details of Assert.That(searchResultViewModel.Items.Count, Is.EqualTo(0)); // no search results or empty search results searchCmd.Execute(searchFilter); searchCmd.WaitForSearchToComplete(); Assert.That(searchResultViewModel.Items.Count, Is.GreaterThan(0)); searchResultViewModel.SelectedItem = searchResultViewModel.Items.First(); Assert.NotNull(searchResultViewModel.SelectedItem); Assert.NotNull(resultVM.CurrentItem); Assert.That(resultVM.CurrentItem.id, Is.Not.EqualTo(item.id)); // delete new item and restore old item to Available var newItem = db.Load <ItemInstance>(resultVM.CurrentItem.id); Assert.That(newItem.status.name, Is.EqualTo("Available")); item.status = db.ReferenceData[nameof(ItemStatus)].ByName <ItemStatus>("Available"); item.removedServiceDate = null; db.Delete(newItem); Assert.IsFalse(db.Exists(newItem)); db.Save(item); item = db.Load <ItemInstance>(SampleItemInstance); Assert.That(item.status.name, Is.EqualTo("Available")); }
/// <summary> /// Displays TestDetails page with user specified values in NominalValues page /// </summary> /// <param name="viewModel">The view model</param> /// <returns></returns> public Task ShowTestDetails(TestDetailsViewModel viewModel) { return(Task.Run(() => MessageBox.Show("Test"))); }
public ActionResult LoadQuestion(int userTestSuiteId) { TestDetailsViewModel testSuiteQuestionModel = TestSuiteQuestion(null, userTestSuiteId, (int)QuestionType.Objective); return(PartialView("_partialViewQuestion", testSuiteQuestionModel)); }
// GET: Tests/Create public ActionResult Create() { TestDetailsViewModel model = new TestDetailsViewModel(); return(View(model)); }
internal TestView(TestDetailsViewModel model) { BindingContext = model; InitializeComponent(); }
public IActionResult Details(int id) { TestDetailsViewModel model = _testService.GetTestDetails(id); return(View(model)); }
public TestDetailsView(TestDetailsViewModel viewModel) { //InitializeComponent(); BindingContext = viewModel; }
// GET: Tests/Details/5 // Pass in an integer that can be null to represent an Id public async Task <IActionResult> Details(int?Id) { // If no Id integer is returned throw a 404 error message if (Id == null) { return(NotFound()); } // Create variable for all UserTests in database var UserTestDisplay = await _context.UserTest .Include(ut => ut.Test) // Select only the UserTests whose Id equals the Id integer passed into the view .FirstOrDefaultAsync(ut => ut.UserTestId == Id); // If no UserTests are returned with a UserTestId that equals the Id integer return 404 error if (UserTestDisplay == null) { return(NotFound()); } var currentUser = await GetCurrentUserAsync(); // Create a list of Responses that include UserResponses and Questions that include their QuestionTypes // Where the UserTestId associated with the responses // Equals the UserTestId associated with the UserTestDisplay variable List <Response> responses = await _context.Response .Include(r => r.Rating) .Include(r => r.UserTest) .ThenInclude(ut => ut.User) .Include(r => r.Question) .ThenInclude(q => q.QuestionType) .Where(r => r.UserTestId == UserTestDisplay.UserTestId && r.UserTest.User == currentUser) .OrderBy(r => r.Question.QuestionId) .ToListAsync(); // Create a list of QuestionTypes // Select the QuestionTypes available through the Questions on the responses // Make the selected QuestionTypes distinct so they don't repeat // Order QuestionTypes by QuestionTypeId List <QuestionType> QuestionTypes = responses.Select(r => r.Question.QuestionType).Distinct().ToList(); // Create a new list of ResponseDataViewModels List <ResponseDataViewModel> responseData = new List <ResponseDataViewModel>(); // Loop over all question types in the QuestionTypes list foreach (QuestionType qt in QuestionTypes) { // Create a new instance of response data view model ResponseDataViewModel rd = new ResponseDataViewModel(); // Give QuestionType in view model instance the value Type from the QuestionTypes list being looped over rd.QuestionType = qt.Type; // Create a variable containing a list of responses // where the QuestionTypeId associated with the question on the response // equals the QuestionTypeId on the list of QuestionTypes being looped over var totalResponses = responses.Where(r => r.Question.QuestionTypeId == qt.QuestionTypeId); // Create a new integer variable named number double number = new double(); // Loop over list of responses held in totalResposnes variable foreach (var r in totalResponses) { // Add a UserResponseId value to the number variable for each interation of the loop number += r.Rating.RatingAmount; } // Divide the number variable by the amount of totalResponses and subtract 1 number = (number / totalResponses.Count()); number = Math.Round(number, 2); // Set the NumberOfResponses variable in the view model to the value of the number variable rd.NumberOfResponses = number; // Add the instance of the view model to the list of responseData view models responseData.Add(rd); } // Create new instance of TestDetailsViewModel TestDetailsViewModel TestDetails = new TestDetailsViewModel(); // Add values to the view model based on variables above TestDetails.UserTest = UserTestDisplay; TestDetails.QuestionTypes = QuestionTypes; TestDetails.Responses = responses; TestDetails.ResponseData = responseData; // Create a new list of datapoints List <DataPoint> dataPoints = new List <DataPoint>(); // Loop over each instance of a view model in the responseData view model list foreach (var rd in responseData) { // Add a new datapoint for each iteration // passing in the values of the QuestionType and NumberOfResponses from the view model dataPoints.Add(new DataPoint(rd.QuestionType, rd.NumberOfResponses)); } // Magic ViewBag.DataPoints = JsonConvert.SerializeObject(dataPoints); // Return TestDetails to the View return(View(TestDetails)); }
public TestDetailsViewModel GetTestDetails(int id) { string connectionString = "server=localhost;uid=root;password=Reset1234;database=OnlineTestManagement;"; TestDetailsViewModel model = new TestDetailsViewModel(); model.QuestionList = new List <QuestionViewModel>(); string queryString = "select OnlineTestManagement.Test.Id, OnlineTestManagement.Test.Name,OnlineTestManagement.Test.CreatedBy, OnlineTestManagement.JobRole.Value as JobRole from (OnlineTestManagement.Test INNER JOIN JobRole ON OnlineTestManagement.Test.JobRoleId = OnlineTestManagement.JobRole.Id) where OnlineTestManagement.Test.Id=" + id + " "; string queList = "select OnlineTestManagement.Question.Id as Id,OnlineTestManagement.Question.Question as Question,OnlineTestManagement.Question.CreatedBy as CreatedBy,OnlineTestManagement.Question.CreatedBy as CreatedBy,OnlineTestManagement.Question.Option1 as Option1,OnlineTestManagement.Question.Option2 as Option2,OnlineTestManagement.Question.Option3 as Option3,OnlineTestManagement.Question.Option4 as Option4 from (OnlineTestManagement.Question INNER JOIN TestQuestion ON OnlineTestManagement.Question.Id = OnlineTestManagement.TestQuestion.QUestionId) where OnlineTestManagement.TestQuestion.TestId=" + id + " "; using (MySqlConnection connection = new MySqlConnection(connectionString)) { MySqlCommand command = new MySqlCommand(queryString, connection); connection.Open(); MySqlDataReader reader = command.ExecuteReader(); // Call Read before accessing data. while (reader.Read()) { model.Id = (int)reader[0]; model.Name = reader[1].ToString(); model.CreatedBy = reader[2].ToString(); model.JobRole = reader[3].ToString(); } connection.Close(); } using (MySqlConnection connection = new MySqlConnection(connectionString)) { MySqlCommand queCommand = new MySqlCommand(queList, connection); connection.Open(); MySqlDataReader reader = queCommand.ExecuteReader(); // Call Read before accessing data. while (reader.Read()) { QuestionViewModel obj = new QuestionViewModel(); obj.Id = (int)reader[0]; obj.Question = reader[1].ToString(); obj.CreatedBy = reader[2].ToString(); obj.CorrectAnswer = reader[3].ToString(); obj.Option1 = reader[4].ToString(); obj.Option2 = reader[5].ToString(); obj.Option3 = reader[6].ToString(); obj.Option4 = reader[7].ToString(); model.QuestionList.Add(obj); } // Call Close when done reading. connection.Close(); } return(model); }
/// <summary> /// Loads multiple tests in order /// </summary> public void LoadTestFile(int testFileNumber) { if (IoC.Communication.TestFileListItems.Count > 0) { // initialize multiple test view model. TestFileListItemViewModel currentTestFile = new TestFileListItemViewModel(); // retrieve the first test currentTestFile = IoC.Communication.TestFileListItems[testFileNumber]; // convert a JSON file to a TestDetailsViewModel to show it the user. using (StreamReader file = File.OpenText(currentTestFile.FullFileName)) { // initialize a new TestDetailsViewModel TestDetailsViewModel test = new TestDetailsViewModel(); // initialize JsonSerializer JsonSerializer serializer = new JsonSerializer(); // convert the JsonSerializer to TestDetailsViewModel test = (TestDetailsViewModel)serializer.Deserialize(file, typeof(TestDetailsViewModel)); // Update values in the single instance of TestDetailsViewModel // update AnalogSignals IoC.TestDetails.AnalogSignals = test.AnalogSignals; // Select Ramping Signal property // Ramping Signal property is Magnitude. // This is also default setting for this property. IoC.TestDetails.IsMagnitude = string.Equals(test.SelectedRampingSignal, nameof(TestDetailsViewModel.RampingSignals.Magnitude)) || string.IsNullOrWhiteSpace(test.SelectedRampingSignal); // Ramping Signal property is Phase. IoC.TestDetails.IsPhase = string.Equals(test.SelectedRampingSignal, nameof(TestDetailsViewModel.RampingSignals.Phase)); // Ramping Signal property is Frequency. IoC.TestDetails.IsFrequency = string.Equals(test.SelectedRampingSignal, nameof(TestDetailsViewModel.RampingSignals.Frequency)); // Ramping Signal property is Harmonics. IoC.TestDetails.IsHarmonics = string.Equals(test.SelectedRampingSignal, nameof(TestDetailsViewModel.RampingSignals.Harmonics)); // update Harmonics Order IoC.TestDetails.HarmonicsOrder = test.HarmonicsOrder; // update Register IoC.TestDetails.Register = test.Register; // update DwellTime IoC.TestDetails.DwellTime = test.DwellTime; // update StartDelayTime IoC.TestDetails.StartDelayTime = test.StartDelayTime; // update MeasurementInterval IoC.TestDetails.MeasurementInterval = test.MeasurementInterval; // update StartMeasurementDelay IoC.TestDetails.StartMeasurementDelay = test.StartMeasurementDelay; // update SelectedRampingSignal IoC.TestDetails.SelectedRampingSignal = test.SelectedRampingSignal; // update Link Ramping Signals status // If SelectedRampingSignal == "Frequency" or If SelectedRampingSignal == "Harmonics" if (Equals(nameof(TestDetailsViewModel.RampingSignals.Frequency), test.SelectedRampingSignal) || Equals(nameof(TestDetailsViewModel.RampingSignals.Harmonics), test.SelectedRampingSignal)) { // frequencies are linked. IoC.TestDetails.IsLinked = test.IsLinked; } else { // frequencies are not linked IoC.TestDetails.IsLinked = false; } // update Hardware Configuration = Voltage IoC.TestDetails.SelectedVoltageConfiguration = test.SelectedVoltageConfiguration; // update Hardware Configuration = Current IoC.TestDetails.SelectedCurrentConfiguration = test.SelectedCurrentConfiguration; // update TestFileName IoC.TestDetails.TestFileName = test.TestFileName; // update Settings view model IoC.Settings.SelectedCurrent = test.SelectedCurrentConfiguration.WiringDiagramString; IoC.Settings.SelectedVoltage = test.SelectedVoltageConfiguration.WiringDiagramString; // if the test file is old, // add a new fileName attribute, // add some missing attributes to "SelectedVoltageConfiguration", // add some missing attributes to "SelectedCurrentConfiguration". if (string.IsNullOrWhiteSpace(IoC.TestDetails.TestFileName)) { // add saved file name IoC.TestDetails.TestFileName = Path.GetFileName(currentTestFile.FullFileName); // add new "WiringDiagramFileLocation" test.SelectedVoltageConfiguration.WiringDiagramFileLocation = "../Images/Omicron/not used voltage.png"; test.SelectedCurrentConfiguration.WiringDiagramFileLocation = "../Images/Omicron/not used current.png"; // add new SelectedCurrent and SelectedVoltage } // update Settings view model IoC.Settings.CurrentDiagramLocation = test.SelectedCurrentConfiguration.WiringDiagramFileLocation; IoC.Settings.VoltageDiagramLocation = test.SelectedVoltageConfiguration.WiringDiagramFileLocation; // change CancelForegroundColor to Red IoC.Commands.CancelForegroundColor = "ff0000"; // set Command buttons IoC.Commands.StartTestAvailable = true; IoC.Commands.NewTestAvailable = false; IoC.Commands.Cancellation = true; IoC.Commands.ConfigurationAvailable = true; IoC.Commands.IsConfigurationAvailable = false; // Show TestDetails page IoC.Application.GoToPage(ApplicationPage.TestDetails, IoC.TestDetails); test = null; serializer = null; } // dispose dialog box Dlg = null; // dispose temp multiple test view model. currentTestFile = null; } }