public void ShouldGenerateKeyForAllSchema() { var form = new FormSchema("F", new TableSchema(), new TableSchema { Name = "Bảng biểu quý 1" }, new FieldSchema(), new FieldSchema { Name = "FullName" }, new FieldSchema { Key = "GTGT01_PL01" } ); Assert.AreEqual("table_1", form[1].Key); Assert.AreEqual("Bng_biu_qu_1", form[2].Key); Assert.AreEqual("field_3", form[3].Key); Assert.AreEqual("FullName", form[4].Key); Assert.AreEqual("GTGT01_PL01", form[5].Key); }
public void CanQueryItemByPathInContainer() { var form = new FormSchema("F", new GroupSchema("G1", new GroupSchema("G2", new GroupSchema("G3", new GroupSchema("G4", new GroupSchema("G5", new TableSchema("T1", new FieldSchema("F1"))))))), new GroupSchema("X1", new FieldSchema("F2")) ); var f = form["G1", "G2", "G3", "G4", "G5", "T1", "F1"]; Assert.IsNotNull(f); Assert.AreEqual("F1", f.Key); var fa = form["G1", "G2", "G3", "G4", "G10", "T1", "F1"]; Assert.IsNull(fa); var fb = form["G1", "G2", "G3", "G4", "G5", "T1", "F10"]; Assert.IsNull(fb); var x = form["X1", "F2"]; Assert.IsNotNull(x); Assert.AreEqual("F2", x.Key); }
public ValidationResult Validate(Element element, Dictionary <string, dynamic> viewModel, FormSchema baseForm) { if (!element.Type.Equals(EElementType.Address) || (element.Type.Equals(EElementType.Address) && !viewModel.IsInitial())) { return new ValidationResult { IsValid = true } } ; if (!element.Properties.StockportPostcode.GetValueOrDefault()) { return new ValidationResult { IsValid = true } } ; if ((!element.Properties.StockportPostcode.HasValue || !element.Properties.StockportPostcode.Value) || !viewModel.ContainsKey($"{element.Properties.QuestionId}{AddressConstants.SEARCH_SUFFIX}")) { return new ValidationResult { IsValid = true } } ; if (string.IsNullOrEmpty(viewModel[$"{element.Properties.QuestionId}{AddressConstants.SEARCH_SUFFIX}"]) && element.Properties.Optional) { return new ValidationResult { IsValid = true } } ; var value = viewModel[$"{element.Properties.QuestionId}{AddressConstants.SEARCH_SUFFIX}"]; var isValid = true; if (!AddressConstants.STOCKPORT_POSTCODE_REGEX.Match(value).Success) { isValid = false; } return(new ValidationResult { IsValid = isValid, Message = isValid ? string.Empty : ValidationConstants.POSTCODE_INCORRECT_FORMAT }); } } }
public ValidationResult Validate(Element element, Dictionary <string, dynamic> viewModel, FormSchema baseForm) { if (!element.Properties.RestrictFutureDate || element.Type == EElementType.DatePicker) { return(new ValidationResult { IsValid = true }); } var valueDay = viewModel.ContainsKey($"{element.Properties.QuestionId}-day") ? viewModel[$"{element.Properties.QuestionId}-day"] : null; var valueMonth = viewModel.ContainsKey($"{element.Properties.QuestionId}-month") ? viewModel[$"{element.Properties.QuestionId}-month"] : null; var valueYear = viewModel.ContainsKey($"{element.Properties.QuestionId}-year") ? viewModel[$"{element.Properties.QuestionId}-year"] : null; if (element.Properties.Optional && string.IsNullOrEmpty(valueDay) && string.IsNullOrEmpty(valueMonth) && string.IsNullOrEmpty(valueYear)) { return(new ValidationResult { IsValid = true }); } var isValidDate = DateTime.TryParse($"{valueDay}/{valueMonth}/{valueYear}", out _); if (!isValidDate) { return(new ValidationResult { IsValid = false, Message = !string.IsNullOrEmpty(element.Properties.CustomValidationMessage) ? element.Properties.CustomValidationMessage : "Check the date and try again" }); } var date = DateTime.Today; var dateOutput = DateTime.Parse($"{valueDay}/{valueMonth}/{valueYear}"); if (dateOutput > date) { return(new ValidationResult { IsValid = false, Message = !string.IsNullOrEmpty(element.Properties.ValidationMessageRestrictFutureDate) ? element.Properties.ValidationMessageRestrictFutureDate : "Check the date and try again" }); } return(new ValidationResult { IsValid = true, Message = string.Empty }); }
public ValidationResult Validate(Element element, Dictionary <string, dynamic> viewModel, FormSchema baseForm) { if (!element.Properties.RestrictPastDate || !element.Type.Equals(EElementType.DatePicker) || element.Properties.Optional) { return new ValidationResult { IsValid = true } } ; var value = viewModel.ContainsKey(element.Properties.QuestionId) ? viewModel[element.Properties.QuestionId] : null; var outDate = DateTime.Now; var isValidDate = DateTime.TryParse(value, out outDate); if (!isValidDate) { return(new ValidationResult { IsValid = false, Message = !string.IsNullOrEmpty(element.Properties.CustomValidationMessage) ? element.Properties.CustomValidationMessage : "Check the date and try again" }); } var date = DateTime.Today; var dateOutput = DateTime.Parse(value); if (dateOutput < date && element.Properties.RestrictPastDate) { return(new ValidationResult { IsValid = false, Message = !string.IsNullOrEmpty(element.Properties.ValidationMessageRestrictPastDate) ? element.Properties.ValidationMessageRestrictPastDate : "Check the date and try again" }); } return(new ValidationResult { IsValid = true, Message = string.Empty }); } }
private async Task <string> ProcessGenuineSubmission(MappingEntity mappingEntity, string form, string sessionGuid, FormSchema baseForm, string reference) { var currentPage = mappingEntity.BaseForm.GetPage(_pageHelper, mappingEntity.FormAnswers.Path); var submitSlug = currentPage.GetSubmitFormEndpoint(mappingEntity.FormAnswers, _environment.EnvironmentName.ToS3EnvPrefix()); HttpResponseMessage response = await _submitProviders.Get(submitSlug.Type).PostAsync(mappingEntity, submitSlug); if (!response.IsSuccessStatusCode) { throw new ApplicationException($"SubmitService::ProcessSubmission, An exception has occurred while attempting to call {submitSlug.URL}, Gateway responded with {response.StatusCode} status code, Message: {JsonConvert.SerializeObject(response)}"); } if (!baseForm.GenerateReferenceNumber && response.Content is not null) { var content = await response.Content.ReadAsStringAsync() ?? string.Empty; reference = JsonConvert.DeserializeObject <string>(content); _pageHelper.SaveCaseReference(sessionGuid, reference); } return(reference); }
public ValidationResult Validate(Element element, Dictionary <string, dynamic> viewModel, FormSchema baseForm) { if (element.Type != EElementType.Textbox) { return(new ValidationResult { IsValid = true }); } if (string.IsNullOrEmpty(viewModel[element.Properties.QuestionId]) && element.Properties.Optional) { return(new ValidationResult { IsValid = true }); } if ((!element.Properties.StockportPostcode.HasValue || !element.Properties.StockportPostcode.Value) || !viewModel.ContainsKey(element.Properties.QuestionId)) { return(new ValidationResult { IsValid = true }); } var value = viewModel[element.Properties.QuestionId]; var isValid = true; if (!AddressConstants.STOCKPORT_POSTCODE_REGEX.Match(value).Success) { isValid = false; } return(new ValidationResult { IsValid = isValid, Message = isValid ? string.Empty : ValidationConstants.POSTCODE_INCORRECT_FORMAT }); }
public ValidationResult Validate(Element element, Dictionary <string, dynamic> viewModel, FormSchema baseForm) { ValidationResult successResult = new() { IsValid = true }; if ((!element.Type.Equals(EElementType.DatePicker) && !element.Type.Equals(EElementType.DateInput)) || string.IsNullOrEmpty(element.Properties.IsDateAfterAbsolute)) { return(successResult); } DateTime?dateValue = new DateTime(); if (element.Type.Equals(EElementType.DatePicker)) { dateValue = DatePicker.GetDate(viewModel, element.Properties.QuestionId); } if (element.Type.Equals(EElementType.DateInput)) { dateValue = DateInput.GetDate(viewModel, element.Properties.QuestionId); } if (!dateValue.HasValue) { return new ValidationResult { IsValid = true } } ; if (!DateTime.TryParse(element.Properties.IsDateAfterAbsolute, out DateTime comparisonDateValue)) { throw new FormatException("IsDateAfterAbsoluteValidator: The comparison date format was incorrect"); } if (dateValue > comparisonDateValue) { return(successResult); } return(new ValidationResult { IsValid = false, Message = !string.IsNullOrEmpty(element.Properties.IsDateAfterValidationMessage) ? element.Properties.IsDateAfterValidationMessage : string.Format(ValidationConstants.IS_DATE_AFTER_VALIDATOR_DEFAULT, element.Properties.IsDateAfterAbsolute) }); } } }
public ValidationResult Validate(Element element, Dictionary <string, dynamic> viewModel, FormSchema baseForm) { if (!element.Type.Equals(EElementType.TimeInput)) { return new ValidationResult { IsValid = true } } ; var valueHours = viewModel.ContainsKey($"{element.Properties.QuestionId}{TimeConstants.HOURS_SUFFIX}") ? viewModel[$"{element.Properties.QuestionId}{TimeConstants.HOURS_SUFFIX}"] : null; var valueMinutes = viewModel.ContainsKey($"{element.Properties.QuestionId}{TimeConstants.MINUTES_SUFFIX}") ? viewModel[$"{element.Properties.QuestionId}{TimeConstants.MINUTES_SUFFIX}"] : null; var valueAmPm = viewModel.ContainsKey($"{element.Properties.QuestionId}{TimeConstants.AM_PM_SUFFIX}") ? viewModel[$"{element.Properties.QuestionId}{TimeConstants.AM_PM_SUFFIX}"] : null; if (string.IsNullOrEmpty(valueHours) && string.IsNullOrEmpty(valueMinutes) && string.IsNullOrEmpty(valueAmPm) && element.Properties.Optional) { return new ValidationResult { IsValid = true } } ; var isValid = !string.IsNullOrEmpty(valueHours) && !string.IsNullOrEmpty(valueMinutes); if (!isValid) { return(new ValidationResult { IsValid = false, Message = !string.IsNullOrEmpty(element.Properties.CustomValidationMessage) ? element.Properties.CustomValidationMessage : "Check the time and try again" }); } var isSelected = !string.IsNullOrEmpty(valueAmPm); if (!isSelected) { return(new ValidationResult { IsValid = isSelected, Message = isSelected ? string.Empty : !string.IsNullOrEmpty(element.Properties.CustomValidationMessageAmPm) ? element.Properties.CustomValidationMessageAmPm : "Choose AM or PM" }); } int.TryParse(valueHours, out int hours); int.TryParse(valueMinutes, out int minutes); var isValidTime = (hours < 13 && hours > 0) && (minutes < 60 && minutes >= 0); return(new ValidationResult { IsValid = isValidTime, Message = isValidTime ? string.Empty : !string.IsNullOrEmpty(element.Properties.ValidationMessageInvalidTime) ? element.Properties.ValidationMessageInvalidTime : "Check the time and try again" }); } } }
public void ContainerShouldEnsureItemKeysAreUniqueWithinAForm() { var form = new FormSchema("F", new GroupSchema(null, new GroupSchema(null, new GroupSchema(null, new GroupSchema(null, new TableSchema(null, new FieldSchema() ), new FileSchema(), new FieldSchema(), new ListSchema() ) ) ) ), new TableSchema(null, new FieldSchema(), new FieldSchema() ), new FieldSchema(), new FileSchema(), new ListSchema() ); var nodes = form.Descendants().ToList(); var keys = nodes.Select(x => x.Key); Assert.AreEqual(16, nodes.Count); CollectionAssert.AllItemsAreNotNull(nodes); CollectionAssert.AllItemsAreUnique(keys); }
private List <dynamic> GenerateSubmissionData(string alias, out string fieldNames) { List <dynamic> resultList = new List <dynamic>(); fieldNames = ""; int formID = FormSchema.GetFormIDFromAlias(alias, false); if (formID > -1) { List <FormStorageSubmissionModel> fetchedSubmissionRecords = new List <FormStorageSubmissionModel>(); string querySQL = "SELECT * FROM FormStorageSubmissions WHERE formID = @formID"; string filterValue = Request.Params["period"]; DateTime filterDate = DateTime.Now.Date; if (!string.IsNullOrEmpty(filterValue)) { int filterDays = 0; int.TryParse(filterValue, out filterDays); filterDate = filterDate.AddDays(filterDays * -1); } try { if (!string.IsNullOrEmpty(filterValue)) { querySQL += " AND datetime >= @datetime"; fetchedSubmissionRecords = DatabaseConnection.Query <FormStorageSubmissionModel>(querySQL, new { formID = formID, datetime = filterDate }).ToList(); } else { fetchedSubmissionRecords = DatabaseConnection.Query <FormStorageSubmissionModel>(querySQL, new { formID = formID }).ToList(); } } catch (Exception ex) { Log.Error("Unable to query FormStorageSubmissions table : " + ex.Message); return(resultList); } // Set-up filters List <string> fieldList = null; List <string> filterFieldList = new List <string>(); fieldNames = WebConfigurationManager.AppSettings["FormStorage:" + alias]; if (!string.IsNullOrEmpty(fieldNames)) { fieldList = new List <string>(fieldNames.Split(',')); fieldList.Add("IP"); fieldList.Add("datetime"); } bool filterApplied = false; if (fieldList != null) { foreach (string fieldName in fieldList) { if (Request.Params[fieldName] != null) { filterFieldList.Add(fieldName); filterApplied = true; } } } foreach (FormStorageSubmissionModel currentSubmissionRecord in fetchedSubmissionRecords) { List <FormStorageEntryModel> fetchedEntryRecords = new List <FormStorageEntryModel>(); querySQL = "SELECT * FROM FormStorageEntries WHERE submissionID = @submissionID"; try { fetchedEntryRecords = DatabaseConnection.Query <FormStorageEntryModel>(querySQL, new { submissionID = currentSubmissionRecord.SubmissionID }).ToList(); } catch (Exception ex) { Log.Error("Unable to query FormStorageEntries table : " + ex.Message); return(resultList); } var currentRecord = new ExpandoObject() as IDictionary <string, Object>; currentRecord.Add("submissionID", currentSubmissionRecord.SubmissionID); currentRecord.Add("datetime", currentSubmissionRecord.Datetime); currentRecord.Add("IP", currentSubmissionRecord.IP); foreach (FormStorageEntryModel formStorageEntry in fetchedEntryRecords) { currentRecord.Add(formStorageEntry.FieldAlias, formStorageEntry.Value); } // Apply filters... bool filteredOut = false; if (filterApplied) { foreach (string fieldName in filterFieldList) { if (((IDictionary <string, Object>)currentRecord).ContainsKey(fieldName)) { filterValue = Request.Params[fieldName]; if (!currentRecord[fieldName].ToString().ToUpper().Contains(filterValue.ToUpper())) { filteredOut = true; break; } } } } if (!filteredOut) { resultList.Add(currentRecord); } } resultList = HandleListSorting(resultList); } return(resultList); }
public void Validate(Dictionary <string, dynamic> viewModel, IEnumerable <IElementValidator> validators, FormSchema baseForm) { foreach (var validator in validators) { var result = validator.Validate(this, viewModel, baseForm); if (!result.IsValid) { validationResult = result; return; } } }
private async Task <ProcessRequestEntity> ProccessInitialOrganisation( Dictionary <string, dynamic> viewModel, Page currentPage, FormSchema baseForm, string guid, string path) { var cachedAnswers = _distributedCache.GetString(guid); var organisationElement = currentPage.Elements.FirstOrDefault(_ => _.Type.Equals(EElementType.Organisation)); var convertedAnswers = cachedAnswers is null ? new FormAnswers { Pages = new List <PageAnswers>() } : JsonConvert.DeserializeObject <FormAnswers>(cachedAnswers); var organisation = (string)viewModel[$"{organisationElement.Properties.QuestionId}"]; if (currentPage.IsValid && organisationElement.Properties.Optional && string.IsNullOrEmpty(organisation)) { _pageHelper.SaveAnswers(viewModel, guid, baseForm.BaseURL, null, currentPage.IsValid); return(new ProcessRequestEntity { Page = currentPage }); } if (!currentPage.IsValid) { var formModel = await _pageFactory.Build(currentPage, viewModel, baseForm, guid, convertedAnswers); formModel.Path = currentPage.PageSlug; formModel.FormName = baseForm.FormName; formModel.PageTitle = currentPage.Title; formModel.HideBackButton = currentPage.HideBackButton; return(new ProcessRequestEntity { Page = currentPage, ViewModel = formModel }); } var foundOrganisationSearchTerm = convertedAnswers .Pages.FirstOrDefault(_ => _.PageSlug.Equals(path))? .Answers?.FirstOrDefault(_ => _.QuestionId.Equals(organisationElement.Properties.QuestionId))? .Response; List <object> searchResults; if (organisation.Equals(foundOrganisationSearchTerm)) { searchResults = (convertedAnswers.FormData[$"{path}{LookUpConstants.SearchResultsKeyPostFix}"] as IEnumerable <object>).ToList(); } else { try { searchResults = (await _organisationProviders.Get(organisationElement.Properties.OrganisationProvider).SearchAsync(organisation)).ToList <object>(); } catch (Exception e) { throw new ApplicationException($"OrganisationService.ProcessInitialOrganisation:: An exception has occurred while attempting to perform organisation lookup, Exception: {e.Message}"); } _pageHelper.SaveAnswers(viewModel, guid, baseForm.BaseURL, null, currentPage.IsValid); _pageHelper.SaveFormData($"{path}{LookUpConstants.SearchResultsKeyPostFix}", searchResults, guid, baseForm.BaseURL); } return(new ProcessRequestEntity { RedirectToAction = true, RedirectAction = "Index", RouteValues = new { form = baseForm.BaseURL, path, subPath = LookUpConstants.Automatic } }); }
public async Task <ProcessRequestEntity> ProcessOrganisation(Dictionary <string, dynamic> viewModel, Page currentPage, FormSchema baseForm, string guid, string path) { viewModel.TryGetValue(LookUpConstants.SubPathViewModelKey, out var subPath); switch (subPath as string) { case LookUpConstants.Automatic: return(await ProccessAutomaticOrganisation(viewModel, currentPage, baseForm, guid, path)); default: return(await ProccessInitialOrganisation(viewModel, currentPage, baseForm, guid, path)); } }
public ValidationResult Validate(Element element, Dictionary <string, dynamic> viewModel, FormSchema baseForm) { if (element.Type != EElementType.Street || (element.Type == EElementType.Street && !viewModel.IsInitial())) { return(new ValidationResult { IsValid = true }); } var streetElement = (Street)element; if (!viewModel.ContainsKey(streetElement.StreetSearchQuestionId)) { return(new ValidationResult { IsValid = true }); } if (string.IsNullOrEmpty(viewModel[streetElement.StreetSearchQuestionId]) && element.Properties.Optional) { return(new ValidationResult { IsValid = true }); } var value = viewModel[streetElement.StreetSearchQuestionId]; var isValid = true; if (!StreetConstants.STREET_REGEX.Match(value).Success) { isValid = false; } return(new ValidationResult { IsValid = isValid, Message = isValid ? string.Empty : ValidationConstants.STREET_INCORRECT_FORMAT }); }
public ValidationResult Validate(Element element, Dictionary <string, dynamic> viewModel, FormSchema baseForm) { if (element.Type != Enum.EElementType.Address) { return(new ValidationResult { IsValid = true }); } var addressElement = (Address)element; if (!viewModel.ContainsKey(addressElement.AddressSelectQuestionId)) { return(new ValidationResult { IsValid = true }); } var value = viewModel[addressElement.AddressSelectQuestionId]; if (addressElement.Properties.Optional && string.IsNullOrEmpty(value)) { return(new ValidationResult { IsValid = true }); } var isValid = AddressConstants.UPRN_REGEX.IsMatch(value); return(new ValidationResult { IsValid = isValid, Message = isValid ? string.Empty : $"please select an address" }); }
private async Task <ProcessRequestEntity> ProcessSearchAddress( Dictionary <string, dynamic> viewModel, Page currentPage, FormSchema baseForm, string guid, string path) { var cachedAnswers = _distributedCache.GetString(guid); var convertedAnswers = cachedAnswers == null ? new FormAnswers { Pages = new List <PageAnswers>() } : JsonConvert.DeserializeObject <FormAnswers>(cachedAnswers); var addressElement = currentPage.Elements.Where(_ => _.Type == EElementType.Address).FirstOrDefault(); if (!currentPage.IsValid) { var formModel = await _pageFactory.Build(currentPage, viewModel, baseForm, guid, convertedAnswers, null); return(new ProcessRequestEntity { Page = currentPage, ViewModel = formModel }); } var postcode = (string)viewModel[$"{addressElement.Properties.QuestionId}{AddressConstants.SEARCH_SUFFIX}"]; if (addressElement.Properties.Optional && string.IsNullOrEmpty(postcode)) { _pageHelper.SaveAnswers(viewModel, guid, baseForm.BaseURL, null, currentPage.IsValid); return(new ProcessRequestEntity { Page = currentPage }); } var foundPostCode = convertedAnswers .Pages.FirstOrDefault(_ => _.PageSlug.Equals(path))? .Answers?.FirstOrDefault(_ => _.QuestionId == $"{addressElement.Properties.QuestionId}{AddressConstants.SEARCH_SUFFIX}")? .Response; var addressResults = new List <object>(); if (postcode.Equals(foundPostCode)) { addressResults = (convertedAnswers.FormData[$"{path}{LookUpConstants.SearchResultsKeyPostFix}"] as IEnumerable <object>).ToList(); } else { try { addressResults = (await _addressProviders.Get(addressElement.Properties.AddressProvider).SearchAsync(postcode)).ToList <object>(); } catch (Exception e) { throw new ApplicationException($"AddressService::ProcessSearchAddress, An exception has occured while attempting to perform postcode lookup on Provider '{addressElement.Properties.AddressProvider}' with searchterm '{postcode}' Exception:", e); } _pageHelper.SaveAnswers(viewModel, guid, baseForm.BaseURL, null, currentPage.IsValid); _pageHelper.SaveFormData($"{path}{LookUpConstants.SearchResultsKeyPostFix}", addressResults, guid, baseForm.BaseURL); } if (!addressResults.Any() && !addressElement.Properties.DisableManualAddress) { return(new ProcessRequestEntity { RedirectToAction = true, RedirectAction = "Index", RouteValues = new { form = baseForm.BaseURL, path, subPath = LookUpConstants.Manual } }); } return(new ProcessRequestEntity { RedirectToAction = true, RedirectAction = "Index", RouteValues = new { form = baseForm.BaseURL, path, subPath = LookUpConstants.Automatic } }); }
public void ListsItemSchemaReflectsTheListItself() { var form = new FormSchema("F1", new ListSchema("abc", DataType.Guid) {ItemFormat = "N"}); var list = form["abc"] as ListSchema; var itemSchema = list.GetItemSchema(); Assert.AreEqual("abc", itemSchema.Key); Assert.AreEqual(DataType.Guid, itemSchema.DataType); Assert.AreEqual("N", itemSchema.DataFormat); Assert.AreEqual(form, itemSchema.Parent); }
private async Task <ProcessRequestEntity> ProcessAutomaticAddress( Dictionary <string, dynamic> viewModel, Page currentPage, FormSchema baseForm, string guid, string path) { var cachedAnswers = _distributedCache.GetString(guid); var convertedAnswers = cachedAnswers == null ? new FormAnswers { Pages = new List <PageAnswers>() } : JsonConvert.DeserializeObject <FormAnswers>(cachedAnswers); var addressElement = currentPage.Elements.FirstOrDefault(_ => _.Type == EElementType.Address); var postcode = (string)convertedAnswers .Pages .FirstOrDefault(_ => _.PageSlug == path) .Answers .FirstOrDefault(_ => _.QuestionId == $"{addressElement.Properties.QuestionId}{AddressConstants.SEARCH_SUFFIX}") .Response; var address = (string)viewModel[$"{addressElement.Properties.QuestionId}{AddressConstants.SELECT_SUFFIX}"]; if (currentPage.IsValid && addressElement.Properties.Optional && string.IsNullOrEmpty(postcode)) { _pageHelper.SaveAnswers(viewModel, guid, baseForm.BaseURL, null, currentPage.IsValid); return(new ProcessRequestEntity { Page = currentPage }); } if (currentPage.IsValid && addressElement.Properties.Optional && string.IsNullOrEmpty(address) && !string.IsNullOrEmpty(postcode)) { _pageHelper.SaveAnswers(viewModel, guid, baseForm.BaseURL, null, currentPage.IsValid); return(new ProcessRequestEntity { Page = currentPage }); } if (!currentPage.IsValid) { var cachedSearchResults = convertedAnswers.FormData[$"{path}{LookUpConstants.SearchResultsKeyPostFix}"] as IEnumerable <object>; var model = await _pageFactory.Build(currentPage, viewModel, baseForm, guid, convertedAnswers, cachedSearchResults.ToList()); return(new ProcessRequestEntity { Page = currentPage, ViewModel = model }); } _pageHelper.SaveAnswers(viewModel, guid, baseForm.BaseURL, null, currentPage.IsValid); return(new ProcessRequestEntity { Page = currentPage }); }
public ValidationResult Validate(Element element, Dictionary <string, dynamic> viewModel, FormSchema baseForm) { if (!element.Type.Equals(EElementType.Booking) || (element.Type.Equals(EElementType.Booking) && viewModel.IsCheckYourBooking())) { return new ValidationResult { IsValid = true } } ; var bookingElement = (Booking)element; var containsBookingDate = viewModel.ContainsKey(bookingElement.DateQuestionId); var containsBookingStartTime = viewModel.ContainsKey(bookingElement.StartTimeQuestionId); if (!containsBookingDate && !containsBookingStartTime && element.Properties.Optional) { return new ValidationResult { IsValid = true } } ; if (!containsBookingDate) { return(new ValidationResult { Message = ValidationMessage(containsBookingDate, containsBookingStartTime, element.Properties.CustomValidationMessage), IsValid = false }); } var date = viewModel[bookingElement.DateQuestionId]; var isValidDate = DateTime.TryParse(date, out DateTime dateValue); if (!isValidDate) { return(new ValidationResult { Message = ValidationMessage(isValidDate, containsBookingStartTime, element.Properties.CustomValidationMessage), IsValid = false }); } return(VerifyStartAndEndTime(bookingElement, viewModel, (containsBookingDate && isValidDate))); }
public string GetFormData(string json) { dynamic jsonObj = Newtonsoft.Json.JsonConvert.DeserializeObject(json); var formId = Convert.ToInt32(jsonObj["FormId"]); FormSchema formSchema = DataService.GetFormSchema(formId); TableSchema tableSchema = DataService.GetTableSchema(formSchema.AppDatabaseId, formSchema.TableName); // generate sql statement List <SqlParameter> sqlParameters = new List <SqlParameter>(); StringBuilder sb = new StringBuilder(); sb.Append("FROM " + formSchema.TableName + " WHERE "); // primary keys var isNewRecord = false; foreach (var key in tableSchema.PrimaryKeys) { if (jsonObj[key.ColumnName] != null) { var keyValue = jsonObj[key.ColumnName].ToString(); if (keyValue == "" || keyValue == "0") { isNewRecord = true; break; } sb.Append(key.ColumnName + "= @" + key.ColumnName + " AND "); sqlParameters.Add(new SqlParameter("@" + key.ColumnName, keyValue)); } else { isNewRecord = true; } } if (isNewRecord) // get empty template with defaults { var defaultValue = ""; sb.Clear(); sb.Append("[ { "); foreach (var column in tableSchema.Columns) { defaultValue = column.DefaultValue; if (defaultValue == "getdate") { defaultValue = DateTime.Now.ToString(); } sb.Append("\"" + column.ColumnName + "\":\"" + defaultValue + "\", "); } json = sb.ToString() + " \"IsNewRecord\": \"" + isNewRecord + "\" } ]"; } else { var sql = sb.ToString(); sql = "SELECT 'False' AS IsNewRecord, * " + sql.Substring(0, sql.Length - 4); json = HelperService.GetJsonData(formSchema.AppDatabaseId, sql, sqlParameters.ToArray()); } return(json); }
public ValidationResult Validate(Element element, Dictionary <string, dynamic> viewModel, FormSchema baseForm) { if (!element.Properties.Numeric || !viewModel.ContainsKey(element.Properties.QuestionId)) { return new ValidationResult { IsValid = true } } ; var value = viewModel[element.Properties.QuestionId]; if (string.IsNullOrEmpty(value) && element.Properties.Optional) { return new ValidationResult { IsValid = true } } ; var isValid = int.TryParse(value, out int output); if (!isValid) { return(new ValidationResult { IsValid = false, Message = !string.IsNullOrEmpty(element.Properties.NotAnIntegerValidationMessage) ? element.Properties.NotAnIntegerValidationMessage : $"{element.Properties.Label} must be a whole number" }); } if (value.Length > element.Properties.MaxLength) { return(new ValidationResult { IsValid = false, Message = $"{element.Properties.Label} must be {element.Properties.MaxLength} digits or less" }); } if (!string.IsNullOrEmpty(element.Properties.Max) && !string.IsNullOrEmpty(element.Properties.Min)) { var max = int.Parse(element.Properties.Max); var min = int.Parse(element.Properties.Min); if (output > max || output < min) { return(new ValidationResult { IsValid = false, Message = !string.IsNullOrEmpty(element.Properties.UpperLimitValidationMessage) ? element.Properties.UpperLimitValidationMessage : $"{ element.Properties.Label} must be between {min} and {max} inclusive" }); } } if (!string.IsNullOrEmpty(element.Properties.Max)) { var max = int.Parse(element.Properties.Max); if (output > max) { return(new ValidationResult { IsValid = false, Message = $"{element.Properties.Label} must be less than or equal to {max}" }); } } if (!string.IsNullOrEmpty(element.Properties.Min)) { var min = int.Parse(element.Properties.Min); if (output < min) { return(new ValidationResult { IsValid = false, Message = $"{element.Properties.Label} must be greater than or equal to {min}" }); } } return(new ValidationResult { IsValid = true }); } } }
public MappingEntityBuilder WithBaseForm(FormSchema baseForm) { _baseForm = baseForm; return(this); }
public ValidationResult Validate(Element element, Dictionary <string, dynamic> viewModel, FormSchema baseForm) { if (!element.Type.Equals(EElementType.DatePicker) || !viewModel.ContainsKey(element.Properties.QuestionId)) { return new ValidationResult { IsValid = true } } ; var date = viewModel[element.Properties.QuestionId]; var isValid = !string.IsNullOrEmpty(date); if (!isValid && element.Properties.Optional) { return new ValidationResult { IsValid = true } } ; if (!isValid && !element.Properties.Optional) { return(new ValidationResult { IsValid = false, Message = !string.IsNullOrEmpty(element.Properties.CustomValidationMessage) ? element.Properties.CustomValidationMessage : ValidationConstants.DatePickerDefault }); } var isValidDate = DateTime.TryParse(date, out DateTime dateValue); var todaysDate = DateTime.Now; var maxDate = string.IsNullOrEmpty(element.Properties.Max) ? todaysDate.AddYears(100) : new DateTime(int.Parse(element.Properties.Max), todaysDate.Month, todaysDate.Day); if (dateValue > maxDate) { return(new ValidationResult { IsValid = false, Message = !string.IsNullOrEmpty(element.Properties.UpperLimitValidationMessage) ? element.Properties.UpperLimitValidationMessage : ValidationConstants.DatePickerDefault }); } return(new ValidationResult { IsValid = isValidDate, Message = isValidDate ? string.Empty : !string.IsNullOrEmpty(element.Properties.ValidationMessageInvalidDate) ? element.Properties.ValidationMessageInvalidDate : ValidationConstants.DatePickerDefault }); } } }
private async Task <ProcessRequestEntity> ProcessSelectedFiles( Dictionary <string, dynamic> viewModel, Page currentPage, FormSchema baseForm, string guid, string path, IEnumerable <CustomFormFile> files, bool modelStateIsValid) { if (!currentPage.IsValid) { var formModel = await _pageFactory.Build(currentPage, new Dictionary <string, dynamic>(), baseForm, guid); return(new ProcessRequestEntity { Page = currentPage, ViewModel = formModel }); } if (currentPage.IsValid && viewModel.ContainsKey(ButtonConstants.SUBMIT) && (files == null || !files.Any()) && modelStateIsValid) { if (currentPage.Elements.Where(_ => _.Type.Equals(EElementType.MultipleFileUpload)).Any(_ => _.Properties.Optional)) { _pageHelper.SaveAnswers(viewModel, guid, baseForm.BaseURL, files, currentPage.IsValid, true); } return(new ProcessRequestEntity { Page = currentPage }); } if (!viewModel.ContainsKey(ButtonConstants.SUBMIT) && (files == null || !files.Any())) { return(new ProcessRequestEntity { RedirectToAction = true, RedirectAction = "Index", RouteValues = new { form = baseForm.BaseURL, path } }); } if (files != null && files.Any()) { _pageHelper.SaveAnswers(viewModel, guid, baseForm.BaseURL, files, currentPage.IsValid, true); } if (viewModel.ContainsKey(ButtonConstants.SUBMIT) && modelStateIsValid) { return(new ProcessRequestEntity { Page = currentPage }); } if (!modelStateIsValid) { var newViewModel = new Dictionary <string, dynamic>(); newViewModel.Add("modelStateInvalid", null); var formModel = await _pageFactory.Build(currentPage, newViewModel, baseForm, guid); return(new ProcessRequestEntity { Page = currentPage, ViewModel = formModel, UseGeneratedViewModel = true }); } return(new ProcessRequestEntity { RedirectToAction = true, RedirectAction = "Index", RouteValues = new { form = baseForm.BaseURL, path } }); }
public IntegrityCheckResult Validate(FormSchema schema) { IntegrityCheckResult result = new(); List <IElement> elements = schema.Pages .SelectMany(page => page.Elements) .Where(element => !string.IsNullOrEmpty(element.Lookup) && element.Lookup.Equals(LookUpConstants.Dynamic)) .ToList(); if (elements.Count.Equals(0)) { return(result); } foreach (var element in elements) { if (element.Properties.LookupSources is null || !element.Properties.LookupSources.Any()) { result.AddFailureMessage($"Dynamic Lookup Check, dynamic lookup with questionId {element.Properties.QuestionId} requires a LookupSource"); return(result); } if (!element.Properties.LookupSources .Any(lookup => lookup.EnvironmentName .Equals(_environment.EnvironmentName, StringComparison.OrdinalIgnoreCase))) { result.AddFailureMessage($"The provided json has no Environment details for this:({_environment.EnvironmentName}) Environment"); } foreach (var env in element.Properties.LookupSources) { if (string.IsNullOrEmpty(env.EnvironmentName)) { result.AddFailureMessage($"The provided json has no Environment Name"); } if (string.IsNullOrEmpty(env.Provider)) { result.AddFailureMessage($"The provided json has no Provider Name"); } try { _lookupProviders.Get(env.Provider); } catch (Exception e) { result.AddFailureMessage($"No specified Providers in form. Error Message {e.Message}"); } if (string.IsNullOrEmpty(env.URL)) { result.AddFailureMessage($"The provided json has no API URL to submit to"); } if (string.IsNullOrEmpty(env.AuthToken)) { result.AddFailureMessage($"The provided json has no auth token for the API"); } if (!_environment.IsEnvironment("local") && !env.EnvironmentName.Equals("local", StringComparison.OrdinalIgnoreCase) && !env.URL.StartsWith("https://")) { result.AddFailureMessage($"SubmitUrl must start with https, in form."); } } } return(result); }
public ValidationResult Validate(Element element, Dictionary <string, dynamic> viewModel, FormSchema baseForm) { if (!element.Type.Equals(EElementType.FileUpload) && !element.Type.Equals(EElementType.MultipleFileUpload)) { return new ValidationResult { IsValid = true } } ; var key = $"{element.Properties.QuestionId}{FileUploadConstants.SUFFIX}"; if (!viewModel.ContainsKey(key)) { return new ValidationResult { IsValid = true } } ; List <DocumentModel> documentModel = viewModel[key]; if (documentModel is null) { return new ValidationResult { IsValid = true } } ; var allowedFileTypes = element.Properties.AllowedFileTypes ?? SystemConstants.AcceptedMimeTypes; var fileTypes = documentModel.Select(_ => new MimeTypeFile { FileType = Convert.FromBase64String(_.Content).GetFileType(), File = _ }); var invalidFiles = new List <MimeTypeFile>(); if (fileTypes is not null) { var availableFileTypes = fileTypes.Where(_ => _ is not null && _.FileType is not null); var unknownFileTypes = fileTypes.Where(_ => _ is not null && _.FileType is null); if (unknownFileTypes.Any()) { invalidFiles.AddRange(unknownFileTypes.ToList()); } invalidFiles.AddRange(availableFileTypes.Where(_ => !allowedFileTypes.Contains($".{_.FileType.Extension}")).ToList()); if (!invalidFiles.Any()) { return new ValidationResult { IsValid = true } } ; } return(element.Type.Equals(EElementType.FileUpload) ? SingleFileUpload(allowedFileTypes, documentModel) : MultiFileUpload(allowedFileTypes, invalidFiles, documentModel)); }
public ValidationResult Validate(Element element, Dictionary <string, dynamic> viewModel, FormSchema baseForm) { if (!element.Type.Equals(EElementType.MultipleFileUpload)) { return new ValidationResult { IsValid = true } } ; if (element.Properties.Optional && viewModel.ContainsKey(ButtonConstants.SUBMIT)) { return new ValidationResult { IsValid = true } } ; var key = $"{ element.Properties.QuestionId}{FileUploadConstants.SUFFIX}"; var isValid = false; List <DocumentModel> value = viewModel.ContainsKey(key) ? viewModel[key] : null; isValid = !(value is null); if (value is null) { var sessionGuid = _sessionHelper.GetSessionGuid(); var cachedAnswers = _distributedCache.GetString(sessionGuid); var convertedAnswers = cachedAnswers is null ? new FormAnswers { Pages = new List <PageAnswers>() } : JsonConvert.DeserializeObject <FormAnswers>(cachedAnswers); var path = viewModel.FirstOrDefault(_ => _.Key.Equals("Path")).Value; var pageAnswersString = convertedAnswers.Pages.FirstOrDefault(_ => _.PageSlug.Equals(path))?.Answers.FirstOrDefault(_ => _.QuestionId.Equals(key)); var response = new List <FileUploadModel>(); if (pageAnswersString is not null) { response = JsonConvert.DeserializeObject <List <FileUploadModel> >(pageAnswersString.Response.ToString()); if (response.Any()) { isValid = true; } } } return(new ValidationResult { IsValid = isValid, Message = ValidationConstants.FILEUPLOAD_EMPTY }); } } }
public void GetReducedAnswers_ShouldRemoveUnusedPage() { // Arrange var formAnswers = new FormAnswers { Pages = new List <PageAnswers> { new PageAnswers { Answers = new List <Answers>(), PageSlug = "page-1" }, new PageAnswers { Answers = new List <Answers>(), PageSlug = "page-2" }, new PageAnswers { Answers = new List <Answers>(), PageSlug = "page-3" } } }; var formSchema = new FormSchema { Pages = new List <Page> { new Page { PageSlug = "page-1", Behaviours = new List <Behaviour> { new Behaviour { BehaviourType = EBehaviourType.GoToPage, PageSlug = "page-3" } } }, new Page { PageSlug = "page-2", Behaviours = new List <Behaviour> { new Behaviour { BehaviourType = EBehaviourType.GoToPage, PageSlug = "page-3" } } }, new Page { PageSlug = "page-3", Behaviours = new List <Behaviour> { new Behaviour { BehaviourType = EBehaviourType.SubmitForm } } } }, FirstPageSlug = "page-1" }; // Act var result = formAnswers.GetReducedAnswers(formSchema); // Assert Assert.Equal(2, result.Count); }
public async Task <IntegrityCheckResult> ValidateAsync(FormSchema schema) => await Task.Run(() => Validate(schema));
public async Task <SuccessPageEntity> FinalisePageJourney(string form, EBehaviourType behaviourType, FormSchema baseForm) { var sessionGuid = _sessionHelper.GetSessionGuid(); if (string.IsNullOrEmpty(sessionGuid)) { throw new ApplicationException("PageService::FinalisePageJourney: Session has expired"); } var formData = _distributedCache.GetString(sessionGuid); if (formData == null) { throw new ApplicationException("PageService::FinalisePageJourney: Session data is null"); } var formAnswers = JsonConvert.DeserializeObject <FormAnswers>(formData); var formFileUploadElements = baseForm.Pages.SelectMany(_ => _.Elements) .Where(_ => _.Type == EElementType.FileUpload || _.Type == EElementType.MultipleFileUpload) .ToList(); if (formFileUploadElements.Any()) { formFileUploadElements.ForEach(fileElement => { var formFileAnswerData = formAnswers.Pages.SelectMany(_ => _.Answers).FirstOrDefault(_ => _.QuestionId == $"{fileElement.Properties.QuestionId}{FileUploadConstants.SUFFIX}")?.Response ?? string.Empty; List <FileUploadModel> convertedFileUploadAnswer = JsonConvert.DeserializeObject <List <FileUploadModel> >(formFileAnswerData.ToString()); if (convertedFileUploadAnswer != null && convertedFileUploadAnswer.Any()) { convertedFileUploadAnswer.ForEach((_) => { _distributedCache.Remove(_.Key); }); } }); } if (baseForm.DocumentDownload) { await _distributedCache.SetStringAsync($"document-{sessionGuid}", JsonConvert.SerializeObject(formAnswers), _distributedCacheExpirationConfiguration.Document); } return(await _successPageContentFactory.Build(form, baseForm, sessionGuid, formAnswers, behaviourType)); }
public async Task Process(List <IAction> actions, FormSchema formSchema, string formName) { var answers = new List <Answers>(); var sessionGuid = _sessionHelper.GetSessionGuid(); var mappingData = await _mappingService.Map(sessionGuid, formName); foreach (var action in actions) { var response = new HttpResponseMessage(); var submitSlug = action.Properties.PageActionSlugs.FirstOrDefault(_ => _.Environment.ToLower().Equals(_environment.EnvironmentName.ToS3EnvPrefix().ToLower())); if (submitSlug == null) { throw new ApplicationException("RetrieveExternalDataService::Process, there is no PageActionSlug defined for this environment"); } var entity = _actionHelper.GenerateUrl(submitSlug.URL, mappingData.FormAnswers); if (!string.IsNullOrEmpty(submitSlug.AuthToken)) { _gateway.ChangeAuthenticationHeader(submitSlug.AuthToken); } if (entity.IsPost) { response = await _gateway.PostAsync(entity.Url, mappingData.Data); } else { response = await _gateway.GetAsync(entity.Url); } if (!response.IsSuccessStatusCode) { throw new ApplicationException($"RetrieveExternalDataService::Process, http request to {entity.Url} returned an unsuccessful status code, Response: {JsonConvert.SerializeObject(response)}"); } if (response.Content == null) { throw new ApplicationException($"RetrieveExternalDataService::Process, response content from {entity.Url} is null."); } var content = await response.Content.ReadAsStringAsync(); if (string.IsNullOrWhiteSpace(content)) { throw new ApplicationException($"RetrieveExternalDataService::Process, Gateway {entity.Url} responded with empty reference"); } answers.Add(new Answers { QuestionId = action.Properties.TargetQuestionId, Response = JsonConvert.DeserializeObject <string>(content) }); } mappingData.FormAnswers.Pages.FirstOrDefault(_ => _.PageSlug.ToLower().Equals(mappingData.FormAnswers.Path.ToLower())).Answers.AddRange(answers); await _distributedCache.SetStringAsync(sessionGuid, JsonConvert.SerializeObject(mappingData.FormAnswers), CancellationToken.None); }
public ValidationResult Validate(Element element, Dictionary <string, dynamic> viewModel, FormSchema baseForm) { if (!element.Properties.Email.GetValueOrDefault()) { return new ValidationResult { IsValid = true } } ; if (string.IsNullOrEmpty(viewModel[element.Properties.QuestionId]) && element.Properties.Optional) { return new ValidationResult { IsValid = true } } ; if (!element.Properties.Email.HasValue || !element.Properties.Email.Value || !viewModel.ContainsKey(element.Properties.QuestionId)) { return new ValidationResult { IsValid = true } } ; var value = viewModel[element.Properties.QuestionId]; var isValid = true; var regex = new Regex(@"^([\w\.\-]+)@([\w\-]+)((\.(\w)+)+)$"); Match match = regex.Match(value); if (!match.Success) { isValid = false; } return(new ValidationResult { IsValid = isValid, Message = ValidationConstants.EMAIL_INCORRECT_FORMAT }); } } }
public void FormSchemaCanAcceptOnlyCertainNodeType(Type nodeType, int expectedCount) { var schema = new FormSchema("X", Activator.CreateInstance(nodeType) as NodeSchema); Assert.AreEqual(expectedCount, schema.Count); }
public async Task <ProcessRequestEntity> ProcessRequest( string form, string path, Dictionary <string, dynamic> viewModel, IEnumerable <CustomFormFile> files, bool modelStateIsValid) { FormSchema baseForm = await _schemaFactory.Build(form); if (!baseForm.IsAvailable(_environment.EnvironmentName)) { throw new ApplicationException($"Form: {form} is not available in this Environment: {_environment.EnvironmentName.ToS3EnvPrefix()}"); } var currentPage = baseForm.GetPage(_pageHelper, path); var sessionGuid = _sessionHelper.GetSessionGuid(); if (sessionGuid == null) { throw new NullReferenceException($"Session guid null."); } if (currentPage == null) { throw new NullReferenceException($"Current page '{path}' object could not be found."); } if (currentPage.HasIncomingPostValues) { viewModel = _incomingDataHelper.AddIncomingFormDataValues(currentPage, viewModel); } currentPage.Validate(viewModel, _validators, baseForm); if (currentPage.Elements.Any(_ => _.Type == EElementType.Address)) { return(await _addressService.ProcessAddress(viewModel, currentPage, baseForm, sessionGuid, path)); } if (currentPage.Elements.Any(_ => _.Type == EElementType.Street)) { return(await _streetService.ProcessStreet(viewModel, currentPage, baseForm, sessionGuid, path)); } if (currentPage.Elements.Any(_ => _.Type == EElementType.Organisation)) { return(await _organisationService.ProcessOrganisation(viewModel, currentPage, baseForm, sessionGuid, path)); } if (currentPage.Elements.Any(_ => _.Type == EElementType.MultipleFileUpload)) { return(await _fileUploadService.ProcessFile(viewModel, currentPage, baseForm, sessionGuid, path, files, modelStateIsValid)); } if (currentPage.Elements.Any(_ => _.Type == EElementType.Booking)) { return(await _bookingService.ProcessBooking(viewModel, currentPage, baseForm, sessionGuid, path)); } _pageHelper.SaveAnswers(viewModel, sessionGuid, baseForm.BaseURL, files, currentPage.IsValid); if (!currentPage.IsValid) { var formModel = await _pageContentFactory.Build(currentPage, viewModel, baseForm, sessionGuid); return(new ProcessRequestEntity { Page = currentPage, ViewModel = formModel }); } return(new ProcessRequestEntity { Page = currentPage }); }