private void MapWithPushpins_MouseDoubleClick(object sender, MouseButtonEventArgs e) { myMap.Children.Remove(currentPushpin); // Disables the default mouse double-click action. e.Handled = true; // Determin the location to place the pushpin at on the map. //Get the mouse click coordinates System.Windows.Point mousePosition = e.GetPosition(this); //Convert the mouse coordinates to a locatoin on the map var pinLocation = myMap.ViewportPointToLocation(mousePosition); string test = pinLocation.ToString(); AddressResult ar = gh.GetAddress(test); cityTextBox.Text = ar.Locality; addressTextBox.Text = ar.AddressLine; // The pushpin to add to the map. currentPushpin.Location = pinLocation; // Adds the pushpin to the map. myMap.Children.Add(currentPushpin); }
private void address_Completed(object sender, AddressResult e) { if (e.TaskResult == TaskResult.OK) { MessageBox.Show("\nName: " + e.DisplayName + "\nAddress: " + e.Address); } }
void addressTask_Completed(object sender, AddressResult e) { if (e.TaskResult == TaskResult.OK) { } }
void addressTask_Completed(object sender, AddressResult e) { if (e.TaskResult == TaskResult.OK) { txtEmails.Text += e.Address + ";"; } }
void addressTask_Completed(object sender, AddressResult e) { if (e.TaskResult == TaskResult.OK) { txtEmails.Text += e.Address + ";"; } }
private string GetAddress(Coordinates coor) { // this function get the address according to the coordinates (geocoding) string content = ""; try { GeoCodingServices service = new GeoCodingServices(); AddressResult address = service.ReverseGeoCoding(coor.lon, coor.lat); string country = string.IsNullOrEmpty(address.Country) ? "" : Convert.ToString(address.Country); string city = string.IsNullOrEmpty(address.City) ? "" : ", " + Convert.ToString(address.City); string road = string.IsNullOrEmpty(address.Road) ? "" : ", " + Convert.ToString(address.Road); string housenumber = string.IsNullOrEmpty(address.HouseNumber) ? "" : ", " + Convert.ToString(address.HouseNumber); string postalcode = address.PostCode == "no" ? "" : ", " + Convert.ToString(address.PostCode); string Fulladdress = country + city + road + housenumber + postalcode; if (!string.IsNullOrEmpty(Fulladdress)) { content = Fulladdress; } } catch (Exception ex) { content = ex.Message; } return(content); }
private void Parse(AddressResult addressResult, AddressDetailDTO addressDetailDTO) { addressDetailDTO.id = addressResult.id; addressDetailDTO.idOwner = addressResult.idOwner; addressDetailDTO.State = addressResult.StateName; addressDetailDTO.City = addressResult.City; addressDetailDTO.District = addressResult.District; }
private void AddressChooserTask_Completed(object sender, AddressResult e) { if (null == e.Error && TaskResult.OK == e.TaskResult) { MessageBox.Show(String.Format("Endereço do(a) {0}: {1}", e.DisplayName, e.Address)); } }
public AddressResult Search(IWin32Window parent, IAddressSearchService addressSearchService = null) { using (var form = new AddressSelectStubForm()) { var result = form.ShowDialog(parent); return(result == DialogResult.OK ? form.Selected : AddressResult.Empty()); } }
protected bool Equals(AddressResult other) { return(string.Equals(Company, other.Company) && string.Equals(Address1, other.Address1) && string.Equals(Address2, other.Address2) && string.Equals(Address3, other.Address3) && string.Equals(Address4, other.Address4) && string.Equals(Address5, other.Address5) && string.Equals(Town, other.Town) && string.Equals(County, other.County) && string.Equals(Postcode, other.Postcode) && string.Equals(Country, other.Country)); }
void addressTask_Completed(object sender, AddressResult e) { if (e.TaskResult == TaskResult.OK) { item.Location += e.Address; txtLocation.Text = e.Address; App.ViewModel.SaveFavorites("Contacts"); } }
void act_Completed(object sender, AddressResult e) { if (e.TaskResult == TaskResult.OK) { string address = e.Address; string name = e.DisplayName; var msgbox = MessageBox.Show(address, name, MessageBoxButton.OK); } }
void addressTask_Completed(object sender, AddressResult e) { if (e.TaskResult == TaskResult.OK) { item.Location += e.Address; txtLocation.Text = e.Address; App.ViewModel.SaveFavorites("Contacts"); } }
void addressTask_Completed(object sender, AddressResult e) { if (e.TaskResult == TaskResult.OK) { //this.displayName = e.DisplayName; //this.tbName.Text = "Name: " + e.DisplayName; //this.tbAddress.Text = "Address: " + e.Address; } }
void phoneNumberChooserTask_Completed(object sender, AddressResult e) { if (e.TaskResult == TaskResult.OK) { ViewModel.FriendList.Add(e.DisplayName); FriendLLS.ItemsSource = null; FriendLLS.ItemsSource = (this.DataContext as AddEditTripViewModel).FriendList; } }
void task_Completed(object sender, AddressResult e) { string message; if (e.Error != null || e.TaskResult != TaskResult.OK) message = "No address chosen"; else message = e.Address.Replace("\r\n", ","); webBrowser.InvokeScript("addressChooserCompleted", message); }
private void addressTask_Completed(object sender, AddressResult e) { if (e.TaskResult == TaskResult.OK) { Contacts contacts = new Contacts(); contacts.SearchCompleted += new EventHandler <ContactsSearchEventArgs>(contacts_SearchCompleted); contacts.SearchAsync(e.DisplayName, FilterKind.DisplayName, null); } }
void addressTask_Completed(object sender, AddressResult e) { if (e.TaskResult == TaskResult.OK) { Contacts contacts = new Contacts(); contacts.SearchCompleted += new EventHandler<ContactsSearchEventArgs>(contacts_SearchCompleted); contacts.SearchAsync(e.DisplayName, FilterKind.DisplayName, null); } }
public static JObject ToDto(this AddressResult address) { return(new JObject { { MedikitApiConstants.AddressNames.Country, address.Country }, { MedikitApiConstants.AddressNames.PostalCode, address.PostalCode }, { MedikitApiConstants.AddressNames.Street, address.Street }, { MedikitApiConstants.AddressNames.StreetNumber, address.StreetNumber }, { MedikitApiConstants.AddressNames.Coordinates, new JArray(address.Coordinates) } }); }
void task_Completed(object sender, AddressResult e) { string message; if (e.Error != null || e.TaskResult != TaskResult.OK) { message = "No address chosen"; } else { message = e.Address.Replace("\r\n", ","); } webBrowser.InvokeScript("addressChooserCompleted", message); }
/// <summary> /// Geocode an address returning <see cref="AddressResult"/> async /// </summary> /// <param name="address">A postal address, structured or not, a street, a city, a postal code, a country, or a combination (required)</param> /// <param name="country">The country where the place/address is. It is used to determine the postal address format and to improve performance. /// It will probably be optional in next version to ease the usability.The value must be the ISO 3166 Alpha 2 code of the country. (optional)</param> /// <param name="postal">Whether the given address is a postal address. default to false. In other words, if the address follow the specification /// or if it is a well-formed address as it was written on an envelope. This parameter will enable the parsing of the address by the address parser /// before geocoding, this way, the relevance will be better because because if parsing is successful, we will know the meaning of each word. Note /// that you can also specify each field if you already know them. (optional)</param> /// <returns><see cref="AddressResult"/> </returns> public async Task <AddressResult> geocodeAsync(string address, string country = null, string postal = null) { if (string.IsNullOrEmpty(address)) { throw new ArgumentNullException("Address is a required parameter"); } if (!string.IsNullOrEmpty(country) && country.Length != 2) { throw new ArgumentOutOfRangeException("Country needs to be the ISO 3166 Alpha 2 code"); } AddressResult result = new AddressResult(); using (var client = DefaultClient) { Dictionary <string, string> param = DefaultParams; param.Add("address", address); if (!string.IsNullOrEmpty(country)) { param.Add("country", country); } if (!string.IsNullOrEmpty(postal)) { param.Add("postal", postal); } var response = await client.GetAsync(string.Format("{0}{1}", Gisgraphy.GEOCODING, param.ToQueryString())); if (!response.IsSuccessStatusCode) { result.resultsFound = 0; result.message = await response.Content.ReadAsStringAsync(); } else { try { result = JsonConvert.DeserializeObject <AddressResult>(await response.Content.ReadAsStringAsync()); } catch (JsonSerializationException ex) { result.resultsFound = 0; result.message = string.Format("{0}\n{1}", ex.Message, ex.StackTrace); } } } return(result); }
IEnumerator GetAddress() { Geourl = "https://maps.googleapis.com/maps/api/geocode/json?latlng=" + xCord + "," + yCord + "&key=" + mapApiKey; using (WWW address = new WWW(Geourl)) { yield return(address); if (address.error != null) { Debug.LogError("Map Error" + address.error); } jsonaddress = JsonUtility.FromJson <AddressResult>(address.text); UIManager.Instance.activeCase.location = jsonaddress.results[0].formatted_address; } }
public PartialViewResult GetShipAddr(string StreetNumber, string StreetName, string StreetType, string PostCode, string Town, string State, string Country) { AddressSearchClient client = new AddressSearchClient(); AddressResult result = client.findAddress(StreetNumber, StreetName, StreetType, Town, PostCode, null); if (result.numRecs != 0) { return(PartialView("_GetShipAddr", result.addresses)); } else { return(PartialView("_GetShipAddr", result.addresses)); } }
void ContactSearch_Completed(object sender, AddressResult e) { try { if (e.TaskResult == TaskResult.OK) { BingMapsDirectionsTask bingMapsDirectionsTask = new BingMapsDirectionsTask(); LabeledMapLocation endLabeledMapLocation = new LabeledMapLocation(e.Address, null); bingMapsDirectionsTask.End = endLabeledMapLocation; bingMapsDirectionsTask.Show(); } } catch (Exception x) { Debug.WriteLine("Contact Search Error: " + x.ToString()); MessageBox.Show("Malformed address"); } }
static void Main() { string json = "{ \"AccountId\": 12345665555, \"InvoicId\": 1235, \"Addresses\": [[\"10 Watkin , , , , , Northampton, Northamptonshire\"], [\"12 Spencer Terrace, , , , , Northampton, Northamptonshire\"], [\"18 Watkin , , , , , Northampton, Northamptonshire\"], [\"22 Watkin , , , , , Northampton, Northamptonshire\"]] }"; RootObject root = JsonConvert.DeserializeObject <RootObject>(json); foreach (List <string> address in root.Addresses) { string[] addressLines = address[0].Split(new char[] { ',' }); AddressResult addressResult = new AddressResult() { Line1 = addressLines[0], Line2 = addressLines[1] //... }; } }
/// <summary> /// Reverse geocode a latitude/longitude position returning <see cref="AddressResult"/> async /// </summary> /// <param name="lat">The latitude(north-south) for the location point to search around.The value is a floating number, between -90 and +90. It uses GPS coordinates.</param> /// <param name="lng">The longitude (east-West) for the location point to search around. The value is a floating number between -180 and +180. It uses GPS coordinates.</param> /// <returns><see cref="AddressResult"/> </returns> public async Task <AddressResult> reverseGeocodeAsync(double lat, double lng) { if (lat > 90 || lat < -90) { throw new ArgumentOutOfRangeException("Latitude must be between -90 an 90"); } if (lng > 180 || lng < -180) { throw new ArgumentOutOfRangeException("Longitude must be between -180 and 180"); } AddressResult result = new AddressResult(); using (var client = DefaultClient) { Dictionary <string, string> param = DefaultParams; param.Add("lat", lat.ToString()); param.Add("lng", lng.ToString()); var response = await client.GetAsync(string.Format("{0}{1}", Gisgraphy.REVERSE_GEOCODING, param.ToQueryString())); if (!response.IsSuccessStatusCode) { result.resultsFound = 0; result.message = await response.Content.ReadAsStringAsync(); } else { try { result = JsonConvert.DeserializeObject <AddressResult>(await response.Content.ReadAsStringAsync()); } catch (JsonSerializationException ex) { result.resultsFound = 0; result.message = string.Format("{0}\n{1}", ex.Message, ex.StackTrace); } } } return(result); }
public Task <AddressResult> Search(string postalCode) { if (postalCode == "0000000") { return(Address("0000000", "宮崎県", "宮崎市", "宮崎")); } if (postalCode == "0000001") { return(Address("0000001", "鹿児島県", "鹿児島市", "名山町")); } if (postalCode == "0000002") { return(Address("0000002", "とにかくですね", "長い長い長い長い", "住所字とかいろいろはいっててめっちゃながい")); } if (postalCode == "9999999") { throw new InvalidOperationException("サーバーに接続できませんでした"); } return(Task.FromResult(AddressResult.Empty())); }
public void ReplaceSubstringTest() { var countryPatern = "Россия, Алтай, 45"; var country = "Россия"; var countryExp = "Алтай, 45"; var indexPatern = "Россия, Алтай, 45, 555555"; var indexExp = "Россия, Алтай, 45"; var indexinPatern = "Россия, Алтай, 45, 555555, дом"; var indexinExp = "Россия, Алтай, 45, , дом"; var result = AddressResult.ReplaceSubstring(countryPatern, country); Assert.AreEqual(result, countryExp); result = AddressResult.ReplaceSubstring(indexPatern, "555555"); Assert.AreEqual(result, indexExp); result = AddressResult.ReplaceSubstring(indexinPatern, "555555"); Assert.AreEqual(result, indexinExp); }
public IActionResult OnGet(string address) { IndexerClient indexerClient = IndexerRpc(); string prefix = AddressPrefix(); Script lockScript; try { lockScript = Address.ParseAddress(address, prefix); } catch { return(NotFound()); } SearchKey searchKey = new(lockScript, "lock"); CellCapacity?cellCapacity = indexerClient.GetCellsCapacity(searchKey); UInt64 balance = 0; if (cellCapacity != null) { balance = Hex.HexToUInt64(cellCapacity.Capacity); } int cellsCount = GetCellsCount(indexerClient, searchKey); AddressResult = new() { AddressHash = address, LockScript = lockScript, Balance = balance.ToString(), LiveCellsCount = cellsCount.ToString(), }; return(Page()); }
/// <summary> /// Choose Address Launcher Handler /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void addressChooserTask_Completed(object sender, AddressResult e) { string js = ""; getAllContacts(); switch (e.TaskResult) { case TaskResult.OK: AddressResult address = (AddressResult)e; js = string.Format("javascript: var e = document.createEvent('Events');" + "e.initEvent('intel.xdk.contacts.choose',true,true);" + "e.success=true;e.contactid='{0}';document.dispatchEvent(e);", ""); busy = false; break; case TaskResult.Cancel: //js = new CommandResponse(new JsEvent { CommandType = CommandTypeEnum.APPMOBI_CONTACTS_CHOOSE, Cancelled = true, ErrorMessage = "Choose contact cancelled." }).ToString(); js = string.Format("javascript: var e = document.createEvent('Events');" + "e.initEvent('intel.xdk.contacts.choose',true,true);e.cancelled=true;" + "e.success=false;e.error='{0}';document.dispatchEvent(e);", "There was a problem choosing a contact."); busy = false; break; case TaskResult.None: //js = new CommandResponse(new JsEvent { CommandType = CommandTypeEnum.APPMOBI_CONTACTS_CHOOSE, ErrorMessage = "There was a problem choosing the contact." }).ToString(); js = string.Format(" var e = document.createEvent('Events');" + "e.initEvent('intel.xdk.contacts.choose',true,true);e.cancelled=false;" + "e.success=false;e.error='{0}';document.dispatchEvent(e);", "There was a problem choosing the contact."); break; } //InjectJS("javascript:" + js); InvokeCustomScript(new ScriptCallback("eval", new string[] { js }), true); }
private void PatchProperties(AddressResult entity, IAddressResultUpdate update) { entity.Latitude = update.Latitude; entity.Longitude = update.Longitude; entity.State = State.Terminado; }
private void dataGridView1_CellContentDoubleClick(object sender, DataGridViewCellEventArgs e) { Selected = _addresses[e.RowIndex]; DialogResult = DialogResult.OK; }
public async Task <IEnumerable <AddressResult> > Parse(string address1) { var addressResults = new List <AddressResult>(); //The following is the list of C2 Secondary Unit Designators (http://pe.usps.gov/text/pub28/28apc_003.htm). These generally preceed an apartment number. var sudLookup = new[] { "APARTMENT", "APT", "BUILDING", "BLDG", "DEPARTMENT", "DEPT", "FLOOR", "FL", "HANGER", "HNGR", "KEY", "LOT", "PIER", "ROOM", "RM", "SLIP", "SPACE", "SPC", "STOP", "SUITE", "STE", "TRAILER", "TRLR", "UNIT" }; //Make the entire string upper case so that we don't have to worry about case sensetivity going forward. address1 = address1.ToUpper(); //Replace the # sign with APT, which is our default SUD. address1 = address1.Replace("#", " APT "); //If the address ends in a 5 digit string, and it isn't preceeded by a SUD, assume it is the zip and remove it. var zipRemoved = false; if (address1.Length >= 5) { var zipRegEx = new Regex(@"^\d{5}$"); var lastFiveChars = address1.Substring(address1.Length - 5, 5); if (zipRegEx.IsMatch(lastFiveChars)) { var remainingAddress = address1.TrimEnd(lastFiveChars.ToCharArray()).Trim(); if (!sudLookup.Any(sud => remainingAddress.EndsWith(sud))) { zipRemoved = true; address1 = remainingAddress; } } } //If the address ends in a 9 digit zip code formatted as 99999-9999, remove the zip. if (!zipRemoved && address1.Length >= 10) { var zipRegEx = new Regex(@"^\d{5}-\d{4}$"); var lastTenChars = address1.Substring(address1.Length - 10, 10); if (zipRegEx.IsMatch(lastTenChars)) { address1 = address1.TrimEnd(lastTenChars.ToCharArray()); } } //Replace 1/2 with H before special characters are stripped out. address1 = address1.Replace("1/2", "H"); //If the number contains .5, replace it with H before special characters are stripped out. var pointFiveRegEx = new Regex(@"^\d+\.5"); var numberPart = address1.Substring(0, address1.IndexOf(" ", StringComparison.Ordinal)); if (pointFiveRegEx.IsMatch(numberPart)) { address1 = pointFiveRegEx.Replace(address1, numberPart.TrimEnd(".5".ToCharArray()) + "H", 1); } //Remove any non alpha-numeric characters var chrsToIgnore = new[] { '~', '`', '!', '@', '$', '%', '^', '&', '*', '(', ')', '_', '=', '+', '{', '}', '[', ']', '|', '\\', '/', '<', '>', ':', ';', '"', '\'', ',', '.', '?' }; address1 = chrsToIgnore.Aggregate(address1, (current, chr) => current.Replace(chr.ToString(), "")); //Replace any instance of two spaces with a single space. while (address1.Contains(" ")) { address1 = address1.Replace(" ", " "); } //Commas have been removed. Now remove "Louisville KY" since this algorithm only parses Louisville addresses. We can't remove "Louisville" because there exists a street with that name. address1 = address1.Replace("LOUISVILLE KY", ""); //Trim leading and trailing spaces and split the address into its parts. var addressParts = address1.Trim().Split(' ').ToList(); //Return an empty result list if the address has no parts. if (addressParts.Count == 0) { return(new List <AddressResult>()); } //If a SUD is found, assume that the following addressPart is an apartment number. Skip the first addresspart since it is already determined to be the number. //At this point, it is possible that we have multiple Secondary Unit Designators, especially if they included both a SUD and a # sign. We will want to consider //the possibility that that is both accurate or inaccurate. Create a new version of the address where any extra SUDs have been removed and pass that back through //this function. Then continue on with the original input. var sudIndexes = new List <int>(); var distinctAddressInputs = new List <string>(); var sudCount = 0; for (var i = 0; i < addressParts.Count; i++) { if (sudLookup.Contains(addressParts[i])) { sudIndexes.Add(i); sudCount++; } } if (sudCount > 1) { foreach (var sudIndex in sudIndexes) { var sudRemoved = addressParts.Where((t, i) => i != sudIndex).Aggregate("", (current, t) => current + (t + " ")); //Don't send this through if we have already passed the exact string (i.e. there were two of the same SUD, 123 Main St Apt Apt 103) if (distinctAddressInputs.Contains(sudRemoved)) { continue; } distinctAddressInputs.Add(sudRemoved); var sudRemovedParsings = await Parse(sudRemoved); addressResults.AddRange(sudRemovedParsings); } } var firstPartNumber = ""; var firstPartHalfHouse = ""; //Break apart the numeric and non-numeric portions of the first part of the address in case the half house is contained in this part of the string. foreach (var chr in addressParts[0]) { var numericRegEx = new Regex("[0-9]"); if (numericRegEx.IsMatch(chr.ToString())) { firstPartNumber += chr; } else { firstPartHalfHouse += chr; } } //If the first part of the address contains numbers, assign them as the "number" part of the address. Otherwise, return null. All addresses must have a number. int iNumber; if (!int.TryParse(firstPartNumber, out iNumber)) { return(new List <AddressResult>()); } //Hard-code a list of possible half houses. Find anything that appeared as part of the number, or the first address part after the number that resembles a half house //and add it to a list of half houses with a the index of the half house as it appears in addressParts. var halfHouseLookup = new[] { "A", "B", "C", "D", "F", "H", "M", "R", "U" }; var halfHouses = new Dictionary <int, string>(); if (halfHouseLookup.Any(hh => firstPartHalfHouse == hh)) { //Since half house was found with no space between it and the number, it is still at the end of addressParts[0]. It needs to be at addressParts[1]. addressParts[0] = addressParts[0].TrimEnd(firstPartHalfHouse.ToCharArray()); addressParts.Insert(1, firstPartHalfHouse); halfHouses.Add(1, firstPartHalfHouse); } else if (halfHouseLookup.Any(hh => addressParts.Count > 1 && addressParts[1] == hh)) { halfHouses.Add(1, addressParts[1]); } //Add empty string as a possible half house. halfHouses.Add(-1, ""); var apts = new Dictionary <int, string>(); var sudFound = false; for (var i = 1; i < addressParts.Count; i++) { if (sudFound) { apts.Add(i, addressParts[i]); sudFound = false; } else if (sudLookup.Contains(addressParts[i])) { sudFound = true; } } //Add empty apartment as a possible apartment. apts.Add(-1, ""); //Get a list of all possible tags (street suffixes). var tagLookup = await _tagRepository.GetCommonAbbreviations(); var directions = new Dictionary <int, string>(); for (var i = 1; i < addressParts.Count; i++) { if (addressParts[i] == "N" || addressParts[i] == "NORTH" || addressParts[i] == "NO") { directions.Add(i, "N"); } if (addressParts[i] == "S" || addressParts[i] == "SOUTH" || addressParts[i] == "SO") { directions.Add(i, "S"); } if (addressParts[i] == "E" || addressParts[i] == "EAST") { directions.Add(i, "E"); } if (addressParts[i] == "W" || addressParts[i] == "WEST") { directions.Add(i, "W"); } } //Add empty string as a possible direction. directions.Add(-1, ""); var tags = new Dictionary <int, string>(); for (var i = 1; i < addressParts.Count; i++) { //Always add the USPSStandardAbbreviation, even if the tag found is a CommonAbbreviation. var commonTagMatches = tagLookup.Where(t => string.Equals(t.CommonAbbreviation, addressParts[i], StringComparison.CurrentCultureIgnoreCase)).ToList(); if (commonTagMatches.Any()) { tags.Add(i, commonTagMatches.First().StandardAbbreviation); continue; } var uspsTagMatches = tagLookup.Where(t => string.Equals(t.StandardAbbreviation, addressParts[i], StringComparison.CurrentCultureIgnoreCase)).ToList(); if (uspsTagMatches.Any()) { tags.Add(i, uspsTagMatches.First().StandardAbbreviation); } } //Add empty string as a possible tag. tags.Add(-1, ""); //Loop through every combination of half house, direction, tag, and apartment. foreach (var halfHouse in halfHouses) { foreach (var direction in directions) { foreach (var tag in tags) { foreach (var apt in apts) { var address = new AddressResult { Address = new AddressModel { Number = iNumber, HalfHouse = halfHouse.Value, Direction = direction.Value, Street = "", Tag = tag.Value, Apartment = apt.Value }, Score = 1 }; //If the address part isn't already designated as a half house, direction, tag, or apartment, add it to the street. If there is an apartment //designated, ignore the previous string since it will be the Secondary Unit Designator. for (var i = 1; i < addressParts.Count; i++) { if (halfHouse.Key != i && direction.Key != i && tag.Key != i && apt.Key != i && apt.Key != i + 1) { address.Address.Street += (i > 1 ? " " : "") + addressParts[i]; } //The score was initialized as 1. 1 is the lowest initial score. Anything less than one indicates an address part that was found out of //place. If this verions contains a half house, increment the score. if (halfHouse.Key == i) { address.Score++; } if (direction.Key == i) { //Only give a point for the direction if it falls in an expected order. if (direction.Key == 1) //After number { address.Score++; } else if (direction.Key == 2 && halfHouse.Key == 1) //After half house { address.Score++; } else if (direction.Key + 1 == addressParts.Count) //At the end. { address.Score++; } else if (direction.Key + 3 == addressParts.Count && apt.Key + 1 == addressParts.Count) //Third from the end if apartment is at end. { address.Score++; } else //Subtract a point for a direction that is out of place. { address.Score--; } } if (tag.Key == i) { //Only give points for the tag if it falls in an expected order. //Tags get a bonus point to give an address with a tag a higher score than one without. For example "123 South St" parsed as 123 S "ST" //would get 1 point for having a direction in the right place. 123 "South" St would get two points for having a tag in the right place. if (tag.Key + 1 == addressParts.Count) //At the end. { address.Score += 2; } else if (tag.Key + 2 == addressParts.Count && direction.Key + 1 == addressParts.Count) //Second from the end if direction is at the end. { address.Score += 2; } else if (tag.Key + 3 == addressParts.Count && apt.Key + 1 == addressParts.Count) //Third from the end if apartment is at the end. { address.Score += 2; } else if (tag.Key + 4 == addressParts.Count && apt.Key + 1 == addressParts.Count && direction.Key + 3 == addressParts.Count) //Fourth from the end if apartment is at the end and direction is third from end. { address.Score += 2; } else //Subtract a point for a tag that is out of place. { address.Score--; } } if (apt.Key == i + 1) { //Only give a point for the apartment if it falls in an expected order. if (apt.Key == addressParts.Count - 1) { address.Score++; //Apartment is at the end. } else //Subtract a point for an apartment that is out of place. { address.Score--; } } } //There is a possiblity that there is a leading space. Trim it off. address.Address.Street = address.Address.Street.Trim(); //Replace numbered street names that are spelled out with their non-spelled out counterpart. (i.e. Third -> 3RD) if (NumberedStreets.ContainsKey(address.Address.Street)) { address.Address.Street = NumberedStreets[address.Address.Street]; } if (!string.IsNullOrWhiteSpace(address.Address.Street)) { addressResults.Add(address); } } } } } //When we reach here, we could have duplicate results if there was more than one Secondary Unit Designator present. For now, I //am just returning a distinct list. We might decide that we need to get a distinct list of addresses with their highest score. //In my testing, the duplicate address parsings had the same score. return(addressResults.Distinct()); }
private Task <AddressResult> Address(string postalCode, string prefecture, string city, string town) { return(Task.FromResult(AddressResult.Success(postalCode, prefecture, city, town))); }
public string GenerateReportPdf(Marks marks, Coordinates coor, ReportExtraInfo reportextrainfo) { try { string serial = Guid.NewGuid().ToString(); string FinalAddressAndReportName = string.Empty; string WordReport = docxReportPath + Path.DirectorySeparatorChar + serial + wordExnt; File.Copy(templateDoc, WordReport, true); Application wordApp = new Application { Visible = true }; Document aDoc = wordApp.Documents.Open(WordReport, ReadOnly: false, Visible: true); aDoc.Activate(); FindAndReplaceMainDoc(wordApp, "[Date]", DateTime.Now.ToString("dd/MM/yyyy")); FindAndReplaceMainDoc(wordApp, "[Serial_Number]", serial); FindAndReplaceMainDoc(wordApp, "[Project Name]", reportextrainfo.ProjName); FindAndReplaceMainDocHeaderAndFooter(aDoc, "[Project Name]", reportextrainfo.ProjName); FindAndReplaceMainDoc(wordApp, "[Company Name]", reportextrainfo.CustomerName); FindAndReplaceMainDoc(wordApp, "[Title]", "Indexes Value of - Coordinates " + Math.Round(coor.lon, 4) + "/" + Math.Round(coor.lat, 4)); FindAndReplaceMainDoc(wordApp, "[Coordinates]", "Coordinates " + Math.Round(coor.lon, 4) + "/" + Math.Round(coor.lat, 4)); // let's get the full address of the location according to the coordinates using OSM reverse geocoding service GeoCodingServices service = new GeoCodingServices(); AddressResult address = service.ReverseGeoCoding(coor.lon, coor.lat); string country = string.IsNullOrEmpty(address.Country) ? "" : Convert.ToString(address.Country); string city = string.IsNullOrEmpty(address.City) ? "" : ", " + Convert.ToString(address.City); string road = string.IsNullOrEmpty(address.Road) ? "" : ", " + Convert.ToString(address.Road); string housenumber = string.IsNullOrEmpty(address.HouseNumber) ? "" : ", " + Convert.ToString(address.HouseNumber); string postalcode = address.PostCode == "no" ? "" : ", " + Convert.ToString(address.PostCode); string Fulladdress = country + city + road + housenumber + postalcode; if (!string.IsNullOrEmpty(Fulladdress)) { FinalAddressAndReportName += StringSeparator + "Address:" + Fulladdress; FindAndReplaceMainDoc(wordApp, "[Address]", Fulladdress); FindAndReplaceMainDoc(wordApp, "[Site Name]", Fulladdress); // if the city name exist, then let's check if the city name have value in wikipedia or not if (!string.IsNullOrEmpty(address.City)) { wikidata data = GetDataFromWiki(address.City); if (data.key != -1) { object oBookMark = "SiteInfo"; aDoc.Bookmarks.get_Item(ref oBookMark).Range.Text = data.value; } else { FindAndReplaceMainDoc(wordApp, "[Site Brief Info]", " "); FindAndReplaceMainDoc(wordApp, "Source: https://en.wikipedia.org/", " "); } } } else { FinalAddressAndReportName += StringSeparator + "Address:" + " "; FindAndReplaceMainDoc(wordApp, "[Address]", " "); FindAndReplaceMainDoc(wordApp, "[Site Name]", " "); FindAndReplaceMainDoc(wordApp, "[Site Brief Info]", " "); FindAndReplaceMainDoc(wordApp, "Source: https://en.wikipedia.org/", " "); } // let's get the site FindAndReplaceMainDoc(wordApp, "{EG}", Math.Round(marks.RadiationEG, 2).ToString()); FindAnndReplaceShapes(aDoc, "{EG}", Math.Round(marks.RadiationEG, 2).ToString()); FindAndReplaceMainDoc(wordApp, "[EG Comments]", CheckinterferenceValue(Types.Radiation, Math.Round(marks.RadiationEG, 2))); FindAndReplaceMainDoc(wordApp, "{SC}", Math.Round(marks.SoilPollution, 2).ToString()); FindAnndReplaceShapes(aDoc, "{SC}", Math.Round(marks.SoilPollution, 2).ToString()); FindAndReplaceMainDoc(wordApp, "[SC Comments]", CheckinterferenceValue(Types.Soil, Math.Round(marks.SoilPollution, 2))); FindAndReplaceMainDoc(wordApp, "{EC}", Math.Round(marks.Ecology, 2).ToString()); FindAnndReplaceShapes(aDoc, "{EC}", Math.Round(marks.Ecology, 2).ToString()); FindAndReplaceMainDoc(wordApp, "[EC Comments]", CheckinterferenceValue(Types.Ecology, Math.Round(marks.Ecology, 2))); FindAndReplaceMainDoc(wordApp, "{NO}", Math.Round(marks.NoiseInterference, 2).ToString()); FindAnndReplaceShapes(aDoc, "{NO}", Math.Round(marks.NoiseInterference, 2).ToString()); FindAndReplaceMainDoc(wordApp, "[NO Comments]", CheckinterferenceValue(Types.Noise, Math.Round(marks.NoiseInterference, 2))); FindAndReplaceMainDoc(wordApp, "{AQ}", Math.Round(marks.AirQuality, 2).ToString()); FindAnndReplaceShapes(aDoc, "{AQ}", Math.Round(marks.AirQuality, 2).ToString()); FindAndReplaceMainDoc(wordApp, "[AO Comments]", CheckinterferenceValue(Types.AirQuality, Math.Round(marks.AirQuality, 2))); // will be change in the future to Solid Waste Management Mark and comments FindAndReplaceMainDoc(wordApp, "{SW}", Math.Round(marks.SoilPollution, 2).ToString()); FindAnndReplaceShapes(aDoc, "{SW}", Math.Round(marks.SoilPollution, 2).ToString()); FindAndReplaceMainDoc(wordApp, "[SW Comments]", " "); // overall index value FindAndReplaceMainDoc(wordApp, "{M}", Math.Round(marks.FinalMark, 2).ToString()); FindAnndReplaceShapes(aDoc, "{M}", Math.Round(marks.FinalMark, 2).ToString()); AddMap(aDoc, coor); //string WordReport = docxReportPath + Path.DirectorySeparatorChar + serial + wordExnt; //wordApp.Documents[1].SaveAs2(WordReport, WdSaveFormat.wdFormatDocumentDefault); wordApp.Documents[1].Save(); string pdfReport = pdfReportPath + Path.DirectorySeparatorChar + serial + PdfExnt; wordApp.Documents[1].SaveAs2(pdfReport, WdSaveFormat.wdFormatPDF); wordApp.Documents[1].Close(); wordApp.Quit(); int res = System.Runtime.InteropServices.Marshal.ReleaseComObject(aDoc); int res1 = System.Runtime.InteropServices.Marshal.ReleaseComObject(wordApp); GC.Collect(); // let's copy the file to authenticate folder for user downloads. FinalAddressAndReportName += StringSeparator + "Report:" + serial + PdfExnt; string downloadFile = pdfReportDownlaodPath + Path.DirectorySeparatorChar + serial + PdfExnt; File.Copy(pdfReport, downloadFile, true); return(FinalAddressAndReportName); } catch (Exception e) { log.Error(e); return(String.Empty); } }
void chooser_Completed(object sender, AddressResult e) { MessageBox.Show("Nome: " + e.DisplayName + "\nEndereço: " + e.Address); }
private static AddressResult Address(string postalCode, string prefecture, string city, string town) { return(AddressResult.Success(postalCode, prefecture, city, town)); }