Esempio n. 1
0
        private SmartyStreetsAPIKey GetAPIKey()
        {
            SmartyStreetsAPIKey apiKey = null;

            if (GetAttributeValue("UseManagedAPIKey").AsBooleanOrNull() ?? true)
            {
                var lastKeyUpdate        = Rock.Web.SystemSettings.GetValue("core_SmartyStreetsApiKeyLastUpdate").AsDateTime() ?? DateTime.MinValue;
                var hoursSinceLastUpdate = (RockDateTime.Now - lastKeyUpdate).TotalHours;
                if (hoursSinceLastUpdate > 24 || true)
                {
                    var rockInstanceId  = Rock.Web.SystemSettings.GetRockInstanceId();
                    var getAPIKeyClient = new RestClient("https://www.rockrms.com/api/SmartyStreets/GetSmartyStreetsApiKey?rockInstanceId={rockInstanceId}");

                    // If debugging locally
                    // var getAPIKeyClient = new RestClient( $"http://localhost:57822/api/SmartyStreets/GetSmartyStreetsApiKey?rockInstanceId={rockInstanceId}" );

                    var getApiKeyRequest  = new RestRequest(Method.GET);
                    var getApiKeyResponse = getAPIKeyClient.Get <SmartyStreetsAPIKey>(getApiKeyRequest);

                    if (getApiKeyResponse.StatusCode == HttpStatusCode.OK)
                    {
                        SmartyStreetsAPIKey managedKey = getApiKeyResponse.Data;
                        if (managedKey.AuthID != null && managedKey.AuthToken != null)
                        {
                            Rock.Web.SystemSettings.SetValue("core_SmartyStreetsApiKeyLastUpdate", RockDateTime.Now.ToString("o"));
                            Rock.Web.SystemSettings.SetValue("core_SmartyStreetsAuthID", Rock.Security.Encryption.EncryptString(managedKey.AuthID));
                            Rock.Web.SystemSettings.SetValue("core_SmartyStreetsAuthToken", Rock.Security.Encryption.EncryptString(managedKey.AuthToken));
                        }
                    }
                }

                string encryptedAuthID    = Rock.Web.SystemSettings.GetValue("core_SmartyStreetsAuthID");
                string encryptedAuthToken = Rock.Web.SystemSettings.GetValue("core_SmartyStreetsAuthToken");

                apiKey           = new SmartyStreetsAPIKey();
                apiKey.AuthID    = Rock.Security.Encryption.DecryptString(encryptedAuthID);
                apiKey.AuthToken = Rock.Security.Encryption.DecryptString(encryptedAuthToken);
            }

            if (apiKey == null || apiKey.AuthID == null || apiKey.AuthToken == null)
            {
                apiKey           = new SmartyStreetsAPIKey();
                apiKey.AuthID    = GetAttributeValue("AuthID");
                apiKey.AuthToken = GetAttributeValue("AuthToken");
            }

            return(apiKey);
        }
Esempio n. 2
0
        /// <summary>
        /// Gets the location from postal code.
        /// </summary>
        /// <param name="postalCode">The postal code.</param>
        /// <param name="resultMsg">The result MSG.</param>
        /// <returns></returns>
        public MapCoordinate GetLocationFromPostalCode(string postalCode, out string resultMsg)
        {
            MapCoordinate result = null;

            resultMsg = string.Empty;

            if (this.IsActive)
            {
                SmartyStreetsAPIKey apiKey = GetAPIKey();

                var payload = new[] { new { zipcode = postalCode } };

                var client  = new RestClient(string.Format("https://us-zipcode.api.smartystreets.com/lookup?auth-id={0}&auth-token={1}", apiKey.AuthID, apiKey.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 lookupResponse = JsonConvert.DeserializeObject(response.Content, typeof(List <LookupResponse>)) as List <LookupResponse>;
                    if (lookupResponse != null && lookupResponse.Any() && lookupResponse.First().zipcodes.Any())
                    {
                        var zipcode = lookupResponse.First().zipcodes.FirstOrDefault();
                        result           = new MapCoordinate();
                        result.Latitude  = zipcode.latitude;
                        result.Longitude = zipcode.longitude;
                        resultMsg        = JsonConvert.SerializeObject(zipcode);
                    }
                    else
                    {
                        resultMsg = "No Match";
                    }
                }
                else
                {
                    resultMsg = response.StatusDescription;
                }
            }
            else
            {
                resultMsg = "Smarty Steets is not active.";
            }

            return(result);
        }
Esempio n. 3
0
        /// <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 successful or not
        /// </returns>
        public override VerificationResult Verify(Rock.Model.Location location, out string resultMsg)
        {
            VerificationResult result = VerificationResult.None;

            resultMsg = string.Empty;

            SmartyStreetsAPIKey apiKey = GetAPIKey();

            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}", apiKey.AuthID, apiKey.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);
        }
Esempio n. 4
0
        /// <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    = null;
            string authToken = null;

            if (GetAttributeValue("UseManagedAPIKey").AsBooleanOrNull() ?? true)
            {
                var lastKeyUpdate        = Rock.Web.SystemSettings.GetValue("core_SmartyStreetsApiKeyLastUpdate").AsDateTime() ?? DateTime.MinValue;
                var hoursSinceLastUpdate = (RockDateTime.Now - lastKeyUpdate).TotalHours;
                if (hoursSinceLastUpdate > 24 || true)
                {
                    var rockInstanceId  = Rock.Web.SystemSettings.GetRockInstanceId();
                    var getAPIKeyClient = new RestClient("https://www.rockrms.com/api/SmartyStreets/GetSmartyStreetsApiKey?rockInstanceId={rockInstanceId}");

                    // If debugging locally
                    // var getAPIKeyClient = new RestClient( $"http://localhost:57822/api/SmartyStreets/GetSmartyStreetsApiKey?rockInstanceId={rockInstanceId}" );

                    var getApiKeyRequest  = new RestRequest(Method.GET);
                    var getApiKeyResponse = getAPIKeyClient.Get <SmartyStreetsAPIKey>(getApiKeyRequest);

                    if (getApiKeyResponse.StatusCode == HttpStatusCode.OK)
                    {
                        SmartyStreetsAPIKey managedKey = getApiKeyResponse.Data;
                        if (managedKey.AuthID != null && managedKey.AuthToken != null)
                        {
                            Rock.Web.SystemSettings.SetValue("core_SmartyStreetsApiKeyLastUpdate", RockDateTime.Now.ToString("o"));
                            Rock.Web.SystemSettings.SetValue("core_SmartyStreetsAuthID", Rock.Security.Encryption.EncryptString(managedKey.AuthID));
                            Rock.Web.SystemSettings.SetValue("core_SmartyStreetsAuthToken", Rock.Security.Encryption.EncryptString(managedKey.AuthToken));
                        }
                    }
                }

                string encryptedAuthID    = Rock.Web.SystemSettings.GetValue("core_SmartyStreetsAuthID");
                string encryptedAuthToken = Rock.Web.SystemSettings.GetValue("core_SmartyStreetsAuthToken");

                authId    = Rock.Security.Encryption.DecryptString(encryptedAuthID);
                authToken = Rock.Security.Encryption.DecryptString(encryptedAuthToken);
            }

            if (authId == null || authToken == null)
            {
                authId    = GetAttributeValue("AuthID");
                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);
        }