/// <summary> /// Geocodes the specified address. /// </summary> /// <param name="location">The location.</param> /// <param name="result">The ServiceObjects result.</param> /// <returns> /// True/False value of whether the address was standardized succesfully /// </returns> public override bool Geocode( Rock.Model.Location location, out string result ) { if ( location != null ) { string licenseKey = GetAttributeValue("LicenseKey"); var client = new DOTSGeoCoderSoapClient(); Location_V3 location_match = client.GetBestMatch_V3( string.Format("{0} {1}", location.Street1, location.Street2), location.City, location.State, location.Zip, licenseKey ); result = location_match.Level; if ( location_match.Level == "S" || location_match.Level == "P" ) { double latitude = double.Parse( location_match.Latitude ); double longitude = double.Parse( location_match.Longitude ); location.SetLocationPointFromLatLong(latitude, longitude); return true; } } else result = "Null Address"; return false; }
/// <summary> /// Geocodes the specified address. /// </summary> /// <param name="location">The location.</param> /// <param name="result">The result.</param> /// <returns> /// True/False value of whether the address was standardized was succesfully /// </returns> public override bool Geocode( Rock.Model.Location location, out string result ) { if ( location != null ) { var registeredUser = new RegisteredUser(); registeredUser.UserID = GetAttributeValue("UserID"); registeredUser.Password = GetAttributeValue("Password"); var licenseInfo = new LicenseInfo(); licenseInfo.RegisteredUser = registeredUser; var client = new USAddressVerificationSoapClient(); SIWsOutputOfUSAddress verifyResult; SubscriptionInfo info = client.VerifyAddressUSA( licenseInfo, location.Street1, location.Street2, string.Format("{0} {1} {2}", location.City, location.State, location.Zip), string.Empty, string.Empty, CasingEnum.PROPER, out verifyResult ); if (verifyResult != null) { result = verifyResult.ServiceStatus.StatusNbr.ToString(); if ( verifyResult.ServiceStatus.StatusNbr == 200 ) { USAddress usAddress = verifyResult.ServiceResult; if ( usAddress != null && usAddress.GeoCode != null ) { location.SetLocationPointFromLatLong( usAddress.GeoCode.Latitude, usAddress.GeoCode.Longitude ); return true; } } } else result = "Null Result"; } else result = "Null Address"; return false; }
/// <summary> /// Geocodes the specified address. /// </summary> /// <param name="location">The location.</param> /// <param name="reVerify">Should location be reverified even if it has already been succesfully verified</param> /// <param name="result">The result code unique to the service.</param> /// <returns> /// True/False value of whether the address was geocoded succesfully /// </returns> public override bool VerifyLocation( Rock.Model.Location location, bool reVerify, out string result ) { bool verified = false; result = string.Empty; // Only verify if location is valid, has not been locked, and // has either never been attempted or last attempt was in last 30 secs (prev active service failed) or reverifying if ( location != null && !(location.IsGeoPointLocked ?? false) && ( !location.GeocodeAttemptedDateTime.HasValue || location.GeocodeAttemptedDateTime.Value.CompareTo( RockDateTime.Now.AddSeconds(-30) ) > 0 || reVerify ) ) { string licenseKey = GetAttributeValue("LicenseKey"); var client = new DOTSGeoCoderSoapClient(); Location_V3 location_match = client.GetBestMatch_V3( string.Format("{0} {1}", location.Street1, location.Street2), location.City, location.State, location.PostalCode, licenseKey ); result = location_match.Level; location.GeocodeAttemptedServiceType = "ServiceObjects"; location.GeocodeAttemptedDateTime = RockDateTime.Now; location.GeocodeAttemptedResult = result; if ( location_match.Level == "S" || location_match.Level == "P" ) { double latitude = double.Parse( location_match.Latitude ); double longitude = double.Parse( location_match.Longitude ); location.SetLocationPointFromLatLong(latitude, longitude); location.GeocodedDateTime = RockDateTime.Now; verified = true; } } return verified; }
/// <summary> /// Geocodes the specified address. /// </summary> /// <param name="location">The location.</param> /// <param name="reVerify">Should location be reverified even if it has already been succesfully verified</param> /// <param name="result">The result code unique to the service.</param> /// <returns> /// True/False value of whether the address was geocoded succesfully /// </returns> public override bool VerifyLocation( Rock.Model.Location location, bool reVerify, out string result ) { bool verified = false; result = string.Empty; if ( location != null && (!location.GeocodeAttemptedDateTime.HasValue || reVerify)) { string licenseKey = GetAttributeValue("LicenseKey"); var client = new DOTSGeoCoderSoapClient(); Location_V3 location_match = client.GetBestMatch_V3( string.Format("{0} {1}", location.Street1, location.Street2), location.City, location.State, location.PostalCode, licenseKey ); result = location_match.Level; location.GeocodeAttemptedServiceType = "ServiceObjects"; location.GeocodeAttemptedDateTime = RockDateTime.Now; location.GeocodeAttemptedResult = result; if ( location_match.Level == "S" || location_match.Level == "P" ) { double latitude = double.Parse( location_match.Latitude ); double longitude = double.Parse( location_match.Longitude ); location.SetLocationPointFromLatLong(latitude, longitude); location.GeocodedDateTime = RockDateTime.Now; verified = true; } } return verified; }
/// <summary> /// Geocodes the specified address. /// </summary> /// <param name="location">The location.</param> /// <param name="resultMsg">The result MSG.</param> /// <returns> /// True/False value of whether the address was geocoded successfully /// </returns> public override VerificationResult Verify( Rock.Model.Location location, out string resultMsg ) { VerificationResult result = VerificationResult.None; resultMsg = string.Empty; string licenseKey = GetAttributeValue("LicenseKey"); var client = new DOTSGeoCoderSoapClient(); Location_V3 location_match = client.GetBestMatch_V3( string.Format("{0} {1}", location.Street1, location.Street2), location.City, location.State, location.PostalCode, licenseKey ); resultMsg = location_match.Level; if ( location_match.Level == "S" || location_match.Level == "P" ) { double latitude = double.Parse( location_match.Latitude ); double longitude = double.Parse( location_match.Longitude ); if ( location.SetLocationPointFromLatLong( latitude, longitude ) ) { result = VerificationResult.Geocoded; } } return result; }
/// <summary> /// Standardizes and Geocodes an address using Bing service /// </summary> /// <param name="location">The location.</param> /// <param name="resultMsg">The result MSG.</param> /// <returns> /// True/False value of whether the verification was successfull or not /// </returns> public override VerificationResult Verify( Rock.Model.Location location, out string resultMsg ) { VerificationResult result = VerificationResult.None; resultMsg = string.Empty; // Verify that bing transaction count hasn't been exceeded for the day DateTime? txnDate = Rock.Web.SystemSettings.GetValue( TXN_DATE ).AsDateTime(); int? dailyTxnCount = 0; if ( txnDate.Equals( RockDateTime.Today ) ) { dailyTxnCount = Rock.Web.SystemSettings.GetValue( DAILY_TXN_COUNT ).AsIntegerOrNull(); } else { Rock.Web.SystemSettings.SetValue( TXN_DATE, RockDateTime.Today.ToShortDateString() ); } int? maxTxnCount = GetAttributeValue( "DailyTransactionLimit" ).AsIntegerOrNull(); if ( !maxTxnCount.HasValue || maxTxnCount.Value == 0 || dailyTxnCount < maxTxnCount.Value ) { dailyTxnCount++; Rock.Web.SystemSettings.SetValue( DAILY_TXN_COUNT, dailyTxnCount.ToString() ); string key = GetAttributeValue( "BingMapsKey" ); var queryValues = new Dictionary<string, string>(); queryValues.Add( "adminDistrict", location.State ); queryValues.Add( "locality", location.City ); queryValues.Add( "postalCode", location.PostalCode ); queryValues.Add( "addressLine", location.Street1 + " " + location.Street2 ); queryValues.Add( "countryRegion", location.Country ); var queryParams = new List<string>(); foreach ( var queryKeyValue in queryValues ) { if ( !string.IsNullOrWhiteSpace( queryKeyValue.Value ) ) { queryParams.Add( string.Format( "{0}={1}", queryKeyValue.Key, HttpUtility.UrlEncode( queryKeyValue.Value.Trim() ) ) ); } } Uri geocodeRequest = new Uri( string.Format( "http://dev.virtualearth.net/REST/v1/Locations?{0}&key={1}", queryParams.AsDelimited( "&" ), key ) ); WebClient wc = new WebClient(); var stream = wc.OpenRead( geocodeRequest ); DataContractJsonSerializer ser = new DataContractJsonSerializer( typeof( Response ) ); var x = ser.ReadObject( stream ) as Response; if ( x != null ) { if ( x.ResourceSets.Length > 0 && x.ResourceSets[0].Resources.Length == 1 ) { var bingLocation = (Location)x.ResourceSets[0].Resources[0]; var matchCodes = bingLocation.MatchCodes.ToList(); resultMsg = string.Format( "Confidence: {0}; MatchCodes: {1}", bingLocation.Confidence, matchCodes.AsDelimited( "," ) ); if ( bingLocation.Confidence == "High" && matchCodes.Contains( "Good" ) ) { if ( location.SetLocationPointFromLatLong( bingLocation.Point.Coordinates[0], bingLocation.Point.Coordinates[1] ) ) { result = VerificationResult.Geocoded; } var address = bingLocation.Address; if ( address != null ) { location.Street1 = address.AddressLine; location.County = address.AdminDistrict2; location.City = address.Locality; location.State = address.AdminDistrict; if ( !String.IsNullOrWhiteSpace( address.PostalCode ) && !( ( location.PostalCode ?? string.Empty ).StartsWith( address.PostalCode ) ) ) { location.PostalCode = address.PostalCode; } result = result | VerificationResult.Standardized; } } } else { resultMsg = "Zero or More than 1 result"; } } else { result = VerificationResult.ConnectionError; resultMsg = "Invalid response"; } } else { result = VerificationResult.ConnectionError; resultMsg = "Daily transaction limit exceeded"; } return result; }
/// <summary> /// Standardizes and Geocodes an address using Bing service /// </summary> /// <param name="location">The location.</param> /// <param name="reVerify">Should location be reverified even if it has already been succesfully verified</param> /// <param name="result">The result code unique to the service.</param> /// <returns> /// True/False value of whether the verification was successfull or not /// </returns> public override bool VerifyLocation( Rock.Model.Location location, bool reVerify, out string result ) { bool verified = false; result = string.Empty; if ( location != null && !( location.IsGeoPointLocked ?? false ) && ( !location.GeocodeAttemptedDateTime.HasValue || reVerify ) ) { string authId = GetAttributeValue( "AuthID" ); string authToken = GetAttributeValue( "AuthToken" ); var dpvCodes = GetAttributeValue("AcceptableDPVCodes").SplitDelimitedValues(); var precisions = GetAttributeValue("AcceptablePrecisions").SplitDelimitedValues(); var payload = new[] { new { addressee = location.Name, street = location.Street1, street2 = location.Street2, city = location.City, state = location.State, zipcode = location.PostalCode, candidates = 1 } }; var client = new RestClient( string.Format( "https://api.smartystreets.com/street-address?auth-id={0}&auth-token={1}", authId, authToken ) ); var request = new RestRequest( Method.POST ); request.RequestFormat = DataFormat.Json; request.AddHeader( "Accept", "application/json" ); request.AddBody( payload ); var response = client.Execute( request ); if (response.StatusCode == HttpStatusCode.OK) { var candidates = JsonConvert.DeserializeObject( response.Content, typeof( List<CandidateAddress> ) ) as List<CandidateAddress>; if (candidates.Any()) { var candidate = candidates.FirstOrDefault(); verified = true; result = string.Format( "record_type: {0}; dpv_match_code: {1}; precision {2}", candidate.metadata.record_type, candidate.analysis.dpv_match_code, candidate.metadata.precision ); location.StandardizeAttemptedResult = candidate.analysis.dpv_match_code; if ( dpvCodes.Contains( candidate.analysis.dpv_match_code ) ) { location.Street1 = candidate.delivery_line_1; location.Street2 = candidate.delivery_line_2; location.City = candidate.components.city_name; location.State = candidate.components.state_abbreviation; location.PostalCode = candidate.components.zipcode + "-" + candidate.components.plus4_code; location.StandardizedDateTime = RockDateTime.Now; } else { verified = false; } location.GeocodeAttemptedResult = candidate.metadata.precision; if ( precisions.Contains( candidate.metadata.precision ) ) { location.SetLocationPointFromLatLong( candidate.metadata.latitude, candidate.metadata.longitude ); location.GeocodedDateTime = RockDateTime.Now; } else { verified = false; } } else { result = "No Match"; } } else { result = response.StatusDescription; } location.StandardizeAttemptedServiceType = "SmartyStreets"; location.StandardizeAttemptedDateTime = RockDateTime.Now; location.GeocodeAttemptedServiceType = "SmartyStreets"; location.GeocodeAttemptedDateTime = RockDateTime.Now; } return verified; }
/// <summary> /// Standardizes and Geocodes an address using Smarty Streets service /// </summary> /// <param name="location">The location.</param> /// <param name="resultMsg">The result MSG.</param> /// <returns> /// True/False value of whether the verification was successfull or not /// </returns> public override VerificationResult Verify( Rock.Model.Location location, out string resultMsg ) { VerificationResult result = VerificationResult.None; resultMsg = string.Empty; string authId = GetAttributeValue( "AuthID" ); string authToken = GetAttributeValue( "AuthToken" ); var dpvCodes = GetAttributeValue("AcceptableDPVCodes").SplitDelimitedValues(); var precisions = GetAttributeValue("AcceptablePrecisions").SplitDelimitedValues(); var payload = new[] { new { addressee = location.Name, street = location.Street1, street2 = location.Street2, city = location.City, state = location.State, zipcode = location.PostalCode, candidates = 1 } }; var client = new RestClient( string.Format( "https://api.smartystreets.com/street-address?auth-id={0}&auth-token={1}", authId, authToken ) ); var request = new RestRequest( Method.POST ); request.RequestFormat = DataFormat.Json; request.AddHeader( "Accept", "application/json" ); request.AddBody( payload ); var response = client.Execute( request ); if (response.StatusCode == HttpStatusCode.OK) { var candidates = JsonConvert.DeserializeObject( response.Content, typeof( List<CandidateAddress> ) ) as List<CandidateAddress>; if (candidates.Any()) { var candidate = candidates.FirstOrDefault(); resultMsg = string.Format( "RecordType:{0}; DPV MatchCode:{1}; Precision:{2}", candidate.metadata.record_type, candidate.analysis.dpv_match_code, candidate.metadata.precision ); location.StandardizeAttemptedResult = candidate.analysis.dpv_match_code; if ( dpvCodes.Contains( candidate.analysis.dpv_match_code ) ) { location.Street1 = candidate.delivery_line_1; location.Street2 = candidate.delivery_line_2; location.City = candidate.components.city_name; location.County = candidate.metadata.county_name; location.State = candidate.components.state_abbreviation; location.PostalCode = candidate.components.zipcode + "-" + candidate.components.plus4_code; location.Barcode = candidate.delivery_point_barcode; result = result | VerificationResult.Standardized; } location.GeocodeAttemptedResult = candidate.metadata.precision; if ( precisions.Contains( candidate.metadata.precision ) ) { if ( location.SetLocationPointFromLatLong( candidate.metadata.latitude, candidate.metadata.longitude ) ) { result = result | VerificationResult.Geocoded; } } } else { resultMsg = "No Match"; } } else { result = VerificationResult.ConnectionError; resultMsg = response.StatusDescription; } return result; }
/// <summary> /// Standardizes and Geocodes an address using Bing service /// </summary> /// <param name="location">The location.</param> /// <param name="reVerify">Should location be reverified even if it has already been succesfully verified</param> /// <param name="result">The result code unique to the service.</param> /// <returns> /// True/False value of whether the verification was successfull or not /// </returns> public override bool VerifyLocation( Rock.Model.Location location, bool reVerify, out string result ) { bool verified = false; result = string.Empty; // Only verify if location is valid, has not been locked, and // has either never been attempted or last attempt was in last 30 secs (prev active service failed) or reverifying if ( location != null && !( location.IsGeoPointLocked ?? false ) && ( !location.GeocodeAttemptedDateTime.HasValue || location.GeocodeAttemptedDateTime.Value.CompareTo( RockDateTime.Now.AddSeconds( -30 ) ) > 0 || reVerify ) ) { // Verify that bing transaction count hasn't been exceeded for the day DateTime? txnDate = Rock.Web.SystemSettings.GetValue( TXN_DATE ).AsDateTime(); int? dailyTxnCount = 0; if ( txnDate.Equals( RockDateTime.Today ) ) { dailyTxnCount = Rock.Web.SystemSettings.GetValue( DAILY_TXN_COUNT ).AsIntegerOrNull(); } else { Rock.Web.SystemSettings.SetValue( TXN_DATE, RockDateTime.Today.ToShortDateString() ); } int? maxTxnCount = GetAttributeValue( "DailyTransactionLimit" ).AsIntegerOrNull(); if ( !maxTxnCount.HasValue || maxTxnCount.Value == 0 || dailyTxnCount < maxTxnCount.Value ) { dailyTxnCount++; Rock.Web.SystemSettings.SetValue( DAILY_TXN_COUNT, dailyTxnCount.ToString() ); string key = GetAttributeValue( "BingMapsKey" ); var queryValues = new Dictionary<string, string>(); queryValues.Add( "adminDistrict", location.State ); queryValues.Add( "locality", location.City ); queryValues.Add( "postalCode", location.PostalCode ); queryValues.Add( "addressLine", location.Street1 + " " + location.Street2 ); queryValues.Add( "countryRegion", location.Country ); var queryParams = new List<string>(); foreach ( var queryKeyValue in queryValues ) { if ( !string.IsNullOrWhiteSpace( queryKeyValue.Value ) ) { queryParams.Add( string.Format( "{0}={1}", queryKeyValue.Key, HttpUtility.UrlEncode( queryKeyValue.Value.Trim() ) ) ); } } Uri geocodeRequest = new Uri( string.Format( "http://dev.virtualearth.net/REST/v1/Locations?{0}&key={1}", queryParams.AsDelimited( "&" ), key ) ); WebClient wc = new WebClient(); var stream = wc.OpenRead( geocodeRequest ); DataContractJsonSerializer ser = new DataContractJsonSerializer( typeof( Response ) ); var x = ser.ReadObject( stream ) as Response; if ( x != null ) { if ( x.ResourceSets.Length > 0 && x.ResourceSets[0].Resources.Length == 1 ) { var bingLocation = (Location)x.ResourceSets[0].Resources[0]; var matchCodes = bingLocation.MatchCodes.ToList(); result = string.Format( "Confidence: {0}; MatchCodes: {1}", bingLocation.Confidence, matchCodes.AsDelimited( "," ) ); if ( bingLocation.Confidence == "High" && matchCodes.Contains( "Good" ) ) { location.SetLocationPointFromLatLong( bingLocation.Point.Coordinates[0], bingLocation.Point.Coordinates[1] ); location.GeocodedDateTime = RockDateTime.Now; verified = true; if ( !location.StandardizedDateTime.HasValue || reVerify ) { var address = bingLocation.Address; if ( address != null ) { location.Street1 = address.AddressLine; location.City = address.Locality; location.State = address.AdminDistrict; if ( !String.IsNullOrWhiteSpace( address.PostalCode ) && !( ( location.PostalCode ?? string.Empty ).StartsWith( address.PostalCode ) ) ) { location.PostalCode = address.PostalCode; } location.StandardizeAttemptedServiceType = "Bing"; location.StandardizeAttemptedResult = "High"; location.StandardizedDateTime = RockDateTime.Now; } } } } else { result = "Zero or More than 1 result"; } } else { result = "Invalid response"; } } else { result = "Daily transaction limit exceeded"; } location.GeocodeAttemptedServiceType = "Bing"; location.GeocodeAttemptedDateTime = RockDateTime.Now; location.GeocodeAttemptedResult = result; } return verified; }
/// <summary> /// Standardizes and Geocodes an address using Bing service /// </summary> /// <param name="location">The location.</param> /// <param name="reVerify">Should location be reverified even if it has already been succesfully verified</param> /// <param name="result">The result code unique to the service.</param> /// <returns> /// True/False value of whether the verification was successfull or not /// </returns> public override bool VerifyLocation( Rock.Model.Location location, bool reVerify, out string result ) { bool verified = false; result = string.Empty; if ( location != null && !(location.IsGeoPointLocked ?? false) && (!location.GeocodeAttemptedDateTime.HasValue || reVerify) ) { // Verify that bing transaction count hasn't been exceeded for the day DateTime? txnDate = Rock.Web.SystemSettings.GetValue( TXN_DATE ).AsDateTime(); int? dailyTxnCount = 0; if (txnDate.Equals(RockDateTime.Today)) { dailyTxnCount = Rock.Web.SystemSettings.GetValue( DAILY_TXN_COUNT ).AsIntegerOrNull(); } else { Rock.Web.SystemSettings.SetValue( TXN_DATE, RockDateTime.Today.ToShortDateString() ); } int? maxTxnCount = GetAttributeValue( "DailyTransactionLimit" ).AsIntegerOrNull(); if ( !maxTxnCount.HasValue || maxTxnCount.Value == 0 || dailyTxnCount < maxTxnCount.Value ) { dailyTxnCount++; Rock.Web.SystemSettings.SetValue( DAILY_TXN_COUNT, dailyTxnCount.ToString() ); string key = GetAttributeValue( "BingMapsKey" ); string query = HttpUtility.UrlEncode( string.Format( "{0} {1} {2} {3} {4}", location.Street1, location.Street2, location.City, location.State, location.PostalCode ) ); Uri geocodeRequest = new Uri( string.Format( "http://dev.virtualearth.net/REST/v1/Locations?q={0}&key={1}", query, key ) ); WebClient wc = new WebClient(); var stream = wc.OpenRead( geocodeRequest ); DataContractJsonSerializer ser = new DataContractJsonSerializer( typeof( Response ) ); var x = ser.ReadObject( stream ) as Response; if ( x != null ) { if ( x.ResourceSets.Length > 0 && x.ResourceSets[0].Resources.Length == 1 ) { var bingLocation = (Location)x.ResourceSets[0].Resources[0]; var matchCodes = bingLocation.MatchCodes.ToList(); result = string.Format( "Confidence: {0}; MatchCodes: {1}", bingLocation.Confidence, matchCodes.AsDelimited( "," ) ); if ( bingLocation.Confidence == "High" && matchCodes.Contains( "Good" ) ) { location.SetLocationPointFromLatLong( bingLocation.Point.Coordinates[0], bingLocation.Point.Coordinates[1] ); location.GeocodedDateTime = RockDateTime.Now; verified = true; if ( !location.StandardizedDateTime.HasValue || reVerify ) { var address = bingLocation.Address; if ( address != null ) { location.Street1 = address.AddressLine; location.City = address.Locality; location.State = address.AdminDistrict; if ( !location.PostalCode.StartsWith( address.PostalCode ) ) { location.PostalCode = address.PostalCode; } location.StandardizeAttemptedServiceType = "Bing"; location.StandardizeAttemptedResult = "High"; location.StandardizedDateTime = RockDateTime.Now; } } } } else { result = "Zero or More than 1 result"; } } else { result = "Invalid response"; } } else { result = "Daily transaction limit exceeded"; } location.GeocodeAttemptedServiceType = "Bing"; location.GeocodeAttemptedDateTime = RockDateTime.Now; location.GeocodeAttemptedResult = result; } return verified; }