Exemple #1
0
        public PageVM GetPageById(string pageId, bool useFile = false)
        {
            FormVM formVm = null;

            if (useFile)
            {
                using (var r = new StreamReader("Content/form-schema.json"))
                {
                    var file = r.ReadToEnd();

                    formVm = JsonConvert.DeserializeObject <FormVM>(file);
                }
            }
            else
            {
                var schema = _repo.GetByIdAsync(1).Result;
                if (schema != null)
                {
                    formVm = JsonConvert.DeserializeObject <FormVM>(schema.SchemaJson);
                }
            }

            var pageVm = string.IsNullOrEmpty(pageId)
                ? formVm.Pages.FirstOrDefault()
                : formVm.Pages.FirstOrDefault(m => m.PageId == pageId);

            return(pageVm);
        }
Exemple #2
0
        public void Index_Should_Return_573_Error()
        {
            //arrange
            FormVM formVm = null;

            //Controller needs a controller context
            var httpContext       = new DefaultHttpContext();
            var controllerContext = new ControllerContext()
            {
                HttpContext = httpContext
            };

            var mockLogger              = new Mock <ILogger <CheckYourAnswersController> >();
            var mockSession             = new Mock <ISessionService>();
            var mockCosmosService       = new Mock <ICosmosService>();
            var mockSubmissionService   = new Mock <ISubmissionService>();
            var mockNotificationService = new Mock <INotificationService>();
            var mockDocumentService     = new Mock <IDocumentService>();
            var mockPageHelper          = new Mock <IPageHelper>();
            var mockConfig              = new Mock <IConfiguration>();

            var sut = new CheckYourAnswersController(mockLogger.Object, mockSubmissionService.Object, mockCosmosService.Object,
                                                     mockNotificationService.Object, mockDocumentService.Object, mockSession.Object,
                                                     mockPageHelper.Object, mockConfig.Object);

            sut.ControllerContext = controllerContext;
            //act
            var result = sut.Index(new CheckYourAnswersVm());

            //assert
            var statusResult = result as StatusResult;

            statusResult.StatusCode.Should().Be(573);
        }
        public ActionResult Create([Bind(Include = "NumberForm, SurveyGeographyId, HousingTypeId, DistrictId, InterviewerId, Address, Phone,InterviewDate, StartTime, EndTime")] FormVM formVM)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    FormDTO formDTO = Mapper.Map <FormDTO>(formVM);
                    //int questionId = QuestionService.AddAndGetId(questionDTO);
                    FormService.Add(formDTO);
                    return(RedirectToAction("Index"));
                }
                ViewBag.SurveyGeographyId = GetSurveyGeographySelectList(formVM.SurveyGeographyId);
                ViewBag.HousingTypeId     = GetHousingTypeSelectList(formVM.HousingTypeId);
                ViewBag.DistrictId        = GetDistrictSelectList(formVM.DistrictId);
                ViewBag.InterviewerId     = GetInterviewerSelectList(formVM.InterviewerId);
                ViewBag.Today             = DateTime.Now.ToString("yyyy-MM-dd");
                ViewBag.Time = DateTime.Now.ToString("HH\\:mm");

                return(View(formVM));
            }
            catch (UniqueConstraintException ex)
            {
                return(Json(new { hasError = true, data = ex.Message }, JsonRequestBehavior.AllowGet));
            }
        }
        /// <summary>
        /// Handle logic for dynamic content within a page, overriding supplied content as required
        /// </summary>
        /// <param name="page">The page with potential dynamic content</param>
        /// <param name="formContext">Form the question is part of</param>
        /// <returns></returns>
        public static PageVM HandleDynamicContent(this PageVM page, FormVM formContext)
        {
            var defaultPage = page;

            try
            {
                if (page.DynamicContent != null)
                {
                    var conditions = page.DynamicContent.Conditions;
                    page.ApplyDynamicContent(conditions, formContext);
                }

                foreach (var question in page.Questions)
                {
                    if (question.DynamicContent != null)
                    {
                        var conditions = question.DynamicContent.Conditions;
                        question.ApplyDynamicContent(conditions, formContext);
                    }
                }
            }
            catch
            {
                return(defaultPage);
            }

            return(page);
        }
Exemple #5
0
        public void Index_Should_Return_575_Error()
        {
            //arrange
            FormVM formVm = new FormVM
            {
                Pages = new List <PageVM>
                {
                    new PageVM
                    {
                        PageId        = "CheckYourAnswers",
                        PreviousPages = new List <PreviousPageVM>
                        {
                            new PreviousPageVM {
                                PageId = "what-you-want-to-tell-us-about", QuestionId = "", Answer = ""
                            },
                            new PreviousPageVM {
                                PageId = "did-you-hear-about-this-form-from-a-charity", QuestionId = "", Answer = ""
                            },
                            new PreviousPageVM {
                                PageId = "give-your-feedback", QuestionId = "", Answer = ""
                            }
                        }
                    }
                }
            };
            //Controller needs a controller context
            var httpContext       = new DefaultHttpContext();
            var controllerContext = new ControllerContext()
            {
                HttpContext = httpContext,
            };

            var mockLogger              = new Mock <ILogger <CheckYourAnswersController> >();
            var mockSession             = new Mock <ISessionService>();
            var mockCosmosService       = new Mock <ICosmosService>();
            var mockSubmissionService   = new Mock <ISubmissionService>();
            var mockNotificationService = new Mock <INotificationService>();
            var mockDocumentService     = new Mock <IDocumentService>();
            var mockPageHelper          = new Mock <IPageHelper>();
            var fakeConfiguration       = new ConfigurationBuilder().Add(configData).Build();

            mockSession.Setup(x => x.GetFormVmFromSession()).Returns(formVm);
            mockSession.Setup(x => x.GetUserSession()).Returns(new UserSessionVM {
                LocationName = "location"
            });
            mockSession.Setup(x => x.GetNavOrder()).Returns(new List <string>());

            var sut = new CheckYourAnswersController(mockLogger.Object, mockSubmissionService.Object, mockCosmosService.Object,
                                                     mockNotificationService.Object, mockDocumentService.Object, mockSession.Object,
                                                     mockPageHelper.Object, fakeConfiguration);

            sut.ControllerContext = controllerContext;
            //act
            var result = sut.Index();

            //assert
            var statusResult = result as StatusResult;

            statusResult.StatusCode.Should().Be(575);
        }
Exemple #6
0
        public JsonResult InsertAndUpdate(FormVM formsVM, int id)
        {
            try
            {
                var json        = JsonConvert.SerializeObject(formsVM);
                var buffer      = System.Text.Encoding.UTF8.GetBytes(json);
                var byteContent = new ByteArrayContent(buffer);
                byteContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");

                if (formsVM.Id == 0)
                {
                    var result = client.PostAsync("forms", byteContent).Result;
                    return(Json(result));
                }
                else if (formsVM.Id == id)
                {
                    var result = client.PutAsync("forms/" + id, byteContent).Result;
                    return(Json(result));
                }

                return(Json(404));
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Exemple #7
0
        /// <summary>
        /// returns true if the next question in the path has been answered
        /// </summary>
        /// <param name="formVm"></param>
        /// <param name="pageVm"></param>
        /// <returns></returns>
        public bool HasNextQuestionBeenAnswered(HttpRequest request, FormVM formVm, PageVM pageVm)
        {
            var isAnswered = false;
            var newAnswer  = GetNewAnswer(request, pageVm.Questions);

            if (!string.IsNullOrWhiteSpace(newAnswer))
            {
                var    question   = pageVm.Questions.FirstOrDefault();
                string nextPageId = string.Empty;
                if (question.AnswerLogic != null)
                {
                    nextPageId =
                        (question.AnswerLogic.Where(an => an.Value == newAnswer).FirstOrDefault() == null
                            ? string.Empty
                            : question.AnswerLogic.Where(an => an.Value == newAnswer)
                         .FirstOrDefault().NextPageId);
                }

                if (string.IsNullOrWhiteSpace(nextPageId))
                {
                    nextPageId = pageVm.NextPageId;
                }
                var nextPageVm = formVm.Pages.Where(p => p.PageId == nextPageId).FirstOrDefault();
                isAnswered = !string.IsNullOrWhiteSpace(nextPageVm.Questions.FirstOrDefault().Answer);
            }

            return(isAnswered);
        }
Exemple #8
0
        public void ReportaProblemShouldReturn555StatusCode()
        {
            //arrange
            var fakeConfiguration = new ConfigurationBuilder()
                                    .Add(configData)
                                    .Build();
            //Controller needs a controller context
            var httpContext       = new DefaultHttpContext();
            var controllerContext = new ControllerContext()
            {
                HttpContext = httpContext,
            };
            var formVm = new FormVM {
                Pages = new List <PageVM>()
            };
            var mockLogger      = new Mock <ILogger <HelpController> >();
            var mockFormService = new Mock <IFormService>();

            mockFormService.Setup(x => x.FindByNameAndVersion("form1", "version1")).ReturnsAsync(formVm);
            var mockGdsValidation       = new Mock <IGdsValidation>();
            var mockNotificationService = new Mock <INotificationService>();
            var mockSessionService      = new Mock <ISessionService>();
            var mockActionService       = new Mock <IActionService>();

            //act
            var sut = new HelpController(mockLogger.Object, mockFormService.Object, mockGdsValidation.Object, fakeConfiguration, mockNotificationService.Object, mockSessionService.Object, mockActionService.Object);

            sut.ControllerContext = controllerContext;
            var response = sut.Feedback("urlReferer");
            //assert
            var result = response as StatusResult;

            result.StatusCode.Should().Be(555);
        }
        public ActionResult Edit([Bind(Include = "Id, NumberForm, SurveyGeographyId, HousingTypeId, DistrictId, InterviewerId, Address, Phone,InterviewDate, StartTime, EndTime")] FormVM formVM)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    FormDTO formDTO = Mapper.Map <FormDTO>(formVM);
                    FormService.Update(formDTO);
                    return(RedirectToAction("Index"));
                }
                else
                {
                    ModelState.AddModelError(null, "Что-то пошло не так. Не удалось сохранить изменения.");
                }

                ViewBag.SurveyGeographyId = GetSurveyGeographySelectList(formVM.SurveyGeographyId);
                ViewBag.HousingTypeId     = GetHousingTypeSelectList(formVM.HousingTypeId);
                ViewBag.DistrictId        = GetDistrictSelectList(formVM.DistrictId);
                ViewBag.InterviewerId     = GetInterviewerSelectList(formVM.InterviewerId);

                return(View(formVM));
            }
            catch (UniqueConstraintException ex)
            {
                return(Json(new { hasError = true, data = ex.Message }, JsonRequestBehavior.AllowGet));
            }
        }
Exemple #10
0
        /// <summary>
        /// Generate a PostFeedbackVM from the specified schema for only one page
        /// </summary>
        /// <param name="formVm">Generic GFC form schema object</param>
        /// <returns></returns>
        private PfSurveyVM GenerateSinglePageSubmission(FormVM formVm)
        {
            var postFeedbackVm = new PfSurveyVM
            {
                Version     = formVm.Version,
                Id          = Guid.NewGuid().ToString(),
                DateCreated = new DateTime().GetLocalDateTime(),
                FormName    = formVm.FormName
            };
            var answers = new List <AnswerVM>();

            var page = formVm.Pages.FirstOrDefault() ?? null;

            answers.AddRange(page.Questions.Where(m => !string.IsNullOrEmpty(m.Answer))
                             .Select(question => new AnswerVM
            {
                PageId        = page.PageId,
                QuestionId    = question.QuestionId,
                Question      = string.IsNullOrEmpty(question.Question) ? page.PageName.StripHtml() : question.Question.StripHtml(),
                Answer        = question.Answer.StripHtml(),
                DocumentOrder = question.DocumentOrder
            }));

            postFeedbackVm.Answers = answers;

            return(postFeedbackVm);
        }
Exemple #11
0
        private void SetupPreviousPagesLists(string pageId, FormVM formVm, ref List <PageVM> previousPages, ref List <PageVM> previousLogicPages, ref List <PageVM> previousPathchangePages)
        {
            var invalidPreviousPages = new List <PageVM>();

            if (previousPages.Count > 1)
            {
                //there is more then one entry to this page
                foreach (var page in previousPages)
                {
                    foreach (var page2 in previousPages.Where(p => p.PageId != page.PageId))
                    {
                        foreach (var question in page2.Questions.Where(q => q.AnswerLogic != null))
                        {
                            foreach (var al in question.AnswerLogic)
                            {
                                if (al.NextPageId == page.PageId)
                                {
                                    invalidPreviousPages.Add(al.Value == question.Answer ? page2 : page);
                                }
                            }
                        }
                    }
                }
            }
            //remove invalid previous pages
            foreach (var page in invalidPreviousPages)
            {
                previousPages.Remove(page);
            }
            //see if there are any previous pages with logic answers pointing to this page
            foreach (var pge in formVm.Pages)
            {
                var questions = pge.Questions.Where(q => q.AnswerLogic != null).Where(a => a.AnswerLogic.Any(x => x.NextPageId == pageId)).ToList();
                if (questions.Count > 0)
                {
                    previousLogicPages.Add(pge);
                }

                if (pge.PathChangeQuestion != null)
                {
                    if (pge.PathChangeQuestion.NextPageId == pageId)
                    {
                        previousPathchangePages.Add(pge);
                    }
                }
            }

            var thisPage = formVm.Pages.FirstOrDefault(p => p.PageId == pageId);

            if (!string.IsNullOrWhiteSpace(thisPage?.NextPageReferenceId))
            {
                var referencePage = formVm.Pages.FirstOrDefault(p => p.PageId == thisPage.NextPageReferenceId);
                if (!previousPages.Contains(referencePage))
                {
                    previousPages.Add(referencePage);
                }
            }
        }
        public IActionResult CreateForm([FromBody] FormVM Form)
        {
            var create = _formRepository.Create(Form);

            if (create > 0)
            {
                return(Ok(create));
            }
            return(BadRequest("Create Form is failed"));
        }
        public IActionResult EditForm(int Id, FormVM Form)
        {
            var edit = _formRepository.Update(Form, Id);

            if (edit > 0)
            {
                return(Ok(edit));
            }
            return(BadRequest("Edit Form is failed"));
        }
Exemple #14
0
        /// <summary>
        /// Bind properties to the inputs.
        /// </summary>
        private void BindProperties()
        {
            if (FormVM == null)
            {
                return;
            }

            Title             = FormVM.Title;
            TimeZoneRegion    = FormVM.TimeZoneRegion;
            SchedulePresenter = FormVM.CreateScheduleCopy(true);
        }
        public ActionResult RootObjectEkle(FormVM model)
        {
            RootObject root = new RootObject();

            root.name        = model.Ad;
            root.description = model.Aciklama;



            RootObjectManager.Add(root);

            return(View(GetFormVM()));
        }
Exemple #16
0
        public virtual bool Validate()
        {
            List <DataGrid> dataGrids = DataGrids;

            DataGridHelper.CommitEdit(dataGrids);
            if (!Validator.Validate(this))
            {
                return(false);
            }
            DataGridHelper.Finalize(dataGrids);
            FormVM.Complete(null);
            return(true);
        }
Exemple #17
0
        /// <summary>
        /// Save settings.
        /// </summary>
        private async Task SaveChangesCommandMethodAsync()
        {
            await RunCommandAsync(() => mModifyFlag, async() =>
            {
                if (IoC.DataContent.ScheduleData.IsRunning)
                {
                    return;
                }

                // Trim.
                string title = Title.Trim();

                // Validate inputs.
                if (!Core.ScheduleTemplateDataViewModel.ValidateInputs(FormVM, title, TimeZoneRegion))
                {
                    // Some error occured during saving changes of the timer.
                    _ = IoC.UI.ShowNotification(new NotificationBoxDialogViewModel()
                    {
                        Title   = "INVALID VALUES",
                        Message = $"Some of the entered values are invalid. Please check them again.",
                        Result  = NotificationBoxResult.Ok,
                    });

                    return;
                }

                // Save changes.
                #region Save changes

                FormVM.LastModifiedTicks = DateTime.Now.Ticks;
                FormVM.Title             = title;
                FormVM.TimeZoneRegion    = TimeZoneRegion;
                FormVM.Schedule          = FormVM.CreateScheduleFromPresenter(SchedulePresenter);

                #endregion

                // Sort schedule.
                FormVM.SortSchedule();

                // Log it.
                IoC.Logger.Log($"Settings changed: template '{FormVM.Title}'.", LogLevel.Info);

                // Update template title list presenter.
                IoC.DataContent.ScheduleData.SetTemplateTitleListPresenter();

                // Move back to the page.
                GoBackCommandMethod();

                await Task.Delay(1);
            });
        }
Exemple #18
0
        public void SaveFormVmToSession(FormVM vm, Dictionary <string, string> replacements)
        {
            var context = _httpContextAccessor.HttpContext;
            var json    = JsonConvert.SerializeObject(vm);

            if (replacements?.Count > 0)
            {
                foreach (var item in replacements)
                {
                    json = json.Replace(item.Key, item.Value);
                }
            }
            context.Session.SetString(schemaKey, json);
        }
Exemple #19
0
        public static void UpdateViewOfVM(UserControl control)
        {
            if (!(control is IValidatable))
            {
                throw new ArgumentException("Invalid control (IValidatable not implemented)");
            }

            FormVM vm = control.DataContext as FormVM;

            if (vm != null)
            {
                vm.View = (IValidatable)control;
                vm.Reload();
            }
        }
Exemple #20
0
 public int Create(FormVM form)
 {
     using (SqlConnection connection = new SqlConnection(_configuration.GetConnectionString("myConn")))
     {
         var procName = "SP_InsertForm";
         parameters.Add("employee", form.employeeId);
         parameters.Add("StartDate", form.StartDate);
         parameters.Add("EndDate", form.EndDate);
         parameters.Add("Duration", form.Duration);
         parameters.Add("supervisor", form.supervisorId);
         parameters.Add("department", form.departmentId);
         var InsertForm = connection.Execute(procName, parameters, commandType: CommandType.StoredProcedure);
         return(InsertForm);
     }
 }
Exemple #21
0
        private string GetNextPageId(FormVM formVm, PageVM pageVm, string location, bool skipNextQuestions, bool serviceNotFound, string rootNextPageId)
        {
            var nextPageId = !string.IsNullOrWhiteSpace(pageVm.NextPageReferenceId) ? _pageHelper.GetNextPageIdFromPage(formVm, pageVm.NextPageReferenceId) : pageVm.NextPageId;

            //We should only apply the path change logic if 1) there is a path change question and 2) we HAVE NOT already changed the nextPageId with answerLogic (which is higher priority)
            if (pageVm.PathChangeQuestion != null && nextPageId == rootNextPageId)
            {
                //branch the user journey if a previous question has a specific answer
                var questions = formVm.Pages.SelectMany(m => m.Questions).ToList();

                var startChangeJourney = questions.FirstOrDefault(m => m.QuestionId == pageVm.PathChangeQuestion.QuestionId);
                if (startChangeJourney != null && startChangeJourney.Answer == pageVm.PathChangeQuestion.Answer)
                {
                    nextPageId = pageVm.PathChangeQuestion.NextPageId;
                }
            }

            //check if this is the end of the changed question flow in edit mode
            if ((_sessionService.GetChangeModeRedirectId() ?? string.Empty) == nextPageId || (_sessionService.GetChangeModeRedirectId() ?? string.Empty) == pageVm.NextPageId || skipNextQuestions)
            {
                nextPageId = _config.Value.SiteTextStrings.ReviewPageId;
            }

            //Special case to handle if we are currently on the first page of the form, which would ordinarily direct the user to 'search'
            if (pageVm.PageId == _config.Value.FormStartPage)
            {
                if (location == _config.Value.SiteTextStrings.NonSelectedServiceName)
                {
                    //this is the first time into the search so show it
                    nextPageId = "search";
                }
                else
                {
                    //skip the search but put it into the page history
                    _sessionService.UpdateNavOrder("search");
                    if (serviceNotFound)
                    {
                        var serviceNotFoundPageId = _config.Value.ServiceNotFoundPage;
                        _sessionService.UpdateNavOrder(serviceNotFoundPageId);
                    }
                }
            }

            return(nextPageId);
        }
        public ActionResult Details(int?id)
        {
            try
            {
                FormDTO formDTO = FormService.Get(id);
                FormVM  formVM  = Mapper.Map <FormVM>(formDTO);

                return(View(formVM));
            }
            catch (ArgumentException)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            catch (NotFoundException)
            {
                return(HttpNotFound());
            }
        }
Exemple #23
0
 public MenuItemVM FindMenuItem(FormVM form)
 {
     foreach (MenuItemVM menuItem in MenuItems)
     {
         if (menuItem.Content == form)
         {
             return(menuItem);
         }
         foreach (MenuItemVM childMenuItem in menuItem.MenuItems)
         {
             if (childMenuItem.Content == form)
             {
                 return(childMenuItem);
             }
         }
     }
     return(null);
 }
Exemple #24
0
        /// <summary>
        /// Add new item to <see cref="ScheduleDataViewModel.ItemCustomList"/>.
        /// </summary>
        private async Task AddItemCommandMethodAsync()
        {
            await RunCommandAsync(() => mModifyFlag, async() =>
            {
                IoC.Logger.Log("Creating new schedule custom item.", LogLevel.Debug);

                if (!IoC.DataContent.ScheduleData.CanAddCustomItem)
                {
                    return;
                }

                if (string.IsNullOrEmpty(NewName))
                {
                    return;
                }

                // Trim.
                string name     = NewName.Trim();
                string colorHex = "000000";

                // Add item.
                if (FormVM.AddItem(name, colorHex, false) == null)
                {
                    // Some error occured during adding item.
                    _ = IoC.UI.ShowNotification(new NotificationBoxDialogViewModel()
                    {
                        Title   = "ERROR OCCURRED!",
                        Message = $"The name of the item is already defined or some of the entered values are invalid. Please, check them again.",
                        Result  = NotificationBoxResult.Ok,
                    });

                    return;
                }

                // Log it.
                IoC.Logger.Log($"Created new schedule custom item '{name}'.", LogLevel.Info);

                // Sort list.
                FormVM.SortItemCustomList();

                await Task.Delay(1);
            });
        }
        /// <summary>
        /// Gets a question. Throws exceptions if there are multiple matches or question cannot be found.
        /// </summary>
        /// <param name="form">Form containing question</param>
        /// <param name="questionId">Question we need</param>
        /// <returns></returns>
        public static QuestionVM GetQuestion(this FormVM form, string questionId)
        {
            var matches = new List <QuestionVM>();

            foreach (PageVM page in form.Pages)
            {
                matches.AddRange(page.Questions.Where(q => q.QuestionId == questionId));
            }
            if (matches.Count > 1)
            {
                throw new Exception("Duplicate questionIds found, unable to resolve match");
            }
            else if (matches.Count == 0)
            {
                throw new Exception("QuestionId cannot be found");
            }

            return(matches.FirstOrDefault());
        }
Exemple #26
0
        public void Index_Should_Return_574_Error()
        {
            //arrange
            FormVM formVm = new FormVM();
            //Task<int> reference = 123;
            int reference = 0;
            //Controller needs a controller context
            var httpContext       = new DefaultHttpContext();
            var controllerContext = new ControllerContext()
            {
                HttpContext = httpContext,
            };
            var mockServiceProvider      = new Mock <IServiceProvider>();
            var mockLogger               = new Mock <ILogger <CheckYourAnswersController> >();
            var mockSession              = new Mock <ISessionService>();
            var mockSubmissionService    = new Mock <ISubmissionService>();
            var mockConfigurationService = new Mock <IConfiguration>();
            var mockNotificationService  = new Mock <INotificationService>();
            var mockDocumentService      = new Mock <IDocumentService>();
            var mockPageHelper           = new Mock <IPageHelper>();

            mockServiceProvider.Setup(x => x.GetService(typeof(IPageHelper))).Returns(mockPageHelper.Object);

            mockSession.Setup(x => x.GetFormVmFromSession()).Returns(formVm);
            //mockSubmissionService.Setup(x => x.GenerateSnowmakerUserRefAsync()).ReturnsAsync(reference);
            mockServiceProvider.Setup(x => x.GetService(typeof(ILogger <CheckYourAnswersController>))).Returns(mockLogger.Object);
            mockServiceProvider.Setup(x => x.GetService(typeof(ISessionService))).Returns(mockSession.Object);
            mockServiceProvider.Setup(x => x.GetService(typeof(ISubmissionService))).Returns(mockSubmissionService.Object);
            mockServiceProvider.Setup(x => x.GetService(typeof(IConfiguration))).Returns(mockConfigurationService.Object);
            mockServiceProvider.Setup(x => x.GetService(typeof(INotificationService))).Returns(mockNotificationService.Object);
            mockServiceProvider.Setup(x => x.GetService(typeof(IDocumentService))).Returns(mockDocumentService.Object);

            var sut = new CheckYourAnswersController(mockServiceProvider.Object);

            sut.ControllerContext = controllerContext;
            //act
            var result = sut.Index(new CheckYourAnswersVm());

            //assert
            var statusResult = result as StatusResult;

            statusResult.StatusCode.Should().Be(574);
        }
Exemple #27
0
        public void Index_Should_Return_571_Error()
        {
            //arrange
            FormVM formVm = new FormVM();
            //Controller needs a controller context
            var httpContext       = new DefaultHttpContext();
            var controllerContext = new ControllerContext()
            {
                HttpContext = httpContext,
            };
            var mockServiceProvider      = new Mock <IServiceProvider>();
            var mockLogger               = new Mock <ILogger <CheckYourAnswersController> >();
            var mockSession              = new Mock <ISessionService>();
            var mockSubmissionService    = new Mock <ISubmissionService>();
            var mockConfigurationService = new Mock <IConfiguration>();
            var mockNotificationService  = new Mock <INotificationService>();
            var mockDocumentService      = new Mock <IDocumentService>();
            var mockPageHelper           = new Mock <IPageHelper>();

            mockServiceProvider.Setup(x => x.GetService(typeof(IPageHelper))).Returns(mockPageHelper.Object);

            mockSession.Setup(x => x.GetFormVmFromSession()).Returns(formVm);
            mockSession.Setup(x => x.GetUserSession()).Returns(new UserSessionVM {
                LocationName = null
            });
            mockServiceProvider.Setup(x => x.GetService(typeof(ILogger <CheckYourAnswersController>))).Returns(mockLogger.Object);
            mockServiceProvider.Setup(x => x.GetService(typeof(ISessionService))).Returns(mockSession.Object);
            mockServiceProvider.Setup(x => x.GetService(typeof(ISubmissionService))).Returns(mockSubmissionService.Object);
            mockServiceProvider.Setup(x => x.GetService(typeof(IConfiguration))).Returns(mockConfigurationService.Object);
            mockServiceProvider.Setup(x => x.GetService(typeof(INotificationService))).Returns(mockNotificationService.Object);
            mockServiceProvider.Setup(x => x.GetService(typeof(IDocumentService))).Returns(mockDocumentService.Object);

            var sut = new CheckYourAnswersController(mockServiceProvider.Object);

            sut.ControllerContext = controllerContext;
            //act
            var result = sut.Index();

            //assert
            var statusResult = result as StatusResult;

            statusResult.StatusCode.Should().Be(571);
        }
Exemple #28
0
        public JsonResult GetById(int Id)
        {
            FormVM formsVM = null;
            var    resTask = client.GetAsync("forms/" + Id);

            resTask.Wait();

            var result = resTask.Result;

            if (result.IsSuccessStatusCode)
            {
                var json = JsonConvert.DeserializeObject(result.Content.ReadAsStringAsync().Result).ToString();
                formsVM = JsonConvert.DeserializeObject <FormVM>(json);
            }
            else
            {
                ModelState.AddModelError(string.Empty, "Server Error.");
            }
            return(Json(formsVM));
        }
Exemple #29
0
        private bool isValidPath(string currentPage, string previousPage, FormVM formVm, string serviceNoteFoundPage, string formStartPage, bool serviceNotFound, ref List <Tuple <string, string> > checkedInvalidPaths)
        {
            //Create a variable to hold the path we would like to check, from this page (pageId) to the previous page (page.PageId)
            var thisPath = new Tuple <string, string>(currentPage, previousPage);

            if (checkedInvalidPaths.Contains(thisPath))
            {
                return(false);
            }

            var validPath = CheckPathToStart2(previousPage, formVm, serviceNoteFoundPage, formStartPage,
                                              serviceNotFound, ref checkedInvalidPaths);

            if (!validPath)
            {
                checkedInvalidPaths.Add(thisPath);
            }

            return(validPath);
        }
Exemple #30
0
        /// <summary>
        /// Remove item from <see cref="ScheduleDataViewModel.ItemCustomList"/>.
        /// </summary>
        /// <param name="parameter"></param>
        private async Task RemoveItemCommandMethodAsync(object parameter)
        {
            await RunCommandAsync(() => mModifyFlag, async() =>
            {
                var par = (ScheduleItemDataViewModel)parameter;

                IoC.Logger.Log($"Removing schedule custom item '{par}'...", LogLevel.Debug);

                // Remove.
                if (!FormVM.DestroyCustomItem(par))
                {
                    IoC.Logger.Log($"Error occured during removing schedule custom item '{par}'!", LogLevel.Error);
                    return;
                }

                // Log it.
                IoC.Logger.Log($"Removed schedule custom item '{par}'.", LogLevel.Info);

                await Task.Delay(1);
            });
        }