public void FillForm(RegistrationUser user) { Gender[0].Click(); FirstName.SendKeys(user.FirstName); LastName.SendKeys(user.LastName); Password.SendKeys(user.Password); Day.SelectByValue(user.Day); Month.SelectByValue(user.Month); Year.SelectByValue(user.Year); RealFirstName.SendKeys(user.RealFirstName); RealLastName.SendKeys(user.RealLastName); Address.SendKeys(user.Address); City.SendKeys(user.City); State.SelectByText(user.State); Postcode.SendKeys(user.Postcode); Phone.SendKeys(user.Phone); Alias.SendKeys(user.Alias); RegisterButton.Click(); }
public override int GetHashCode() { unchecked { var hashCode = Address1 != null?Address1.GetHashCode() : 0; hashCode = (hashCode * 397) ^ (Address2 != null ? Address2.GetHashCode() : 0); hashCode = (hashCode * 397) ^ (City != null ? City.GetHashCode() : 0); hashCode = (hashCode * 397) ^ (Company != null ? Company.GetHashCode() : 0); hashCode = (hashCode * 397) ^ (Country != null ? Country.GetHashCode() : 0); hashCode = (hashCode * 397) ^ (Email != null ? Email.GetHashCode() : 0); hashCode = (hashCode * 397) ^ (FirstName != null ? FirstName.GetHashCode() : 0); hashCode = (hashCode * 397) ^ (LastName != null ? LastName.GetHashCode() : 0); hashCode = (hashCode * 397) ^ (Phone != null ? Phone.GetHashCode() : 0); hashCode = (hashCode * 397) ^ (Postcode != null ? Postcode.GetHashCode() : 0); hashCode = (hashCode * 397) ^ (State != null ? State.GetHashCode() : 0); return(hashCode); } }
/// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { unchecked // Overflow is fine, just wrap { var hashCode = 41; // Suitable nullity checks etc, of course :) if (MailingName != null) { hashCode = hashCode * 59 + MailingName.GetHashCode(); } if (AddressLine1 != null) { hashCode = hashCode * 59 + AddressLine1.GetHashCode(); } if (AddressLine2 != null) { hashCode = hashCode * 59 + AddressLine2.GetHashCode(); } if (AddressLine3 != null) { hashCode = hashCode * 59 + AddressLine3.GetHashCode(); } if (Postcode != null) { hashCode = hashCode * 59 + Postcode.GetHashCode(); } if (City != null) { hashCode = hashCode * 59 + City.GetHashCode(); } if (State != null) { hashCode = hashCode * 59 + State.GetHashCode(); } if (Country != null) { hashCode = hashCode * 59 + Country.GetHashCode(); } return(hashCode); } }
public List <Postcode> GetPostcodesNumbersByPlaceNameAndStatecode(string placename, string statecode) { Boolean exist = false; List <Postcode> list = new List <Postcode>(); foreach (GeoData sb in db.GeoDatas.Where(stpcsub => stpcsub.place == placename && stpcsub.state == statecode)) { if (list.Count != 0) { foreach (Postcode sbps in list) { exist = false; if (sb.postcode == sbps.postcode) { exist = true; break; } } if (!exist) { Postcode postcodeDto = new Postcode(); postcodeDto.postcode = sb.postcode; postcodeDto.parentplace = sb.place; postcodeDto.suburbs = GetSuburbNamesByPostcodeAndPlace(postcodeDto.postcode, postcodeDto.parentplace); //postcodeDto.suburbs = ((OkNegotiatedContentResult<List<Suburb>>)GetSuburbNamesByPostcodeAndPlace(postcodeDto.postcode, postcodeDto.parentplace)).Content; list.Add(postcodeDto); } } else { Postcode postcodeDto = new Postcode(); postcodeDto.postcode = sb.postcode; postcodeDto.parentplace = sb.place; postcodeDto.suburbs = GetSuburbNamesByPostcodeAndPlace(postcodeDto.postcode, postcodeDto.parentplace); //postcodeDto.suburbs = ((OkNegotiatedContentResult<List<Suburb>>)GetSuburbNamesByPostcodeAndPlace(postcodeDto.postcode, postcodeDto.parentplace)).Content; list.Add(postcodeDto); } } return(list); }
public async Task <OneOf <ModelWithErrors <Command>, Success> > Handle(Command request, CancellationToken cancellationToken) { var journeyInstance = _journeyInstanceProvider.GetInstance <AddVenueJourneyModel>(); journeyInstance.ThrowIfCompleted(); // Normalize the postcode; validation accepts postcodes with no spaces but ONSPD lookup requires spaces. // Also ensures we have postcodes consistently capitalized. if (Postcode.TryParse(request.Postcode, out var postcode)) { request.Postcode = postcode; } var postcodeInfo = await _sqlQueryDispatcher.ExecuteQuery(new GetPostcodeInfo() { Postcode = request.Postcode }); var validator = new CommandValidator(postcodeInfo); var validationResult = await validator.ValidateAsync(request); if (!validationResult.IsValid) { return(new ModelWithErrors <Command>(request, validationResult)); } journeyInstance.UpdateState(state => { state.AddressLine1 = request.AddressLine1; state.AddressLine2 = request.AddressLine2; state.Town = request.Town; state.County = request.County; state.Postcode = request.Postcode; state.Latitude = postcodeInfo.Latitude; state.Longitude = postcodeInfo.Longitude; state.AddressIsOutsideOfEngland = !postcodeInfo.InEngland; state.ValidStages |= AddVenueCompletedStages.Address; }); return(new Success()); }
static void Main(string[] args) { Console.WriteLine("Enter Postcode:"); string postcode = Console.ReadLine(); var PostcodeApiClient = new PostcodeApiClient(); Postcode postcodeData = PostcodeApiClient.GetLatLong(postcode); var TflApiClient = new TflApiClient(); List <Stop> busStops = TflApiClient.GetBusStopCodes(postcodeData); int[] zeroOne = new int[] { 0, 1 }; foreach (int i in zeroOne) { var nextStop = busStops[i]; Console.WriteLine(nextStop.commonName); var nearestStopCode = nextStop.naptanId; PrintBusTimes(TflApiClient.GetBusTimes(nearestStopCode)); } Console.ReadLine(); }
public Postcode Get(string postCodeText) { //pattern string pattern = @"[A-Za-z][1-9][1-9][A-Za-z]{2}"; //use regular expression by creating regex instance Regex reg = new Regex(pattern); //validate postcode if (!reg.IsMatch(postCodeText)) { throw new InvalidDataException("Wrong Postcode supplied"); } //TODO:connect to database and retrieve list of address Postcode postcode = new Postcode(); //store the address return(postcode); }
public void FillForm(RegistrationUser user) { Titles[user.Title].Click(); CustomerFirstName.Type(user.CustomerFirstName); CustomerLastName.Type(user.CustomerLastName); Password.Type(user.Password); Days.SelectByValue(user.Day); Months.SelectByValue(user.Month); Years.SelectByValue(user.Year); FirstName.Type(user.FirstName); LastName.Type(user.LastName); Company.Type(user.Address); Address.Type(user.Address); Country.SelectByText(user.Country); State.SelectByText(user.State); City.Type(user.City); Postcode.Type(user.Postcode); MobilePhone.Type(user.MobilePhone); registerSubmit.Click(); }
public IHttpActionResult GetPostcodesByPlaceId(int placeId) { try { List <Postcode> list = new List <Postcode>(); foreach (Postcode pc in db.Postcodes.Where(pc => pc.placeId == placeId).OrderBy(pc => pc.number)) { Postcode pcdto = new Postcode(); pcdto.id = pc.id; pcdto.number = pc.number; pcdto.placeId = pc.placeId; pcdto.suburbs = ((OkNegotiatedContentResult <List <Suburb> >)subctr.GetSuburbsByPostcodeId(pc.id)).Content; list.Add(pcdto); } return(Ok <List <Postcode> >(list)); } catch (Exception) { ModelState.AddModelError("Message", "An unexpected error has occured during getting all postcodes!"); return(BadRequest(ModelState)); } }
public async Task <IHttpActionResult> PutPostcode(int id, Postcode postcode) { if (!ModelState.IsValid) { ModelState.AddModelError("Message", "The postcode details are not valid!"); return(BadRequest(ModelState)); } if (id != postcode.id) { ModelState.AddModelError("Message", "The postcode id is not valid!"); return(BadRequest(ModelState)); } db.Entry(postcode).State = EntityState.Modified; try { await db.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!PostcodeExists(id)) { ModelState.AddModelError("Message", "Postcode not found!"); return(BadRequest(ModelState)); } else { throw; } } Postcode cat = await db.Postcodes.Where(cor => cor.id == id).FirstAsync(); return(Ok <Postcode>(cat)); }
public List <int> VerifyPostcode() { var errors = new List <int>(); if (Postcode == null) { return new List <int> { 15 } } ; Postcode = Postcode.Trim().Replace(HidroConstants.WHITE_SPACE, string.Empty); if (string.IsNullOrWhiteSpace(Postcode)) { return new List <int> { 15 } } ; var lenTest = new Regex(@".{1,10}"); if (!lenTest.IsMatch(Postcode)) { errors.Add(16); } var rx = new Regex(@"^[\d]*$"); if (!rx.IsMatch(Postcode)) { errors.Add(17); } return(errors); }
private List <int> VerifyPostcode() { var errors = new List <int>(); if (Postcode == null) { return new List <int> { 10 } } ; Postcode = Postcode.Trim().Replace(SharedConstants.DoubleSpace, SharedConstants.MonoSpace); if (!Helpers.IsProperString(Postcode)) { return new List <int> { 10 } } ; var lenTest = new Regex(@".{1,20}"); if (!lenTest.IsMatch(Postcode)) { errors.Add(11); } var rx = new Regex(@"^[\d]*$"); if (!rx.IsMatch(Postcode)) { errors.Add(12); } return(errors); }
public ActionResult BusInfo(PostcodeSelection selection) { bool valid = true; List <Stop> stops = new List <Stop>(); var PostcodeApiClient = new PostcodeApiClient(); Postcode postcodeData = PostcodeApiClient.GetLatLong(selection.Postcode); if (postcodeData == null) { valid = false; } else { var TflApiClient = new TflApiClient(); stops = TflApiClient.GetBusStopCodes(postcodeData); if (!stops.Any()) { valid = false; } foreach (Stop s in stops) { s.buses = TflApiClient.GetBusTimes(s.naptanId); } } var info = new BusInfo(selection.Postcode) { PostCode = selection.Postcode, Stops = stops, Valid = valid }; return(View(info)); }
public JsonResult GetLocality(string post) { Postcode postcode = new Postcode(); List <Postcode> listing = new List <Postcode>(); string cs = ConfigurationManager.ConnectionStrings["SailiDbContext"].ConnectionString; using (SqlConnection con = new SqlConnection(cs)) { SqlCommand cmd = new SqlCommand("spGetLocality", con); cmd.CommandType = CommandType.StoredProcedure; SqlParameter parameter = new SqlParameter(); parameter.ParameterName = "@postcode"; parameter.Value = post; cmd.Parameters.Add(parameter); con.Open(); SqlDataReader rdr = cmd.ExecuteReader(); while (rdr.Read()) { listing.Add(new Postcode() { PostcodeID = Convert.ToInt32(rdr["PostcodeID"].ToString()), postcode = rdr["postcode"].ToString(), Locality = rdr["Locality"].ToString(), State = rdr["State"].ToString(), Country = rdr["Country"].ToString() }); } rdr.Close(); } return(Json(listing, JsonRequestBehavior.AllowGet)); }
public async Task <OneOf <ModelWithErrors <Command>, UploadStatus> > Handle(Command request, CancellationToken cancellationToken) { var(_, otherRows) = await GetRow(request.RowNumber); var postcodeInfo = Postcode.TryParse(request.Postcode, out var postcode) ? await _sqlQueryDispatcher.ExecuteQuery(new GetPostcodeInfo() { Postcode = postcode }) : null; var validator = new CommandValidator(otherRows, postcodeInfo); var validationResult = await validator.ValidateAsync(request); if (!validationResult.IsValid) { return(new ModelWithErrors <Command>(request, validationResult)); } return(await _fileUploadProcessor.UpdateVenueUploadRowForProvider( _providerContextProvider.GetProviderId(), request.RowNumber, new Core.DataManagement.Schemas.CsvVenueRow() { ProviderVenueRef = request.ProviderVenueRef, VenueName = request.Name, AddressLine1 = request.AddressLine1, AddressLine2 = request.AddressLine2, Town = request.Town, County = request.County, Postcode = request.Postcode, Email = request.Email, Telephone = request.Telephone, Website = request.Website })); }
private void buttonOK_Click(object sender, EventArgs e) { string errorString = "You must fill in this field"; errorProvider.Clear(); //create the patient _patient = new Patient(); //validate and add fields if (comboBoxTitle.SelectedIndex != -1) { _patient.Title = (Patient.TitleType)comboBoxTitle.SelectedIndex; } else { errorProvider.SetError(comboBoxTitle, errorString); return; } if (textBoxLastName.Text.Trim() == "") { errorProvider.SetError(textBoxLastName, errorString); return; } else { _patient.LastName = textBoxLastName.Text; } if (textBoxFirstName.Text.Trim() == "") { errorProvider.SetError(textBoxFirstName, errorString); return; } else { _patient.FirstName = textBoxFirstName.Text; } if (textBoxID.Text.Trim() == "") { errorProvider.SetError(textBoxID, errorString); return; } else { _patient.PatientID = textBoxID.Text; } if (comboBoxGender.SelectedIndex != -1) { _patient.Gender = (Patient.GenderType)comboBoxGender.SelectedIndex; } else { errorProvider.SetError(comboBoxGender, errorString); return; } if (dateTimePicker.Value.Date == DateTime.Today) { errorProvider.SetError(dateTimePicker, errorString); return; } _patient.DOB = dateTimePicker.Value; Postcode validatedPostcode; bool postcodeResult = Postcode.TryParse(textBoxPostcode.Text, out validatedPostcode, true); if (postcodeResult == false) { errorProvider.SetError(textBoxPostcode, "Invalid Post Code"); return; } else { _patient.Address.Postcode = validatedPostcode; } if (!_patient.ContactNumber.TryParse(textBoxContactNumber.Text)) { errorProvider.SetError(textBoxContactNumber, "Invalid Number"); return; } this.DialogResult = DialogResult.OK; this.Close(); }
public Address_Old(string street, string city, Postcode postcode) { this.street = street; this.city = city; this.postcode = postcode; }
private void AddPatientRecord() { if (!VerifyRequiredFields()) { return; } DateTime dateOfBirth = (DateTime)DOB; SQLiteConnection connection = OpenConnection("Patients"); string cmdString = ""; if (string.IsNullOrWhiteSpace(Middlename)) { cmdString = @"SELECT COUNT(*) FROM PatientData WHERE Firstname = @firstname" + " AND Lastname = @lastname AND DOB = @dob AND Gender = @gender AND ST_Number = @streetNumber AND Postcode = @postcode"; } else { cmdString = @"SELECT COUNT(*) FROM PatientData WHERE Firstname = @firstname AND Middlename = @middlename " + " AND Lastname = @lastname AND DOB = @dob AND Gender = @gender AND ST_Number = @streetNumber AND Postcode = @postcode"; } SQLiteCommand cmd = new SQLiteCommand(cmdString, connection); cmd.Prepare(); cmd.Parameters.Add("@firstname", DbType.String).Value = Firstname.ToLower(new System.Globalization.CultureInfo("en-UK", false)); if (!string.IsNullOrWhiteSpace(Middlename)) { cmd.Parameters.Add("@middlename", DbType.String).Value = Middlename.ToLower(new System.Globalization.CultureInfo("en-UK", false)); } cmd.Parameters.Add("@lastname", DbType.String).Value = Lastname.ToLower(new System.Globalization.CultureInfo("en-UK", false)); cmd.Parameters.Add("@dob", DbType.String).Value = dateOfBirth.ToString("dd/MM/yyyy"); cmd.Parameters.Add("@gender", DbType.String).Value = Gender; cmd.Parameters.Add("@streetNumber", DbType.String).Value = AddressNo; cmd.Parameters.Add("@postcode", DbType.String).Value = Postcode.Replace(" ", "").ToUpper(); // Checks if record already exists, if it does a prompt is shown to the user, // user decides if duplicate record is required. int recordsFound = Convert.ToInt32(cmd.ExecuteScalar()); if (recordsFound > 0) { string createDuplicate = Confirmation("Are you sure?", "Patient Record with identical information already exists. Are you sure you want to create another record with this data?"); if (createDuplicate != "Yes") { return; } } // Record added to patient database. if (string.IsNullOrWhiteSpace(Middlename)) { cmdString = @"INSERT INTO PatientData (Firstname, Lastname, DOB, Gender, ST_Number, Postcode) VALUES (@firstname, @lastname, @dob, @gender, @streetNumber, @postcode)"; } else { cmdString = @"INSERT INTO PatientData (Firstname, Middlename, Lastname, DOB, Gender, ST_Number, Postcode) VALUES (@firstname, @middlename, @lastname, @dob, @gender, @streetNumber, @postcode)"; } cmd = new SQLiteCommand(cmdString, connection); cmd.Prepare(); cmd.Parameters.Add("@firstname", DbType.String).Value = Firstname.ToLower(new System.Globalization.CultureInfo("en-UK", false)); if (!string.IsNullOrEmpty(Middlename)) { cmd.Parameters.Add("@middlename", DbType.String).Value = Middlename.ToLower(new System.Globalization.CultureInfo("en-UK", false)); } cmd.Parameters.Add("@lastname", DbType.String).Value = Lastname.ToLower(new System.Globalization.CultureInfo("en-UK", false)); cmd.Parameters.Add("@dob", DbType.String).Value = dateOfBirth.ToString("dd/MM/yyyy"); cmd.Parameters.Add("@gender", DbType.String).Value = Gender; cmd.Parameters.Add("@streetNumber", DbType.String).Value = AddressNo; cmd.Parameters.Add("@postcode", DbType.String).Value = Postcode.Replace(" ", "").ToUpper(); cmd.ExecuteNonQuery(); Success("Success", "Record created. You can now proceed to create an appointment."); connection.Close(); }
public void SetUp() { _postcode = new Postcode(); }
public List <BusStop> GetStopsNear(Postcode postcode) { return(GetStopsNear(postcode.Latitude, postcode.Longitude)); }
public BusInfoViewModel(string postCode) { PostCode = pApi.GetPostcodeInfo(postCode); }
public async Task <OneOf <ProblemDetails, SearchViewModel> > Handle(Query request, CancellationToken cancellationToken) { var filters = new List <string>(); // If either lat or lng is specified then both must be specified if (request.Latitude.HasValue != request.Longitude.HasValue) { return(new ProblemDetails() { Detail = "Latitude & longitude must both be specified.", Status = 400, Title = "InvalidLatLng" }); } if (request.SortBy == SearchSortBy.Distance && (string.IsNullOrWhiteSpace(request.Postcode) && (!request.Latitude.HasValue || !request.Longitude.HasValue))) { return(new ProblemDetails() { Detail = "Postcode is required to sort by Distance.", Status = 400, Title = "PostcodeRequired" }); } Postcode postcode = null; if (!string.IsNullOrWhiteSpace(request.Postcode)) { if (!Postcode.TryParse(request.Postcode, out postcode)) { return(new ProblemDetails() { Detail = "Postcode is not valid.", Status = 400, Title = "InvalidPostcode" }); } } var geoFilterRequired = request.Distance.GetValueOrDefault(0) > 0 && (postcode != null || (request.Latitude.HasValue && request.Longitude.HasValue)); // lat/lng required if Distance filter is specified *or* sorting by Distance var getPostcodeCoords = (geoFilterRequired || request.SortBy == SearchSortBy.Distance) && !request.Latitude.HasValue; double?latitude = request.Latitude; double?longitude = request.Longitude; if (getPostcodeCoords) { var coords = await TryGetCoordinatesForPostcode(postcode); if (!coords.HasValue) { return(new ProblemDetails() { Detail = "Specified postcode cannot be found.", Status = 400, Title = "PostcodeNotFound" }); } latitude = coords.Value.lat; longitude = coords.Value.lng; } if (request.StartDateFrom.HasValue || request.StartDateTo.HasValue || request.HideOutOfDateCourses.HasValue || request.HideFlexiCourses.HasValue) { var dateFilter = TryGetDateFilters( request.StartDateFrom, request.StartDateTo, request.HideOutOfDateCourses, request.HideFlexiCourses); if (!string.IsNullOrEmpty(dateFilter)) { filters.Add(dateFilter); } } if (request.AttendancePatterns?.Any() ?? false) { // TODO Validate AttendancePatterns? Consider using enum instead of int filters.Add($"({string.Join(" or ", request.AttendancePatterns.Select(ap => $"{nameof(FindACourseOffering.AttendancePattern)} eq {ap}"))} or {nameof(FindACourseOffering.DeliveryMode)} ne {(int)CourseDeliveryMode.ClassroomBased})"); } if (request.QualificationLevels?.Any() ?? false) { // TODO Validate QualificationLevels? filters.Add($"search.in({nameof(FindACourseOffering.NotionalNVQLevelv2)}, '{string.Join("|", request.QualificationLevels.Select(EscapeFilterValue))}', '|')"); } if (geoFilterRequired) { var distanceInKm = Convert.ToDecimal(GeoHelper.MilesToKilometers(request.Distance.Value)); filters.Add( $"(geo.distance({nameof(FindACourseOffering.Position)}, geography'POINT({longitude.Value} {latitude.Value})') le {distanceInKm}" + $" or {nameof(FindACourseOffering.National)} eq true" + $" or {nameof(FindACourseOffering.DeliveryMode)} eq 2)"); } if (!string.IsNullOrWhiteSpace(request.Town)) { filters.Add($"search.ismatch('{EscapeFilterValue(request.Town)}', '{nameof(FindACourseOffering.VenueTown)}')"); } if (request.StudyModes?.Any() ?? false) { filters.Add($"({string.Join(" or ", request.StudyModes.Select(sm => $"{nameof(FindACourseOffering.StudyMode)} eq {sm}"))} or {nameof(FindACourseOffering.DeliveryMode)} ne {(int)CourseDeliveryMode.ClassroomBased})"); } if (request.DeliveryModes?.Any() ?? false) { filters.Add($"({string.Join(" or ", request.DeliveryModes.Select(dm => $"{nameof(FindACourseOffering.DeliveryMode)} eq {dm}"))})"); } if (!string.IsNullOrWhiteSpace(request.ProviderName)) { filters.Add($"search.ismatchscoring('{EscapeFilterValue(request.ProviderName)}', '{nameof(FindACourseOffering.ProviderDisplayName)}', 'simple', 'any')"); } if (!string.IsNullOrWhiteSpace(request.CampaignCode)) { filters.Add($"{nameof(FindACourseOffering.CampaignCodes)}/any(c: c eq '{EscapeFilterValue(request.CampaignCode)}')"); } var orderBy = request.SortBy == SearchSortBy.StartDateDescending ? "StartDate desc" : request.SortBy == SearchSortBy.StartDateAscending ? "StartDate asc" : request.SortBy == SearchSortBy.Distance ? $"geo.distance({nameof(FindACourseOffering.Position)}, geography'POINT({longitude.Value} {latitude.Value})')" : "search.score() desc"; if (!TryResolvePagingParams(request.Limit, request.Start, out var size, out var skip, out var problem)) { return(problem); } var searchText = TranslateCourseSearchSubjectText(request.SubjectKeyword); var query = new FindACourseOfferingSearchQuery() { Facets = new[] { "NotionalNVQLevelv2,count:100", "StudyMode", "AttendancePattern", "DeliveryMode", "ProviderDisplayName,count:100", "RegionName,count:100" }, Filters = filters, CourseName = searchText, Size = size, Skip = skip, OrderBy = orderBy }; var result = await _courseSearchClient.Search(query); return(new SearchViewModel() { Limit = size, Start = skip, Total = Convert.ToInt32(result.TotalCount.Value), Facets = result.Facets.ToDictionary( f => _courseSearchFacetMapping.GetValueOrDefault(f.Key, f.Key), f => f.Value.Select(v => new FacetCountResultViewModel() { Value = v.Key.ToString(), Count = v.Value.Value })), Results = result.Items.Select(i => { return new SearchResultViewModel() { Cost = !string.IsNullOrEmpty(i.Record.Cost) ? Convert.ToInt32(decimal.Parse(i.Record.Cost)) : (int?)null, CostDescription = HtmlEncode(i.Record.CostDescription), CourseDescription = HtmlEncode(NormalizeCourseDataEncodedString(i.Record.CourseDescription)), CourseName = NormalizeCourseRunDataEncodedString(i.Record.CourseName), CourseId = i.Record.CourseId, CourseRunId = i.Record.CourseRunId, CourseText = HtmlEncode(NormalizeCourseDataEncodedString(i.Record.CourseDescription)), DeliveryMode = ((int)i.Record.DeliveryMode).ToString(), DeliveryModeDescription = (i.Record.DeliveryMode.GetValueOrDefault(0)).ToDescription(), Distance = GetDistanceFromLatLngForResult(i), DurationUnit = i.Record.DurationUnit ?? 0, DurationValue = i.Record.DurationValue, FlexibleStartDate = i.Record.FlexibleStartDate, LearnAimRef = i.Record.LearnAimRef, National = i.Record.National, QualificationLevel = i.Record.NotionalNVQLevelv2, OfferingType = i.Record.OfferingType, ProviderName = i.Record.ProviderDisplayName, QualificationCourseTitle = HtmlEncode(i.Record.QualificationCourseTitle), Region = i.Record.RegionName, SearchScore = i.Score.Value, StartDate = !i.Record.FlexibleStartDate.GetValueOrDefault() ? i.Record.StartDate : null, TLevelId = i.Record.TLevelId, TLevelLocationId = i.Record.TLevelLocationId, Ukprn = i.Record.ProviderUkprn.ToString(), UpdatedOn = i.Record.UpdatedOn, VenueAddress = HtmlEncode(i.Record.VenueAddress), VenueAttendancePattern = ((int?)i.Record.AttendancePattern)?.ToString(), VenueAttendancePatternDescription = i.Record.DeliveryMode == CourseDeliveryMode.ClassroomBased ? i.Record.AttendancePattern?.ToDescription() : null, VenueLocation = i.Record.Position != null ? new CoordinatesViewModel() { Latitude = i.Record.Position.Latitude, Longitude = i.Record.Position.Longitude } : null, VenueName = HtmlEncode(i.Record.VenueName), VenueStudyMode = ((int?)i.Record.StudyMode)?.ToString(), VenueStudyModeDescription = i.Record.DeliveryMode == CourseDeliveryMode.ClassroomBased ? i.Record.StudyMode?.ToDescription() : null, VenueTown = HtmlEncode(i.Record.VenueTown) };
public PostcodeXml(Postcode postcode) { Postcode = postcode; }
public PostcodeTests() { _postcode = new Postcode(); }
public void ToStringReturnsValueOfTupleForTupleValuedObjects() { Address address1 = Address.From(("16 Food Street", "London", Postcode.From("N1 1LT"))); Assert.AreEqual(address1.Value.ToString(), address1.ToString()); }
public void TestInvalid(string s) { Assert.False(Postcode.TryParse(s, out var postcode)); Assert.Equal(default(Postcode), postcode); }
protected override void Process() { foreach (Connector connector in Connectors.Where(x => x.ZipCodes)) { log.DebugFormat("Start Process zipcode import for {0}", connector.Name); DateTime start = DateTime.Now; try { using (ZipCodesSoapClient soap = new ZipCodesSoapClient()) { using (WebsiteDataContext context = new WebsiteDataContext(ConfigurationManager.ConnectionStrings[connector.Connection].ConnectionString)) { var zips = (from p in context.Postcodes select p).ToList(); var ms = soap.GetZipcodes(); Stream s = new MemoryStream(ms); XmlSerializer x = new XmlSerializer(typeof(Postcode)); List <Postcode> importZips = (List <Postcode>)x.Deserialize(s); foreach (var newzip in importZips) { var existingVar = (from c in zips where c.ZipCodeID == newzip.ZipCodeID select c).FirstOrDefault(); if (existingVar == null) { log.DebugFormat("Try inserting new zipcode {0}", newzip.PCWIJK); Postcode newZipCode = new Postcode { PCWIJK = newzip.PCWIJK, PCLETTER = newzip.PCLETTER, PCREEKSID = newzip.PCREEKSID, PCREEKSVAN = newzip.PCREEKSVAN, PCREEKSTOT = newzip.PCREEKSTOT, PCCITYTPG = newzip.PCCITYTPG, PCCITYNEN = newzip.PCCITYNEN, PCSTRTPG = newzip.PCSTRTPG, PCSTRNEN = newzip.PCSTRNEN, PCSTROFF = newzip.PCSTROFF, PCCITYEXT = newzip.PCCITYEXT, PCGEMEENTEID = newzip.PCGEMEENTEID, PCGEMEENTENAAM = newzip.PCGEMEENTENAAM, PCPROVINCIE = newzip.PCPROVINCIE.Value, PCCEBUCO = newzip.PCCEBUCO, PCSTREXT = newzip.PCSTREXT }; context.Postcodes.InsertOnSubmit(newZipCode); } else { existingVar.PCWIJK = newzip.PCWIJK; existingVar.PCLETTER = newzip.PCLETTER; existingVar.PCREEKSID = newzip.PCREEKSID.Value; existingVar.PCREEKSVAN = newzip.PCREEKSVAN; existingVar.PCREEKSTOT = newzip.PCREEKSTOT; existingVar.PCCITYTPG = newzip.PCCITYTPG; existingVar.PCCITYNEN = newzip.PCCITYNEN; existingVar.PCSTRTPG = newzip.PCSTRTPG; existingVar.PCSTRNEN = newzip.PCSTRNEN; existingVar.PCSTROFF = newzip.PCSTROFF; existingVar.PCCITYEXT = newzip.PCCITYEXT; existingVar.PCGEMEENTEID = newzip.PCGEMEENTEID; existingVar.PCGEMEENTENAAM = newzip.PCGEMEENTENAAM; existingVar.PCPROVINCIE = newzip.PCPROVINCIE.Value; existingVar.PCCEBUCO = newzip.PCCEBUCO; existingVar.PCSTREXT = newzip.PCSTREXT; } context.SubmitChanges(); } } } } catch (Exception ex) { log.Fatal(ex); } log.DebugFormat("Finish Process zipcode import for {0}", connector.Name); } }
// internal for testing internal async Task <(UploadStatus uploadStatus, IReadOnlyCollection <VenueUploadRow> Rows)> ValidateVenueUploadFile( ISqlQueryDispatcher sqlQueryDispatcher, Guid venueUploadId, Guid providerId, VenueDataUploadRowInfoCollection rows) { // We need to ensure that any venues that have live offerings attached are not removed when publishing this // upload. We do that by adding an additional row to this upload for any venues that are not included in // this file that have live offerings attached. This must be done *before* validation so that duplicate // checks consider these additional added rows. var originalRowCount = rows.Count; var existingVenues = await sqlQueryDispatcher.ExecuteQuery(new GetVenueMatchInfoForProvider() { ProviderId = providerId }); // For each row in the file try to match it to an existing venue var rowVenueIdMapping = MatchRowsToExistingVenues(rows, existingVenues); // Add a row for any existing venues that are linked to live offerings and haven't been matched var matchedVenueIds = rowVenueIdMapping.Where(m => m.HasValue).Select(m => m.Value).ToArray(); var venuesWithLiveOfferingsNotInFile = existingVenues .Where(v => v.HasLiveOfferings && !matchedVenueIds.Contains(v.VenueId)) .ToArray(); rows = new VenueDataUploadRowInfoCollection( lastRowNumber: rows.LastRowNumber + venuesWithLiveOfferingsNotInFile.Length, rows: rows.Concat( venuesWithLiveOfferingsNotInFile.Select((v, i) => new VenueDataUploadRowInfo(CsvVenueRow.FromModel(v), rowNumber: rows.LastRowNumber + i + 1, isSupplementary: true)))); rowVenueIdMapping = rowVenueIdMapping.Concat(venuesWithLiveOfferingsNotInFile.Select(v => (Guid?)v.VenueId)).ToArray(); // Grab PostcodeInfo for all of the valid postcodes in the file. // We need this for both the validator and to track whether the venue is outside of England var allPostcodeInfo = await GetPostcodeInfoForRows(sqlQueryDispatcher, rows); var uploadIsValid = true; var validator = new VenueUploadRowValidator(rows, allPostcodeInfo); var upsertRecords = new List <SetVenueUploadRowsRecord>(); for (int i = 0; i < rows.Count; i++) { var row = rows[i].Data; var rowNumber = rows[i].RowNumber; var venueId = rowVenueIdMapping[i] ?? Guid.NewGuid(); var isSupplementaryRow = i >= originalRowCount; // A row is deletable if it is *not* matched to an existing venue that has attached offerings var isDeletable = rowVenueIdMapping[i] is null || !existingVenues.Single(v => v.VenueId == rowVenueIdMapping[i]).HasLiveOfferings; row.ProviderVenueRef = row.ProviderVenueRef?.Trim(); row.Postcode = Postcode.TryParse(row.Postcode, out var postcode) ? postcode : row.Postcode; PostcodeInfo postcodeInfo = null; if (postcode != null) { allPostcodeInfo.TryGetValue(postcode, out postcodeInfo); } var rowValidationResult = validator.Validate(row); var errors = rowValidationResult.Errors.Select(e => e.ErrorCode).ToArray(); var rowIsValid = rowValidationResult.IsValid; uploadIsValid &= rowIsValid; upsertRecords.Add(new SetVenueUploadRowsRecord() { RowNumber = rowNumber, IsValid = rowIsValid, Errors = errors, IsSupplementary = isSupplementaryRow, OutsideOfEngland = postcodeInfo != null ? !postcodeInfo.InEngland : (bool?)null, VenueId = venueId, IsDeletable = isDeletable, ProviderVenueRef = row.ProviderVenueRef, VenueName = row.VenueName, AddressLine1 = row.AddressLine1, AddressLine2 = row.AddressLine2, Town = row.Town, County = row.County, Postcode = row.Postcode, Email = row.Email, Telephone = row.Telephone, Website = row.Website }); } var updatedRows = await sqlQueryDispatcher.ExecuteQuery(new SetVenueUploadRows() { VenueUploadId = venueUploadId, ValidatedOn = _clock.UtcNow, Records = upsertRecords }); await sqlQueryDispatcher.ExecuteQuery(new SetVenueUploadProcessed() { VenueUploadId = venueUploadId, ProcessingCompletedOn = _clock.UtcNow, IsValid = uploadIsValid }); var uploadStatus = uploadIsValid ? UploadStatus.ProcessedSuccessfully : UploadStatus.ProcessedWithErrors; return(uploadStatus, updatedRows); }
//Method created for saving data in Edit Contact window public void SaveEditContactwithValidData() { ExcelLib.PopulateInCollection(Test.Base.ExcelPath, "Employees"); Driver.wait(2); // ClearAllFieldsOnEditContactForm(); FirstName.SendKeys(ExcelLib.ReadData(10, "FirstName")); LastName.SendKeys(ExcelLib.ReadData(10, "LastName")); Phone.SendKeys(ExcelLib.ReadData(10, "Phone")); Email.SendKeys(ExcelLib.ReadData(10, "Email")); Street.SendKeys(ExcelLib.ReadData(10, "Street")); City.SendKeys(ExcelLib.ReadData(10, "City")); Postcode.SendKeys(ExcelLib.ReadData(10, "Post")); Country.SendKeys(ExcelLib.ReadData(10, "Country")); Driver.wait(2); try { // Check if User is able to save Save_Contact_btn.Click(); Driver.driver.SwitchTo().ParentFrame(); Driver.wait(2); Test.Base.test.Log(RelevantCodes.ExtentReports.LogStatus.Pass, "Save button clicked succesfully on Edit Contact Popup Window"); } catch (Exception e) { Test.Base.test.Log(RelevantCodes.ExtentReports.LogStatus.Fail, "Unable to save Contact details on Edit Contact Popup Window"); } try { //Check is Edit client window closes and control switches back to Create New Employee Page IWebElement x = Driver.driver.FindElement(By.XPath("html/body/div[4]/h2")); string Page_title = x.Text; Console.WriteLine(Page_title); Assert.AreEqual("Employee Details", Page_title); Test.Base.test.Log(RelevantCodes.ExtentReports.LogStatus.Pass, "Sucessully switched back to Page with EMPLOYEE DETAILS title"); } catch (Exception e) { Test.Base.test.Log(RelevantCodes.ExtentReports.LogStatus.Fail, "Failed to navigate back to Page with EMPLOYEE DETAILS title "); } try { //Check if Edit contact/ Edit Billing Contact textfield is disabled and loaded with contact details // for Edit Contact Textfield IWebElement j = Driver.driver.FindElement(By.XPath("html/body/div[4]/form/div/div[3]/div/input")); bool Txtbox_status = j.Enabled; Console.WriteLine(Txtbox_status); //string val = j.GetAttribute("value"); //Console.WriteLine(j); Assert.AreEqual("False", Convert.ToString(Txtbox_status)); Test.Base.test.Log(RelevantCodes.ExtentReports.LogStatus.Pass, "Test Pass: Edit contact Textbox is disabled as it is populated by contact details"); } catch (Exception e) { Test.Base.test.Log(RelevantCodes.ExtentReports.LogStatus.Fail, "Test Fail: Edit contact Textbox is still enabled and blank"); } }
// Create a new Property internal void CreateProperty() { Global.ExcelLib.PopulateInCollection(Config.PropertyManagementResource.ExcelPath, "Property"); //Explicit Wait Thread.Sleep(1000); //Click on Owners tab Owners.Click(); //Click Properties option Properties.Click(); //Click on Add New Property button AddPropertybtn.Click(); Thread.Sleep(500); // ************PropertyDetails*************** //Enter Property Name PropertyName.SendKeys(Global.ExcelLib.ReadData(2, "PropertyName")); Thread.Sleep(500); //Click on Property type dropdown PropertyTypeDropdown.Click(); //Select the value from property type dropdown PropertyTypedropdownvalue.Click(); //Enter Description Description.SendKeys(Global.ExcelLib.ReadData(2, "Description")); //Enter Street Number StreetNo.SendKeys(Global.ExcelLib.ReadData(2, "StreetNumber")); //Enter Street Name StreetName.SendKeys(Global.ExcelLib.ReadData(2, "StreetName")); //Enter Suburb Suburb.SendKeys(Global.ExcelLib.ReadData(2, "Suburb")); //Enter City City.SendKeys(Global.ExcelLib.ReadData(2, "City")); //Enter Postcode Postcode.SendKeys(Global.ExcelLib.ReadData(2, "PostCode")); //Enter Region Region.SendKeys(Global.ExcelLib.ReadData(2, "Region")); //Enter Target Rent TargetRent.SendKeys(Global.ExcelLib.ReadData(2, "TargetRent")); Thread.Sleep(1000); //Click on Rent drop down //RentTypeDropdown.Click(); //Select value from Rent dropdown // RentTypeDropdownvalue.Click(); //Enter Land Area LandArea.SendKeys(Global.ExcelLib.ReadData(2, "LandArea")); //Enter Floor Area FloorArea.SendKeys(Global.ExcelLib.ReadData(2, "FloorArea")); //Enter Bedroom Bedrooms.SendKeys(Global.ExcelLib.ReadData(2, "BedRooms")); //Enter Bathroom Bathrooms.SendKeys(Global.ExcelLib.ReadData(2, "BathRooms")); //Enter CarParks Carparks.SendKeys(Global.ExcelLib.ReadData(2, "CarParks")); Thread.Sleep(1000); //Enter Year built YearBuilt.SendKeys(Global.ExcelLib.ReadData(2, "YearBuilt")); // File Upload Approach1: Send Keys /* * FileUploadbtn.SendKeys(@"C:\Users\Shahabuddin\Desktop\Rumana\testiamge.jpg"); * Thread.Sleep(1000); * photo.Click(); */ // File Upload Approach2: AutoIt- Handles windows that do not belong to browser photo.Click(); FileUploadbtn.Click(); AutoItX3 AutoIt = new AutoItX3(); AutoIt.ControlFocus("Open", "", "Edit1"); Thread.Sleep(2000); AutoIt.ControlSetText("Open", "", "Edit1", @"C:\Users\Shahabuddin\Desktop\Rumana\house2_image.jpg"); Thread.Sleep(1000); AutoIt.ControlClick("Open", "", "Button1"); //Click on Next button NextbtnProptertyDetails.Click(); // ************Financialdetails*************** //Enter Purchase Price purchaseprice.SendKeys(Global.ExcelLib.ReadData(2, "PurchasePrice")); //Enter Mortgage Mortgage.SendKeys(Global.ExcelLib.ReadData(2, "Mortgage")); //HomeValue HomeValue.SendKeys(Global.ExcelLib.ReadData(2, "HomeValue")); //Click on Home Value Type drop down HomeValueType.Click(); //Select Home Value type HomeValueTypeSelection.Click(); //Click on Add Repayment button AddRePayment.Click(); //Enter Amount RePaymentAmount.SendKeys(Global.ExcelLib.ReadData(2, "RepaymentAmount")); //Enter RepaymentStartDate RePaymentStartdate.Clear(); RePaymentStartdate.SendKeys("26/05/2018"); Thread.Sleep(500); //Enter RepaymentEndDate RePaymentEnddate.Clear(); RePaymentEnddate.SendKeys("29/06/2018"); Thread.Sleep(500); //Click on Add Expense link AddExpense.Click(); //Enter Expense Amount ExpenseAmount.SendKeys(Global.ExcelLib.ReadData(2, "ExpenseAmount")); // Enter Expense Description ExpenseDescription.SendKeys(Global.ExcelLib.ReadData(2, "ExpenseDescription")); //Enter date for ExpenseDate //ExpenseDateCalender.Clear(); ExpenseDateCalender.SendKeys("30/06/2018"); Thread.Sleep(500); //Click on Next button NextbtnFinanceDetails.Click(); // ************Tenantdetails*************** //Enter TenantEmail TenantEmail.SendKeys(Global.ExcelLib.ReadData(2, "TenantEmail")); //Click on IsmainTenant IsMainTenant.Click(); //Select IsmainTenant IsMainTenantSelectYes.Click(); //Enter Tenant FirstName TenantFirstName.SendKeys(Global.ExcelLib.ReadData(2, "TenantFirstName")); //Enter Tenant LastName TenantLastName.SendKeys(Global.ExcelLib.ReadData(2, "TenantLastName")); //Enter Tenant StartDate TenantStartDate.Clear(); TenantStartDate.SendKeys("20/06/2018"); //Enter Tenant EndDate TenantEndDate.Clear(); TenantEndDate.SendKeys("30/09/2018"); //Enter TenantRentAmount TenantRentAmount.SendKeys(Global.ExcelLib.ReadData(2, "TenantRentAmount")); Thread.Sleep(1000); //Click on PaymentfrequencyDropdown //PaymentFrequencydropdown.Click(); //Select Monthly from PaymentFrequencyDropdown //PaymentFrequencydropdownMonth.Click(); //TenantPaymentStartdate TenantPaymentStartdate.Clear(); TenantPaymentStartdate.SendKeys("10/07/2018"); Thread.Sleep(1000); //Click on PaymentDueDay drop down //PaymentDueDayDropdown.Click(); //Select PaymentDueDay value //PaymentDueDayDropdownvalue.Click(); //Click on AddNewLiabilityLink AddNewLiability.Click(); //Click on LiabilityNameDropDown // LiabilityNameDropdown.Click(); //Select Liability Name Dropdown value //LiabilityNameDropdownInsurance.Click(); //Enter LiabilityAmount //LiabilityAmount.SendKeys(Global.ExcelLib.ReadData(2,"LiabilityAmount")); try { Assert.IsTrue(SavePropertyButton.Displayed); } catch (Exception e) { Console.Write(e); } //Click on Save button SavePropertyButton.Click(); //Add Property Verification //Click on Owners tab Owners.Click(); //Click Properties option Properties.Click(); string msg1 = Global.GlobalDefinition.driver.FindElement(By.XPath("//*[@id='main-content']/section/div[1]/div/div[3]/div/div[1]/div/div/div[2]/div[1]/div[1]/a/h3")).Text; string Actmsg = Global.ExcelLib.ReadData(2, "CreatePropertyVerification"); Thread.Sleep(2000); if (msg1 == Actmsg) { Global.Base.test.Log(LogStatus.Pass, "Test Passed, Record has been created successfully"); Global.SaveScreenShotClass.SaveScreenshot(Global.GlobalDefinition.driver, "PropertyListAdded"); } else { Global.Base.test.Log(LogStatus.Pass, "Test Failed, Record has not created"); } }